Search is not available for this dataset
content
stringlengths
60
399M
max_stars_repo_name
stringlengths
6
110
<|start_filename|>src/utils/config.go<|end_filename|> package utils import ( "gopkg.in/yaml.v3" "io/ioutil" "os" ) var Config struct { Site struct { AppName string `yaml:"app_name"` RunMode string `yaml:"runmode"` DeployHost string `yaml:"deploy_host"` ListenAddr string `yaml:"listen_addr"` } `yaml:"site"` Prod struct { StaticPrefix string `yaml:"static_prefix"` // http prefix of static and views files } `yaml:"prod"` Dev struct { StaticPrefix string `yaml:"static_prefix"` // https prefix of only static files //StaticPrefix string `yaml:"static_prefix"` // prefix of static files in dev mode. // redirect static files requests to this address, redirect "StaticPrefix" to "StaticRedirect + StaticPrefix" // for example, StaticPrefix is "static", StaticRedirect is "localhost:8080/dist", // this will redirect all requests having prefix "static" to "localhost:8080/dist/" StaticRedirect string `yaml:"static_redirect"` // http server will read static file from this dir if StaticRedirect is empty StaticDir string `yaml:"static_dir"` ViewsPrefix string `yaml:"views_prefix"` // https prefix of only views files // path of view files (we can not redirect view files) to be served. ViewsDir string `yaml:"views_dir"` // todo } `yaml:"dev"` SSH struct { BufferCheckerCycleTime int `yaml:"buffer_checker_cycle_time"` } `yaml:"ssh"` Jwt struct { Secret string `yaml:"jwt_secret"` TokenLifetime int64 `yaml:"token_lifetime"` Issuer string `yaml:"issuer"` QueryTokenKey string `yaml:"query_token_key"` } `yaml:"jwt"` } func InitConfig(filepath string) error { f, err := os.Open(filepath) if err != nil { return err } defer f.Close() content, err := ioutil.ReadAll(f) if err != nil { return err } err = yaml.Unmarshal(content, &Config) if err != nil { return err } return nil } <|start_filename|>src/controllers/websocket.go<|end_filename|> package controllers import ( "context" "fmt" "github.com/genshen/ssh-web-console/src/models" "github.com/genshen/ssh-web-console/src/utils" "golang.org/x/crypto/ssh" "io" "log" "net/http" "nhooyr.io/websocket" "time" ) //const SSH_EGG = `genshen<<EMAIL>> https://github.com/genshen/sshWebConsole"` type SSHWebSocketHandle struct { bufferFlushCycle int } func NewSSHWSHandle(bfc int) *SSHWebSocketHandle { var handle SSHWebSocketHandle handle.bufferFlushCycle = bfc return &handle } // clear session after ssh closed. func (c *SSHWebSocketHandle) ShouldClearSessionAfterExec() bool { return true } // handle webSocket connection. func (c *SSHWebSocketHandle) ServeAfterAuthenticated(w http.ResponseWriter, r *http.Request, claims *utils.Claims, session utils.Session) { // init webSocket connection conn, err := websocket.Accept(w, r, nil) if err != nil { http.Error(w, "Cannot setup WebSocket connection:", 400) log.Println("Error: Cannot setup WebSocket connection:", err) return } defer conn.Close(websocket.StatusNormalClosure, "closed") userInfo := session.Value.(models.UserInfo) cols := utils.GetQueryInt32(r, "cols", 120) rows := utils.GetQueryInt32(r, "rows", 32) sshAuth := ssh.Password(userInfo.Password) if err := c.SSHShellOverWS(r.Context(), conn, claims.Host, claims.Port, userInfo.Username, sshAuth, cols, rows); err != nil { log.Println("Error,", err) utils.Abort(w, err.Error(), 500) } } // ssh shell over websocket // first,we establish a ssh connection to ssh server when a webSocket comes; // then we deliver ssh data via ssh connection between browser and ssh server. // That is, read webSocket data from browser (e.g. 'ls' command) and send data to ssh server via ssh connection; // the other hand, read returned ssh data from ssh server and write back to browser via webSocket API. func (c *SSHWebSocketHandle) SSHShellOverWS(ctx context.Context, ws *websocket.Conn, host string, port int, username string, auth ssh.AuthMethod, cols, rows uint32) error { //setup ssh connection sshEntity := utils.SSHShellSession{ Node: utils.NewSSHNode(host, port), } // set io for ssh session var wsBuff WebSocketBufferWriter sshEntity.WriterPipe = &wsBuff var sshConn utils.SSHConnInterface = &sshEntity // set interface err := sshConn.Connect(username, auth) if err != nil { return fmt.Errorf("cannot setup ssh connection %w", err) } defer sshConn.Close() // config ssh sshSession, err := sshConn.Config(cols, rows) if err != nil { return fmt.Errorf("configure ssh error: %w", err) } // an egg: //if err := sshSession.Setenv("SSH_EGG", SSH_EGG); err != nil { // log.Println(err) //} // after configure, the WebSocket is ok. defer wsBuff.Flush(ctx, websocket.MessageBinary, ws) done := make(chan bool, 3) setDone := func() { done <- true } // most messages are ssh output, not webSocket input writeMessageToSSHServer := func(wc io.WriteCloser) { // read messages from webSocket defer setDone() for { msgType, p, err := ws.Read(ctx) // if WebSocket is closed by some reason, then this func will return, // and 'done' channel will be set, the outer func will reach to the end. // then ssh session will be closed in defer. if err != nil { log.Println("Error: error reading webSocket message:", err) return } if err = DispatchMessage(sshSession, msgType, p, wc); err != nil { log.Println("Error: error write data to ssh server:", err) return } } } stopper := make(chan bool) // timer stopper // check webSocketWriterBuffer(if not empty,then write back to webSocket) every 120 ms. writeBufferToWebSocket := func() { defer setDone() tick := time.NewTicker(time.Millisecond * time.Duration(c.bufferFlushCycle)) //for range time.Tick(120 * time.Millisecond){} defer tick.Stop() for { select { case <-tick.C: if err := wsBuff.Flush(ctx, websocket.MessageBinary, ws); err != nil { log.Println("Error: error sending data via webSocket:", err) return } case <-stopper: return } } } go writeMessageToSSHServer(sshEntity.StdinPipe) go writeBufferToWebSocket() go func() { defer setDone() if err := sshSession.Wait(); err != nil { log.Println("ssh exist from server", err) } // if ssh is closed (wait returns), then 'done', web socket will be closed. // by the way, buffered data will be flushed before closing WebSocket. }() <-done stopper <- true // stop tick timer(if tick is finished by due to the bad WebSocket, this line will just only set channel(no bad effect). ) log.Println("Info: websocket finished!") return nil } <|start_filename|>Dockerfile<|end_filename|> # build method: just run `docker build --rm --build-arg -t genshen/ssh-web-console .` # build frontend code FROM node:14.15.4-alpine3.12 AS frontend-builder COPY web web-console/ RUN cd web-console \ && yarn install \ && yarn build FROM golang:1.15.7-alpine3.13 AS builder # set to 'on' if using go module ARG STATIC_DIR=build RUN apk add --no-cache git \ && go get -u github.com/rakyll/statik COPY ./ /go/src/github.com/genshen/ssh-web-console/ COPY --from=frontend-builder web-console/build /go/src/github.com/genshen/ssh-web-console/${STATIC_DIR}/ RUN cd ./src/github.com/genshen/ssh-web-console/ \ && statik -src=${STATIC_DIR} \ && go build \ && go install ## copy binary FROM alpine:3.13 ARG HOME="/home/web" RUN adduser -D web -h ${HOME} COPY --from=builder --chown=web /go/bin/ssh-web-console ${HOME}/ssh-web-console WORKDIR ${HOME} USER web VOLUME ["${HOME}/conf"] CMD ["./ssh-web-console"] <|start_filename|>Makefile<|end_filename|> PACKAGE=github.com/genshen/ssh-web-console .PHONY: clean all all: ssh-web-console-linux-amd64 ssh-web-console-linux-arm64 ssh-web-console-darwin-amd64 ssh-web-console-windows-amd64.exe ssh-web-console-linux-amd64: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ssh-web-console-linux-amd64 ${PACKAGE} ssh-web-console-linux-arm64: CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o ssh-web-console-linux-arm64 ${PACKAGE} ssh-web-console-darwin-amd64: CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -o ssh-web-console-darwin-amd64 ${PACKAGE} ssh-web-console-windows-amd64.exe: CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o ssh-web-console-windows-amd64.exe ${PACKAGE} ssh-web-console : go build -o ssh-web-console clean: rm -f ssh-web-console-linux-amd64 ssh-web-console-linux-arm64 ssh-web-console-darwin-amd64 ssh-web-console-windows-amd64.exe <|start_filename|>src/controllers/files/ls_controller.go<|end_filename|> package files import ( "github.com/genshen/ssh-web-console/src/models" "github.com/genshen/ssh-web-console/src/utils" "log" "net/http" "os" "path" ) type List struct{} type Ls struct { Name string `json:"name"` Path string `json:"path"` // including Name Mode os.FileMode `json:"mode"` // todo: use io/fs.FileMode } func (f List) ShouldClearSessionAfterExec() bool { return false } func (f List) ServeAfterAuthenticated(w http.ResponseWriter, r *http.Request, claims *utils.Claims, session utils.Session) { response := models.JsonResponse{HasError: true} cid := r.URL.Query().Get("cid") // get connection id. if client := utils.ForkSftpClient(cid); client == nil { utils.Abort(w, "error: lost sftp connection.", 400) log.Println("Error: lost sftp connection.") return } else { if wd, err := client.Getwd(); err == nil { relativePath := r.URL.Query().Get("path") // get path. fullPath := path.Join(wd, relativePath) if files, err := client.ReadDir(fullPath); err != nil { response.Addition = "no such path" } else { response.HasError = false fileList := make([]Ls, 0) // this will not be converted to null if slice is empty. for _, file := range files { fileList = append(fileList, Ls{Name: file.Name(), Mode: file.Mode(), Path: path.Join(relativePath, file.Name())}) } response.Message = fileList } } else { response.Addition = "no such path" } } utils.ServeJSON(w, response) } <|start_filename|>src/controllers/main_controller.go<|end_filename|> package controllers import ( "github.com/genshen/ssh-web-console/src/models" "github.com/genshen/ssh-web-console/src/utils" "golang.org/x/crypto/ssh" "net/http" "strconv" ) func SignIn(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, "Invalid request method.", 405) } else { var err error var errUnmarshal models.JsonResponse err = r.ParseForm() if err != nil { panic(err) } userinfo := models.UserInfo{} userinfo.Host = r.Form.Get("host") port := r.Form.Get("port") userinfo.Username = r.Form.Get("username") userinfo.Password = r.Form.Get("passwd") userinfo.Port, err = strconv.Atoi(port) if err != nil { userinfo.Port = 22 } if userinfo.Host != "" && userinfo.Username != "" { //try to login session account session := utils.SSHShellSession{} session.Node = utils.NewSSHNode(userinfo.Host, userinfo.Port) err := session.Connect(userinfo.Username, ssh.Password(userinfo.Password)) if err != nil { errUnmarshal = models.JsonResponse{HasError: true, Message: models.SIGN_IN_FORM_TYPE_ERROR_PASSWORD} } else { defer session.Close() // create session client, err := session.GetClient() if err != nil { // bad connection. return } if session, err := client.NewSession(); err == nil { if err := session.Run("whoami"); err == nil { if token, expireUnix, err := utils.JwtNewToken(userinfo.JwtConnection, utils.Config.Jwt.Issuer); err == nil { errUnmarshal = models.JsonResponse{HasError: false, Addition: token} utils.ServeJSON(w, errUnmarshal) utils.SessionStorage.Put(token, expireUnix, userinfo) return } } } errUnmarshal = models.JsonResponse{HasError: true, Message: models.SIGN_IN_FORM_TYPE_ERROR_TEST} } } else { errUnmarshal = models.JsonResponse{HasError: true, Message: models.SIGN_IN_FORM_TYPE_ERROR_VALID} } utils.ServeJSON(w, errUnmarshal) } }
onlyrico/ssh-web-console
<|start_filename|>build/sync/plan/checks_test.go<|end_filename|> package plan_test import ( "fmt" "io/ioutil" "os" "path" "path/filepath" "testing" git "github.com/go-git/go-git/v5" "github.com/stretchr/testify/assert" "github.com/mattermost/mattermost-plugin-starter-template/build/sync/plan" ) // Tests for the RepoIsClean checker. func TestRepoIsCleanChecker(t *testing.T) { assert := assert.New(t) // Create a git repository in a temporary dir. dir, err := ioutil.TempDir("", "test") assert.Nil(err) defer os.RemoveAll(dir) repo, err := git.PlainInit(dir, false) assert.Nil(err) // Repo should be clean. checker := plan.RepoIsCleanChecker{} checker.Params.Repo = plan.TargetRepo ctx := plan.Setup{ Target: plan.RepoSetup{ Path: dir, Git: repo, }, } assert.Nil(checker.Check("", ctx)) // Create a file in the repository. err = ioutil.WriteFile(path.Join(dir, "data.txt"), []byte("lorem ipsum"), 0600) assert.Nil(err) err = checker.Check("", ctx) assert.EqualError(err, "\"target\" repository is not clean") assert.True(plan.IsCheckFail(err)) } func TestPathExistsChecker(t *testing.T) { assert := assert.New(t) wd, err := os.Getwd() assert.Nil(err) checker := plan.PathExistsChecker{} checker.Params.Repo = plan.SourceRepo ctx := plan.Setup{ Source: plan.RepoSetup{ Path: wd, }, } // Check with existing directory. assert.Nil(checker.Check("testdata", ctx)) // Check with existing file. assert.Nil(checker.Check("testdata/a", ctx)) err = checker.Check("nosuchpath", ctx) assert.NotNil(err) assert.True(plan.IsCheckFail(err)) } func TestUnalteredCheckerSameFile(t *testing.T) { assert := assert.New(t) // Path to the root of the repo. wd, err := filepath.Abs("../../../") assert.Nil(err) gitRepo, err := git.PlainOpen(wd) assert.Nil(err) ctx := plan.Setup{ Source: plan.RepoSetup{ Path: wd, Git: gitRepo, }, Target: plan.RepoSetup{ Path: wd, }, } checker := plan.FileUnalteredChecker{} checker.Params.SourceRepo = plan.SourceRepo checker.Params.TargetRepo = plan.TargetRepo // Check with the same file - check should succeed hashPath := "build/sync/plan/testdata/a" err = checker.Check(hashPath, ctx) assert.Nil(err) } func TestUnalteredCheckerDifferentContents(t *testing.T) { assert := assert.New(t) // Path to the root of the repo. wd, err := filepath.Abs("../../../") assert.Nil(err) gitRepo, err := git.PlainOpen(wd) assert.Nil(err) ctx := plan.Setup{ Source: plan.RepoSetup{ Path: wd, Git: gitRepo, }, Target: plan.RepoSetup{ Path: wd, }, } checker := plan.FileUnalteredChecker{} checker.Params.SourceRepo = plan.SourceRepo checker.Params.TargetRepo = plan.TargetRepo // Create a file with the same suffix path, but different contents. hashPath := "build/sync/plan/testdata/a" tmpDir, err := ioutil.TempDir("", "test") assert.Nil(err) defer os.RemoveAll(tmpDir) fullPath := filepath.Join(tmpDir, "build/sync/plan/testdata") err = os.MkdirAll(fullPath, 0777) assert.Nil(err) file, err := os.OpenFile(filepath.Join(fullPath, "a"), os.O_CREATE|os.O_WRONLY, 0755) assert.Nil(err) _, err = file.WriteString("this file has different contents") assert.Nil(err) assert.Nil(file.Close()) // Set the plugin path to the temporary directory. ctx.Target.Path = tmpDir err = checker.Check(hashPath, ctx) assert.True(plan.IsCheckFail(err)) assert.EqualError(err, fmt.Sprintf("file %q has been altered", filepath.Join(tmpDir, hashPath))) } // TestUnalteredCheckerNonExistant tests running the unaltered file checker // in the case where the target file does not exist. If the files has no history, // the checker should pass. func TestUnalteredCheckerNonExistant(t *testing.T) { assert := assert.New(t) hashPath := "build/sync/plan/testdata/a" // Path to the root of the repo. wd, err := filepath.Abs("../../../") assert.Nil(err) gitRepo, err := git.PlainOpen(wd) assert.Nil(err) // Temporary repo. tmpDir, err := ioutil.TempDir("", "test") assert.Nil(err) defer os.RemoveAll(tmpDir) trgRepo, err := git.PlainInit(tmpDir, false) assert.Nil(err) ctx := plan.Setup{ Source: plan.RepoSetup{ Path: wd, Git: gitRepo, }, Target: plan.RepoSetup{ Path: tmpDir, Git: trgRepo, }, } checker := plan.FileUnalteredChecker{} checker.Params.SourceRepo = plan.SourceRepo checker.Params.TargetRepo = plan.TargetRepo err = checker.Check(hashPath, ctx) assert.Nil(err) }
amit11893/my-plugin
<|start_filename|>test.js<|end_filename|> 'use strict'; const {promisify} = require('util'); const {lstat, mkdir, writeFile} = require('graceful-fs'); const rmfr = require('.'); const test = require('tape'); const promisifiedLstat = promisify(lstat); const promisifiedMkdir = promisify(mkdir); const promisifiedWriteFile = promisify(writeFile); test('rmfr()', async t => { await Promise.all([ promisifiedWriteFile('tmp_file', ''), promisifiedMkdir('tmp_dir') ]); await rmfr('tmp_file'); try { await promisifiedLstat('tmp_file'); t.fail('File not removed.'); } catch ({code}) { t.equal( code, 'ENOENT', 'should remove a file.' ); } await rmfr('tmp_d*', {}); t.ok( (await promisifiedLstat('tmp_dir')).isDirectory(), 'should disable `glob` option by default.' ); await rmfr('../{tmp_d*,test.js}', { glob: { cwd: 'node_modules', ignore: __filename } }); try { await promisifiedLstat('../{tmp_d*,package.json}'); t.fail('Directory not removed.'); } catch ({code}) { t.equal( code, 'ENOENT', 'should support glob.' ); } t.ok( (await promisifiedLstat(__filename)).isFile(), 'should support glob options.' ); await rmfr('test.js', { glob: { cwd: 'this/directory/does/not/exist' } }); t.ok( (await promisifiedLstat(__filename)).isFile(), 'should consider `cwd` even if the path contains no special characters.' ); const error = new Error('_'); try { await rmfr('.gitignore', {unlink: (path, cb) => cb(error)}); t.fail('Unexpectedly succeeded.'); } catch (err) { t.equal( err, error, 'should fail when an error occurs while calling rimraf.' ); } try { await rmfr(); t.fail('Unexpectedly succeeded.'); } catch ({message}) { t.equal( message, 'Expected 1 or 2 arguments (<string>[, <Object>]), but got no arguments.', 'should fail when it takes no arguments.' ); } try { await rmfr('<', {o: 'O'}, '/'); t.fail('Unexpectedly succeeded.'); } catch ({message}) { t.equal( message, 'Expected 1 or 2 arguments (<string>[, <Object>]), but got 3 arguments.', 'should fail when it takes too many arguments.' ); } try { await rmfr(['1'], {glob: true}); t.fail('Unexpectedly succeeded.'); } catch ({message}) { t.equal( message, 'rimraf: path should be a string', 'should fail when the first argument is not a string.' ); } try { await rmfr('foo', 1); t.fail('Unexpectedly succeeded.'); } catch ({message}) { t.ok( /^Expected an option object passed to rimraf.*, but got 1 \(number\)\./.test(message), 'should fail when the second argument is not an object.' ); } try { await rmfr('foo', {chmod: new Set(['a'])}); t.fail('Unexpectedly succeeded.'); } catch ({name}) { t.equal( name, 'TypeError', 'should fail when it takes an invalid option.' ); } try { await rmfr('foo', { maxBusyTries: 'foo', emfileWait: 'bar', glob: 'baz' }); t.fail('Unexpectedly succeeded.'); } catch ({name}) { t.equal( name, 'TypeError', 'should fail when it takes invalid options.' ); } try { await rmfr('foo', { glob: { stat: true } }); t.fail('Unexpectedly succeeded.'); } catch ({message}) { t.equal( message, 'rmfr doesn\'t support `stat` option in `glob` option, but got true (boolean).', 'should fail when it takes unsupported glob option.' ); } try { await rmfr('foo', { glob: { nosort: false } }); t.fail('Unexpectedly succeeded.'); } catch ({message}) { t.equal( message, 'rmfr doesn\'t allow `nosort` option in `glob` option to be disabled, but `false` was passed to it.', 'should fail when the forcedly enabled option is disabled.' ); } try { await rmfr('foo', {disableGlob: true}); t.fail('Unexpectedly succeeded.'); } catch ({message}) { t.equal( message, 'rmfr doesn\'t support `disableGlob` option, but a value true (boolean) was provided. rmfr disables glob feature by default.', 'should fail when `disableGlob` option is provided.' ); } try { await rmfr('foo', { glob: { ignore: new WeakSet() } }); t.fail('Unexpectedly succeeded.'); } catch ({message}) { t.equal( message, 'node-glob expected `ignore` option to be an array or string, but got WeakSet {}.', 'should fail when it takes invalid glob options.' ); } t.end(); });
shinnn/rmfr
<|start_filename|>src/pages/politicians/Senators.js<|end_filename|> export default [ { "id": "0", "name": "<NAME>", "state": "Abia South", "phoneNo": "08033129452", "email": "<EMAIL>" }, { "id": "1", "name": "<NAME>", "state": "Abia North", "phoneNo": "08034000001", "email": "<EMAIL>" }, { "id": "2", "name": "<NAME>", "state": "Abia Central", "phoneNo": "07082800000", "email": "<EMAIL>" }, { "id": "3", "name": "<NAME>", "state": "Adamawa South", "phoneNo": "08034050460", "email": "<EMAIL> " }, { "id": "4", "name": "<NAME>", "state": "Adamawa North", "phoneNo": "08066285112", "email": "<EMAIL>" }, { "id": "5", "name": "<NAME>", "state": "Adamawa Central", "phoneNo": "", "email": "<EMAIL>" }, { "id": "6", "name": "<NAME>", "state": "Akwa Ibom North East", "phoneNo": "08055555188", "email": "<EMAIL>" }, { "id": "7", "name": "<NAME>", "state": "Akwa Ibom South", "phoneNo": "08035054282", "email": "<EMAIL>" }, { "id": "8", "name": "<NAME>", "state": "Akwa Ibom North West", "phoneNo": "08027785234", "email": "<EMAIL>" }, { "id": "9", "name": "<NAME>", "state": "Anambra South", "phoneNo": "09096655596", "email": " <EMAIL>" }, { "id": "10", "name": "<NAME>", "state": "Anambra Central", "phoneNo": "08037620002", "email": "<EMAIL>" }, { "id": "11", "name": "<NAME>", "state": "Anambra North", "phoneNo": "08055084340", "email": "<EMAIL>" }, { "id": "12", "name": "<NAME>", "state": "Bauchi Central", "phoneNo": "08038666690", "email": "<EMAIL>" }, { "id": "13", "name": "<NAME>", "state": "Bauchi North", "phoneNo": "", "email": "<EMAIL>" }, { "id": "14", "name": "<NAME>", "state": "Bauchi South", "phoneNo": "", "email": "<EMAIL>" }, { "id": "15", "name": "<NAME>", "state": "Bayelsa West", "phoneNo": "09031352791", "email": "<EMAIL>" }, { "id": "16", "name": "<NAME>", "state": "Bayelsa Central", "phoneNo": "08036668698", "email": "<EMAIL>" }, { "id": "110", "name": "<NAME>", "state": "Bayelsa East", "phoneNo": "", "email": "<EMAIL>" }, { "id": "17", "name": "<NAME>", "state": "Benue North West", "phoneNo": "", "email": "<EMAIL>" }, { "id": "111", "name": "<NAME>", "state": "Benue North East", "phoneNo": "", "email": "" }, { "id": "18", "name": "<NAME>", "state": "Benue South", "phoneNo": "08068870606", "email": "<EMAIL>" }, { "id": "19", "name": "<NAME>", "state": "Ebonyi North", "phoneNo": "08039665848 ", "email": "<EMAIL>" }, { "id": "20", "name": "<NAME>", "state": "Ebonyi Central", "phoneNo": "08037791346", "email": "<EMAIL>" }, { "id": "21", "name": "<NAME>", "state": "Ebonyi South", "phoneNo": "08034528595", "email": "<EMAIL>" }, { "id": "22", "name": "<NAME>", "state": "Borno North", "phoneNo": "", "email": "<EMAIL>" }, { "id": "23", "name": "<NAME>", "state": "Borno Central", "phoneNo": "08034459047", "email": "<EMAIL>" }, { "id": "24", "name": "<NAME>", "state": "Borno South", "phoneNo": "08109480004", "email": "<EMAIL>" }, { "id": "25", "name": "<NAME>", "state": "Cross River North", "phoneNo": "", "email": "<EMAIL>" }, { "id": "26", "name": "<NAME>", "state": "Cross River South", "phoneNo": "08034444555", "email": "<EMAIL>" }, { "id": "27", "name": "<NAME>", "state": "Cross River Central", "phoneNo": "08030998460", "email": "<EMAIL>" }, { "id": "28", "name": "<NAME>", "state": "Delta Central", "phoneNo": "07033399937", "email": "<EMAIL>" }, { "id": "29", "name": "<NAME>", "state": "Delta South", "phoneNo": "08143103829", "email": "<EMAIL>" }, { "id": "30", "name": "<NAME>", "state": "Delta North", "phoneNo": "08037200999", "email": "<EMAIL>" }, { "id": "31", "name": "<NAME>", "state": "Edo Central", "phoneNo": "08038403877", "email": "<EMAIL>" }, { "id": "32", "name": "<NAME>", "state": "Edo North", "phoneNo": "08155555884", "email": "<EMAIL>" }, { "id": "33", "name": "<NAME>", "state": "Edo South", "phoneNo": "08033855557", "email": "<EMAIL>" }, { "id": "34", "name": "<NAME>", "state": "Ekiti South", "phoneNo": "08023051100", "email": "<EMAIL>" }, { "id": "35", "name": "<NAME>", "state": "Ekiti North", "phoneNo": "08064487689", "email": "<EMAIL>" }, { "id": "36", "name": "<NAME>", "state": "Ekiti Central", "phoneNo": "080911112", "email": "<EMAIL>" }, { "id": "37", "name": "<NAME>", "state": "Enugu East", "phoneNo": "08022255522", "email": "<EMAIL>" }, { "id": "38", "name": "<NAME>", "state": "Enugu West", "phoneNo": "08075757000", "email": "<EMAIL>" }, { "id": "39", "name": "<NAME>", "state": "Enugu North", "phoneNo": "", "email": "<EMAIL>" }, { "id": "40", "name": "<NAME>", "state": "Gombe South", "phoneNo": "", "email": "<EMAIL>" }, { "id": "41", "name": "<NAME>", "state": "Gombe Central", "phoneNo": "07068686699", "email": "<EMAIL>" }, { "id": "42", "name": "<NAME>", "state": "Gombe North", "phoneNo": "08026032222", "email": "<EMAIL>" }, { "id": "43", "name": "<NAME>", "state": "Imo East", "phoneNo": "08032012132", "email": "<EMAIL>" }, { "id": "44", "name": "<NAME>", "state": "Imo West", "phoneNo": "", "email": "<EMAIL>" }, { "id": "45", "name": "<NAME>", "state": "Imo North", "phoneNo": "", "email": "<EMAIL>" }, { "id": "46", "name": "<NAME>", "state": "Jigawa West", "phoneNo": "08037032577", "email": "<EMAIL>" }, { "id": "47", "name": "<NAME>", "state": "Jigawa South West", "phoneNo": "08022902648", "email": "<EMAIL>" }, { "id": "48", "name": "<NAME>", "state": "Jigawa North East", "phoneNo": "", "email": "<EMAIL>" }, { "id": "49", "name": "<NAME>", "state": "Kaduna North", "phoneNo": "08033019005", "email": "<EMAIL>" }, { "id": "50", "name": "<NAME>", "state": "Kaduna South", "phoneNo": "08118887772", "email": "<EMAIL>" }, { "id": "51", "name": "<NAME>", "state": "Kano South", "phoneNo": "", "email": "<EMAIL>" }, { "id": "52", "name": "<NAME>", "state": "Kano North", "phoneNo": "", "email": "<EMAIL>" }, { "id": "53", "name": "<NAME>", "state": "Kano Central", "phoneNo": "08099199111", "email": "<EMAIL>" }, { "id": "54", "name": "<NAME>", "state": "Katsina North", "phoneNo": "", "email": "<EMAIL>" }, { "id": "55", "name": "<NAME>", "state": "Katsina South", "phoneNo": "", "email": "<EMAIL>" }, { "id": "56", "name": "<NAME>", "state": "Katsina Central", "phoneNo": "08138360742", "email": "<EMAIL>" }, { "id": "58", "name": "<NAME>", "state": "Kebbi Central", "phoneNo": "07066847000", "email": "<EMAIL>" }, { "id": "59", "name": "<NAME>", "state": "Kebbi North", "phoneNo": "", "email": "<EMAIL>" }, { "id": "60", "name": "<NAME>", "state": "Kebbi South", "phoneNo": "", "email": "<EMAIL>" }, { "id": "61", "name": "<NAME>", "state": "Kwara South", "phoneNo": "07055221111", "email": " <EMAIL>" }, { "id": "62", "name": "<NAME>", "state": "Kwara North", "phoneNo": "", "email": "<EMAIL>" }, { "id": "63", "name": "<NAME>", "state": "Kwara Central", "phoneNo": "08033581695", "email": "<EMAIL>" }, { "id": "64", "name": "<NAME>", "state": "Lagos Central", "phoneNo": "08095300251", "email": "<EMAIL>" }, { "id": "65", "name": "<NAME>", "state": "Lagos West", "phoneNo": "08033049369", "email": "<EMAIL>" }, { "id": "66", "name": "<NAME>", "state": "Lagos East", "phoneNo": "08074000040", "email": "<EMAIL>" }, { "id": "67", "name": "<NAME>", "state": "Nassarawa North", "phoneNo": "", "email": "<EMAIL>" }, { "id": "68", "name": "<NAME>", "state": "Nassarawa East", "phoneNo": "08099321703", "email": "<EMAIL>" }, { "id": "69", "name": "<NAME>", "state": "Nassarawa South", "phoneNo": "08077253989", "email": "<EMAIL>" }, { "id": "70", "name": "<NAME>", "state": "Kogi East", "phoneNo": "08185651909", "email": "<EMAIL>" }, { "id": "71", "name": "<NAME>", "state": "Kogi Central", "phoneNo": "07032642674", "email": "<EMAIL>" }, { "id": "72", "name": "<NAME>", "state": "Niger North", "phoneNo": "08052046555", "email": "<EMAIL>" }, { "id": "73", "name": "<NAME>", "state": "Niger South", "phoneNo": "08173479797", "email": "<EMAIL>" }, { "id": "74", "name": "<NAME>", "state": "Niger East", "phoneNo": "08033114615", "email": "<EMAIL>" }, { "id": "75", "name": "<NAME>", "state": "Ogun East", "phoneNo": "08033047403", "email": "<EMAIL>" }, { "id": "76", "name": "<NAME>", "state": "Ogun Central", "phoneNo": "08033213993", "email": "<EMAIL>" }, { "id": "77", "name": "<NAME>", "state": "Ogun West", "phoneNo": "08036058080", "email": "<EMAIL>" }, { "id": "78", "name": "<NAME>", "state": "Ondo Central", "phoneNo": "08091707000", "email": "<EMAIL>" }, { "id": "79", "name": "<NAME>", "state": "Ondo South", "phoneNo": "08054546666", "email": "<EMAIL>" }, { "id": "80", "name": "<NAME>", "state": "Ondo North", "phoneNo": "08176406557", "email": "<EMAIL>" }, { "id": "81", "name": "<NAME>", "state": "Osun Central", "phoneNo": "08034753343", "email": "<EMAIL>" }, { "id": "82", "name": "<NAME>", "state": "Osun East", "phoneNo": "08052242211", "email": "<EMAIL>" }, { "id": "83", "name": "<NAME>", "state": "Osun West", "phoneNo": "08033565979", "email": "<EMAIL>" }, { "id": "84", "name": "<NAME>", "state": "Oyo Central", "phoneNo": "08055544411", "email": "<EMAIL>" }, { "id": "85", "name": "<NAME>", "state": "Oyo North", "phoneNo": "08037053375", "email": "<EMAIL>" }, { "id": "86", "name": "<NAME>", "state": "Oyo South", "phoneNo": "08132956057", "email": "<EMAIL>" }, { "id": "87", "name": "<NAME>", "state": "Plateau South", "phoneNo": "07044442045", "email": "<EMAIL>" }, { "id": "88", "name": "<NAME>", "state": "Plateau Central", "phoneNo": "08033359443", "email": "<EMAIL>" }, { "id": "89", "name": "<NAME>", "state": "Plateau North", "phoneNo": "08097777712", "email": "<EMAIL>" }, { "id": "90", "name": "<NAME>", "state": "Rivers West", "phoneNo": "", "email": "<EMAIL>" }, { "id": "91", "name": "<NAME>", "state": "Rivers East", "phoneNo": "", "email": "<EMAIL>" }, { "id": "92", "name": "<NAME>", "state": "Rivers South East", "phoneNo": "08037419000", "email": "<EMAIL>" }, { "id": "93", "name": "<NAME>", "state": "Sokoto East", "phoneNo": "", "email": "<EMAIL>" }, { "id": "94", "name": "<NAME>", "state": "Sokoto North", "phoneNo": "07033181818", "email": "<EMAIL>" }, { "id": "112", "name": "<NAME>", "state": "Sokoto South", "phoneNo": "", "email": "" }, { "id": "95", "name": "<NAME>", "state": "Taraba North", "phoneNo": "", "email": "<EMAIL>" }, { "id": "96", "name": "<NAME>", "state": "Taraba South", "phoneNo": "07063795588", "email": "<EMAIL>" }, { "id": "97", "name": "<NAME>", "state": "Taraba Central", "phoneNo": "08033109493", "email": "<EMAIL>" }, { "id": "98", "name": "Senate President Lawan", "state": "Yobe North", "phoneNo": "07055090323", "email": "" }, { "id": "99", "name": "<NAME>", "state": "Yobe East", "phoneNo": "", "email": "<EMAIL>" }, { "id": "100", "name": "<NAME>", "state": "Yobe South", "phoneNo": "", "email": "<EMAIL>" }, { "id": "101", "name": "<NAME>", "state": "Zamfara North", "phoneNo": "08186567173", "email": "<EMAIL>" }, { "id": "102", "name": "<NAME>", "state": "Zamfara Central", "phoneNo": "", "email": "<EMAIL>" }, { "id": "103", "name": "<NAME>", "state": "Zamfara West", "phoneNo": "08033412454", "email": "<EMAIL>" }, { "id": "104", "name": "<NAME>", "state": "FCT", "phoneNo": "08034509106", "email": "<EMAIL>" }, { "id": "105", "name": "<NAME>", "state": "Oyo", "phoneNo": "09057302409", "email": "<EMAIL>" }, { "id": "106", "name": "<NAME>", "state": "Kaduna", "phoneNo": "08168355552", "email": "<EMAIL>" }, { "id": "107", "name": "<NAME>", "state": "Ogun", "phoneNo": "08037470021", "email": "<EMAIL>" }, { "id": "108", "name": "<NAME>", "state": "Lagos", "phoneNo": "08033019132", "email": "<EMAIL>" }, { "id": "109", "name": "<NAME>", "state": "Kwara", "phoneNo": "08033967037", "email": "<EMAIL>" }, { "id": "110", "name": "<NAME>", "state": "Kastina", "phoneNo": "09072211111", "email": "<EMAIL>" }, { "id": "111", "name": "<NAME>", "state": "Maiduguri", "phoneNo": "08064932222", "email": "<EMAIL>" }, { "id": "112", "name": "<NAME>", "state": "Nassarawa", "phoneNo": "08035970277", "email": "<EMAIL>" }, { "id": "113", "name": "<NAME>", "state": "Niger", "phoneNo": "08036442043", "email": "<EMAIL>" }, { "id": "114", "name": "<NAME>", "state": "Niger", "phoneNo": "08082046021", "email": "<EMAIL>" }, { "id": "115", "name": "<NAME>", "state": "Sokoto", "phoneNo": "08036067910", "email": "<EMAIL>" }, { "id": "116", "name": "<NAME>", "state": "Niger", "phoneNo": "08038181888", "email": "<EMAIL>" }, { "id": "117", "name": "<NAME>", "state": "Niger", "phoneNo": "07067777044", "email": "<EMAIL>" }, { "id": "118", "name": "<NAME>", "state": "Kano", "phoneNo": "08033265478", "email": "<EMAIL>" }, { "id": "119", "name": "<NAME>", "state": "Bauchi", "phoneNo": "08088444050", "email": "<EMAIL>" }, { "id": "120", "name": "<NAME>", "state": "Nassarawa", "phoneNo": "08069662637", "email": "<EMAIL>" }, { "id": "121", "name": "<NAME>", "state": "Kwara", "phoneNo": "08181007936", "email": "<EMAIL>" }, { "id": "122", "name": "<NAME>", "state": "Adamawa", "phoneNo": "08104222222", "email": "<EMAIL>" }, { "id": "123", "name": "<NAME>", "state": "Adamawa", "phoneNo": "07034724818", "email": "<EMAIL>" }, { "id": "124", "name": "<NAME>", "state": "Taraba", "phoneNo": "08038297492", "email": "<EMAIL>" }, { "id": "125", "name": "<NAME>", "state": "Lagos", "phoneNo": "08033069103", "email": "<EMAIL>" }, { "id": "126", "name": "<NAME>", "state": "Ondo", "phoneNo": "08166189531", "email": "<EMAIL>" }, { "id": "127", "name": "<NAME>", "state": "Sokoto", "phoneNo": "08036179414", "email": "<EMAIL>" }, { "id": "128", "name": "<NAME>", "state": "Jigawa", "phoneNo": "08033120968", "email": "<EMAIL>" }, { "id": "129", "name": "<NAME>", "state": "Nassarawa", "phoneNo": "08113616344", "email": "<EMAIL>" }, { "id": "130", "name": "<NAME>", "state": "Kano", "phoneNo": "08135403288", "email": "<EMAIL>" }, { "id": "131", "name": "<NAME>", "state": "Niger", "phoneNo": "08036314405", "email": "<EMAIL>" }, { "id": "132", "name": "<NAME>", "state": "Nassarawa", "phoneNo": "0862423728", "email": "<EMAIL>" }, { "id": "133", "name": "<NAME>", "state": "Sokoto", "phoneNo": "08036029300", "email": "<EMAIL>" }, { "id": "134", "name": "<NAME>", "state": "Kastina", "phoneNo": "07030000618", "email": "<EMAIL>" } ] <|start_filename|>src/mockData.js<|end_filename|> export const crimeKeywords = [ "Killing us", "Harassing us", "Torturing us", "Extorting us", "Murdering us", "threatening us", "Shooting us", "Fighting us", "Beating us", "Kidnapping us", ] <|start_filename|>src/shared/gtag/index.js<|end_filename|> import ReactGA from "react-ga"; ReactGA.initialize("UA-139159286-4"); ReactGA.pageview( window.location.pathname + window.location.search ); <|start_filename|>src/pages/home/broadcast.js<|end_filename|> export default encodeURI(` *ATTENTION* ‼️‼️ Why The Special Anti Robbery Squad (SARS) Must be Scrapped. The Special Anti robbery Squad is a unit in the Nigerian Police Force originally formed to combat robberies. Unfortunately, officers of the unit who mostly dress in mufti and carry Ak 47 guns in unmarked cars have engaged in several cases of kidnapping, murder, theft, rape, torture, illegal raids, unlawful arrests, highhandedness, humiliation, unlawful detention and extortion (both documented and undocumented). These activities are carried out under the pretext of looking for thieves and fraudsters. For no reason at all, many innocent Nigerians have been killed by these dangerous police officers. Some of them are: ▪️ *Remi*, killed in Osogbo, September 15 2020 ▪️ *<NAME>*, 17 year old girl, killed for standing at a bus stop in Lagos in 2020 ▪️ *<NAME>*, 33 year old man killed in Sagamu, Ogun State ▪️ *<NAME>*, killed in Nasarawa in 2014 ▪️ *<NAME>*, who was killed while watching a football match in Lagos ▪️ *<NAME>*, aka Kaka, footballer at Remo Stars FC, killed in Sagamu, Ogun State ▪️ *<NAME>*, raped and murdered in a SARS Station in 2020 ▪️ *<NAME>*, killed while relaxing with a friend ▪️ *<NAME>*, killed while attending his aunt’s wake keep ▪️ *<NAME>*, killed for not paying bribe ▪️ *<NAME>*, killed for not giving 50 naira bribe ▪️ *<NAME>*, killed in his home ▪️ These are just some of the hundreds of innocent Nigerian youths killed by SARS officers. For many years, Nigerians have protested and written petitions for the SRAS unit to be scrapped but nothing has changed. After numerous failed promises from the federal Government and reforms that did not change anything, young Nigerians are protesting in many cities and the protest is attracting international attention. Nigerians in the Diaspora are also joining on social media. We need everyone to join us this time around so that this unit can be scrapped once and for all because the officers have proven that they are beyond being reformed. We know that the entire force needs to be overhauled but this killer squad must go first. Please join us at these protests, encourage us with your voice and money, lobby and talk to your friends in power, and release your wards to protest. We are all that we have, our voices must be heard. Signed, Millions of Nigerian Youths Protesting `); <|start_filename|>src/components/typewriter/index.js<|end_filename|> import React from 'react'; import Typewriter from 'typewriter-effect'; const TypeWriter = ({ texts }) => ( <Typewriter options={{ strings: texts, autoStart: true, loop: true, deleteSpeed: 50, wrapperClassName: 'sars_tags' }} /> ); export default TypeWriter; <|start_filename|>src/components/popup/Popup.module.css<|end_filename|> .popup { position: fixed; width: 100vw; left: 0; right: 0; bottom: 0; top: 0; background-color: rgba(0, 0, 0, 0.692); display: flex; align-items: center; justify-content: center; } .popup .box { width: 50%; height: fit-content; background-color: #fff; border-radius: 6px; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 2rem; } @media(max-width: 700px) { .popup .box { width: 80%; } .popup h2 { font-size: 1rem; } .popup p { font-size: .9rem; } .popup button { padding-right: 0; padding-left: 0; width: 100%; } } .popup i { font-size: 4rem; margin-bottom: .5rem; color: green; } .popup h2 { font-size: 1.2rem; margin-bottom: 1.2rem; text-align: center; } .popup p { margin: 5px 0; } .popup button { margin: 1.5rem 0; padding: .7rem 3rem; background-color: green; border: none; color: #fff; font-family: inherit; border-radius: 6px; }
oshosanya/endsars
<|start_filename|>test.js<|end_filename|> let arr = [1,2,3] let result = arr.forEach((item) =>{ if(item > 1) { console.log(item) } else{ return false } }) console.log(result)
duzuimoye/H5
<|start_filename|>server/app/views/templates/widgets/progress.scala.html<|end_filename|> @(progress: Int, total: Int, color: String) @import scala.util.Try @defining(Try(100 * progress / total) getOrElse 0) { percent => <div class="content-progres-bar"> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="@percent" aria-valuemin="0" aria-valuemax="100" style="background-color: @color; width : @percent% ;"></div> </div> <span> @progress / @total </span> </div> } <|start_filename|>server/app/views/templates/home/libraryGridItem.scala.html<|end_filename|> @import org.scalaexercises.types.exercises._ @import org.scalaexercises.types.progress._ @import org.scalaexercises.exercises.utils.StringUtils._ @(library: Library, progress: Option[OverallUserProgressItem]) <div class="col-xs-12 col-sm-6 col-md-4"> <a href="@library.name"> <div class="tech scala"> <div class="panel panel-default"> <div class="panel-heading" style="background-color: @library.color;"> <img src='data:image/svg+xml;base64,@library.logoData.getOrElse("")'/> <h3 class="panel-title">@library.name.humanizeUnderscore</h3> </div> <div class="panel-body"> @Html(library.description) @progress match { case None => { <div><button class="btn btn-primary btn-sm" style="background-color: @library.color;">Start</button></div> } case Some(p) if p.completedSections == 0 => { <div><button class="btn btn-primary btn-sm" style="background-color: @library.color;">Start</button></div> } case Some(p) => { @templates.widgets.progress(p.completedSections, p.totalSections, library.color) } } </div> </div> </div> </a> </div> <|start_filename|>server/public/javascripts/forfun/interop/oo.js<|end_filename|> /* From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript */ function Foo(){ alert("Foo") } function Alert(msg){ alert(msg) } // Define the Person constructor function Person(firstName) { this.firstName = firstName; } var person1 = new Person('Alice'); var person2 = new Person('Bob'); // Add a couple of methods to Person.prototype Person.prototype.walk = function(){ alert("I am walking!"); }; Person.prototype.sayHello = function(){ alert("Hello, I'm "+ this.firstName); }; // Define the Student constructor function Student(firstName, subject) { // Call the parent constructor, making sure (using Function#call) that "this" is // set correctly during the call Person.call(this, firstName); // Initialize our Student-specific properties this.subject = subject; }; // Create a Student.prototype object that inherits from Person.prototype. // Note: A common error here is to use "new Person()" to create the Student.prototype. // That's incorrect for several reasons, not least that we don't have anything to // give Person for the "firstName" argument. The correct place to call Person is // above, where we call it from Student. Student.prototype = Object.create(Person.prototype); // See note below // Set the "constructor" property to refer to Student Student.prototype.constructor = Student; // Replace the "sayHello" method Student.prototype.sayHello = function(){ alert("Hello, I'm " + this.firstName + ". I'm studying " + this.subject + "."); }; // Add a "sayGoodBye" method Student.prototype.sayGoodBye = function(){ alert("Goodbye!"); }; /* // Example usage: var student1 = new Student("Janet", "Applied Physics"); student1.sayHello(); // "Hello, I'm Janet. I'm studying Applied Physics." student1.walk(); // "I am walking!" student1.sayGoodBye(); // "Goodbye!" // Check that instanceof works correctly alert(student1 instanceof Person); // true alert(student1 instanceof Student); // true */
xhudik/scala-exercises
<|start_filename|>consumer/src/main/java/com/davromalc/demotwitterkafka/model/InfluencerJsonSchema.java<|end_filename|> package com.davromalc.demotwitterkafka.model; import java.util.Arrays; import java.util.List; import com.davromalc.demotwitterkafka.DemoTwitterKafkaConsumerApplication.Influencer; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; /** * https://gist.github.com/rmoff/2b922fd1f9baf3ba1d66b98e9dd7b364 * * */ @Getter public class InfluencerJsonSchema { Schema schema; Influencer payload; InfluencerJsonSchema(long tweetCounts, String username, String content, long likes) { this.payload = new Influencer(tweetCounts, username, content, likes); Field fieldTweetCounts = Field.builder().field("tweets").type("int64").build(); Field fieldContent = Field.builder().field("content").type("string").build(); Field fieldUsername = Field.builder().field("username").type("string").build(); Field fieldLikes = Field.builder().field("likes").type("int64").build(); this.schema = new Schema("struct", Arrays.asList(fieldUsername,fieldContent,fieldLikes,fieldTweetCounts)); } public InfluencerJsonSchema(Influencer influencer) { this(influencer.getTweets(),influencer.getUsername(),influencer.getContent(),influencer.getLikes()); } @Getter @AllArgsConstructor static class Schema { String type; List<Field> fields; } @Getter @Builder static class Field { String type; String field; } } <|start_filename|>consumer/src/main/java/com/davromalc/demotwitterkafka/DemoTwitterKafkaConsumerApplication.java<|end_filename|> package com.davromalc.demotwitterkafka; import java.util.HashMap; import java.util.Map; import org.apache.kafka.common.serialization.Serde; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.Materialized; import org.apache.kafka.streams.kstream.Produced; import org.apache.kafka.streams.state.KeyValueStore; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.kafka.KafkaProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafkaStreams; import org.springframework.kafka.annotation.KafkaStreamsDefaultConfiguration; import org.springframework.kafka.support.serializer.JsonSerde; import com.davromalc.demotwitterkafka.model.InfluencerJsonSchema; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @SpringBootApplication @Slf4j public class DemoTwitterKafkaConsumerApplication { public static void main(String[] args) { SpringApplication.run(DemoTwitterKafkaConsumerApplication.class, args); } @Configuration @EnableKafkaStreams static class KafkaConsumerConfiguration { final Serde<Influencer> jsonSerde = new JsonSerde<>(Influencer.class); final Materialized<String, Influencer, KeyValueStore<Bytes, byte[]>> materialized = Materialized.<String, Influencer, KeyValueStore<Bytes, byte[]>>as("aggregation-tweets-by-likes").withValueSerde(jsonSerde); @Bean KStream<String, String> stream(StreamsBuilder streamBuilder){ final KStream<String, String> stream = streamBuilder.stream("tweets"); stream .selectKey(( key , value ) -> String.valueOf(value.split("::::")[0])) .groupByKey() .aggregate(Influencer::init, this::aggregateInfoToInfluencer, materialized) .mapValues(InfluencerJsonSchema::new) .toStream() .peek( (username, jsonSchema) -> log.info("Sending a new tweet from user: {}", username)) .to("influencers", Produced.with(Serdes.String(), new JsonSerde<>(InfluencerJsonSchema.class))); return stream; } private Influencer aggregateInfoToInfluencer(String username, String tweet, Influencer influencer) { final long likes = Long.valueOf(tweet.split("::::")[2]); if ( likes >= influencer.getLikes() ) { return new Influencer(influencer.getTweets()+1, username, String.valueOf(tweet.split("::::")[1]), likes); } else { return new Influencer(influencer.getTweets()+1, username, influencer.getContent(), influencer.getLikes()); } } @Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME) public StreamsConfig kStreamsConfigs(KafkaProperties kafkaProperties) { Map<String, Object> props = new HashMap<>(); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "demo-twitter-kafka-application"); props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getBootstrapServers()); props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass()); props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass()); return new StreamsConfig(props); } } @RequiredArgsConstructor @Getter public static class Influencer { final long tweets; final String username; final String content; final long likes; static Influencer init() { return new Influencer(0, "","", 0); } @JsonCreator static Influencer fromJson(@JsonProperty("tweets") long tweetCounts, @JsonProperty("username") String username, @JsonProperty("content") String content, @JsonProperty("likes") long likes) { return new Influencer(tweetCounts, username, content, likes); } } } <|start_filename|>producer/src/main/java/com/davromalc/demotwitterkafka/DemoTwitterKafkaProducerApplication.java<|end_filename|> package com.davromalc.demotwitterkafka; import java.util.Properties; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import lombok.extern.slf4j.Slf4j; import twitter4j.FilterQuery; import twitter4j.StallWarning; import twitter4j.Status; import twitter4j.StatusDeletionNotice; import twitter4j.StatusListener; import twitter4j.TwitterStream; import twitter4j.TwitterStreamFactory; @SpringBootApplication @Slf4j public class DemoTwitterKafkaProducerApplication { public static void main(String[] args) { // Kafka config Properties properties = new Properties(); properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); //Kafka cluster hosts. properties.put(ProducerConfig.CLIENT_ID_CONFIG, "demo-twitter-kafka-application-producer"); // Group id properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); Producer<String, String> producer = new KafkaProducer<>(properties); // Twitter Stream final TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); final StatusListener listener = new StatusListener() { public void onStatus(Status status) { final long likes = getLikes(status); final String tweet = status.getText(); final String content = status.getUser().getName() + "::::" + tweet + "::::" + likes; log.info(content); producer.send(new ProducerRecord<>("tweets", content)); } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onException(Exception ex) { log.error("Unable to get tweets", ex); } @Override public void onScrubGeo(long userId, long upToStatusId) { } @Override public void onStallWarning(StallWarning warning) { } private long getLikes(Status status) { return status.getRetweetedStatus() != null ? status.getRetweetedStatus().getFavoriteCount() : 0; } }; twitterStream.addListener(listener); final FilterQuery tweetFilterQuery = new FilterQuery(); tweetFilterQuery.track(new String[] { "Java" }); twitterStream.filter(tweetFilterQuery); SpringApplication.run(DemoTwitterKafkaProducerApplication.class, args); Runtime.getRuntime().addShutdownHook(new Thread(() -> producer.close())); //Kafka producer should close when application finishes. } } <|start_filename|>reader/src/main/kotlin/com/davromalc/demotwitterkafkamysql/DemoTwitterKafkaPostgreSqlApplication.kt<|end_filename|> package com.davromalc.demotwitterkafkamysql import com.davromalc.demotwitterkafkamysql.service.InfluencerHandler import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.context.annotation.Bean import org.springframework.http.MediaType import org.springframework.web.reactive.function.server.router import org.springframework.web.cors.reactive.CorsWebFilter import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource import java.util.* @SpringBootApplication class DemoTwitterKafkaPostgreSqlApplication { @Bean fun influencerRoute(handler: InfluencerHandler) = router { ("/influencer" and accept(MediaType.APPLICATION_JSON)) .nest { GET("/count", handler::getTotalTweets) GET("/stats", handler::getRanking) GET("/active", handler::getMoreActive) } } @Bean fun corsWebFilter(): CorsWebFilter { val corsConfig = CorsConfiguration() corsConfig.allowedOrigins = Arrays.asList("*") corsConfig.maxAge = 8000L corsConfig.addAllowedMethod("GET") val source = UrlBasedCorsConfigurationSource() source.registerCorsConfiguration("/**", corsConfig) return CorsWebFilter(source) } } fun main(args: Array<String>) { runApplication<DemoTwitterKafkaPostgreSqlApplication>(*args) }
xiaotiandadaqyhux/david-romero
<|start_filename|>Sources/SubstrateCExtras/SubstrateCExtras.c<|end_filename|> #include "include/SubstrateCExtras.h" _Bool LinkedNodeHeaderCompareAndSwap(LinkedNodeHeader *insertionNode, LinkedNodeHeader *nodeToInsert) { LinkedNodeHeader *expected = nodeToInsert->next; return atomic_compare_exchange_weak(&insertionNode->next, &expected, nodeToInsert); } <|start_filename|>Sources/CSDL2/SDL2.h<|end_filename|> #pragma once #include <SDL.h> #include <SDL_syswm.h> #if __has_include(<SDL_vulkan.h>) #include <SDL_vulkan.h> #endif <|start_filename|>Sources/SubstrateCExtras/vk_mem_alloc.cpp<|end_filename|> #if __has_include(<vulkan/vulkan.h>) #define VMA_IMPLEMENTATION #include "include/vk_mem_alloc.h" #endif // __has_include(<vulkan/vulkan.h>) <|start_filename|>Sources/Vulkan/Vulkan.h<|end_filename|> #pragma once #if __has_include(<vulkan/vulkan.h>) #include <vulkan/vulkan.h> #include <vulkan/vk_platform.h> #if __has_include(<X11/Xlib.h>) #include <X11/Xlib.h> #include <vulkan/vulkan_xlib.h> #endif #else #include "/usr/local/include/vulkan/vulkan.h" #endif <|start_filename|>Sources/SPIRVCrossExtras/include/SPIRVCrossExtras.h<|end_filename|> // // SPIRVCrossExtras.h // // // Created by <NAME> on 19/02/21. // #ifndef SPIRVCrossExtras_h #define SPIRVCrossExtras_h #include <spirv_cross_c.h> #ifdef __cplusplus extern "C" { #endif spvc_result spvc_compiler_make_position_invariant(spvc_compiler compiler); #ifdef __cplusplus } #endif #endif /* SPIRVCrossExtras_h */ <|start_filename|>Sources/SPIRVCrossExtras/include/SPIRVCrossExtras.cpp<|end_filename|> // // SPIRVCrossExtras.c // // // Created by <NAME> on 19/02/21. // #include "SPIRVCrossExtras.h" #include <cstddef> #include <unordered_set> // This is incredibly brittle, but it's also only intended as a short-term fix; HLSL should gain support // for 'invariant' in the near future (https://github.com/KhronosGroup/glslang/issues/1911). struct ScratchMemoryAllocation { virtual ~ScratchMemoryAllocation() = default; }; struct spvc_set_s: ScratchMemoryAllocation { std::unordered_set<uint32_t> values; }; spvc_result spvc_compiler_make_position_invariant(spvc_compiler compiler) { spvc_set activeSet = NULL; spvc_compiler_get_active_interface_variables(compiler, &activeSet); for (uint32_t varId : activeSet->values) { if (spvc_compiler_has_decoration(compiler, varId, SpvDecorationBuiltIn) && spvc_compiler_get_decoration(compiler, varId, SpvDecorationBuiltIn) == SpvBuiltInPosition) { spvc_compiler_set_decoration(compiler, varId, SpvDecorationInvariant, 0); } } return SPVC_SUCCESS; } <|start_filename|>Sources/SubstrateCExtras/include/SubstrateCExtras.h<|end_filename|> #ifndef FRAMEGRAPH_C_EXTRAS_H #define FRAMEGRAPH_C_EXTRAS_H #include <stdatomic.h> #include <stdbool.h> #include "vk_mem_alloc.h" typedef struct LinkedNodeHeader { struct LinkedNodeHeader *_Atomic next; } LinkedNodeHeader; bool LinkedNodeHeaderCompareAndSwap(LinkedNodeHeader *insertionNode, LinkedNodeHeader *nodeToInsert); #endif // FRAMEGRAPH_C_EXTRAS_H <|start_filename|>Sources/CNativeFileDialog/nfd_default.c<|end_filename|> #if !__has_include(<windows.h>) && !__has_include(<gtk/gtk.h>)&& !__has_include(<AppKit/AppKit.h>) #include <stdio.h> #include "include/nfd.h" /* single file open dialog */ nfdresult_t NFD_OpenDialog( const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath ) { printf("NFD found no platform interface.\n"); return NFD_ERROR; } /* multiple file open dialog */ nfdresult_t NFD_OpenDialogMultiple( const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdpathset_t *outPaths ) { printf("NFD found no platform interface.\n"); return NFD_ERROR; } /* save dialog */ nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath ) { printf("NFD found no platform interface.\n"); return NFD_ERROR; } /* select folder dialog */ nfdresult_t NFD_PickFolder( const nfdchar_t *defaultPath, nfdchar_t **outPath) { printf("NFD found no platform interface.\n"); return NFD_ERROR; } #endif <|start_filename|>swift-format-configuration.json<|end_filename|> { "blankLineBetweenMembers" : { "ignoreSingleLineProperties" : true }, "indentation" : { "spaces" : 4 }, "indentConditionalCompilationBlocks" : false, "lineBreakBeforeControlFlowKeywords" : false, "lineBreakBeforeEachArgument" : false, "lineLength" : 400, "maximumBlankLines" : 1, "respectsExistingLineBreaks" : true, "rules" : { "AllPublicDeclarationsHaveDocumentation" : true, "AlwaysUseLowerCamelCase" : true, "AmbiguousTrailingClosureOverload" : true, "BeginDocumentationCommentWithOneLineSummary" : true, "BlankLineBetweenMembers" : true, "CaseIndentLevelEqualsSwitch" : true, "DoNotUseSemicolons" : true, "DontRepeatTypeInStaticProperties" : true, "FullyIndirectEnum" : true, "GroupNumericLiterals" : true, "IdentifiersMustBeASCII" : true, "MultiLineTrailingCommas" : true, "NeverForceUnwrap" : false, "NeverUseForceTry" : false, "NeverUseImplicitlyUnwrappedOptionals" : false, "NoAccessLevelOnExtensionDeclaration" : true, "NoBlockComments" : true, "NoCasesWithOnlyFallthrough" : true, "NoEmptyTrailingClosureParentheses" : true, "NoLabelsInCasePatterns" : true, "NoLeadingUnderscores" : false, "NoParensAroundConditions" : true, "NoVoidReturnOnFunctionSignature" : true, "OneCasePerLine" : true, "OneVariableDeclarationPerLine" : true, "OnlyOneTrailingClosureArgument" : true, "OrderedImports" : true, "ReturnVoidInsteadOfEmptyTuple" : true, "UseEnumForNamespacing" : true, "UseLetInEveryBoundCaseVariable" : true, "UseShorthandTypeNames" : true, "UseSingleLinePropertyGetter" : true, "UseSynthesizedInitializer" : true, "UseTripleSlashForDocumentationComments" : true, "ValidateDocumentationComments" : true }, "tabWidth" : 4, "version" : 1 }
elijah-semyonov/Substrate
<|start_filename|>lib/errors/oauth2error.js<|end_filename|> // Copyright IBM Corp. 2015,2017. All Rights Reserved. // Node module: loopback-component-oauth2 // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT /** * `OAuth2Error` error. * * @api public */ function OAuth2Error(message, code, uri, status) { Error.call(this); this.message = message; this.code = code || 'server_error'; this.uri = uri; this.status = status || 500; } /** * Inherit from `Error`. */ OAuth2Error.prototype.__proto__ = Error.prototype; /** * Expose `OAuth2Error`. */ module.exports = OAuth2Error; <|start_filename|>lib/utils.js<|end_filename|> // Copyright IBM Corp. 2012,2017. All Rights Reserved. // Node module: loopback-component-oauth2 // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT 'use strict'; exports.merge = require('utils-merge'); exports.uid = require('uid2');
signatu/loopback-component-oauth2
<|start_filename|>src/Avalonia.Visuals/Rendering/SceneGraph/LineNode.cs<|end_filename|> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Platform; using Avalonia.VisualTree; namespace Avalonia.Rendering.SceneGraph { /// <summary> /// A node in the scene graph which represents a line draw. /// </summary> internal class LineNode : BrushDrawOperation { /// <summary> /// Initializes a new instance of the <see cref="GeometryNode"/> class. /// </summary> /// <param name="transform">The transform.</param> /// <param name="pen">The stroke pen.</param> /// <param name="p1">The start point of the line.</param> /// <param name="p2">The end point of the line.</param> /// <param name="childScenes">Child scenes for drawing visual brushes.</param> public LineNode( Matrix transform, IPen pen, Point p1, Point p2, IDictionary<IVisual, Scene> childScenes = null) : base(LineBoundsHelper.CalculateBounds(p1, p2, pen), transform) { Transform = transform; Pen = pen?.ToImmutable(); P1 = p1; P2 = p2; ChildScenes = childScenes; } /// <summary> /// Gets the transform with which the node will be drawn. /// </summary> public Matrix Transform { get; } /// <summary> /// Gets the stroke pen. /// </summary> public ImmutablePen Pen { get; } /// <summary> /// Gets the start point of the line. /// </summary> public Point P1 { get; } /// <summary> /// Gets the end point of the line. /// </summary> public Point P2 { get; } /// <inheritdoc/> public override IDictionary<IVisual, Scene> ChildScenes { get; } /// <summary> /// Determines if this draw operation equals another. /// </summary> /// <param name="transform">The transform of the other draw operation.</param> /// <param name="pen">The stroke of the other draw operation.</param> /// <param name="p1">The start point of the other draw operation.</param> /// <param name="p2">The end point of the other draw operation.</param> /// <returns>True if the draw operations are the same, otherwise false.</returns> /// <remarks> /// The properties of the other draw operation are passed in as arguments to prevent /// allocation of a not-yet-constructed draw operation object. /// </remarks> public bool Equals(Matrix transform, IPen pen, Point p1, Point p2) { return transform == Transform && Equals(Pen, pen) && p1 == P1 && p2 == P2; } public override void Render(IDrawingContextImpl context) { context.Transform = Transform; context.DrawLine(Pen, P1, P2); } public override bool HitTest(Point p) { if (!Transform.HasInverse) return false; p *= Transform.Invert(); var halfThickness = Pen.Thickness / 2; var minX = Math.Min(P1.X, P2.X) - halfThickness; var maxX = Math.Max(P1.X, P2.X) + halfThickness; var minY = Math.Min(P1.Y, P2.Y) - halfThickness; var maxY = Math.Max(P1.Y, P2.Y) + halfThickness; if (p.X < minX || p.X > maxX || p.Y < minY || p.Y > maxY) return false; var a = P1; var b = P2; //If dot1 or dot2 is negative, then the angle between the perpendicular and the segment is obtuse. //The distance from a point to a straight line is defined as the //length of the vector formed by the point and the closest point of the segment Vector ap = p - a; var dot1 = Vector.Dot(b - a, ap); if (dot1 < 0) return ap.Length <= Pen.Thickness / 2; Vector bp = p - b; var dot2 = Vector.Dot(a - b, bp); if (dot2 < 0) return bp.Length <= halfThickness; var bXaX = b.X - a.X; var bYaY = b.Y - a.Y; var distance = (bXaX * (p.Y - a.Y) - bYaY * (p.X - a.X)) / (Math.Sqrt(bXaX * bXaX + bYaY * bYaY)); return Math.Abs(distance) <= halfThickness; } } }
gabornemeth/Avalonia
<|start_filename|>torch_imputer/best_alignment.cu<|end_filename|> // Copyright (c) 2018 MathInf GmbH, <NAME> // Licensed under the BSD-3-Clause license // This is the GPU implementation of the Connectionist Temporal Loss. // We mostly follow Graves. // 1. Graves et al: http://www.cs.toronto.edu/~graves/icml_2006.pdf // We use the equations from above link, but note that [1] has 1-based indexing // and we (of course) use 0-based. Graves et al call the probabilities y, we use // log_probs (also calling them inputs) A few optimizations (simmilar to those // here, but also some I didn't take) are described in // 2. Minmin Sun: // http://on-demand.gputechconf.com/gtc/2016/presentation/s6383-minmin-sun-speech-recognition.pdf #include <ATen/TensorUtils.h> #include <c10/macros/Macros.h> #include <c10/util/Exception.h> #include <ATen/ATen.h> #include <ATen/Dispatch.h> #include <ATen/cuda/CUDAApplyUtils.cuh> #include <numeric> #include <type_traits> using namespace at; // this ad-hoc converts from targets (l in [1]) to augmented targets (l' in [1]) // so if l is l_0 l_1 ... l_(tl-1) then this looks up idx in // l' = BLANK l_0 BLANK l_1 BLANK ... BLANK l_(tl-1) BLANK // - note that no bound-checking is done // - it is important to only call it witth idx == 0 if the target length is 0 // - __restrict__ impact to be measured, see // https://devblogs.nvidia.com/cuda-pro-tip-optimize-pointer-aliasing/ template <typename target_t> __device__ static inline int64_t get_target_prime(const target_t *__restrict__ target, int64_t offset, int64_t stride, int64_t idx, int64_t BLANK) { if (idx % 2 == 0) { return BLANK; } else { return target[offset + stride * (idx / 2)]; } } // this kernel is a relatively straightforward implementation of the alpha // calculation in the forward backward algorithm (section 4.1). A (minor) twist // is that we are using log-calculations to enhance numerical stability // (log_probs and log_alpha). In total it would be more efficient to compute the // beta in the same kernel (e.g. cudnn does this). While the beta are not needed // for the loss itself (just the grad), we can return log_alpha+log_beta (so // same space as currently) and the overhead is small and the use-case for loss // without grad is relatively limited. We parallelize by batch and target // sequence. Empirically, it is faster to loop over the input (log probs) // sequence and do target in parallel, even if it means more frequent // __syncthreads. In contrast to the cuDNN implementation, we allow large target // lengths. For this we need that all previous `s` have been computed when we // start a new block_s. This is why we have our own for loop here. template <typename scalar_t, typename target_t> __global__ void #if defined(__HIP_PLATFORM_HCC__) C10_LAUNCH_BOUNDS_2((std::is_same<scalar_t, float>::value ? 1024 : 896), 1) #endif ctc_alignment_log_alpha_gpu_kernel( scalar_t *__restrict__ log_alpha_data, int64_t *__restrict__ paths_data, const scalar_t *log_probs_data, const int64_t *__restrict__ input_lengths, int64_t max_input_length, const target_t *__restrict__ targets_data, const int64_t *__restrict__ target_lengths, int64_t max_target_length, scalar_t *__restrict__ neg_log_likelihood_data, int64_t lp_input_stride, int64_t lp_batch_stride, int64_t lp_char_stride, int64_t la_batch_stride, int64_t la_input_stride, int64_t la_target_stride, const int64_t *__restrict__ tg_batch_offsets, int64_t tg_target_stride, int64_t batch_size, int64_t BLANK) { constexpr scalar_t neginf = -INFINITY; // bookkeeping int64_t b = threadIdx.y + blockIdx.y * blockDim.y; int64_t input_length = input_lengths[b]; int64_t target_length = target_lengths[b]; int64_t lp_batch_offset = b * lp_batch_stride; int64_t la_batch_offset = b * la_batch_stride; int64_t tg_batch_offset = tg_batch_offsets[b]; if (b >= batch_size) return; // first row (t=0), the three equations for alpha_1 above eq (6) for (int64_t block_s = 0; block_s < 2 * max_target_length + 1; block_s += blockDim.x) { int64_t s = threadIdx.x + block_s; scalar_t la; switch (s) { case 0: la = log_probs_data[lp_batch_offset + lp_char_stride * BLANK]; break; case 1: la = target_length == 0 ? neginf : log_probs_data[lp_batch_offset + lp_char_stride * get_target_prime( targets_data, tg_batch_offset, tg_target_stride, 1, BLANK)]; break; default: la = neginf; } if (s < 2 * max_target_length + 1) log_alpha_data[la_batch_offset + /* la_input_stride * 0 */ +la_target_stride * s] = la; } for (int64_t block_s = 0; block_s < 2 * max_target_length + 1; block_s += blockDim.x) { int64_t s = threadIdx.x + block_s; // These two only depend on s, so we can cache them. int64_t current_char; // l_s in eq (6) bool have_three; // flag which of the two cases in eq (6) we have if (s < 2 * target_length + 1 && target_length > 0) { current_char = get_target_prime(targets_data, tg_batch_offset, tg_target_stride, s, BLANK); have_three = ((s > 1) && (get_target_prime(targets_data, tg_batch_offset, tg_target_stride, s - 2, BLANK) != current_char)); } else { current_char = BLANK; have_three = false; } for (int64_t t = 1; t < max_input_length; t++) { __syncthreads(); // on cuda 9 we might use partial synchronization of only // the threads within the same batch if ((t < input_length) && (s < 2 * target_length + 1)) { // only for valid t, s. This is equation (6) and (7), la1, la2, la3 are // the three summands, lamax is the maximum for the logsumexp trick. scalar_t la1 = log_alpha_data[la_batch_offset + la_input_stride * (t - 1) + la_target_stride * s]; scalar_t lamax = la1; int64_t max_path = s; scalar_t la2, la3; if (s > 0) { la2 = log_alpha_data[la_batch_offset + la_input_stride * (t - 1) + la_target_stride * (s - 1)]; if (la2 > lamax) { lamax = la2; max_path = s - 1; } } else { la2 = neginf; } if (have_three) { la3 = log_alpha_data[la_batch_offset + la_input_stride * (t - 1) + la_target_stride * (s - 2)]; if (la3 > lamax) { lamax = la3; max_path = s - 2; } } else { la3 = neginf; } /*if (lamax == neginf) // when all are neginf. (then the whole thing is // neginf, but we can pretend) lamax = 0;*/ int64_t log_alpha_i = la_batch_offset + la_input_stride * t + la_target_stride * s; int64_t log_prob_i = lp_batch_offset + t * lp_input_stride + lp_char_stride * current_char; log_alpha_data[log_alpha_i] = lamax + log_probs_data[log_prob_i]; paths_data[log_alpha_i] = max_path; } else { // otherwise we just set to neginf if (s < 2 * max_target_length + 1) log_alpha_data[la_batch_offset + la_input_stride * t + la_target_stride * s] = neginf; } } } __syncthreads(); // on cuda 9 we might use partial synchronization of only the // threads within the same batch // compute the loss (eq (8)) if (threadIdx.x == 0) { scalar_t l1 = log_alpha_data[la_batch_offset + la_input_stride * (input_length - 1) + la_target_stride * (target_length * 2)]; scalar_t l2 = target_length > 0 ? log_alpha_data[la_batch_offset + la_input_stride * (input_length - 1) + la_target_stride * (target_length * 2 - 1)] : neginf; scalar_t m = ((l1 > l2) ? l1 : l2); m = ((m == neginf) ? 0 : m); scalar_t log_likelihood = std::log(std::exp(l1 - m) + std::exp(l2 - m)) + m; neg_log_likelihood_data[b] = -log_likelihood; } } // The forward computation. Lot's of admin and a call to the alpha kernel. // Note: we do not check that the labels are in the valid range. As we use // them for indexing in the kernels, you'll see memory errors when you // pass corrupt labels. // We support both a 2-dimensional tensor as targets (one set of targets in each // row) and a 1-dimensional tensor where all targets are concatenated (and we // use target_lengths to figure out where they begin). We return log_alpha // (currently, might change to (log_alpha+log_beta) to be passed to the // backward. The dispatch function will only return the loss. template <typename scalar_t, ScalarType target_scalar_type> std::tuple<Tensor, Tensor, Tensor> best_alignment_gpu_template(const Tensor &log_probs, const Tensor &targets, IntArrayRef input_lengths, IntArrayRef target_lengths, int64_t BLANK) { // log_probs: input_len x batch_size x num_labels // targets [int64]: batch_size x target_length OR sum(target_lengths) CheckedFrom c = "ctc_alignment_gpu"; using target_t = typename std::conditional<target_scalar_type == kInt, int, int64_t>::type; auto log_probs_arg = TensorArg(log_probs, "log_probs", 1); auto targets_arg = TensorArg(targets, "targets", 2); checkAllSameGPU(c, {log_probs_arg, targets_arg}); checkScalarType(c, targets_arg, target_scalar_type); checkDim(c, log_probs_arg, 3); checkDimRange(c, targets_arg, 1, 3); int64_t batch_size = log_probs.size(1); int64_t num_labels = log_probs.size(2); TORCH_CHECK((0 <= BLANK) && (BLANK < num_labels), "blank must be in label range"); TORCH_CHECK(input_lengths.size() == batch_size, "input_lengths must be of size batch_size"); TORCH_CHECK(target_lengths.size() == batch_size, "target_lengths must be of size batch_size"); int64_t lp_input_stride = log_probs.stride(0); int64_t lp_char_stride = log_probs.stride(2); int64_t tg_target_stride; int64_t max_target_length = 0; auto tg_batch_offsets = at::empty({batch_size}, at::device(at::kCPU).dtype(at::kLong)); auto tg_batch_offsets_data = tg_batch_offsets.data_ptr<int64_t>(); if (targets.dim() == 1) { // concatenated targets int64_t pos = 0; for (int64_t i = 0; i < batch_size; i++) { tg_batch_offsets_data[i] = pos; pos += target_lengths[i]; if (max_target_length < target_lengths[i]) max_target_length = target_lengths[i]; } tg_target_stride = targets.stride(0); checkSize(c, targets_arg, 0, pos); } else { // batch x max_target_length // dim is 2 int64_t tg_batch_stride = targets.stride(0); for (int64_t i = 0; i < batch_size; i++) { tg_batch_offsets_data[i] = i * tg_batch_stride; if (max_target_length < target_lengths[i]) max_target_length = target_lengths[i]; } tg_target_stride = targets.stride(1); checkSize(c, targets_arg, 0, batch_size); TORCH_CHECK(targets.size(1) >= max_target_length, "Expected tensor to have size at least ", max_target_length, " at dimension 1, but got size ", targets.size(1), " for ", targets_arg, " (while checking arguments for ", c, ")"); } int64_t max_input_length = log_probs.size(0); for (int64_t b = 0; b < batch_size; b++) { TORCH_CHECK(input_lengths[b] <= max_input_length, "Expected input_lengths to have value at most ", max_input_length, ", but got value ", input_lengths[b], " (while checking arguments for ", c, ")"); } auto target_lengths_t = at::tensor(target_lengths, targets.options().dtype(kLong)); auto input_lengths_t = at::tensor(input_lengths, targets.options().dtype(kLong)); tg_batch_offsets = tg_batch_offsets.cuda(); Tensor log_alpha = at::empty({batch_size, log_probs.size(0), 2 * max_target_length + 1}, log_probs.options()); Tensor paths = at::full_like(log_alpha, -1, log_alpha.options().dtype(kLong)); Tensor neg_log_likelihood = at::empty({batch_size}, log_probs.options()); // Very likely, we could be more clever here, e.g. learning (or genralizing // and reusing) from SoftMax.cu... constexpr int max_threads = std::is_same<scalar_t, float>::value ? 512 : 896; // we need 72 or so 32 bit registers for double int threads_target = max_threads; while (threads_target / 2 >= 2 * max_target_length + 1) { threads_target /= 2; } int threads_batch = std::min(max_threads / threads_target, (int)batch_size); dim3 block(threads_target, threads_batch); dim3 grid((2 * max_target_length + 1 + threads_target - 1) / threads_target, (batch_size + threads_batch - 1) / threads_batch); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); ctc_alignment_log_alpha_gpu_kernel<scalar_t, target_t> <<<grid, block, 0, stream>>>( log_alpha.data_ptr<scalar_t>(), paths.data_ptr<int64_t>(), log_probs.data_ptr<scalar_t>(), input_lengths_t.data_ptr<int64_t>(), log_probs.size(0), targets.data_ptr<target_t>(), target_lengths_t.data_ptr<int64_t>(), max_target_length, neg_log_likelihood.data_ptr<scalar_t>(), log_probs.stride(0), log_probs.stride(1), log_probs.stride(2), log_alpha.stride(0), log_alpha.stride(1), log_alpha.stride(2), tg_batch_offsets.data_ptr<int64_t>(), tg_target_stride, batch_size, BLANK); AT_CUDA_CHECK(cudaGetLastError()); // catch launch errors return std::make_tuple(neg_log_likelihood, log_alpha, paths); } std::tuple<Tensor, Tensor, Tensor> best_alignment_op(const Tensor &log_probs, const Tensor &targets, IntArrayRef input_lengths, IntArrayRef target_lengths, int64_t BLANK, bool zero_infinity) { (void)zero_infinity; // only used for backward return AT_DISPATCH_FLOATING_TYPES( log_probs.scalar_type(), "ctc_alignment_cuda", [&] { if (targets.scalar_type() == kLong) { return best_alignment_gpu_template<scalar_t, kLong>( log_probs, targets, input_lengths, target_lengths, BLANK); } else { return best_alignment_gpu_template<scalar_t, kInt>( log_probs, targets, input_lengths, target_lengths, BLANK); } }); } <|start_filename|>torch_imputer/imputer.cpp<|end_filename|> #include <torch/extension.h> #include <tuple> std::tuple<torch::Tensor, torch::Tensor> imputer_loss_op(const torch::Tensor &log_probs, const torch::Tensor &targets, const torch::Tensor &force_emits, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, int64_t BLANK, bool zero_infinity); torch::Tensor imputer_loss_backward_op( const torch::Tensor &grad, const torch::Tensor &log_probs, const torch::Tensor &targets, const torch::Tensor &force_emits, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, const torch::Tensor &neg_log_likelihood, const torch::Tensor &log_alpha, int64_t BLANK, bool zero_infinity); std::tuple<torch::Tensor, torch::Tensor, torch::Tensor> best_alignment_op(const torch::Tensor &log_probs, const torch::Tensor &targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, int64_t BLANK, bool zero_infinity); std::tuple<torch::Tensor, torch::Tensor> imputer_loss( const torch::Tensor &log_probs, const torch::Tensor &targets, const torch::Tensor &force_emits, const torch::Tensor &input_lengths, const torch::Tensor &target_lengths, int64_t BLANK, bool zero_infinity) { torch::Tensor ilc = input_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); torch::Tensor tlc = target_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); at::IntArrayRef il(ilc.data_ptr<int64_t>(), ilc.numel()); at::IntArrayRef tl(tlc.data_ptr<int64_t>(), tlc.numel()); auto res = imputer_loss_op(log_probs, targets.to(log_probs.device(), at::kLong), force_emits.to(log_probs.device(), at::kLong), il, tl, BLANK, zero_infinity); return res; } torch::Tensor imputer_loss_backward( const torch::Tensor &grad, const torch::Tensor &log_probs, const torch::Tensor &targets, const torch::Tensor &force_emits, const torch::Tensor &input_lengths, const torch::Tensor &target_lengths, const torch::Tensor &neg_log_likelihood, const torch::Tensor &log_alpha, int64_t BLANK, bool zero_infinity) { torch::Tensor ilc = input_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); torch::Tensor tlc = target_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); at::IntArrayRef il(ilc.data_ptr<int64_t>(), ilc.numel()); at::IntArrayRef tl(tlc.data_ptr<int64_t>(), tlc.numel()); torch::Tensor res; res = imputer_loss_backward_op( grad, log_probs, targets.to(log_probs.device(), at::kLong), force_emits.to(log_probs.device(), at::kLong), il, tl, neg_log_likelihood, log_alpha, BLANK, zero_infinity); return res; } std::tuple<torch::Tensor, torch::Tensor, torch::Tensor> best_alignment(const torch::Tensor &log_probs, const torch::Tensor &targets, const torch::Tensor &input_lengths, const torch::Tensor &target_lengths, int64_t BLANK, bool zero_infinity) { torch::Tensor ilc = input_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); torch::Tensor tlc = target_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); at::IntArrayRef il(ilc.data_ptr<int64_t>(), ilc.numel()); at::IntArrayRef tl(tlc.data_ptr<int64_t>(), tlc.numel()); auto res = best_alignment_op(log_probs, targets.to(log_probs.device(), at::kLong), il, tl, BLANK, zero_infinity); return res; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("imputer_loss", &imputer_loss, "calculate imputer loss"); m.def("imputer_loss_backward", &imputer_loss_backward, "calculate imputer loss gradient"); m.def("best_alignment", &best_alignment, "get best alignments for ctc"); }
rosinality/imputer-pytorch
<|start_filename|>src/infinity/queues/QueuePair.h<|end_filename|> /** * Queues - Queue Pair * * (c) 2018 <NAME>, ETH Zurich * Contact: <EMAIL> * */ #ifndef QUEUES_QUEUEPAIR_H_ #define QUEUES_QUEUEPAIR_H_ #include <infiniband/verbs.h> #include <infinity/core/Context.h> #include <infinity/memory/Atomic.h> #include <infinity/memory/Buffer.h> #include <infinity/memory/RegionToken.h> #include <infinity/requests/RequestToken.h> namespace infinity { namespace queues { class QueuePairFactory; } } namespace infinity { namespace queues { class OperationFlags { public: bool fenced; bool signaled; bool inlined; OperationFlags() : fenced(false), signaled(false), inlined(false) { }; /** * Turn the bools into a bit field. */ int ibvFlags(); }; class QueuePair { friend class infinity::queues::QueuePairFactory; public: /** * Constructor */ QueuePair(infinity::core::Context *context); /** * Destructor */ ~QueuePair(); protected: /** * Activation methods */ void activate(uint16_t remoteDeviceId, uint32_t remoteQueuePairNumber, uint32_t remoteSequenceNumber); void setRemoteUserData(void *userData, uint32_t userDataSize); public: /** * User data received during connection setup */ bool hasUserData(); uint32_t getUserDataSize(); void * getUserData(); public: /** * Queue pair information */ uint16_t getLocalDeviceId(); uint32_t getQueuePairNumber(); uint32_t getSequenceNumber(); public: /** * Buffer operations */ void send(infinity::memory::Buffer *buffer, infinity::requests::RequestToken *requestToken = NULL); void send(infinity::memory::Buffer *buffer, uint32_t sizeInBytes, infinity::requests::RequestToken *requestToken = NULL); void send(infinity::memory::Buffer *buffer, uint64_t localOffset, uint32_t sizeInBytes, OperationFlags flags, infinity::requests::RequestToken *requestToken = NULL); void write(infinity::memory::Buffer *buffer, infinity::memory::RegionToken *destination, infinity::requests::RequestToken *requestToken = NULL); void write(infinity::memory::Buffer *buffer, infinity::memory::RegionToken *destination, uint32_t sizeInBytes, infinity::requests::RequestToken *requestToken = NULL); void write(infinity::memory::Buffer *buffer, uint64_t localOffset, infinity::memory::RegionToken *destination, uint64_t remoteOffset, uint32_t sizeInBytes, OperationFlags flags, infinity::requests::RequestToken *requestToken = NULL); void read(infinity::memory::Buffer *buffer, infinity::memory::RegionToken *source, infinity::requests::RequestToken *requestToken = NULL); void read(infinity::memory::Buffer *buffer, infinity::memory::RegionToken *source, uint32_t sizeInBytes, infinity::requests::RequestToken *requestToken = NULL); void read(infinity::memory::Buffer *buffer, uint64_t localOffset, infinity::memory::RegionToken *source, uint64_t remoteOffset, uint32_t sizeInBytes, OperationFlags flags, infinity::requests::RequestToken *requestToken = NULL); public: /** * Complex buffer operations */ void multiWrite(infinity::memory::Buffer **buffers, uint32_t *sizesInBytes, uint64_t *localOffsets, uint32_t numberOfElements, infinity::memory::RegionToken *destination, uint64_t remoteOffset, OperationFlags flags, infinity::requests::RequestToken *requestToken = NULL); void sendWithImmediate(infinity::memory::Buffer *buffer, uint64_t localOffset, uint32_t sizeInBytes, uint32_t immediateValue, OperationFlags flags, infinity::requests::RequestToken *requestToken = NULL); void writeWithImmediate(infinity::memory::Buffer *buffer, uint64_t localOffset, infinity::memory::RegionToken *destination, uint64_t remoteOffset, uint32_t sizeInBytes, uint32_t immediateValue, OperationFlags flags, infinity::requests::RequestToken *requestToken = NULL); void multiWriteWithImmediate(infinity::memory::Buffer **buffers, uint32_t *sizesInBytes, uint64_t *localOffsets, uint32_t numberOfElements, infinity::memory::RegionToken *destination, uint64_t remoteOffset, uint32_t immediateValue, OperationFlags flags, infinity::requests::RequestToken *requestToken = NULL); public: /** * Atomic value operations */ void compareAndSwap(infinity::memory::RegionToken *destination, uint64_t compare, uint64_t swap, infinity::requests::RequestToken *requestToken = NULL); void compareAndSwap(infinity::memory::RegionToken *destination, infinity::memory::Atomic *previousValue, uint64_t compare, uint64_t swap, OperationFlags flags, infinity::requests::RequestToken *requestToken = NULL); void fetchAndAdd(infinity::memory::RegionToken *destination, uint64_t add, infinity::requests::RequestToken *requestToken = NULL); void fetchAndAdd(infinity::memory::RegionToken *destination, infinity::memory::Atomic *previousValue, uint64_t add, OperationFlags flags, infinity::requests::RequestToken *requestToken = NULL); protected: infinity::core::Context * const context; ibv_qp* ibvQueuePair; uint32_t sequenceNumber; void *userData; uint32_t userDataSize; }; } /* namespace queues */ } /* namespace infinity */ #endif /* QUEUES_QUEUEPAIR_H_ */ <|start_filename|>src/infinity/queues/QueuePair.cpp<|end_filename|> /** * Queues - Queue Pair * * (c) 2018 <NAME>, ETH Zurich * Contact: <EMAIL> * */ #include "QueuePair.h" #include <random> #include <string.h> #include <arpa/inet.h> #include <cerrno> #include <infinity/core/Configuration.h> #include <infinity/utils/Debug.h> #define MAX(a,b) ((a) > (b) ? (a) : (b)) namespace infinity { namespace queues { int OperationFlags::ibvFlags() { int flags = 0; if (fenced) { flags |= IBV_SEND_FENCE; } if (signaled) { flags |= IBV_SEND_SIGNALED; } if (inlined) { flags |= IBV_SEND_INLINE; } return flags; } QueuePair::QueuePair(infinity::core::Context* context) : context(context) { ibv_qp_init_attr qpInitAttributes; memset(&qpInitAttributes, 0, sizeof(qpInitAttributes)); qpInitAttributes.send_cq = context->getSendCompletionQueue(); qpInitAttributes.recv_cq = context->getReceiveCompletionQueue(); qpInitAttributes.srq = context->getSharedReceiveQueue(); qpInitAttributes.cap.max_send_wr = MAX(infinity::core::Configuration::SEND_COMPLETION_QUEUE_LENGTH, 1); qpInitAttributes.cap.max_send_sge = infinity::core::Configuration::MAX_NUMBER_OF_SGE_ELEMENTS; qpInitAttributes.cap.max_recv_wr = MAX(infinity::core::Configuration::RECV_COMPLETION_QUEUE_LENGTH, 1); qpInitAttributes.cap.max_recv_sge = infinity::core::Configuration::MAX_NUMBER_OF_SGE_ELEMENTS; qpInitAttributes.qp_type = IBV_QPT_RC; qpInitAttributes.sq_sig_all = 0; this->ibvQueuePair = ibv_create_qp(context->getProtectionDomain(), &(qpInitAttributes)); INFINITY_ASSERT(this->ibvQueuePair != NULL, "[INFINITY][QUEUES][QUEUEPAIR] Cannot create queue pair.\n"); ibv_qp_attr qpAttributes; memset(&qpAttributes, 0, sizeof(qpAttributes)); qpAttributes.qp_state = IBV_QPS_INIT; qpAttributes.pkey_index = 0; qpAttributes.port_num = context->getDevicePort(); qpAttributes.qp_access_flags = IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_REMOTE_READ | IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_ATOMIC; int32_t returnValue = ibv_modify_qp(this->ibvQueuePair, &(qpAttributes), IBV_QP_STATE | IBV_QP_PORT | IBV_QP_ACCESS_FLAGS | IBV_QP_PKEY_INDEX); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Cannot transition to INIT state.\n"); std::random_device randomGenerator; std::uniform_int_distribution<int> range(0, 1<<24); this->sequenceNumber = range(randomGenerator); this->userData = NULL; this->userDataSize = 0; } QueuePair::~QueuePair() { int32_t returnValue = ibv_destroy_qp(this->ibvQueuePair); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Cannot delete queue pair.\n"); if (this->userData != NULL && this->userDataSize != 0) { free(this->userData); this->userDataSize = 0; } } void QueuePair::activate(uint16_t remoteDeviceId, uint32_t remoteQueuePairNumber, uint32_t remoteSequenceNumber) { ibv_qp_attr qpAttributes; memset(&(qpAttributes), 0, sizeof(qpAttributes)); qpAttributes.qp_state = IBV_QPS_RTR; qpAttributes.path_mtu = IBV_MTU_4096; qpAttributes.dest_qp_num = remoteQueuePairNumber; qpAttributes.rq_psn = remoteSequenceNumber; qpAttributes.max_dest_rd_atomic = 1; qpAttributes.min_rnr_timer = 12; qpAttributes.ah_attr.is_global = 0; qpAttributes.ah_attr.dlid = remoteDeviceId; qpAttributes.ah_attr.sl = 0; qpAttributes.ah_attr.src_path_bits = 0; qpAttributes.ah_attr.port_num = context->getDevicePort(); int32_t returnValue = ibv_modify_qp(this->ibvQueuePair, &qpAttributes, IBV_QP_STATE | IBV_QP_AV | IBV_QP_PATH_MTU | IBV_QP_DEST_QPN | IBV_QP_RQ_PSN | IBV_QP_MIN_RNR_TIMER | IBV_QP_MAX_DEST_RD_ATOMIC); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Cannot transition to RTR state.\n"); qpAttributes.qp_state = IBV_QPS_RTS; qpAttributes.timeout = 14; qpAttributes.retry_cnt = 7; qpAttributes.rnr_retry = 7; qpAttributes.sq_psn = this->getSequenceNumber(); qpAttributes.max_rd_atomic = 1; returnValue = ibv_modify_qp(this->ibvQueuePair, &qpAttributes, IBV_QP_STATE | IBV_QP_TIMEOUT | IBV_QP_RETRY_CNT | IBV_QP_RNR_RETRY | IBV_QP_SQ_PSN | IBV_QP_MAX_QP_RD_ATOMIC); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Cannot transition to RTS state.\n"); } void QueuePair::setRemoteUserData(void* userData, uint32_t userDataSize) { if (userDataSize > 0) { this->userData = new char[userDataSize]; memcpy(this->userData, userData, userDataSize); this->userDataSize = userDataSize; } } uint16_t QueuePair::getLocalDeviceId() { return this->context->getLocalDeviceId(); } uint32_t QueuePair::getQueuePairNumber() { return this->ibvQueuePair->qp_num; } uint32_t QueuePair::getSequenceNumber() { return this->sequenceNumber; } void QueuePair::send(infinity::memory::Buffer* buffer, infinity::requests::RequestToken *requestToken) { send(buffer, 0, buffer->getSizeInBytes(), OperationFlags(), requestToken); } void QueuePair::send(infinity::memory::Buffer* buffer, uint32_t sizeInBytes, infinity::requests::RequestToken *requestToken) { send(buffer, 0, sizeInBytes, OperationFlags(), requestToken); } void QueuePair::send(infinity::memory::Buffer* buffer, uint64_t localOffset, uint32_t sizeInBytes, OperationFlags send_flags, infinity::requests::RequestToken *requestToken) { if (requestToken != NULL) { requestToken->reset(); requestToken->setRegion(buffer); } struct ibv_sge sgElement; struct ibv_send_wr workRequest; struct ibv_send_wr *badWorkRequest; memset(&sgElement, 0, sizeof(ibv_sge)); sgElement.addr = buffer->getAddress() + localOffset; sgElement.length = sizeInBytes; sgElement.lkey = buffer->getLocalKey(); INFINITY_ASSERT(sizeInBytes <= buffer->getRemainingSizeInBytes(localOffset), "[INFINITY][QUEUES][QUEUEPAIR] Segmentation fault while creating scatter-getter element.\n"); memset(&workRequest, 0, sizeof(ibv_send_wr)); workRequest.wr_id = reinterpret_cast<uint64_t>(requestToken); workRequest.sg_list = &sgElement; workRequest.num_sge = 1; workRequest.opcode = IBV_WR_SEND; workRequest.send_flags = send_flags.ibvFlags(); if (requestToken != NULL) { workRequest.send_flags |= IBV_SEND_SIGNALED; } int returnValue = ibv_post_send(this->ibvQueuePair, &workRequest, &badWorkRequest); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Posting send request failed. %s.\n", strerror(errno)); INFINITY_DEBUG("[INFINITY][QUEUES][QUEUEPAIR] Send request created (id %lu).\n", workRequest.wr_id); } void QueuePair::sendWithImmediate(infinity::memory::Buffer* buffer, uint64_t localOffset, uint32_t sizeInBytes, uint32_t immediateValue, OperationFlags send_flags, infinity::requests::RequestToken* requestToken) { if (requestToken != NULL) { requestToken->reset(); requestToken->setRegion(buffer); requestToken->setImmediateValue(immediateValue); } struct ibv_sge sgElement; struct ibv_send_wr workRequest; struct ibv_send_wr *badWorkRequest; memset(&sgElement, 0, sizeof(ibv_sge)); sgElement.addr = buffer->getAddress() + localOffset; sgElement.length = sizeInBytes; sgElement.lkey = buffer->getLocalKey(); INFINITY_ASSERT(sizeInBytes <= buffer->getRemainingSizeInBytes(localOffset), "[INFINITY][QUEUES][QUEUEPAIR] Segmentation fault while creating scatter-getter element.\n"); memset(&workRequest, 0, sizeof(ibv_send_wr)); workRequest.wr_id = reinterpret_cast<uint64_t>(requestToken); workRequest.sg_list = &sgElement; workRequest.num_sge = 1; workRequest.opcode = IBV_WR_SEND_WITH_IMM; workRequest.imm_data = htonl(immediateValue); workRequest.send_flags = send_flags.ibvFlags(); if (requestToken != NULL) { workRequest.send_flags |= IBV_SEND_SIGNALED; } int returnValue = ibv_post_send(this->ibvQueuePair, &workRequest, &badWorkRequest); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Posting send request failed. %s.\n", strerror(errno)); INFINITY_DEBUG("[INFINITY][QUEUES][QUEUEPAIR] Send request created (id %lu).\n", workRequest.wr_id); } void QueuePair::write(infinity::memory::Buffer* buffer, infinity::memory::RegionToken* destination, infinity::requests::RequestToken *requestToken) { write(buffer, 0, destination, 0, buffer->getSizeInBytes(), OperationFlags(), requestToken); INFINITY_ASSERT(buffer->getSizeInBytes() <= ((uint64_t) UINT32_MAX), "[INFINITY][QUEUES][QUEUEPAIR] Request must be smaller or equal to UINT_32_MAX bytes. This memory region is larger. Please explicitly indicate the size of the data to transfer.\n"); } void QueuePair::write(infinity::memory::Buffer* buffer, infinity::memory::RegionToken* destination, uint32_t sizeInBytes, infinity::requests::RequestToken *requestToken) { write(buffer, 0, destination, 0, sizeInBytes, OperationFlags(), requestToken); } void QueuePair::write(infinity::memory::Buffer* buffer, uint64_t localOffset, infinity::memory::RegionToken* destination, uint64_t remoteOffset, uint32_t sizeInBytes, OperationFlags send_flags, infinity::requests::RequestToken *requestToken) { if (requestToken != NULL) { requestToken->reset(); requestToken->setRegion(buffer); } struct ibv_sge sgElement; struct ibv_send_wr workRequest; struct ibv_send_wr *badWorkRequest; memset(&sgElement, 0, sizeof(ibv_sge)); sgElement.addr = buffer->getAddress() + localOffset; sgElement.length = sizeInBytes; sgElement.lkey = buffer->getLocalKey(); INFINITY_ASSERT(sizeInBytes <= buffer->getRemainingSizeInBytes(localOffset), "[INFINITY][QUEUES][QUEUEPAIR] Segmentation fault while creating scatter-getter element.\n"); memset(&workRequest, 0, sizeof(ibv_send_wr)); workRequest.wr_id = reinterpret_cast<uint64_t>(requestToken); workRequest.sg_list = &sgElement; workRequest.num_sge = 1; workRequest.opcode = IBV_WR_RDMA_WRITE; workRequest.send_flags = send_flags.ibvFlags(); if (requestToken != NULL) { workRequest.send_flags |= IBV_SEND_SIGNALED; } workRequest.wr.rdma.remote_addr = destination->getAddress() + remoteOffset; workRequest.wr.rdma.rkey = destination->getRemoteKey(); INFINITY_ASSERT(sizeInBytes <= destination->getRemainingSizeInBytes(remoteOffset), "[INFINITY][QUEUES][QUEUEPAIR] Segmentation fault while writing to remote memory.\n"); int returnValue = ibv_post_send(this->ibvQueuePair, &workRequest, &badWorkRequest); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Posting write request failed. %s.\n", strerror(errno)); INFINITY_DEBUG("[INFINITY][QUEUES][QUEUEPAIR] Write request created (id %lu).\n", workRequest.wr_id); } void QueuePair::writeWithImmediate(infinity::memory::Buffer* buffer, uint64_t localOffset, infinity::memory::RegionToken* destination, uint64_t remoteOffset, uint32_t sizeInBytes, uint32_t immediateValue, OperationFlags send_flags, infinity::requests::RequestToken* requestToken) { if (requestToken != NULL) { requestToken->reset(); requestToken->setRegion(buffer); requestToken->setImmediateValue(immediateValue); } struct ibv_sge sgElement; struct ibv_send_wr workRequest; struct ibv_send_wr *badWorkRequest; memset(&sgElement, 0, sizeof(ibv_sge)); sgElement.addr = buffer->getAddress() + localOffset; sgElement.length = sizeInBytes; sgElement.lkey = buffer->getLocalKey(); INFINITY_ASSERT(sizeInBytes <= buffer->getRemainingSizeInBytes(localOffset), "[INFINITY][QUEUES][QUEUEPAIR] Segmentation fault while creating scatter-getter element.\n"); memset(&workRequest, 0, sizeof(ibv_send_wr)); workRequest.wr_id = reinterpret_cast<uint64_t>(requestToken); workRequest.sg_list = &sgElement; workRequest.num_sge = 1; workRequest.opcode = IBV_WR_RDMA_WRITE_WITH_IMM; workRequest.imm_data = htonl(immediateValue); workRequest.send_flags = send_flags.ibvFlags(); if (requestToken != NULL) { workRequest.send_flags |= IBV_SEND_SIGNALED; } workRequest.wr.rdma.remote_addr = destination->getAddress() + remoteOffset; workRequest.wr.rdma.rkey = destination->getRemoteKey(); INFINITY_ASSERT(sizeInBytes <= destination->getRemainingSizeInBytes(remoteOffset), "[INFINITY][QUEUES][QUEUEPAIR] Segmentation fault while writing to remote memory.\n"); int returnValue = ibv_post_send(this->ibvQueuePair, &workRequest, &badWorkRequest); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Posting write request failed. %s.\n", strerror(errno)); INFINITY_DEBUG("[INFINITY][QUEUES][QUEUEPAIR] Write request created (id %lu).\n", workRequest.wr_id); } void QueuePair::multiWrite(infinity::memory::Buffer** buffers, uint32_t* sizesInBytes, uint64_t* localOffsets, uint32_t numberOfElements, infinity::memory::RegionToken* destination, uint64_t remoteOffset, OperationFlags send_flags, infinity::requests::RequestToken* requestToken) { if (requestToken != NULL) { requestToken->reset(); requestToken->setRegion(buffers[0]); } struct ibv_sge *sgElements = (ibv_sge *) calloc(numberOfElements, sizeof(ibv_sge)); struct ibv_send_wr workRequest; struct ibv_send_wr *badWorkRequest; INFINITY_ASSERT(numberOfElements <= infinity::core::Configuration::MAX_NUMBER_OF_SGE_ELEMENTS, "[INFINITY][QUEUES][QUEUEPAIR] Request contains too many SGE.\n"); uint32_t totalSizeInBytes = 0; for (uint32_t i = 0; i < numberOfElements; ++i) { if (localOffsets != NULL) { sgElements[i].addr = buffers[i]->getAddress() + localOffsets[i]; } else { sgElements[i].addr = buffers[i]->getAddress(); } if (sizesInBytes != NULL) { sgElements[i].length = sizesInBytes[i]; } else { sgElements[i].length = buffers[i]->getSizeInBytes(); } totalSizeInBytes += sgElements[i].length; sgElements[i].lkey = buffers[i]->getLocalKey(); } memset(&workRequest, 0, sizeof(ibv_send_wr)); workRequest.wr_id = reinterpret_cast<uint64_t>(requestToken); workRequest.sg_list = sgElements; workRequest.num_sge = numberOfElements; workRequest.opcode = IBV_WR_RDMA_WRITE; workRequest.send_flags = send_flags.ibvFlags(); if (requestToken != NULL) { workRequest.send_flags |= IBV_SEND_SIGNALED; } workRequest.wr.rdma.remote_addr = destination->getAddress() + remoteOffset; workRequest.wr.rdma.rkey = destination->getRemoteKey(); INFINITY_ASSERT(totalSizeInBytes <= destination->getRemainingSizeInBytes(remoteOffset), "[INFINITY][QUEUES][QUEUEPAIR] Segmentation fault while writing to remote memory.\n"); int returnValue = ibv_post_send(this->ibvQueuePair, &workRequest, &badWorkRequest); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Posting write request failed. %s.\n", strerror(errno)); INFINITY_DEBUG("[INFINITY][QUEUES][QUEUEPAIR] Multi-Write request created (id %lu).\n", workRequest.wr_id); } void QueuePair::multiWriteWithImmediate(infinity::memory::Buffer** buffers, uint32_t* sizesInBytes, uint64_t* localOffsets, uint32_t numberOfElements, infinity::memory::RegionToken* destination, uint64_t remoteOffset, uint32_t immediateValue, OperationFlags send_flags, infinity::requests::RequestToken* requestToken) { if (requestToken != NULL) { requestToken->reset(); requestToken->setRegion(buffers[0]); requestToken->setImmediateValue(immediateValue); } struct ibv_sge *sgElements = (ibv_sge *) calloc(numberOfElements, sizeof(ibv_sge)); struct ibv_send_wr workRequest; struct ibv_send_wr *badWorkRequest; INFINITY_ASSERT(numberOfElements <= infinity::core::Configuration::MAX_NUMBER_OF_SGE_ELEMENTS, "[INFINITY][QUEUES][QUEUEPAIR] Request contains too many SGE.\n"); uint32_t totalSizeInBytes = 0; for (uint32_t i = 0; i < numberOfElements; ++i) { if (localOffsets != NULL) { sgElements[i].addr = buffers[i]->getAddress() + localOffsets[i]; } else { sgElements[i].addr = buffers[i]->getAddress(); } if (sizesInBytes != NULL) { sgElements[i].length = sizesInBytes[i]; } else { sgElements[i].length = buffers[i]->getSizeInBytes(); } totalSizeInBytes += sgElements[i].length; sgElements[i].lkey = buffers[i]->getLocalKey(); } memset(&workRequest, 0, sizeof(ibv_send_wr)); workRequest.wr_id = reinterpret_cast<uint64_t>(requestToken); workRequest.sg_list = sgElements; workRequest.num_sge = numberOfElements; workRequest.opcode = IBV_WR_RDMA_WRITE_WITH_IMM; workRequest.imm_data = htonl(immediateValue); workRequest.send_flags = send_flags.ibvFlags(); if (requestToken != NULL) { workRequest.send_flags |= IBV_SEND_SIGNALED; } workRequest.wr.rdma.remote_addr = destination->getAddress() + remoteOffset; workRequest.wr.rdma.rkey = destination->getRemoteKey(); INFINITY_ASSERT(totalSizeInBytes <= destination->getRemainingSizeInBytes(remoteOffset), "[INFINITY][QUEUES][QUEUEPAIR] Segmentation fault while writing to remote memory.\n"); int returnValue = ibv_post_send(this->ibvQueuePair, &workRequest, &badWorkRequest); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Posting write request failed. %s.\n", strerror(errno)); INFINITY_DEBUG("[INFINITY][QUEUES][QUEUEPAIR] Multi-Write request created (id %lu).\n", workRequest.wr_id); } void QueuePair::read(infinity::memory::Buffer* buffer, infinity::memory::RegionToken* source, infinity::requests::RequestToken *requestToken) { read(buffer, 0, source, 0, buffer->getSizeInBytes(), OperationFlags(), requestToken); INFINITY_ASSERT(buffer->getSizeInBytes() <= ((uint64_t) UINT32_MAX), "[INFINITY][QUEUES][QUEUEPAIR] Request must be smaller or equal to UINT_32_MAX bytes. This memory region is larger. Please explicitly indicate the size of the data to transfer.\n"); } void QueuePair::read(infinity::memory::Buffer* buffer, infinity::memory::RegionToken* source, uint32_t sizeInBytes, infinity::requests::RequestToken *requestToken) { read(buffer, 0, source, 0, sizeInBytes, OperationFlags(), requestToken); } void QueuePair::read(infinity::memory::Buffer* buffer, uint64_t localOffset, infinity::memory::RegionToken* source, uint64_t remoteOffset, uint32_t sizeInBytes, OperationFlags send_flags, infinity::requests::RequestToken *requestToken) { if (requestToken != NULL) { requestToken->reset(); requestToken->setRegion(buffer); } struct ibv_sge sgElement; struct ibv_send_wr workRequest; struct ibv_send_wr *badWorkRequest; memset(&sgElement, 0, sizeof(ibv_sge)); sgElement.addr = buffer->getAddress() + localOffset; sgElement.length = sizeInBytes; sgElement.lkey = buffer->getLocalKey(); INFINITY_ASSERT(sizeInBytes <= buffer->getRemainingSizeInBytes(localOffset), "[INFINITY][QUEUES][QUEUEPAIR] Segmentation fault while creating scatter-getter element.\n"); memset(&workRequest, 0, sizeof(ibv_send_wr)); workRequest.wr_id = reinterpret_cast<uint64_t>(requestToken); workRequest.sg_list = &sgElement; workRequest.num_sge = 1; workRequest.opcode = IBV_WR_RDMA_READ; workRequest.send_flags = send_flags.ibvFlags(); if (requestToken != NULL) { workRequest.send_flags |= IBV_SEND_SIGNALED; } workRequest.wr.rdma.remote_addr = source->getAddress() + remoteOffset; workRequest.wr.rdma.rkey = source->getRemoteKey(); INFINITY_ASSERT(sizeInBytes <= source->getRemainingSizeInBytes(remoteOffset), "[INFINITY][QUEUES][QUEUEPAIR] Segmentation fault while reading from remote memory.\n"); int returnValue = ibv_post_send(this->ibvQueuePair, &workRequest, &badWorkRequest); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Posting read request failed. %s.\n", strerror(errno)); INFINITY_DEBUG("[INFINITY][QUEUES][QUEUEPAIR] Read request created (id %lu).\n", workRequest.wr_id); } void QueuePair::compareAndSwap(infinity::memory::RegionToken* destination, infinity::memory::Atomic* previousValue, uint64_t compare, uint64_t swap, OperationFlags send_flags, infinity::requests::RequestToken *requestToken) { if (requestToken != NULL) { requestToken->reset(); requestToken->setRegion(previousValue); } struct ibv_sge sgElement; struct ibv_send_wr workRequest; struct ibv_send_wr *badWorkRequest; memset(&sgElement, 0, sizeof(ibv_sge)); sgElement.addr = previousValue->getAddress(); sgElement.length = previousValue->getSizeInBytes(); sgElement.lkey = previousValue->getLocalKey(); memset(&workRequest, 0, sizeof(ibv_send_wr)); workRequest.wr_id = reinterpret_cast<uint64_t>(requestToken); workRequest.sg_list = &sgElement; workRequest.num_sge = 1; workRequest.opcode = IBV_WR_ATOMIC_CMP_AND_SWP; workRequest.send_flags = send_flags.ibvFlags(); if (requestToken != NULL) { workRequest.send_flags |= IBV_SEND_SIGNALED; } workRequest.wr.atomic.remote_addr = destination->getAddress(); workRequest.wr.atomic.rkey = destination->getRemoteKey(); workRequest.wr.atomic.compare_add = compare; workRequest.wr.atomic.swap = swap; int returnValue = ibv_post_send(this->ibvQueuePair, &workRequest, &badWorkRequest); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Posting cmp-and-swp request failed. %s.\n", strerror(errno)); INFINITY_DEBUG("[INFINITY][QUEUES][QUEUEPAIR] Cmp-and-swp request created (id %lu).\n", workRequest.wr_id); } void QueuePair::compareAndSwap(infinity::memory::RegionToken* destination, uint64_t compare, uint64_t swap, infinity::requests::RequestToken *requestToken) { compareAndSwap(destination, context->defaultAtomic, compare, swap, OperationFlags(), requestToken); } void QueuePair::fetchAndAdd(infinity::memory::RegionToken* destination, uint64_t add, infinity::requests::RequestToken *requestToken) { fetchAndAdd(destination, context->defaultAtomic, add, OperationFlags(), requestToken); } void QueuePair::fetchAndAdd(infinity::memory::RegionToken* destination, infinity::memory::Atomic* previousValue, uint64_t add, OperationFlags send_flags, infinity::requests::RequestToken *requestToken) { if (requestToken != NULL) { requestToken->reset(); requestToken->setRegion(previousValue); } struct ibv_sge sgElement; struct ibv_send_wr workRequest; struct ibv_send_wr *badWorkRequest; memset(&sgElement, 0, sizeof(ibv_sge)); sgElement.addr = previousValue->getAddress(); sgElement.length = previousValue->getSizeInBytes(); sgElement.lkey = previousValue->getLocalKey(); memset(&workRequest, 0, sizeof(ibv_send_wr)); workRequest.wr_id = reinterpret_cast<uint64_t>(requestToken); workRequest.sg_list = &sgElement; workRequest.num_sge = 1; workRequest.opcode = IBV_WR_ATOMIC_FETCH_AND_ADD; workRequest.send_flags = send_flags.ibvFlags(); if (requestToken != NULL) { workRequest.send_flags |= IBV_SEND_SIGNALED; } workRequest.wr.atomic.remote_addr = destination->getAddress(); workRequest.wr.atomic.rkey = destination->getRemoteKey(); workRequest.wr.atomic.compare_add = add; int returnValue = ibv_post_send(this->ibvQueuePair, &workRequest, &badWorkRequest); INFINITY_ASSERT(returnValue == 0, "[INFINITY][QUEUES][QUEUEPAIR] Posting fetch-add request failed. %s.\n", strerror(errno)); INFINITY_DEBUG("[INFINITY][QUEUES][QUEUEPAIR] Fetch-add request created (id %lu).\n", workRequest.wr_id); } bool QueuePair::hasUserData() { return (this->userData != NULL && this->userDataSize != 0); } uint32_t QueuePair::getUserDataSize() { return this->userDataSize; } void* QueuePair::getUserData() { return this->userData; } } /* namespace queues */ } /* namespace infinity */ <|start_filename|>src/infinity/core/Context.cpp<|end_filename|> /** * Core - Context * * (c) 2018 <NAME>, ETH Zurich * Contact: <EMAIL> * */ #include "Context.h" #include <string.h> #include <limits> #include <arpa/inet.h> #include <infinity/core/Configuration.h> #include <infinity/queues/QueuePair.h> #include <infinity/memory/Atomic.h> #include <infinity/memory/Buffer.h> #include <infinity/requests/RequestToken.h> #include <infinity/utils/Debug.h> #define MAX(a,b) ((a) > (b) ? (a) : (b)) namespace infinity { namespace core { /******************************* * Context ******************************/ Context::Context(uint16_t device, uint16_t devicePort) { // Get IB device list int32_t numberOfInstalledDevices = 0; ibv_device **ibvDeviceList = ibv_get_device_list(&numberOfInstalledDevices); INFINITY_ASSERT(numberOfInstalledDevices > 0, "[INFINITY][CORE][CONTEXT] No InfiniBand devices found.\n"); INFINITY_ASSERT(device < numberOfInstalledDevices, "[INFINITY][CORE][CONTEXT] Requested device %d not found. There are %d devices available.\n", device, numberOfInstalledDevices); INFINITY_ASSERT(ibvDeviceList != NULL, "[INFINITY][CORE][CONTEXT] Device list was NULL.\n"); // Get IB device this->ibvDevice = ibvDeviceList[device]; INFINITY_ASSERT(this->ibvDevice != NULL, "[INFINITY][CORE][CONTEXT] Requested device %d was NULL.\n", device); // Open IB device and allocate protection domain this->ibvContext = ibv_open_device(this->ibvDevice); INFINITY_ASSERT(this->ibvContext != NULL, "[INFINITY][CORE][CONTEXT] Could not open device %d.\n", device); this->ibvProtectionDomain = ibv_alloc_pd(this->ibvContext); INFINITY_ASSERT(this->ibvProtectionDomain != NULL, "[INFINITY][CORE][CONTEXT] Could not allocate protection domain.\n"); // Get the LID ibv_port_attr portAttributes; ibv_query_port(this->ibvContext, devicePort, &portAttributes); this->ibvLocalDeviceId = portAttributes.lid; this->ibvDevicePort = devicePort; // Allocate completion queues this->ibvSendCompletionQueue = ibv_create_cq(this->ibvContext, MAX(Configuration::SEND_COMPLETION_QUEUE_LENGTH, 1), NULL, NULL, 0); this->ibvReceiveCompletionQueue = ibv_create_cq(this->ibvContext, MAX(Configuration::RECV_COMPLETION_QUEUE_LENGTH, 1), NULL, NULL, 0); // Allocate shared receive queue ibv_srq_init_attr sia; memset(&sia, 0, sizeof(ibv_srq_init_attr)); sia.srq_context = this->ibvContext; sia.attr.max_wr = MAX(Configuration::SHARED_RECV_QUEUE_LENGTH, 1); sia.attr.max_sge = 1; this->ibvSharedReceiveQueue = ibv_create_srq(this->ibvProtectionDomain, &sia); INFINITY_ASSERT(this->ibvSharedReceiveQueue != NULL, "[INFINITY][CORE][CONTEXT] Could not allocate shared receive queue.\n"); // Create a default request token defaultRequestToken = new infinity::requests::RequestToken(this); defaultAtomic = new infinity::memory::Atomic(this); } Context::~Context() { // Delete default token delete defaultRequestToken; delete defaultAtomic; // Destroy shared receive queue int returnValue = ibv_destroy_srq(this->ibvSharedReceiveQueue); INFINITY_ASSERT(returnValue == 0, "[INFINITY][CORE][CONTEXT] Could not delete shared receive queue\n"); // Destroy completion queues returnValue = ibv_destroy_cq(this->ibvSendCompletionQueue); INFINITY_ASSERT(returnValue == 0, "[INFINITY][CORE][CONTEXT] Could not delete send completion queue\n"); returnValue = ibv_destroy_cq(this->ibvReceiveCompletionQueue); INFINITY_ASSERT(returnValue == 0, "[INFINITY][CORE][CONTEXT] Could not delete receive completion queue\n"); // Destroy protection domain returnValue = ibv_dealloc_pd(this->ibvProtectionDomain); INFINITY_ASSERT(returnValue == 0, "[INFINITY][CORE][CONTEXT] Could not delete protection domain\n"); // Close device returnValue = ibv_close_device(this->ibvContext); INFINITY_ASSERT(returnValue == 0, "[INFINITY][CORE][CONTEXT] Could not close device\n"); } void Context::postReceiveBuffer(infinity::memory::Buffer* buffer) { INFINITY_ASSERT(buffer->getSizeInBytes() <= std::numeric_limits<uint32_t>::max(), "[INFINITY][CORE][CONTEXT] Cannot post receive buffer which is larger than max(uint32_t).\n"); // Create scatter-getter ibv_sge isge; memset(&isge, 0, sizeof(ibv_sge)); isge.addr = buffer->getAddress(); isge.length = static_cast<uint32_t>(buffer->getSizeInBytes()); isge.lkey = buffer->getLocalKey(); // Create work request ibv_recv_wr wr; memset(&wr, 0, sizeof(ibv_recv_wr)); wr.wr_id = reinterpret_cast<uint64_t>(buffer); wr.next = NULL; wr.sg_list = &isge; wr.num_sge = 1; // Post buffer to shared receive queue ibv_recv_wr *badwr; uint32_t returnValue = ibv_post_srq_recv(this->ibvSharedReceiveQueue, &wr, &badwr); INFINITY_ASSERT(returnValue == 0, "[INFINITY][CORE][CONTEXT] Cannot post buffer to receive queue.\n"); } bool Context::receive(receive_element_t* receiveElement) { return receive(&(receiveElement->buffer), &(receiveElement->bytesWritten), &(receiveElement->immediateValue), &(receiveElement->immediateValueValid), &(receiveElement->queuePair)); } bool Context::receive(infinity::memory::Buffer** buffer, uint32_t *bytesWritten, uint32_t *immediateValue, bool *immediateValueValid, infinity::queues::QueuePair **queuePair) { ibv_wc wc; if (ibv_poll_cq(this->ibvReceiveCompletionQueue, 1, &wc) > 0) { if(wc.opcode == IBV_WC_RECV) { *(buffer) = reinterpret_cast<infinity::memory::Buffer*>(wc.wr_id); *(bytesWritten) = wc.byte_len; } else if (wc.opcode == IBV_WC_RECV_RDMA_WITH_IMM) { *(buffer) = NULL; *(bytesWritten) = wc.byte_len; infinity::memory::Buffer* receiveBuffer = reinterpret_cast<infinity::memory::Buffer*>(wc.wr_id); this->postReceiveBuffer(receiveBuffer); } if(wc.wc_flags & IBV_WC_WITH_IMM) { *(immediateValue) = ntohl(wc.imm_data); *(immediateValueValid) = true; } else { *(immediateValue) = 0; *(immediateValueValid) = false; } if(queuePair != NULL) { *(queuePair) = queuePairMap.at(wc.qp_num); } return true; } return false; } bool Context::pollSendCompletionQueue() { ibv_wc wc; if (ibv_poll_cq(this->ibvSendCompletionQueue, 1, &wc) > 0) { infinity::requests::RequestToken * request = reinterpret_cast<infinity::requests::RequestToken*>(wc.wr_id); if (request != NULL) { request->setCompleted(wc.status == IBV_WC_SUCCESS); } if (wc.status == IBV_WC_SUCCESS) { INFINITY_DEBUG("[INFINITY][CORE][CONTEXT] Request completed (id %lu).\n", wc.wr_id); } else { INFINITY_DEBUG("[INFINITY][CORE][CONTEXT] Request failed (id %lu).\n", wc.wr_id); } return true; } return false; } void Context::registerQueuePair(infinity::queues::QueuePair* queuePair) { this->queuePairMap.insert({queuePair->getQueuePairNumber(), queuePair}); } ibv_context* Context::getInfiniBandContext() { return this->ibvContext; } uint16_t Context::getLocalDeviceId() { return this->ibvLocalDeviceId; } uint16_t Context::getDevicePort() { return this->ibvDevicePort; } ibv_pd* Context::getProtectionDomain() { return this->ibvProtectionDomain; } ibv_cq* Context::getSendCompletionQueue() { return this->ibvSendCompletionQueue; } ibv_cq* Context::getReceiveCompletionQueue() { return this->ibvReceiveCompletionQueue; } ibv_srq* Context::getSharedReceiveQueue() { return this->ibvSharedReceiveQueue; } } /* namespace core */ } /* namespace infinity */ <|start_filename|>Makefile<|end_filename|> ################################################## # # (c) 2018 <NAME>, ETH Zurich # # Call 'make library' to build the library # Call 'make examples' to build the examples # Call 'make all' to build everything # ################################################## PROJECT_NAME = libinfinity ################################################## CC = g++ CC_FLAGS = -O3 -std=c++0x LD_FLAGS = -linfinity -libverbs ################################################## SOURCE_FOLDER = src BUILD_FOLDER = build RELEASE_FOLDER = release INCLUDE_FOLDER = include EXAMPLES_FOLDER = examples ################################################## SOURCE_FILES = $(SOURCE_FOLDER)/infinity/core/Context.cpp \ $(SOURCE_FOLDER)/infinity/memory/Atomic.cpp \ $(SOURCE_FOLDER)/infinity/memory/Buffer.cpp \ $(SOURCE_FOLDER)/infinity/memory/Region.cpp \ $(SOURCE_FOLDER)/infinity/memory/RegionToken.cpp \ $(SOURCE_FOLDER)/infinity/memory/RegisteredMemory.cpp \ $(SOURCE_FOLDER)/infinity/queues/QueuePair.cpp \ $(SOURCE_FOLDER)/infinity/queues/QueuePairFactory.cpp \ $(SOURCE_FOLDER)/infinity/requests/RequestToken.cpp \ $(SOURCE_FOLDER)/infinity/utils/Address.cpp HEADER_FILES = $(SOURCE_FOLDER)/infinity/infinity.h \ $(SOURCE_FOLDER)/infinity/core/Context.h \ $(SOURCE_FOLDER)/infinity/core/Configuration.h \ $(SOURCE_FOLDER)/infinity/memory/Atomic.h \ $(SOURCE_FOLDER)/infinity/memory/Buffer.h \ $(SOURCE_FOLDER)/infinity/memory/Region.h \ $(SOURCE_FOLDER)/infinity/memory/RegionToken.h \ $(SOURCE_FOLDER)/infinity/memory/RegionType.h \ $(SOURCE_FOLDER)/infinity/memory/RegisteredMemory.h \ $(SOURCE_FOLDER)/infinity/queues/QueuePair.h \ $(SOURCE_FOLDER)/infinity/queues/QueuePairFactory.h \ $(SOURCE_FOLDER)/infinity/requests/RequestToken.h \ $(SOURCE_FOLDER)/infinity/utils/Debug.h \ $(SOURCE_FOLDER)/infinity/utils/Address.h ################################################## OBJECT_FILES = $(patsubst $(SOURCE_FOLDER)/%.cpp,$(BUILD_FOLDER)/%.o,$(SOURCE_FILES)) SOURCE_DIRECTORIES = $(dir $(HEADER_FILES)) BUILD_DIRECTORIES = $(patsubst $(SOURCE_FOLDER)/%,$(BUILD_FOLDER)/%,$(SOURCE_DIRECTORIES)) ################################################## all: library examples ################################################## $(BUILD_FOLDER)/%.o: $(SOURCE_FILES) $(HEADER_FILES) mkdir -p $(BUILD_FOLDER) mkdir -p $(BUILD_DIRECTORIES) $(CC) $(CC_FLAGS) -c $(SOURCE_FOLDER)/$*.cpp -I $(SOURCE_FOLDER) -o $(BUILD_FOLDER)/$*.o ################################################## library: $(OBJECT_FILES) mkdir -p $(RELEASE_FOLDER) ar rvs $(RELEASE_FOLDER)/$(PROJECT_NAME).a $(OBJECT_FILES) rm -rf $(RELEASE_FOLDER)/$(INCLUDE_FOLDER) cp --parents $(HEADER_FILES) $(RELEASE_FOLDER) mv $(RELEASE_FOLDER)/$(SOURCE_FOLDER)/ $(RELEASE_FOLDER)/$(INCLUDE_FOLDER) ################################################## clean: rm -rf $(BUILD_FOLDER) rm -rf $(RELEASE_FOLDER) ################################################## examples: mkdir -p $(RELEASE_FOLDER)/$(EXAMPLES_FOLDER) $(CC) src/examples/read-write-send.cpp $(CC_FLAGS) $(LD_FLAGS) -I $(RELEASE_FOLDER)/$(INCLUDE_FOLDER) -L $(RELEASE_FOLDER) -o $(RELEASE_FOLDER)/$(EXAMPLES_FOLDER)/read-write-send $(CC) src/examples/send-performance.cpp $(CC_FLAGS) $(LD_FLAGS) -I $(RELEASE_FOLDER)/$(INCLUDE_FOLDER) -L $(RELEASE_FOLDER) -o $(RELEASE_FOLDER)/$(EXAMPLES_FOLDER)/send-performance ################################################## <|start_filename|>src/infinity/memory/Region.h<|end_filename|> /* * Memory - Region * * (c) 2018 <NAME>, ETH Zurich * Contact: <EMAIL> * */ #ifndef MEMORY_REGION_H_ #define MEMORY_REGION_H_ #include <stdint.h> #include <infiniband/verbs.h> #include <infinity/core/Context.h> #include <infinity/memory/RegionType.h> namespace infinity { namespace memory { class RegionToken; class Region { public: virtual ~Region(); RegionToken * createRegionToken(); RegionToken * createRegionToken(uint64_t offset); RegionToken * createRegionToken(uint64_t offset, uint64_t size); public: RegionType getMemoryRegionType(); uint64_t getSizeInBytes(); uint64_t getRemainingSizeInBytes(uint64_t offset); uint64_t getAddress(); uint64_t getAddressWithOffset(uint64_t offset); uint32_t getLocalKey(); uint32_t getRemoteKey(); protected: infinity::core::Context* context; RegionType memoryRegionType; ibv_mr *ibvMemoryRegion; protected: void * data; uint64_t sizeInBytes; }; } /* namespace memory */ } /* namespace infinity */ #endif /* MEMORY_REGION_H_ */
YisakH/infinity-test
<|start_filename|>Makefile<|end_filename|> SHELL := /bin/bash VIRTUALENV_DIR ?= venv PYTHON_VERSION = python3.6 .PHONY: virtualenv virtualenv: @echo @echo "==================== virtualenv ====================" @echo test -f $(VIRTUALENV_DIR)/bin/activate || python3.6 -m venv $(VIRTUALENV_DIR) .PHONY: requirements requirements: virtualenv @echo @echo "==================== requirements ====================" @echo # Install requirements . $(VIRTUALENV_DIR)/bin/activate; $(VIRTUALENV_DIR)/bin/pip install -r requirements.txt .PHONY: lint-requirements lint-requirements: requirements @echo @echo "==================== lint requirements ====================" @echo # Install requirements . $(VIRTUALENV_DIR)/bin/activate; $(VIRTUALENV_DIR)/bin/pip install pylint flake8 .PHONY: lint lint: .flake8 .pylint .PHONY: .pylint .pylint: @echo @echo "================== pylint ====================" @echo . $(VIRTUALENV_DIR)/bin/activate; PYTHONPATH=. pylint -E *.py .PHONY: .flake8 .flake8: @echo @echo "==================== flake ====================" @echo . $(VIRTUALENV_DIR)/bin/activate; flake8 *.py
ExplorerFreda/concreteness
<|start_filename|>Core/Inc/gw_linker.h<|end_filename|> #pragma once extern uint32_t _etext; extern uint32_t _sbss; extern uint32_t _ebss; extern uint32_t _sidata; extern uint32_t _sdata; extern uint32_t _edata; <|start_filename|>Core/Src/ips.c<|end_filename|> /** * Helpful source: * https://zerosoft.zophar.net/ips.php */ #include <string.h> #include "ips.h" static char IPS_HEADER[] = {'P', 'A', 'T', 'C', 'H'}; static char IPS_TRAILER[] = {'E', 'O', 'F'}; #define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x]))))) #define BYTE3_TO_UINT(bp) \ (((unsigned int)(bp)[0] << 16) & 0x00FF0000) | \ (((unsigned int)(bp)[1] << 8) & 0x0000FF00) | \ ((unsigned int)(bp)[2] & 0x000000FF) #define BYTE2_TO_UINT(bp) \ (((unsigned int)(bp)[0] << 8) & 0xFF00) | \ ((unsigned int) (bp)[1] & 0x00FF) /** * Assumes the ROM is already copied to dst and the patch will be applied inplace */ ips_patch_res_t ips_patch(uint8_t *dst, const uint8_t *patch){ // Check Header Magic if(memcmp(patch, IPS_HEADER, COUNT_OF(IPS_HEADER))) return IPS_PATCH_WRONG_HEADER; patch += 5; // Iterate over Records until EOF trailer is hit. while(memcmp(patch, IPS_TRAILER, COUNT_OF(IPS_TRAILER))){ uint32_t offset = BYTE3_TO_UINT(patch); // We operate headerless patch += 3; uint16_t size = BYTE2_TO_UINT(patch); patch += 2; if(size){ // Directly copy over memcpy(&dst[offset], patch, size); patch += size; } else{ // RLE data size = BYTE2_TO_UINT(patch); patch += 2; uint8_t val = *patch++; memset(&dst[offset], val, size); } } return IPS_PATCH_OK; } <|start_filename|>Core/Src/main.c<|end_filename|> #include "main.h" #include "stock_firmware.h" #include <inttypes.h> #include "cmsis_gcc.h" #include <assert.h> #include "gw_linker.h" #include "stm32h7xx_hal.h" #include "LzmaDec.h" #include <string.h> #include "ips.h" #define MSP_ADDRESS 0x08000000 #define BANK_2_ADDRESS 0x08100000 #define BOOTLOADER_MAGIC 0x544F4F42 // "BOOT" #define BOOTLOADER_MAGIC_ADDRESS ((uint32_t *)0x2001FFF8) #define BOOTLOADER_JUMP_ADDRESS ((uint32_t **)0x2001FFFC) static void __attribute__((naked)) start_app(void (* const pc)(void), uint32_t sp) { __asm(" \n\ msr msp, r1 /* load r1 into MSP */\n\ bx r0 /* branch to the address at r0 */\n\ "); } static inline void set_bootloader(uint32_t address){ *BOOTLOADER_MAGIC_ADDRESS = BOOTLOADER_MAGIC; *BOOTLOADER_JUMP_ADDRESS = (uint32_t *)address; } /** * Executed on boot; will jump to a non-default program if: * 1. the value at `BOOTLOADER_MAGIC_ADDRESS` is `BOOTLOADER_MAGIC` * 2. the value at `BOOTLOADER_JUMP_ADDRESS` is the beginning of * the firmware to execute. * So to run that app, set those values and execute a reset. */ void bootloader(){ if(*BOOTLOADER_MAGIC_ADDRESS == BOOTLOADER_MAGIC) { *BOOTLOADER_MAGIC_ADDRESS = 0; uint32_t sp = (*BOOTLOADER_JUMP_ADDRESS)[0]; uint32_t pc = (*BOOTLOADER_JUMP_ADDRESS)[1]; start_app((void (* const)(void)) pc, (uint32_t) sp); } start_app(stock_Reset_Handler, *(uint32_t *) MSP_ADDRESS); while(1); } static inline void start_bank_2() { set_bootloader(BANK_2_ADDRESS); NVIC_SystemReset(); } #if ENABLE_SMB1_GRAPHIC_MODS #define SMB1_GRAPHIC_MODS_MAX 8 const uint8_t * const SMB1_GRAPHIC_MODS[SMB1_GRAPHIC_MODS_MAX] = { 0 }; static volatile uint8_t smb1_graphics_idx = 0; uint8_t * prepare_clock_rom(void *mario_rom, size_t len){ const uint8_t *patch = NULL; if(smb1_graphics_idx > SMB1_GRAPHIC_MODS_MAX){ smb1_graphics_idx = 0; } if(smb1_graphics_idx){ patch = SMB1_GRAPHIC_MODS[smb1_graphics_idx - 1]; } memcpy(smb1_clock_working, mario_rom, len); if(patch) { // Load custom graphics if(IPS_PATCH_WRONG_HEADER == ips_patch(smb1_clock_working, patch)){ // Attempt a direct graphics override memcpy_inflate(smb1_clock_graphics_working, patch, 0x1ec0); } } else{ smb1_graphics_idx = 0; } return stock_prepare_clock_rom(smb1_clock_working, len); } #endif #if ENABLE_SMB1_GRAPHIC_MODS bool is_menu_open(){ return *ui_draw_status_addr == 5; } #endif gamepad_t read_buttons() { static gamepad_t gamepad_last = 0; gamepad_t gamepad = 0; gamepad = stock_read_buttons(); #if CLOCK_ONLY if(gamepad & GAMEPAD_GAME){ #else if((gamepad & GAMEPAD_LEFT) && (gamepad & GAMEPAD_GAME)){ #endif start_bank_2(); } #if ENABLE_SMB1_GRAPHIC_MODS gnw_mode_t mode = get_gnw_mode(); if(mode == GNW_MODE_CLOCK && !is_menu_open()){ // Actions to only perform on the clock screen if((gamepad & GAMEPAD_DOWN) && !(gamepad_last &GAMEPAD_DOWN)){ // TODO: detect if menu is up or not smb1_graphics_idx++; // Force a reload *(uint8_t *)0x2000103d = 1; // Not sure the difference between setting 1 or 2. } } #endif gamepad_last = gamepad; return gamepad; } const uint8_t LZMA_PROP_DATA[5] = {0x5d, 0x00, 0x40, 0x00, 0x00}; #define LZMA_BUF_SIZE 16256 static void *SzAlloc(ISzAllocPtr p, size_t size) { void* res = p->Mem; return res; } static void SzFree(ISzAllocPtr p, void *address) { } const ISzAlloc g_Alloc = { SzAlloc, SzFree }; static unsigned char lzma_heap[LZMA_BUF_SIZE]; /** * Dropin replacement for memcpy for loading compressed assets. * @param n Compressed data length. Can be larger than necessary. */ void *memcpy_inflate(uint8_t *dst, const uint8_t *src, size_t n){ ISzAlloc allocs = { .Alloc=SzAlloc, .Free=SzFree, .Mem=lzma_heap, }; ELzmaStatus status; size_t dst_len = 393216; LzmaDecode(dst, &dst_len, src, &n, LZMA_PROP_DATA, 5, LZMA_FINISH_ANY, &status, &allocs); return dst; } /** * This gets hooked into the rwdata/bss init table. */ int32_t *rwdata_inflate(int32_t *table){ uint8_t *data = (uint8_t *)table + table[0]; int32_t len = table[1]; uint8_t *ram = (uint8_t *) table[2]; memcpy_inflate(ram, data, len); return table + 3; } /** * This gets hooked into the rwdata/bss init table. */ int32_t *bss_rwdata_init(int32_t *table){ /* Copy init values from text to data */ uint32_t *init_values_ptr = &_sidata; uint32_t *data_ptr = &_sdata; if (init_values_ptr != data_ptr) { for (; data_ptr < &_edata;) { *data_ptr++ = *init_values_ptr++; } } /* Clear the zero segment */ for (uint32_t *bss_ptr = &_sbss; bss_ptr < &_ebss;) { *bss_ptr++ = 0; } return table; } #if ENABLE_SMB1_GRAPHIC_MODS gnw_mode_t get_gnw_mode(){ uint8_t val = *gnw_mode_addr; if(val == 0x20) return GNW_MODE_SMB2; else if(val == 0x10) return GNW_MODE_SMB1; else if(val == 0x08) return GNW_MODE_BALL; else return GNW_MODE_CLOCK; } #endif void NMI_Handler(void) { __BKPT(0); } void HardFault_Handler(void) { __BKPT(0); } <|start_filename|>Core/Inc/stock_firmware.h<|end_filename|> #pragma once #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wint-conversion" #pragma GCC diagnostic ignored "-Wbuiltin-declaration-mismatch" #include "stock_firmware_common.h" #if GNW_DEVICE_MARIO #include "stock_firmware_mario.h" #elif GNW_DEVICE_ZELDA #include "stock_firmware_zelda.h" #else #error "Invalid GNW Device specified." #endif #pragma GCC diagnostic pop <|start_filename|>Makefile<|end_filename|> ###################################### # target ###################################### TARGET = gw_patch ####################################### # paths ####################################### # Build path BUILD_DIR = build ###################################### # source ###################################### # C sources C_SOURCES = \ Core/Src/ips.c \ Core/Src/main.c \ Core/lzma/LzmaDec.c \ # ASM sources ASM_SOURCES = \ ####################################### # binaries ####################################### PREFIX = arm-none-eabi- # The gcc compiler bin path can be either defined in make command via GCC_PATH variable (> make GCC_PATH=xxx) # either it can be added to the PATH environment variable. ifdef GCC_PATH CC = $(GCC_PATH)/$(PREFIX)gcc AS = $(GCC_PATH)/$(PREFIX)gcc -x assembler-with-cpp CP = $(GCC_PATH)/$(PREFIX)objcopy SZ = $(GCC_PATH)/$(PREFIX)size else CC = $(PREFIX)gcc AS = $(PREFIX)gcc -x assembler-with-cpp CP = $(PREFIX)objcopy SZ = $(PREFIX)size endif HEX = $(CP) -O ihex BIN = $(CP) -O binary -S ECHO = echo OPENOCD ?= openocd GDB ?= $(PREFIX)gdb PYTHON ?= python3 ####################################### # Detect OS ####################################### UNAME := $(shell uname) ifeq ($(UNAME), Darwin) NOTIFY_COMMAND=say -v Samantha -r 300 \"flash complete\" endif ifeq ($(UNAME), Linux) NOTIFY_COMMAND=echo -en "\007" endif ###################################### # building variables ###################################### PATCH_PARAMS ?= GNW_DEVICE := $(shell $(PYTHON) -m scripts.device_from_patch_params $(PATCH_PARAMS)) C_DEFS += -DGNW_DEVICE_$(GNW_DEVICE)=1 ifneq (,$(findstring --clock-only, $(PATCH_PARAMS))) C_DEFS += -DCLOCK_ONLY endif ifneq (,$(findstring --smb1-graphics, $(PATCH_PARAMS))) C_DEFS += -DENABLE_SMB1_GRAPHIC_MODS endif ifneq (,$(findstring --debug, $(PATCH_PARAMS))) DEBUG = 1 C_DEFS += -DDEBUG endif ADAPTER ?= stlink LARGE_FLASH ?= 0 export LARGE_FLASH # Used in stm32h7x_spiflash.cfg ifeq ($(LARGE_FLASH), 0) PROGRAM_VERIFY="verify" else # Currently verify is broken for large chips PROGRAM_VERIFY="" endif ####################################### # CFLAGS ####################################### # cpu CPU = -mcpu=cortex-m7 # fpu FPU = -mfpu=fpv5-d16 # float-abi FLOAT-ABI = -mfloat-abi=hard # mcu MCU = $(CPU) -mthumb $(FPU) $(FLOAT-ABI) # macros for gcc # AS defines AS_DEFS = # C defines C_DEFS += \ -DUSE_HAL_DRIVER \ -DSTM32H7B0xx \ # AS includes AS_INCLUDES = # C includes C_INCLUDES = \ -ICore/Inc \ -ICore/lzma \ -IDrivers/STM32H7xx_HAL_Driver/Inc \ -IDrivers/STM32H7xx_HAL_Driver/Inc/Legacy \ -IDrivers/CMSIS/Device/ST/STM32H7xx/Include \ -IDrivers/CMSIS/Include # compile gcc flags ASFLAGS = $(MCU) $(AS_DEFS) $(AS_INCLUDES) $(OPT) -Wall -fdata-sections -ffunction-sections CFLAGS = $(MCU) $(C_DEFS) $(C_INCLUDES) $(OPT) -Wall -fdata-sections -ffunction-sections ifeq ($(DEBUG), 1) CFLAGS += -g -gdwarf-2 -O0 else CFLAGS += -Os endif # Generate dependency information CFLAGS += -MMD -MP -MF"$(@:%.o=%.d)" ####################################### # LDFLAGS ####################################### # link script LDSCRIPT = STM32H7B0VBTx_FLASH.ld # libraries LIBS = -lc -lm -lnosys LIBDIR = LDFLAGS = $(MCU) -specs=nano.specs -T$(LDSCRIPT) $(LIBDIR) $(LIBS) -Wl,-Map=$(BUILD_DIR)/$(TARGET).map,--cref \ -Wl,--gc-sections \ -Wl,--undefined=HardFault_Handler \ -Wl,--undefined=NMI_Handler \ -Wl,--undefined=SMB1_GRAPHIC_MODS \ -Wl,--undefined=SMB1_ROM \ -Wl,--undefined=bootloader \ -Wl,--undefined=bss_rwdata_init \ -Wl,--undefined=memcpy_inflate \ -Wl,--undefined=prepare_clock_rom \ -Wl,--undefined=read_buttons \ -Wl,--undefined=rwdata_inflate \ # default action: build all all: $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).hex $(BUILD_DIR)/$(TARGET).bin $(BUILD_DIR)/internal_flash_patched.bin include Makefile.sdk ####################################### # build the application ####################################### # list of objects OBJECTS = $(addprefix $(BUILD_DIR)/,$(notdir $(C_SOURCES:.c=.o))) vpath %.c $(sort $(dir $(C_SOURCES))) # list of ASM program objects OBJECTS += $(addprefix $(BUILD_DIR)/,$(notdir $(ASM_SOURCES:.s=.o))) vpath %.s $(sort $(dir $(ASM_SOURCES))) $(BUILD_DIR)/%.o: %.c Makefile $(BUILD_DIR)/env | $(BUILD_DIR) $(CC) -c $(CFLAGS) -Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@ $(BUILD_DIR)/%.o: %.s Makefile $(BUILD_DIR)/env | $(BUILD_DIR) $(AS) -c $(CFLAGS) $< -o $@ $(BUILD_DIR)/$(TARGET).elf: $(OBJECTS) Makefile $(CC) $(OBJECTS) $(LDFLAGS) -o $@ $(SZ) $@ $(BUILD_DIR)/%.hex: $(BUILD_DIR)/%.elf | $(BUILD_DIR) $(HEX) $< $@ $(BUILD_DIR)/%.bin: $(BUILD_DIR)/%.elf | $(BUILD_DIR) $(BIN) $< $@ $(BUILD_DIR): mkdir -p $@ # Rebuild if PATCH_PARAMS doesn't match the values when last ran $(BUILD_DIR)/env: $(BUILD_DIR) scripts/check_env_vars.py FORCE $(PYTHON) scripts/check_env_vars.py "$(MAKECMDGOALS)" $@ "$(PATCH_PARAMS)" FORCE: ; .EXPORT_ALL_VARIABLES: openocd_dump_image: ${OPENOCD} -f "openocd/interface_$(ADAPTER).cfg" \ -c "init;" \ -c "halt;" \ -c "dump_image dump_image.bin 0x90000000 0x400000;" \ -c "exit;" .PHONY: openocd_dump_image reset: $(OPENOCD) -f openocd/interface_$(ADAPTER).cfg -c "init; reset; exit" .PHONY: reset erase_int: $(OPENOCD) -f openocd/interface_$(ADAPTER).cfg -c "init; halt; flash erase_address 0x08000000 131072; resume; exit" .PHONY: erase_int $(BUILD_DIR)/dummy.bin: $(PYTHON) -c "with open('$@', 'wb') as f: f.write(b'\xFF'*1048576)" erase_ext: $(BUILD_DIR)/dummy.bin ${OPENOCD} -f "openocd/interface_$(ADAPTER).cfg" \ -c "init;" \ -c "halt;" \ -c "program $< 0x90000000 $(PROGRAM_VERIFY);" \ -c "exit;" make reset .PHONY: erase_ext dump_ext: $(OPENOCD) -f openocd/interface_$(ADAPTER).cfg -c "init; halt; dump_image \"dump_ext.bin\" 0x90000000 0x100000; resume; exit;" .PHONY: dump_ext flash_stock_int: internal_flash_backup_$(GNW_DEVICE).bin $(OPENOCD) -f openocd/interface_"$(ADAPTER)".cfg \ -c "init; halt;" \ -c "program $< 0x08000000 $(PROGRAM_VERIFY);" \ -c "reset; exit;" .PHONY: flash_stock_int flash_stock_ext: flash_backup_$(GNW_DEVICE).bin ${OPENOCD} -f "openocd/interface_$(ADAPTER).cfg" \ -c "init; halt;" \ -c "program $< 0x90000000 $(PROGRAM_VERIFY);" \ -c "exit;" make reset .PHONY: flash_stock_ext flash_stock: flash_stock_ext flash_stock_int reset .PHONY: flash_stock $(BUILD_DIR)/internal_flash_patched.bin $(BUILD_DIR)/external_flash_patched.bin &: $(BUILD_DIR)/$(TARGET).bin patch.py $(shell find patches -type f) $(PYTHON) patch.py $(PATCH_PARAMS) patch: $(BUILD_DIR)/internal_flash_patched.bin $(BUILD_DIR)/external_flash_patched.bin .PHONY: patch flash_patched_int: build/internal_flash_patched.bin $(OPENOCD) -f openocd/interface_"$(ADAPTER)".cfg \ -c "init; halt;" \ -c "program $< 0x08000000 $(PROGRAM_VERIFY);" \ -c "reset; exit;" .PHONY: flash_patched_int flash_patched_ext: build/external_flash_patched.bin if [ -s $< ]; then \ ${OPENOCD} -f "openocd/interface_$(ADAPTER).cfg" \ -c "init; halt;" \ -c "program $< 0x90000000 $(PROGRAM_VERIFY);" \ -c "exit;" \ && make reset; \ fi .PHONY: flash_patched_ext flash_patched: flash_patched_int flash_patched_ext .PHONY: flash_patched flash: flash_patched .PHONY: flash # Useful when developing and you get distracted easily notify: @$(NOTIFY_COMMAND) .PHONY: notify flash_notify: flash notify .PHONY: flash_notify flash_stock_notify: flash_stock notify .PHONY: flash_stock_notify dump: arm-none-eabi-objdump -xDSs build/gw_patch.elf > dump.txt && vim dump.txt .PHONY: dump # Starts openocd and attaches to the target. To be used with 'flash_intflash_nc' and 'gdb' openocd: $(OPENOCD) -f openocd/interface_$(ADAPTER).cfg -c "init; halt" .PHONY: openocd gdb: $(BUILD_DIR)/$(TARGET).elf $(GDB) $< -ex "target extended-remote :3333" .PHONY: gdb start_bank_2: $(OPENOCD) -f openocd/interface_$(ADAPTER).cfg \ -c 'init; reset halt' \ -c 'set MSP 0x[string range [mdw 0x08100000] 12 19]' \ -c 'set PC 0x[string range [mdw 0x08100004] 12 19]' \ -c 'echo "Setting MSP -> $$MSP"' \ -c 'echo "Setting PC -> $$PC"' \ -c 'reg msp $$MSP' \ -c 'reg pc $$PC' \ -c 'resume;exit' .PHONY: start_bank_2 help: @$(PYTHON) patch.py --help @echo "" @echo "Commandline arguments:" @echo " PATCH_PARAMS - Options to pass to the python patching utility." @echo " Most options go here and will start with two dashes." @echo " ADAPTER - One of {stlink, jlink, rpi}. Defaults to stlink." @echo "" @echo "Example:" @echo " make PATCH_PARAMS=\"--sleep-time=120 --slim\" flash_patched_ext" ####################################### # clean up ####################################### clean: -rm -fR $(BUILD_DIR) ####################################### # dependencies ####################################### -include $(wildcard $(BUILD_DIR)/*.d) # *** EOF *** <|start_filename|>Core/Inc/ips.h<|end_filename|> #pragma once #include <stddef.h> #include <stdint.h> #include <stdbool.h> enum { IPS_PATCH_OK = 0, IPS_PATCH_WRONG_HEADER, }; typedef uint8_t ips_patch_res_t; ips_patch_res_t ips_patch(uint8_t *dst, const uint8_t *patch); <|start_filename|>Core/Inc/stock_firmware_mario.h<|end_filename|> #pragma once /** * */ void (* const stock_Reset_Handler)(void) = 0x08017a45; gamepad_t (* const stock_read_buttons)(void) = 0x08010d48 | THUMB; /** * Returns `true` if USB power is connected, `false` otherwise. */ bool (* const is_usb_connected)(void) = 0x08010dc2 | THUMB; /** * Put system to sleep. */ void (* const sleep)(void) = 0x080063a0 | THUMB; /** * Address for checking to see if we are in {Clock, BALL, SMB1, SMB2}. * See `get_gnw_mode()` */ volatile uint8_t * const gnw_mode_addr = 0x20001044; /** * This will most likely be overriden by the patcher. */ const uint8_t * const SMB1_ROM = 0x90001e60; #define SMB1_CLOCK_WORKING 0x24000000 uint8_t * const smb1_clock_working = SMB1_CLOCK_WORKING; uint8_t * const smb1_clock_graphics_working = SMB1_CLOCK_WORKING + 0x8000; volatile uint8_t * const ui_draw_status_addr = 0x20010694; /** * Function that loads the SMB1 rom into memory and prepares all the sprite * data. */ uint8_t * (* const stock_prepare_clock_rom)(uint8_t *src, size_t len) = 0x08010e10 | THUMB; <|start_filename|>Core/Inc/stock_firmware_common.h<|end_filename|> #pragma once #include <stddef.h> #include <stdint.h> #include <stdbool.h> #define THUMB 0x00000001 typedef uint16_t gamepad_t; /** * * Mapping * Note: * * if UP is pressed, it explicitly disables DOWN (UP gets priority) * * if RIGHT is pressed, it explicitly disables LEFT (RIGHT gets priority) * * Bit Pin Description * ------------------------- * 0 PD15 RIGHT * 1 PD11 LEFT * 2 PD14 DOWN * 3 PD0 UP * 4 PC11 START (if supported) * 5 PC12 SELECT (if supported) * 6 PD5 B * 7 PD9 A * 8 PC5 TIME * 9 PC13 PAUSE/SET * 10 PC1 GAME * 11 * 12 * 13 * 14 * 15 */ #define GAMEPAD_RIGHT ((gamepad_t) ( 1 << 0 )) #define GAMEPAD_LEFT ((gamepad_t) ( 1 << 1 )) #define GAMEPAD_DOWN ((gamepad_t) ( 1 << 2 )) #define GAMEPAD_UP ((gamepad_t) ( 1 << 3 )) #define GAMEPAD_START ((gamepad_t) ( 1 << 4 )) #define GAMEPAD_SELECT ((gamepad_t) ( 1 << 5 )) #define GAMEPAD_B ((gamepad_t) ( 1 << 6 )) #define GAMEPAD_A ((gamepad_t) ( 1 << 7 )) #define GAMEPAD_TIME ((gamepad_t) ( 1 << 8 )) #define GAMEPAD_PAUSE ((gamepad_t) ( 1 << 9 )) #define GAMEPAD_GAME ((gamepad_t) ( 1 << 10 )) <|start_filename|>Core/Inc/stock_firmware_zelda.h<|end_filename|> #pragma once void (* const stock_Reset_Handler)(void) = 0x0801ad49; gamepad_t (* const stock_read_buttons)(void) = 0x08016808 | THUMB;
unhold/game-and-watch-patch
<|start_filename|>fsw/unit_test/hs_test_utils.h<|end_filename|> /************************************************************************* ** File: hs_test_utils.h ** ** NASA Docket No. GSC-18,476-1, and identified as "Core Flight System ** (cFS) Health and Safety (HS) Application version 2.3.2” ** ** Copyright © 2020 United States Government as represented by the ** Administrator of the National Aeronautics and Space Administration. ** All Rights Reserved. ** ** 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. ** ** Purpose: ** This file contains the function prototypes and global variables for ** the unit test utilities for the HS application. ** *************************************************************************/ /* * Includes */ #include "hs_app.h" #include "ut_cfe_evs_hooks.h" #include "ut_cfe_time_stubs.h" #include "ut_cfe_psp_memutils_stubs.h" #include "ut_cfe_tbl_stubs.h" #include "ut_cfe_tbl_hooks.h" #include "ut_cfe_fs_stubs.h" #include "ut_cfe_time_stubs.h" #include "ut_osapi_stubs.h" #include "ut_osfileapi_stubs.h" #include "ut_cfe_sb_stubs.h" #include "ut_cfe_es_stubs.h" #include "ut_cfe_evs_stubs.h" #include <time.h> /* * Function Definitions */ void HS_Test_Setup(void); void HS_Test_TearDown(void); /************************/ /* End of File Comment */ /************************/ <|start_filename|>fsw/unit_test/hs_test_utils.c<|end_filename|> /************************************************************************* ** File: hs_test_utils.c ** ** NASA Docket No. GSC-18,476-1, and identified as "Core Flight System ** (cFS) Health and Safety (HS) Application version 2.3.2” ** ** Copyright © 2020 United States Government as represented by the ** Administrator of the National Aeronautics and Space Administration. ** All Rights Reserved. ** ** 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. ** ** Purpose: ** This file contains unit test utilities for the HS application. ** *************************************************************************/ /* * Includes */ #include "hs_test_utils.h" #include "hs_app.h" extern HS_AppData_t HS_AppData; /* * Function Definitions */ void HS_Test_Setup(void) { /* initialize test environment to default state for every test */ CFE_PSP_MemSet(&HS_AppData, 0, sizeof(HS_AppData_t)); Ut_CFE_EVS_Reset(); Ut_CFE_FS_Reset(); Ut_CFE_TIME_Reset(); Ut_CFE_TBL_Reset(); Ut_CFE_SB_Reset(); Ut_CFE_ES_Reset(); Ut_OSAPI_Reset(); Ut_OSFILEAPI_Reset(); } /* end HS_Test_Setup */ void HS_Test_TearDown(void) { /* cleanup test environment */ } /* end HS_Test_TearDown */ /************************/ /* End of File Comment */ /************************/ <|start_filename|>fsw/src/hs_utils.h<|end_filename|> /************************************************************************* ** File: hs_utils.h ** ** NASA Docket No. GSC-18,476-1, and identified as "Core Flight System ** (cFS) Health and Safety (HS) Application version 2.3.2" ** ** Copyright © 2020 United States Government as represented by the ** Administrator of the National Aeronautics and Space Administration. ** All Rights Reserved. ** ** 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. ** ** Purpose: ** Utility functions for the cFS Health and Safety (HS) application. ** **************************************************************************/ #ifndef _hs_utils_h_ #define _hs_utils_h_ /************************************************************************* ** Includes *************************************************************************/ #include "cfe.h" /************************************************************************/ /** \brief Verify message length ** ** \par Description ** Checks if the actual length of a software bus message matches ** the expected length and sends an error event if a mismatch ** occurs ** ** \par Assumptions, External Events, and Notes: ** None ** ** \param [in] msg A #CFE_SB_MsgPtr_t pointer that ** references the software bus message ** ** \param [in] ExpectedLength The expected length of the message ** based upon the command code ** ** \returns ** \retstmt Returns TRUE if the length is as expected \endcode ** \retstmt Returns FALSE if the length is not as expected \endcode ** \endreturns ** ** \sa #HS_LEN_ERR_EID ** *************************************************************************/ bool HS_VerifyMsgLength(CFE_SB_MsgPtr_t msg, uint16 ExpectedLength); /************************************************************************/ /** \brief Verify AMT Action Type ** ** \par Description ** Checks if the specified value is a valid AMT Action Type. ** ** \par Assumptions, External Events, and Notes: ** None ** ** \param [in] msg An ActionType to validate ** ** \returns ** \retstmt Returns TRUE if the ActionType is valid \endcode ** \retstmt Returns FALSE if the ActionType is not valid \endcode ** \endreturns ** *************************************************************************/ bool HS_AMTActionIsValid(uint16 ActionType); /************************************************************************/ /** \brief Verify EMT Action Type ** ** \par Description ** Checks if the specified value is a valid EMT Action Type. ** ** \par Assumptions, External Events, and Notes: ** None ** ** \param [in] msg An ActionType to validate ** ** \returns ** \retstmt Returns TRUE if the ActionType is valid \endcode ** \retstmt Returns FALSE if the ActionType is not valid \endcode ** \endreturns ** *************************************************************************/ bool HS_EMTActionIsValid(uint16 ActionType); #endif /* _hs_utils_h_ */ <|start_filename|>fsw/unit_test/hs_monitors_test.c<|end_filename|> /************************************************************************* ** File: hs_monitors_test.c ** ** NASA Docket No. GSC-18,476-1, and identified as "Core Flight System ** (cFS) Health and Safety (HS) Application version 2.3.2” ** ** Copyright © 2020 United States Government as represented by the ** Administrator of the National Aeronautics and Space Administration. ** All Rights Reserved. ** ** 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. ** ** Purpose: ** This file contains unit test cases for the functions contained in ** the file hs_monitors.c ** *************************************************************************/ /* * Includes */ #include "hs_monitors_test.h" #include "hs_app.h" #include "hs_monitors.h" #include "hs_custom.h" #include "hs_msg.h" #include "hs_msgdefs.h" #include "hs_msgids.h" #include "hs_events.h" #include "hs_version.h" #include "hs_test_utils.h" #include "ut_osapi_stubs.h" #include "ut_cfe_sb_stubs.h" #include "ut_cfe_es_stubs.h" #include "ut_cfe_es_hooks.h" #include "ut_cfe_evs_stubs.h" #include "ut_cfe_evs_hooks.h" #include "ut_cfe_time_stubs.h" #include "ut_cfe_psp_memutils_stubs.h" #include "ut_cfe_psp_watchdog_stubs.h" #include "ut_cfe_psp_timer_stubs.h" #include "ut_cfe_tbl_stubs.h" #include "ut_cfe_fs_stubs.h" #include "ut_cfe_time_stubs.h" #include <sys/fcntl.h> #include <unistd.h> #include <stdlib.h> /* * Function Definitions */ int32 HS_MONITORS_TEST_CFE_ES_GetAppInfoHook1(CFE_ES_AppInfo_t *AppInfo, uint32 AppId) { AppInfo->ExecutionCounter = 3; return CFE_SUCCESS; } void HS_MonitorApplications_Test_AppNameNotFound(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; HS_AppData.AMTablePtr[0].ActionType = -1; HS_AppData.AppMonCheckInCountdown[0] = 1; HS_AppData.AMTablePtr[0].CycleCount = 1; strncpy (HS_AppData.AMTablePtr[0].AppName, "AppName", 10); /* Set CFE_ES_GetAppIDByName to fail on first call, to generate error HS_APPMON_APPNAME_ERR_EID */ Ut_CFE_ES_SetReturnCode(UT_CFE_ES_GETAPPIDBYNAME_INDEX, -1, 1); /* Execute the function being tested */ HS_MonitorApplications(); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_APPMON_APPNAME_ERR_EID, CFE_EVS_ERROR, "App Monitor App Name not found: APP:(AppName)"), "App Monitor App Name not found: APP:(AppName)"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_MonitorApplications_Test_AppNameNotFound */ void HS_MonitorApplications_Test_GetExeCountFailure(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; HS_AppData.AMTablePtr[0].ActionType = -1; HS_AppData.AppMonCheckInCountdown[0] = 1; HS_AppData.AMTablePtr[0].CycleCount = 1; strncpy (HS_AppData.AMTablePtr[0].AppName, "AppName", 10); /* Causes "failure to get an execution counter" */ Ut_CFE_ES_SetFunctionHook(UT_CFE_ES_GETAPPINFO_INDEX, &HS_MONITORS_TEST_CFE_ES_GetAppInfoHook1); HS_AppData.AppMonLastExeCount[0] = 1; HS_AppData.AMTablePtr[0].CycleCount = 2; /* Execute the function being tested */ HS_MonitorApplications(); /* Verify results */ UtAssert_True (HS_AppData.AppMonCheckInCountdown[0] == 2, "HS_AppData.AppMonCheckInCountdown[0] == 2"); UtAssert_True (HS_AppData.AppMonLastExeCount[0] == 3, "HS_AppData.AppMonLastExeCount[0] == 3"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_MonitorApplications_Test_GetExeCountFailure */ void HS_MonitorApplications_Test_ProcessorResetError(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; HS_AppData.AMTablePtr[0].ActionType = HS_AMT_ACT_PROC_RESET; HS_AppData.AppMonCheckInCountdown[0] = 1; HS_AppData.AMTablePtr[0].CycleCount = 1; strncpy (HS_AppData.AMTablePtr[0].AppName, "AppName", 10); /* Prevents "failure to get an execution counter" */ Ut_CFE_ES_SetFunctionHook(UT_CFE_ES_GETAPPINFO_INDEX, &HS_MONITORS_TEST_CFE_ES_GetAppInfoHook1); HS_AppData.AppMonLastExeCount[0] = 3; HS_AppData.CDSData.MaxResets = 10; HS_AppData.CDSData.ResetsPerformed = 1; HS_AppData.AppMonEnables[0] = 1; /* Execute the function being tested */ HS_MonitorApplications(); /* Verify results */ UtAssert_True (HS_AppData.AppMonCheckInCountdown[0] == 0, "HS_AppData.AppMonCheckInCountdown[0] == 0"); UtAssert_True (HS_AppData.AppMonEnables[0] == 0, "HS_AppData.AppMonEnables[0] == 0"); UtAssert_True (HS_AppData.ServiceWatchdogFlag == HS_STATE_DISABLED, "HS_AppData.ServiceWatchdogFlag == HS_STATE_DISABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_APPMON_PROC_ERR_EID, CFE_EVS_ERROR, "App Monitor Failure: APP:(AppName): Action: Processor Reset"), "App Monitor Failure: APP:(AppName): Action: Processor Reset"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); UtAssert_True (Ut_CFE_ES_SysLogWritten("HS App: App Monitor Failure: APP:(AppName): Action: Processor Reset\n"), "HS App: App Monitor Failure: APP:(AppName): Action: Processor Reset"); UtAssert_True (Ut_CFE_ES_GetSysLogQueueDepth() == 1, "Ut_CFE_ES_GetSysLogQueueDepth() == 1"); } /* end HS_MonitorApplications_Test_ProcessorResetError */ void HS_MonitorApplications_Test_ProcessorResetActionLimitError(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; HS_AppData.AMTablePtr[0].ActionType = HS_AMT_ACT_PROC_RESET; HS_AppData.AppMonCheckInCountdown[0] = 1; HS_AppData.AMTablePtr[0].CycleCount = 1; strncpy (HS_AppData.AMTablePtr[0].AppName, "AppName", 10); /* Prevents "failure to get an execution counter" */ Ut_CFE_ES_SetFunctionHook(UT_CFE_ES_GETAPPINFO_INDEX, &HS_MONITORS_TEST_CFE_ES_GetAppInfoHook1); HS_AppData.AppMonLastExeCount[0] = 3; HS_AppData.CDSData.MaxResets = 10; HS_AppData.CDSData.ResetsPerformed = 11; HS_AppData.AppMonEnables[0] = 1; /* Execute the function being tested */ HS_MonitorApplications(); /* Verify results */ UtAssert_True (HS_AppData.AppMonCheckInCountdown[0] == 0, "HS_AppData.AppMonCheckInCountdown[0] == 0"); UtAssert_True (HS_AppData.AppMonEnables[0] == 0, "HS_AppData.AppMonEnables[0] == 0"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_APPMON_PROC_ERR_EID, CFE_EVS_ERROR, "App Monitor Failure: APP:(AppName): Action: Processor Reset"), "App Monitor Failure: APP:(AppName): Action: Processor Reset"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_RESET_LIMIT_ERR_EID, CFE_EVS_ERROR, "Processor Reset Action Limit Reached: No Reset Performed"), "Processor Reset Action Limit Reached: No Reset Performed"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_MonitorApplications_Test_ProcessorResetActionLimitError */ void HS_MonitorApplications_Test_RestartAppErrorsGetAppInfoSuccess(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; HS_AppData.AMTablePtr[0].ActionType = HS_AMT_ACT_APP_RESTART; HS_AppData.AppMonCheckInCountdown[0] = 1; HS_AppData.AMTablePtr[0].CycleCount = 1; strncpy (HS_AppData.AMTablePtr[0].AppName, "AppName", 10); /* Set CFE_ES_RestartApp to fail on first call, to generate error HS_APPMON_NOT_RESTARTED_ERR_EID */ Ut_CFE_ES_SetReturnCode(UT_CFE_ES_RESTARTAPP_INDEX, 0xFFFFFFFF, 1); /* Prevents "failure to get an execution counter" */ Ut_CFE_ES_SetFunctionHook(UT_CFE_ES_GETAPPINFO_INDEX, &HS_MONITORS_TEST_CFE_ES_GetAppInfoHook1); HS_AppData.AppMonLastExeCount[0] = 3; HS_AppData.AppMonEnables[0] = 1; /* Execute the function being tested */ HS_MonitorApplications(); /* Verify results */ UtAssert_True (HS_AppData.AppMonCheckInCountdown[0] == 0, "HS_AppData.AppMonCheckInCountdown[0] == 0"); UtAssert_True (HS_AppData.AppMonEnables[0] == 0, "HS_AppData.AppMonEnables[0] == 0"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_APPMON_RESTART_ERR_EID, CFE_EVS_ERROR, "App Monitor Failure: APP:(AppName) Action: Restart Application"), "App Monitor Failure: APP:(AppName) Action: Restart Application"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_APPMON_NOT_RESTARTED_ERR_EID, CFE_EVS_ERROR, "Call to Restart App Failed: APP:(AppName) ERR: 0xFFFFFFFF"), "Call to Restart App Failed: APP:(AppName) ERR: 0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_MonitorApplications_Test_RestartAppErrorsGetAppInfoSuccess */ void HS_MonitorApplications_Test_RestartAppErrorsGetAppInfoNotSuccess(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; HS_AppData.AMTablePtr[0].ActionType = HS_AMT_ACT_APP_RESTART; HS_AppData.AppMonCheckInCountdown[0] = 1; HS_AppData.AMTablePtr[0].CycleCount = 1; strncpy (HS_AppData.AMTablePtr[0].AppName, "AppName", 10); /* Set CFE_ES_GetAppInfo to fail on first call, to generate error HS_APPMON_NOT_RESTARTED_ERR_EID */ Ut_CFE_ES_SetReturnCode(UT_CFE_ES_GETAPPINFO_INDEX, -1, 1); HS_AppData.AppMonLastExeCount[0] = 3; HS_AppData.AppMonEnables[0] = 1; /* Execute the function being tested */ HS_MonitorApplications(); /* Verify results */ UtAssert_True (HS_AppData.AppMonCheckInCountdown[0] == 0, "HS_AppData.AppMonCheckInCountdown[0] == 0"); UtAssert_True (HS_AppData.AppMonEnables[0] == 0, "HS_AppData.AppMonEnables[0] == 0"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_APPMON_RESTART_ERR_EID, CFE_EVS_ERROR, "App Monitor Failure: APP:(AppName) Action: Restart Application"), "App Monitor Failure: APP:(AppName) Action: Restart Application"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_APPMON_NOT_RESTARTED_ERR_EID, CFE_EVS_ERROR, "Call to Restart App Failed: APP:(AppName) ERR: 0xFFFFFFFF"), "Call to Restart App Failed: APP:(AppName) ERR: 0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_MonitorApplications_Test_RestartAppErrorsGetAppInfoNotSuccess */ void HS_MonitorApplications_Test_FailError(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; HS_AppData.AMTablePtr[0].ActionType = HS_AMT_ACT_EVENT; HS_AppData.AppMonCheckInCountdown[0] = 1; HS_AppData.AMTablePtr[0].CycleCount = 1; strncpy (HS_AppData.AMTablePtr[0].AppName, "AppName", 10); /* Prevents "failure to get an execution counter" */ Ut_CFE_ES_SetFunctionHook(UT_CFE_ES_GETAPPINFO_INDEX, &HS_MONITORS_TEST_CFE_ES_GetAppInfoHook1); HS_AppData.AppMonLastExeCount[0] = 3; HS_AppData.AppMonEnables[0] = 1; /* Execute the function being tested */ HS_MonitorApplications(); /* Verify results */ UtAssert_True (HS_AppData.AppMonCheckInCountdown[0] == 0, "HS_AppData.AppMonCheckInCountdown[0] == 0"); UtAssert_True (HS_AppData.AppMonEnables[0] == 0, "HS_AppData.AppMonEnables[0] == 0"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_APPMON_FAIL_ERR_EID, CFE_EVS_ERROR, "App Monitor Failure: APP:(AppName): Action: Event Only"), "App Monitor Failure: APP:(AppName): Action: Event Only"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_MonitorApplications_Test_FailError */ void HS_MonitorApplications_Test_MsgActsNOACT(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; HS_AppData.MATablePtr = &MATable[0]; CFE_SB_InitMsg ((HS_NoArgsCmd_t *)&HS_AppData.MATablePtr[0].Message, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&HS_AppData.MATablePtr[0].Message, HS_NOOP_CC); HS_AppData.AMTablePtr = AMTable; HS_AppData.MATablePtr = MATable; HS_AppData.AMTablePtr[0].ActionType = HS_AMT_ACT_NOACT; /* Causes most of the function to be skipped, due to first if-statement */ HS_AppData.AppMonCheckInCountdown[0] = 1; HS_AppData.AMTablePtr[0].CycleCount = 1; HS_AppData.MsgActsState = HS_STATE_ENABLED; strncpy (HS_AppData.AMTablePtr[0].AppName, "AppName", 10); /* Prevents "failure to get an execution counter" */ Ut_CFE_ES_SetFunctionHook(UT_CFE_ES_GETAPPINFO_INDEX, &HS_MONITORS_TEST_CFE_ES_GetAppInfoHook1); HS_AppData.AppMonLastExeCount[0] = 3; HS_AppData.AppMonEnables[0] = 1; HS_AppData.MsgActCooldown[0] = 0; /* (HS_AMT_ACT_LAST_NONMSG + 1) - HS_AMT_ACT_LAST_NONMSG - 1 = 0 */ HS_AppData.MATablePtr[0].EnableState = HS_MAT_STATE_ENABLED; HS_AppData.MATablePtr[0].Cooldown = 1; /* Execute the function being tested */ HS_MonitorApplications(); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_MonitorApplications_Test_MsgActsNOACT */ void HS_MonitorApplications_Test_MsgActsErrorDefault(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; HS_AppData.MATablePtr = &MATable[0]; CFE_SB_InitMsg ((HS_NoArgsCmd_t *)&HS_AppData.MATablePtr[0].Message, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&HS_AppData.MATablePtr[0].Message, HS_NOOP_CC); HS_AppData.AMTablePtr = AMTable; HS_AppData.MATablePtr = MATable; HS_AppData.AMTablePtr[0].ActionType = HS_AMT_ACT_LAST_NONMSG + 1; HS_AppData.AppMonCheckInCountdown[0] = 1; HS_AppData.AMTablePtr[0].CycleCount = 1; HS_AppData.MsgActsState = HS_STATE_ENABLED; strncpy (HS_AppData.AMTablePtr[0].AppName, "AppName", 10); /* Prevents "failure to get an execution counter" */ Ut_CFE_ES_SetFunctionHook(UT_CFE_ES_GETAPPINFO_INDEX, &HS_MONITORS_TEST_CFE_ES_GetAppInfoHook1); HS_AppData.AppMonLastExeCount[0] = 3; HS_AppData.AppMonEnables[0] = 1; HS_AppData.MsgActCooldown[0] = 0; /* (HS_AMT_ACT_LAST_NONMSG + 1) - HS_AMT_ACT_LAST_NONMSG - 1 = 0 */ HS_AppData.MATablePtr[0].EnableState = HS_MAT_STATE_ENABLED; HS_AppData.MATablePtr[0].Cooldown = 1; /* Execute the function being tested */ HS_MonitorApplications(); /* Verify results */ UtAssert_True (HS_AppData.AppMonCheckInCountdown[0] == 0, "HS_AppData.AppMonCheckInCountdown[0] == 0"); UtAssert_True (HS_AppData.AppMonEnables[0] == 0, "HS_AppData.AppMonEnables[0] == 0"); UtAssert_True (HS_AppData.MsgActExec == 1, "HS_AppData.MsgActExec == 1"); UtAssert_True (HS_AppData.MsgActCooldown[0] == 1, "HS_AppData.MsgActCooldown[0] == 1"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_APPMON_MSGACTS_ERR_EID, CFE_EVS_ERROR, "App Monitor Failure: APP:(AppName): Action: Message Action Index: 0"), "App Monitor Failure: APP:(AppName): Action: Message Action Index: 0"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_MonitorApplications_Test_MsgActsErrorDefault */ void HS_MonitorEvent_Test_ProcErrorReset(void) { HS_EMTEntry_t EMTable[HS_MAX_MONITORED_APPS]; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; CFE_EVS_Packet_t Packet; HS_AppData.MATablePtr = &MATable[0]; CFE_SB_InitMsg (&Packet, HS_CMD_MID, sizeof(CFE_EVS_Packet_t), TRUE); Packet.Payload.PacketID.EventID = 3; HS_AppData.EMTablePtr = EMTable; HS_AppData.MATablePtr = MATable; HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_PROC_RESET; HS_AppData.EMTablePtr[0].EventID = Packet.Payload.PacketID.EventID; HS_AppData.CDSData.MaxResets = 10; HS_AppData.CDSData.ResetsPerformed = 1; strncpy (HS_AppData.EMTablePtr[0].AppName, "AppName", 10); strncpy (Packet.Payload.PacketID.AppName, "AppName", 10); /* Execute the function being tested */ HS_MonitorEvent((CFE_SB_MsgPtr_t)&Packet); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_PROC_ERR_EID, CFE_EVS_ERROR, "Event Monitor: APP:(AppName) EID:(3): Action: Processor Reset"), "Event Monitor: APP:(AppName) EID:(3): Action: Processor Reset"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); UtAssert_True (Ut_CFE_ES_SysLogWritten("HS App: Event Monitor: APP:(AppName) EID:(3): Action: Processor Reset\n"), "HS App: Event Monitor: APP:(AppName) EID:(3): Action: Processor Reset"); UtAssert_True (Ut_CFE_ES_GetSysLogQueueDepth() == 1, "Ut_CFE_ES_GetSysLogQueueDepth() == 1"); UtAssert_True (HS_AppData.ServiceWatchdogFlag == HS_STATE_DISABLED, "HS_AppData.ServiceWatchdogFlag == HS_STATE_DISABLED"); } /* end HS_MonitorEvent_Test_ProcErrorReset */ void HS_MonitorEvent_Test_ProcErrorNoReset(void) { HS_EMTEntry_t EMTable[HS_MAX_MONITORED_APPS]; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; CFE_EVS_Packet_t Packet; HS_AppData.MATablePtr = &MATable[0]; CFE_SB_InitMsg (&Packet, HS_CMD_MID, sizeof(CFE_EVS_Packet_t), TRUE); Packet.Payload.PacketID.EventID = 3; HS_AppData.EMTablePtr = EMTable; HS_AppData.MATablePtr = MATable; HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_PROC_RESET; HS_AppData.EMTablePtr[0].EventID = Packet.Payload.PacketID.EventID; HS_AppData.CDSData.MaxResets = 10; HS_AppData.CDSData.ResetsPerformed = 11; strncpy (HS_AppData.EMTablePtr[0].AppName, "AppName", 10); strncpy (Packet.Payload.PacketID.AppName, "AppName", 10); /* Execute the function being tested */ HS_MonitorEvent((CFE_SB_MsgPtr_t)&Packet); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_PROC_ERR_EID, CFE_EVS_ERROR, "Event Monitor: APP:(AppName) EID:(3): Action: Processor Reset"), "Event Monitor: APP:(AppName) EID:(3): Action: Processor Reset"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_RESET_LIMIT_ERR_EID, CFE_EVS_ERROR, "Processor Reset Action Limit Reached: No Reset Performed"), "Processor Reset Action Limit Reached: No Reset Performed"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_MonitorEvent_Test_ProcErrorNoReset */ void HS_MonitorEvent_Test_AppRestartErrors(void) { HS_EMTEntry_t EMTable[HS_MAX_MONITORED_APPS]; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; CFE_EVS_Packet_t Packet; HS_AppData.MATablePtr = &MATable[0]; CFE_SB_InitMsg (&Packet, HS_CMD_MID, sizeof(CFE_EVS_Packet_t), TRUE); Packet.Payload.PacketID.EventID = 3; HS_AppData.EMTablePtr = EMTable; HS_AppData.MATablePtr = MATable; HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_APP_RESTART; HS_AppData.EMTablePtr[0].EventID = Packet.Payload.PacketID.EventID; strncpy (HS_AppData.EMTablePtr[0].AppName, "AppName", 10); strncpy (Packet.Payload.PacketID.AppName, "AppName", 10); /* Set CFE_ES_RestartApp to return -1, in order to generate error message HS_EVENTMON_NOT_RESTARTED_ERR_EID */ Ut_CFE_ES_SetReturnCode(UT_CFE_ES_RESTARTAPP_INDEX, -1, 1); /* Execute the function being tested */ HS_MonitorEvent((CFE_SB_MsgPtr_t)&Packet); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_RESTART_ERR_EID, CFE_EVS_ERROR, "Event Monitor: APP:(AppName) EID:(3): Action: Restart Application"), "Event Monitor: APP:(AppName) EID:(3): Action: Restart Application"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_NOT_RESTARTED_ERR_EID, CFE_EVS_ERROR, "Call to Restart App Failed: APP:(AppName) ERR: 0xFFFFFFFF"), "Call to Restart App Failed: APP:(AppName) ERR: 0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_MonitorEvent_Test_AppRestartErrors */ void HS_MonitorEvent_Test_OnlySecondAppRestartError(void) { HS_EMTEntry_t EMTable[HS_MAX_MONITORED_APPS]; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; CFE_EVS_Packet_t Packet; HS_AppData.MATablePtr = &MATable[0]; CFE_SB_InitMsg (&Packet, HS_CMD_MID, sizeof(CFE_EVS_Packet_t), TRUE); Packet.Payload.PacketID.EventID = 3; HS_AppData.EMTablePtr = EMTable; HS_AppData.MATablePtr = MATable; HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_APP_RESTART; HS_AppData.EMTablePtr[0].EventID = Packet.Payload.PacketID.EventID; strncpy (HS_AppData.EMTablePtr[0].AppName, "AppName", 10); strncpy (Packet.Payload.PacketID.AppName, "AppName", 10); /* Set CFE_ES_GetAppIDByName to return -1, in order to generate error message HS_EVENTMON_NOT_RESTARTED_ERR_EID */ Ut_CFE_ES_SetReturnCode(UT_CFE_ES_GETAPPIDBYNAME_INDEX, -1, 1); /* Execute the function being tested */ HS_MonitorEvent((CFE_SB_MsgPtr_t)&Packet); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_NOT_RESTARTED_ERR_EID, CFE_EVS_ERROR, "Call to Restart App Failed: APP:(AppName) ERR: 0xFFFFFFFF"), "Call to Restart App Failed: APP:(AppName) ERR: 0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_MonitorEvent_Test_OnlySecondAppRestartError */ void HS_MonitorEvent_Test_DeleteErrors(void) { HS_EMTEntry_t EMTable[HS_MAX_MONITORED_APPS]; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; CFE_EVS_Packet_t Packet; HS_AppData.MATablePtr = &MATable[0]; CFE_SB_InitMsg (&Packet, HS_CMD_MID, sizeof(CFE_EVS_Packet_t), TRUE); Packet.Payload.PacketID.EventID = 3; HS_AppData.EMTablePtr = EMTable; HS_AppData.MATablePtr = MATable; HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_APP_DELETE; HS_AppData.EMTablePtr[0].EventID = Packet.Payload.PacketID.EventID; strncpy (HS_AppData.EMTablePtr[0].AppName, "AppName", 10); strncpy (Packet.Payload.PacketID.AppName, "AppName", 10); /* Set CFE_ES_DeleteApp to return -1, in order to generate error message HS_EVENTMON_NOT_DELETED_ERR_EID */ Ut_CFE_ES_SetReturnCode(UT_CFE_ES_DELETEAPP_INDEX, -1, 1); /* Execute the function being tested */ HS_MonitorEvent((CFE_SB_MsgPtr_t)&Packet); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_DELETE_ERR_EID, CFE_EVS_ERROR, "Event Monitor: APP:(AppName) EID:(3): Action: Delete Application"), "Event Monitor: APP:(AppName) EID:(3): Action: Delete Application"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_NOT_DELETED_ERR_EID, CFE_EVS_ERROR, "Call to Delete App Failed: APP:(AppName) ERR: 0xFFFFFFFF"), "Call to Delete App Failed: APP:(AppName) ERR: 0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_MonitorEvent_Test_DeleteErrors */ void HS_MonitorEvent_Test_OnlySecondDeleteError(void) { HS_EMTEntry_t EMTable[HS_MAX_MONITORED_APPS]; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; CFE_EVS_Packet_t Packet; HS_AppData.MATablePtr = &MATable[0]; CFE_SB_InitMsg (&Packet, HS_CMD_MID, sizeof(CFE_EVS_Packet_t), TRUE); Packet.Payload.PacketID.EventID = 3; HS_AppData.EMTablePtr = EMTable; HS_AppData.MATablePtr = MATable; HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_APP_DELETE; HS_AppData.EMTablePtr[0].EventID = Packet.Payload.PacketID.EventID; strncpy (HS_AppData.EMTablePtr[0].AppName, "AppName", 10); strncpy (Packet.Payload.PacketID.AppName, "AppName", 10); /* Set CFE_ES_GetAppIDByName to fail on first call, to generate error HS_EVENTMON_NOT_DELETED_ERR_EID */ Ut_CFE_ES_SetReturnCode(UT_CFE_ES_GETAPPIDBYNAME_INDEX, -1, 1); /* Execute the function being tested */ HS_MonitorEvent((CFE_SB_MsgPtr_t)&Packet); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_NOT_DELETED_ERR_EID, CFE_EVS_ERROR, "Call to Delete App Failed: APP:(AppName) ERR: 0xFFFFFFFF"), "Call to Delete App Failed: APP:(AppName) ERR: 0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_MonitorEvent_Test_OnlySecondDeleteError */ void HS_MonitorEvent_Test_MsgActsError(void) { HS_EMTEntry_t EMTable[HS_MAX_MONITORED_APPS]; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; CFE_EVS_Packet_t Packet; HS_AppData.MATablePtr = &MATable[0]; CFE_SB_InitMsg (&Packet, HS_CMD_MID, sizeof(CFE_EVS_Packet_t), TRUE); Packet.Payload.PacketID.EventID = 3; HS_AppData.EMTablePtr = EMTable; HS_AppData.MATablePtr = MATable; HS_AppData.EMTablePtr[0].ActionType = HS_AMT_ACT_LAST_NONMSG + 1; HS_AppData.EMTablePtr[0].EventID = Packet.Payload.PacketID.EventID; strncpy (HS_AppData.EMTablePtr[0].AppName, "AppName", 10); strncpy (Packet.Payload.PacketID.AppName, "AppName", 10); /* Set CFE_ES_DeleteApp to return -1, in order to generate error message HS_EVENTMON_NOT_DELETED_ERR_EID */ Ut_CFE_ES_SetReturnCode(UT_CFE_ES_DELETEAPP_INDEX, -1, 1); HS_AppData.MsgActsState = HS_STATE_ENABLED; HS_AppData.MsgActCooldown[0] = 0; HS_AppData.MATablePtr[0].EnableState = HS_MAT_STATE_ENABLED; HS_AppData.MATablePtr[0].Cooldown = 5; /* Execute the function being tested */ HS_MonitorEvent((CFE_SB_MsgPtr_t)&Packet); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_MSGACTS_ERR_EID, CFE_EVS_ERROR, "Event Monitor: APP:(AppName) EID:(3): Action: Message Action Index: 0"), "Event Monitor: APP:(AppName) EID:(3): Action: Message Action Index: 0"); UtAssert_True (HS_AppData.MsgActExec == 1, "HS_AppData.MsgActExec == 1"); UtAssert_True (HS_AppData.MsgActCooldown[0] == 5, "HS_AppData.MsgActCooldown[0] == 5"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_MonitorEvent_Test_MsgActsError */ void HS_MonitorUtilization_Test_HighCurrentUtil(void) { HS_CustomData.LastIdleTaskInterval = 1; HS_CustomData.UtilMult1 = -3; HS_CustomData.UtilMult2 = 1; HS_CustomData.UtilDiv = 1; HS_AppData.CurrentCPUUtilIndex = HS_UTIL_PEAK_NUM_INTERVAL - 2; /* Execute the function being tested */ HS_MonitorUtilization(); /* Verify results */ UtAssert_True (HS_AppData.UtilizationTracker[HS_AppData.CurrentCPUUtilIndex - 1] == HS_UTIL_PER_INTERVAL_TOTAL, "HS_AppData.UtilizationTracker[HS_AppData.CurrentCPUUtilIndex - 1] == HS_UTIL_PER_INTERVAL_TOTAL"); /* For this test case, we don't care about any messages or variables changed after this is set */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_MonitorUtilization_Test_HighCurrentUtil */ void HS_MonitorUtilization_Test_CurrentUtilLessThanZero(void) { HS_CustomData.LastIdleTaskInterval = 1; HS_CustomData.UtilMult1 = HS_UTIL_PER_INTERVAL_TOTAL + 1; HS_CustomData.UtilMult2 = 1; HS_CustomData.UtilDiv = 1; HS_AppData.CurrentCPUUtilIndex = 0; /* Execute the function being tested */ HS_MonitorUtilization(); /* Verify results */ UtAssert_True (HS_AppData.UtilizationTracker[HS_AppData.CurrentCPUUtilIndex - 1] == 0, "HS_AppData.UtilizationTracker[HS_AppData.CurrentCPUUtilIndex - 1] == 0"); /* For this test case, we don't care about any messages or variables changed after this is set */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_MonitorUtilization_Test_CurrentUtilLessThanZero */ void HS_MonitorUtilization_Test_CPUHogging(void) { HS_CustomData.LastIdleTaskInterval = 0; HS_CustomData.UtilMult1 = 1; HS_CustomData.UtilMult2 = 1; HS_CustomData.UtilDiv = 1; HS_AppData.CurrentCPUHogState = HS_STATE_ENABLED; HS_AppData.MaxCPUHoggingTime = 1; HS_AppData.CurrentCPUUtilIndex = HS_UTIL_PEAK_NUM_INTERVAL; /* Execute the function being tested */ HS_MonitorUtilization(); /* Verify results */ UtAssert_True (HS_AppData.CurrentCPUHoggingTime == 1, "HS_AppData.CurrentCPUHoggingTime == 1"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_CPUMON_HOGGING_ERR_EID, CFE_EVS_ERROR, "CPU Hogging Detected"), "CPU Hogging Detected"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); UtAssert_True (Ut_CFE_ES_SysLogWritten("HS App: CPU Hogging Detected\n"), "HS App: CPU Hogging Detected"); UtAssert_True (Ut_CFE_ES_GetSysLogQueueDepth() == 1, "Ut_CFE_ES_GetSysLogQueueDepth() == 1"); /* For this test case, we don't care about any variables changed after this message */ } /* end HS_MonitorUtilization_Test_CPUHogging */ void HS_MonitorUtilization_Test_CurrentCPUHogStateDisabled(void) { HS_CustomData.LastIdleTaskInterval = 0; HS_CustomData.UtilMult1 = 1; HS_CustomData.UtilMult2 = 1; HS_CustomData.UtilDiv = 1; HS_AppData.CurrentCPUHogState = HS_STATE_DISABLED; HS_AppData.MaxCPUHoggingTime = 1; HS_AppData.CurrentCPUUtilIndex = HS_UTIL_PEAK_NUM_INTERVAL; /* Execute the function being tested */ HS_MonitorUtilization(); /* Verify results */ UtAssert_True (HS_AppData.CurrentCPUHoggingTime == 0, "HS_AppData.CurrentCPUHoggingTime == 0"); /* For this test case, we don't care about any variables changed after this variable is set */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_MonitorUtilization_Test_CurrentCPUHogStateDisabled */ void HS_MonitorUtilization_Test_HighUtilIndex(void) { HS_CustomData.LastIdleTaskInterval = 0; HS_CustomData.UtilMult1 = 1; HS_CustomData.UtilMult2 = 1; HS_CustomData.UtilDiv = 1; HS_AppData.CurrentCPUHogState = HS_STATE_DISABLED; HS_AppData.MaxCPUHoggingTime = 1; HS_AppData.CurrentCPUUtilIndex = HS_UTIL_PEAK_NUM_INTERVAL - 1; /* Execute the function being tested */ HS_MonitorUtilization(); /* Verify results */ UtAssert_True (HS_AppData.CurrentCPUHoggingTime == 0, "HS_AppData.CurrentCPUHoggingTime == 0"); UtAssert_True (HS_AppData.UtilCpuAvg == (HS_UTIL_PER_INTERVAL_TOTAL / HS_UTIL_AVERAGE_NUM_INTERVAL) , "HS_AppData.UtilCpuAvg == (HS_UTIL_PER_INTERVAL_TOTAL / HS_UTIL_AVERAGE_NUM_INTERVAL)"); UtAssert_True (HS_AppData.UtilCpuPeak == HS_UTIL_PER_INTERVAL_TOTAL, "HS_AppData.UtilCpuPeak == HS_UTIL_PER_INTERVAL_TOTAL"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_MonitorUtilization_Test_HighUtilIndex */ void HS_MonitorUtilization_Test_LowUtilIndex(void) { HS_CustomData.LastIdleTaskInterval = 0; HS_CustomData.UtilMult1 = 1; HS_CustomData.UtilMult2 = 1; HS_CustomData.UtilDiv = 1; HS_AppData.CurrentCPUHogState = HS_STATE_DISABLED; HS_AppData.MaxCPUHoggingTime = 1; HS_AppData.CurrentCPUUtilIndex = 1; /* Execute the function being tested */ HS_MonitorUtilization(); /* Verify results */ UtAssert_True (HS_AppData.CurrentCPUHoggingTime == 0, "HS_AppData.CurrentCPUHoggingTime == 0"); UtAssert_True (HS_AppData.UtilCpuAvg == (HS_UTIL_PER_INTERVAL_TOTAL / HS_UTIL_AVERAGE_NUM_INTERVAL) , "HS_AppData.UtilCpuAvg == (HS_UTIL_PER_INTERVAL_TOTAL / HS_UTIL_AVERAGE_NUM_INTERVAL)"); UtAssert_True (HS_AppData.UtilCpuPeak == HS_UTIL_PER_INTERVAL_TOTAL, "HS_AppData.UtilCpuPeak == HS_UTIL_PER_INTERVAL_TOTAL"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_MonitorUtilization_Test_LowUtilIndex */ void HS_ValidateAMTable_Test_UnusedTableEntryCycleCountZero(void) { int32 Result; uint32 i; HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; for (i=0; i < HS_MAX_MONITORED_APPS; i++) { HS_AppData.AMTablePtr[i].ActionType = 99; HS_AppData.AMTablePtr[i].CycleCount = 0; HS_AppData.AMTablePtr[i].NullTerm = 0; } /* Execute the function being tested */ Result = HS_ValidateAMTable(HS_AppData.AMTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_AMTVAL_INF_EID, CFE_EVS_INFORMATION, "AppMon verify results: good = 0, bad = 0, unused = 32"), "AppMon verify results: good = 0, bad = 0, unused = 32"); UtAssert_True(Result == CFE_SUCCESS, "Result == CFE_SUCCESS"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ValidateAMTable_Test_UnusedTableEntryCycleCountZero */ void HS_ValidateAMTable_Test_UnusedTableEntryActionTypeNOACT(void) { int32 Result; uint32 i; HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; for (i=0; i < HS_MAX_MONITORED_APPS; i++) { HS_AppData.AMTablePtr[i].ActionType = HS_EMT_ACT_NOACT; HS_AppData.AMTablePtr[i].CycleCount = 1; HS_AppData.AMTablePtr[i].NullTerm = 0; } /* Execute the function being tested */ Result = HS_ValidateAMTable(HS_AppData.AMTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_AMTVAL_INF_EID, CFE_EVS_INFORMATION, "AppMon verify results: good = 0, bad = 0, unused = 32"), "AppMon verify results: good = 0, bad = 0, unused = 32"); UtAssert_True(Result == CFE_SUCCESS, "Result == CFE_SUCCESS"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ValidateAMTable_Test_UnusedTableEntryActionTypeNOACT */ void HS_ValidateAMTable_Test_BufferNotNull(void) { int32 Result; uint32 i; HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; for (i=0; i < HS_MAX_MONITORED_APPS; i++) { HS_AppData.AMTablePtr[i].ActionType = 99; HS_AppData.AMTablePtr[i].CycleCount = 1; HS_AppData.AMTablePtr[i].NullTerm = 2; } strncpy(HS_AppData.AMTablePtr[0].AppName, "AppName", OS_MAX_API_NAME); /* Execute the function being tested */ Result = HS_ValidateAMTable(HS_AppData.AMTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_AMTVAL_ERR_EID, CFE_EVS_ERROR, "AppMon verify err: Entry = 0, Err = -2, Action = 99, App = AppName"), "AppMon verify err: Entry = 0, Err = -2, Action = 99, App = AppName"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_AMTVAL_INF_EID, CFE_EVS_INFORMATION, "AppMon verify results: good = 0, bad = 32, unused = 0"), "AppMon verify results: good = 0, bad = 32, unused = 0"); UtAssert_True(Result == HS_AMTVAL_ERR_NUL, "Result == HS_AMTVAL_ERR_NUL"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_ValidateAMTable_Test_BufferNotNull */ void HS_ValidateAMTable_Test_ActionTypeNotValid(void) { int32 Result; uint32 i; HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; for (i=0; i < HS_MAX_MONITORED_APPS; i++) { HS_AppData.AMTablePtr[i].ActionType = HS_AMT_ACT_LAST_NONMSG + HS_MAX_MSG_ACT_TYPES + 1; HS_AppData.AMTablePtr[i].CycleCount = 1; HS_AppData.AMTablePtr[i].NullTerm = 0; } strncpy(HS_AppData.AMTablePtr[0].AppName, "AppName", OS_MAX_API_NAME); /* Execute the function being tested */ Result = HS_ValidateAMTable(HS_AppData.AMTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_AMTVAL_INF_EID, CFE_EVS_INFORMATION, "AppMon verify results: good = 0, bad = 32, unused = 0"), "AppMon verify results: good = 0, bad = 32, unused = 0"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_AMTVAL_ERR_EID, CFE_EVS_ERROR, "AppMon verify err: Entry = 0, Err = -1, Action = 12, App = AppName"), "AppMon verify err: Entry = 0, Err = -1, Action = 12, App = AppName"); UtAssert_True(Result == HS_AMTVAL_ERR_ACT, "Result == HS_AMTVAL_ERR_ACT"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_ValidateAMTable_Test_ActionTypeNotValid */ void HS_ValidateAMTable_Test_EntryGood(void) { int32 Result; uint32 i; HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; for (i=0; i < HS_MAX_MONITORED_APPS; i++) { HS_AppData.AMTablePtr[i].ActionType = HS_AMT_ACT_LAST_NONMSG; HS_AppData.AMTablePtr[i].CycleCount = 1; HS_AppData.AMTablePtr[i].NullTerm = 0; } strncpy(HS_AppData.AMTablePtr[0].AppName, "AppName", OS_MAX_API_NAME); /* Execute the function being tested */ Result = HS_ValidateAMTable(HS_AppData.AMTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_AMTVAL_INF_EID, CFE_EVS_INFORMATION, "AppMon verify results: good = 32, bad = 0, unused = 0"), "AppMon verify results: good = 32, bad = 0, unused = 0"); UtAssert_True(Result == CFE_SUCCESS, "Result == CFE_SUCCESS"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ValidateAMTable_Test_EntryGood */ void HS_ValidateAMTable_Test_Null(void) { int32 Result; /* Execute the function being tested */ Result = HS_ValidateAMTable(NULL); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_AM_TBL_NULL_ERR_EID, CFE_EVS_ERROR, "Error in AM Table Validation. Table is null."), "Error in AM Table Validation. Table is null."); UtAssert_True(Result == HS_TBL_VAL_ERR, "Result == HS_TBL_VAL_ERR"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } void HS_ValidateEMTable_Test_UnusedTableEntryEventIDZero(void) { int32 Result; uint32 i; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_AppData.EMTablePtr = EMTable; for (i=0; i < HS_MAX_MONITORED_EVENTS; i++) { HS_AppData.EMTablePtr[i].ActionType = 99; HS_AppData.EMTablePtr[i].EventID = 0; HS_AppData.EMTablePtr[i].NullTerm = 0; } /* Execute the function being tested */ Result = HS_ValidateEMTable(HS_AppData.EMTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EMTVAL_INF_EID, CFE_EVS_INFORMATION, "EventMon verify results: good = 0, bad = 0, unused = 16"), "EventMon verify results: good = 0, bad = 0, unused = 16"); UtAssert_True(Result == CFE_SUCCESS, "Result == CFE_SUCCESS"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ValidateEMTable_Test_UnusedTableEntryEventIDZero */ void HS_ValidateEMTable_Test_UnusedTableEntryActionTypeNOACT(void) { int32 Result; uint32 i; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_AppData.EMTablePtr = EMTable; for (i=0; i < HS_MAX_MONITORED_EVENTS; i++) { HS_AppData.EMTablePtr[i].ActionType = HS_EMT_ACT_NOACT; HS_AppData.EMTablePtr[i].EventID = 1; HS_AppData.EMTablePtr[i].NullTerm = 0; } /* Execute the function being tested */ Result = HS_ValidateEMTable(HS_AppData.EMTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EMTVAL_INF_EID, CFE_EVS_INFORMATION, "EventMon verify results: good = 0, bad = 0, unused = 16"), "EventMon verify results: good = 0, bad = 0, unused = 16"); UtAssert_True(Result == CFE_SUCCESS, "Result == CFE_SUCCESS"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ValidateEMTable_Test_UnusedTableEntryActionTypeNOACT */ void HS_ValidateEMTable_Test_BufferNotNull(void) { int32 Result; uint32 i; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_AppData.EMTablePtr = EMTable; for (i=0; i < HS_MAX_MONITORED_EVENTS; i++) { HS_AppData.EMTablePtr[i].ActionType = 99; HS_AppData.EMTablePtr[i].EventID = 1; HS_AppData.EMTablePtr[i].NullTerm = 2; } strncpy(HS_AppData.EMTablePtr[0].AppName, "AppName", OS_MAX_API_NAME); /* Execute the function being tested */ Result = HS_ValidateEMTable(HS_AppData.EMTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EMTVAL_ERR_EID, CFE_EVS_ERROR, "EventMon verify err: Entry = 0, Err = -2, Action = 99, ID = 1 App = AppName"), "EventMon verify err: Entry = 0, Err = -2, Action = 99, ID = 1 App = AppName"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_EMTVAL_INF_EID, CFE_EVS_INFORMATION, "EventMon verify results: good = 0, bad = 16, unused = 0"), "EventMon verify results: good = 0, bad = 16, unused = 0"); UtAssert_True(Result == HS_EMTVAL_ERR_NUL, "Result == HS_EMTVAL_ERR_NUL"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_ValidateEMTable_Test_BufferNotNull */ void HS_ValidateEMTable_Test_ActionTypeNotValid(void) { int32 Result; uint32 i; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_AppData.EMTablePtr = EMTable; for (i=0; i < HS_MAX_MONITORED_EVENTS; i++) { HS_AppData.EMTablePtr[i].ActionType = HS_EMT_ACT_LAST_NONMSG + HS_MAX_MSG_ACT_TYPES + 1; HS_AppData.EMTablePtr[i].EventID = 1; HS_AppData.EMTablePtr[i].NullTerm = 0; } strncpy(HS_AppData.EMTablePtr[0].AppName, "AppName", OS_MAX_API_NAME); /* Execute the function being tested */ Result = HS_ValidateEMTable(HS_AppData.EMTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EMTVAL_INF_EID, CFE_EVS_INFORMATION, "EventMon verify results: good = 0, bad = 16, unused = 0"), "EventMon verify results: good = 0, bad = 16, unused = 0"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_EMTVAL_ERR_EID, CFE_EVS_ERROR, "EventMon verify err: Entry = 0, Err = -1, Action = 12, ID = 1 App = AppName"), "EventMon verify err: Entry = 0, Err = -1, Action = 12, ID = 1 App = AppName"); UtAssert_True(Result == HS_AMTVAL_ERR_ACT, "Result == HS_AMTVAL_ERR_ACT"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_ValidateEMTable_Test_ActionTypeNotValid */ void HS_ValidateEMTable_Test_EntryGood(void) { int32 Result; uint32 i; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_AppData.EMTablePtr = EMTable; for (i=0; i < HS_MAX_MONITORED_EVENTS; i++) { HS_AppData.EMTablePtr[i].ActionType = HS_EMT_ACT_LAST_NONMSG; HS_AppData.EMTablePtr[i].EventID = 1; HS_AppData.EMTablePtr[i].NullTerm = 0; } strncpy(HS_AppData.EMTablePtr[0].AppName, "AppName", OS_MAX_API_NAME); /* Execute the function being tested */ Result = HS_ValidateEMTable(HS_AppData.EMTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EMTVAL_INF_EID, CFE_EVS_INFORMATION, "EventMon verify results: good = 16, bad = 0, unused = 0"), "EventMon verify results: good = 16, bad = 0, unused = 0"); UtAssert_True(Result == CFE_SUCCESS, "Result == CFE_SUCCESS"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ValidateEMTable_Test_EntryGood */ void HS_ValidateEMTable_Test_Null(void) { int32 Result; /* Execute the function being tested */ Result = HS_ValidateEMTable(NULL); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_EM_TBL_NULL_ERR_EID, CFE_EVS_ERROR, "Error in EM Table Validation. Table is null."), "Error in EM Table Validation. Table is null."); UtAssert_True(Result == HS_TBL_VAL_ERR, "Result == HS_TBL_VAL_ERR"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_ValidateXCTable_Test_UnusedTableEntry(void) { int32 Result; uint32 i; HS_XCTEntry_t XCTable[HS_MAX_EXEC_CNT_SLOTS]; HS_AppData.XCTablePtr = XCTable; for (i=0; i < HS_MAX_EXEC_CNT_SLOTS; i++) { HS_AppData.XCTablePtr[i].ResourceType = HS_XCT_TYPE_NOTYPE; HS_AppData.XCTablePtr[i].NullTerm = 0; } /* Execute the function being tested */ Result = HS_ValidateXCTable(HS_AppData.XCTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_XCTVAL_INF_EID, CFE_EVS_INFORMATION, "ExeCount verify results: good = 0, bad = 0, unused = 32"), "ExeCount verify results: good = 0, bad = 0, unused = 32"); UtAssert_True(Result == CFE_SUCCESS, "Result == CFE_SUCCESS"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ValidateXCTable_Test_UnusedTableEntry */ #endif #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_ValidateXCTable_Test_BufferNotNull(void) { int32 Result; uint32 i; HS_XCTEntry_t XCTable[HS_MAX_EXEC_CNT_SLOTS]; HS_AppData.XCTablePtr = XCTable; for (i=0; i < HS_MAX_EXEC_CNT_SLOTS; i++) { HS_AppData.XCTablePtr[i].ResourceType = 99; HS_AppData.XCTablePtr[i].NullTerm = 1; } strncpy(HS_AppData.XCTablePtr[0].ResourceName, "ResourceName", OS_MAX_API_NAME); /* Execute the function being tested */ Result = HS_ValidateXCTable(HS_AppData.XCTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_XCTVAL_ERR_EID, CFE_EVS_ERROR, "ExeCount verify err: Entry = 0, Err = -2, Type = 99, Name = ResourceName"), "ExeCount verify err: Entry = 0, Err = -2, Type = 99, Name = ResourceName"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_XCTVAL_INF_EID, CFE_EVS_INFORMATION, "ExeCount verify results: good = 0, bad = 32, unused = 0"), "ExeCount verify results: good = 0, bad = 32, unused = 0"); UtAssert_True(Result == HS_XCTVAL_ERR_NUL, "Result == HS_XCTVAL_ERR_NUL"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_ValidateXCTable_Test_BufferNotNull */ #endif #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_ValidateXCTable_Test_ResourceTypeNotValid(void) { int32 Result; uint32 i; HS_XCTEntry_t XCTable[HS_MAX_EXEC_CNT_SLOTS]; HS_AppData.XCTablePtr = XCTable; for (i=0; i < HS_MAX_EXEC_CNT_SLOTS; i++) { HS_AppData.XCTablePtr[i].ResourceType = 99; HS_AppData.XCTablePtr[i].NullTerm = 0; } strncpy(HS_AppData.XCTablePtr[0].ResourceName, "ResourceName", OS_MAX_API_NAME); /* Execute the function being tested */ Result = HS_ValidateXCTable(HS_AppData.XCTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_XCTVAL_ERR_EID, CFE_EVS_ERROR, "ExeCount verify err: Entry = 0, Err = -1, Type = 99, Name = ResourceName"), "ExeCount verify err: Entry = 0, Err = -1, Type = 99, Name = ResourceName"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_XCTVAL_INF_EID, CFE_EVS_INFORMATION, "ExeCount verify results: good = 0, bad = 32, unused = 0"), "ExeCount verify results: good = 0, bad = 32, unused = 0"); UtAssert_True(Result == HS_XCTVAL_ERR_TYPE, "Result == HS_XCTVAL_ERR_TYPE"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_ValidateXCTable_Test_ResourceTypeNotValid */ #endif #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_ValidateXCTable_Test_EntryGood(void) { int32 Result; uint32 i; HS_XCTEntry_t XCTable[HS_MAX_EXEC_CNT_SLOTS]; HS_AppData.XCTablePtr = XCTable; for (i=0; i < HS_MAX_EXEC_CNT_SLOTS; i++) { HS_AppData.XCTablePtr[i].ResourceType = HS_XCT_TYPE_APP_MAIN; HS_AppData.XCTablePtr[i].NullTerm = 0; } /* Execute the function being tested */ Result = HS_ValidateXCTable(HS_AppData.XCTablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_XCTVAL_INF_EID, CFE_EVS_INFORMATION, "ExeCount verify results: good = 32, bad = 0, unused = 0"), "ExeCount verify results: good = 32, bad = 0, unused = 0"); UtAssert_True(Result == CFE_SUCCESS, "Result == CFE_SUCCESS"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ValidateXCTable_Test_EntryGood */ #endif #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_ValidateXCTable_Test_Null(void) { int32 Result; /* Execute the function being tested */ Result = HS_ValidateXCTable(NULL); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_XC_TBL_NULL_ERR_EID, CFE_EVS_ERROR, "Error in XC Table Validation. Table is null."), "Error in XC Table Validation. Table is null."); UtAssert_True(Result == HS_TBL_VAL_ERR, "Result == HS_TBL_VAL_ERR"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } #endif void HS_ValidateMATable_Test_UnusedTableEntry(void) { int32 Result; uint32 i; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; HS_AppData.MATablePtr = MATable; for (i=0; i < HS_MAX_MSG_ACT_TYPES; i++) { HS_AppData.MATablePtr[i].EnableState = HS_MAT_STATE_DISABLED; CFE_SB_InitMsg ((HS_NoArgsCmd_t *)&HS_AppData.MATablePtr[i].Message, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); } /* Execute the function being tested */ Result = HS_ValidateMATable(HS_AppData.MATablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_MATVAL_INF_EID, CFE_EVS_INFORMATION, "MsgActs verify results: good = 0, bad = 0, unused = 8"), "MsgActs verify results: good = 0, bad = 0, unused = 8"); UtAssert_True(Result == CFE_SUCCESS, "Result == CFE_SUCCESS"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ValidateMATable_Test_UnusedTableEntry */ void HS_ValidateMATable_Test_InvalidEnableState(void) { int32 Result; uint32 i; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; HS_AppData.MATablePtr = MATable; for (i=0; i < HS_MAX_MSG_ACT_TYPES; i++) { HS_AppData.MATablePtr[i].EnableState = 99; CFE_SB_InitMsg ((HS_NoArgsCmd_t *)&HS_AppData.MATablePtr[i].Message, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); } /* Execute the function being tested */ Result = HS_ValidateMATable(HS_AppData.MATablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_MATVAL_ERR_EID, CFE_EVS_ERROR, "MsgActs verify err: Entry = 0, Err = -3, Length = 8, ID = 6318"), "MsgActs verify err: Entry = 0, Err = -3, Length = 8, ID = 6318"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_MATVAL_INF_EID, CFE_EVS_INFORMATION, "MsgActs verify results: good = 0, bad = 8, unused = 0"), "MsgActs verify results: good = 0, bad = 8, unused = 0"); UtAssert_True(Result == HS_MATVAL_ERR_ENA, "Result == HS_MATVAL_ERR_ENA"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_ValidateMATable_Test_InvalidEnableState */ void HS_ValidateMATable_Test_MessageIDTooHigh(void) { int32 Result; uint32 i; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; HS_AppData.MATablePtr = MATable; for (i=0; i < HS_MAX_MSG_ACT_TYPES; i++) { HS_AppData.MATablePtr[i].EnableState = HS_MAT_STATE_ENABLED; CFE_SB_InitMsg ((HS_NoArgsCmd_t *)&HS_AppData.MATablePtr[i].Message, CFE_SB_HIGHEST_VALID_MSGID + 1, sizeof(HS_NoArgsCmd_t), TRUE); } /* Execute the function being tested */ Result = HS_ValidateMATable(HS_AppData.MATablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_MATVAL_ERR_EID, CFE_EVS_ERROR, "MsgActs verify err: Entry = 0, Err = -1, Length = 8, ID = 8192"), "MsgActs verify err: Entry = 0, Err = -1, Length = 8, ID = 8192"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_MATVAL_INF_EID, CFE_EVS_INFORMATION, "MsgActs verify results: good = 0, bad = 8, unused = 0"), "MsgActs verify results: good = 0, bad = 8, unused = 0"); UtAssert_True(Result == HS_MATVAL_ERR_ID, "Result == HS_MATVAL_ERR_ID"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_ValidateMATable_Test_MessageIDTooHigh */ void HS_ValidateMATable_Test_LengthTooHigh(void) { int32 Result; uint32 i; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; HS_AppData.MATablePtr = MATable; for (i=0; i < HS_MAX_MSG_ACT_TYPES; i++) { HS_AppData.MATablePtr[i].EnableState = HS_MAT_STATE_ENABLED; CFE_SB_InitMsg ((HS_NoArgsCmd_t *)&HS_AppData.MATablePtr[i].Message, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); } /* Causes Length to be set to satisfy condition (Length > CFE_SB_MAX_SB_MSG_SIZE) */ Ut_CFE_SB_SetReturnCode(UT_CFE_SB_GETTOTALMSGLENGTH_INDEX, CFE_SB_MAX_SB_MSG_SIZE + 1, 1); Ut_CFE_SB_ContinueReturnCodeAfterCountZero(UT_CFE_SB_GETTOTALMSGLENGTH_INDEX); /* Execute the function being tested */ Result = HS_ValidateMATable(HS_AppData.MATablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_MATVAL_ERR_EID, CFE_EVS_ERROR, "MsgActs verify err: Entry = 0, Err = -2, Length = 32769, ID = 6318"), "MsgActs verify err: Entry = 0, Err = -2, Length = 32769, ID = 6318"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_MATVAL_INF_EID, CFE_EVS_INFORMATION, "MsgActs verify results: good = 0, bad = 8, unused = 0"), "MsgActs verify results: good = 0, bad = 8, unused = 0"); UtAssert_True(Result == HS_MATVAL_ERR_LEN, "Result == HS_MATVAL_ERR_LEN"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 2, "Ut_CFE_EVS_GetEventQueueDepth() == 2"); } /* end HS_ValidateMATable_Test_LengthTooHigh */ void HS_ValidateMATable_Test_EntryGood(void) { int32 Result; uint32 i; HS_MATEntry_t MATable[HS_MAX_MSG_ACT_TYPES]; HS_AppData.MATablePtr = MATable; for (i=0; i < HS_MAX_MSG_ACT_TYPES; i++) { HS_AppData.MATablePtr[i].EnableState = HS_MAT_STATE_ENABLED; CFE_SB_InitMsg ((HS_NoArgsCmd_t *)&HS_AppData.MATablePtr[i].Message, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); } /* Execute the function being tested */ Result = HS_ValidateMATable(HS_AppData.MATablePtr); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_MATVAL_INF_EID, CFE_EVS_INFORMATION, "MsgActs verify results: good = 8, bad = 0, unused = 0"), "MsgActs verify results: good = 8, bad = 0, unused = 0"); UtAssert_True(Result == CFE_SUCCESS, "Result == CFE_SUCCESS"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ValidateMATable_Test_EntryGood */ void HS_ValidateMATable_Test_Null(void) { int32 Result; /* Execute the function being tested */ Result = HS_ValidateMATable(NULL); /* Verify results */ UtAssert_True (Ut_CFE_EVS_EventSent(HS_MA_TBL_NULL_ERR_EID, CFE_EVS_ERROR, "Error in MA Table Validation. Table is null."), "Error in MA Table Validation. Table is null."); UtAssert_True(Result == HS_TBL_VAL_ERR, "Result == HS_TBL_VAL_ERR"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } void HS_SetCDSData_Test(void) { uint16 ResetsPerformed = 1; uint16 MaxResets = 2; HS_AppData.CDSState = HS_STATE_ENABLED; /* Execute the function being tested */ HS_SetCDSData(ResetsPerformed, MaxResets); /* Verify results */ UtAssert_True(HS_AppData.CDSData.ResetsPerformed == 1, "HS_AppData.CDSData.ResetsPerformed == 1"); UtAssert_True(HS_AppData.CDSData.ResetsPerformedNot == (uint16)(~HS_AppData.CDSData.ResetsPerformed), "HS_AppData.CDSData.ResetsPerformedNot == (uint16)(~HS_AppData.CDSData.ResetsPerformed)"); UtAssert_True(HS_AppData.CDSData.MaxResets == 2, "HS_AppData.CDSData.MaxResets == 2"); UtAssert_True(HS_AppData.CDSData.MaxResetsNot == (uint16)(~HS_AppData.CDSData.MaxResets), "HS_AppData.CDSData.MaxResetsNot == (uint16)(~HS_AppData.CDSData.MaxResets)"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_SetCDSData_Test */ void HS_Monitors_Test_AddTestCases(void) { UtTest_Add(HS_MonitorApplications_Test_AppNameNotFound, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorApplications_Test_AppNameNotFound"); UtTest_Add(HS_MonitorApplications_Test_GetExeCountFailure, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorApplications_Test_GetExeCountFailure"); UtTest_Add(HS_MonitorApplications_Test_ProcessorResetError, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorApplications_Test_ProcessorResetError"); UtTest_Add(HS_MonitorApplications_Test_ProcessorResetActionLimitError, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorApplications_Test_ProcessorResetActionLimitError"); UtTest_Add(HS_MonitorApplications_Test_RestartAppErrorsGetAppInfoSuccess, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorApplications_Test_RestartAppErrorsGetAppInfoSuccess"); UtTest_Add(HS_MonitorApplications_Test_RestartAppErrorsGetAppInfoNotSuccess, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorApplications_Test_RestartAppErrorsGetAppInfoNotSuccess"); UtTest_Add(HS_MonitorApplications_Test_FailError, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorApplications_Test_FailError"); UtTest_Add(HS_MonitorApplications_Test_MsgActsNOACT, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorApplications_Test_MsgActsNOACT"); UtTest_Add(HS_MonitorApplications_Test_MsgActsErrorDefault, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorApplications_Test_MsgActsErrorDefault"); UtTest_Add(HS_MonitorEvent_Test_ProcErrorReset, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorEvent_Test_ProcErrorReset"); UtTest_Add(HS_MonitorEvent_Test_ProcErrorNoReset, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorEvent_Test_ProcErrorNoReset"); UtTest_Add(HS_MonitorEvent_Test_AppRestartErrors, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorEvent_Test_AppRestartErrors"); UtTest_Add(HS_MonitorEvent_Test_OnlySecondAppRestartError, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorEvent_Test_OnlySecondAppRestartError"); UtTest_Add(HS_MonitorEvent_Test_DeleteErrors, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorEvent_Test_DeleteErrors"); UtTest_Add(HS_MonitorEvent_Test_OnlySecondDeleteError, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorEvent_Test_OnlySecondDeleteError"); UtTest_Add(HS_MonitorEvent_Test_MsgActsError, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorEvent_Test_MsgActsError"); UtTest_Add(HS_MonitorUtilization_Test_HighCurrentUtil, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorUtilization_Test_HighCurrentUtil"); UtTest_Add(HS_MonitorUtilization_Test_CurrentUtilLessThanZero, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorUtilization_Test_CurrentUtilLessThanZero"); UtTest_Add(HS_MonitorUtilization_Test_CPUHogging, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorUtilization_Test_CPUHogging"); UtTest_Add(HS_MonitorUtilization_Test_CurrentCPUHogStateDisabled, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorUtilization_Test_CurrentCPUHogStateDisabled"); UtTest_Add(HS_MonitorUtilization_Test_HighUtilIndex, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorUtilization_Test_HighUtilIndex"); UtTest_Add(HS_MonitorUtilization_Test_LowUtilIndex, HS_Test_Setup, HS_Test_TearDown, "HS_MonitorUtilization_Test_LowUtilIndex"); UtTest_Add(HS_ValidateAMTable_Test_UnusedTableEntryCycleCountZero, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateAMTable_Test_UnusedTableEntryCycleCountZero"); UtTest_Add(HS_ValidateAMTable_Test_UnusedTableEntryActionTypeNOACT, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateAMTable_Test_UnusedTableEntryActionTypeNOACT"); UtTest_Add(HS_ValidateAMTable_Test_BufferNotNull, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateAMTable_Test_BufferNotNull"); UtTest_Add(HS_ValidateAMTable_Test_ActionTypeNotValid, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateAMTable_Test_ActionTypeNotValid"); UtTest_Add(HS_ValidateAMTable_Test_EntryGood, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateAMTable_Test_EntryGood"); UtTest_Add(HS_ValidateAMTable_Test_Null, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateAMTable_Test_Null"); UtTest_Add(HS_ValidateEMTable_Test_UnusedTableEntryEventIDZero, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateEMTable_Test_UnusedTableEntryEventIDZero"); UtTest_Add(HS_ValidateEMTable_Test_UnusedTableEntryActionTypeNOACT, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateEMTable_Test_UnusedTableEntryActionTypeNOACT"); UtTest_Add(HS_ValidateEMTable_Test_BufferNotNull, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateEMTable_Test_BufferNotNull"); UtTest_Add(HS_ValidateEMTable_Test_ActionTypeNotValid, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateEMTable_Test_ActionTypeNotValid"); UtTest_Add(HS_ValidateEMTable_Test_EntryGood, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateEMTable_Test_EntryGood"); UtTest_Add(HS_ValidateEMTable_Test_Null, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateEMTable_Test_Null"); #if HS_MAX_EXEC_CNT_SLOTS != 0 UtTest_Add(HS_ValidateXCTable_Test_UnusedTableEntry, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateXCTable_Test_UnusedTableEntry"); UtTest_Add(HS_ValidateXCTable_Test_BufferNotNull, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateXCTable_Test_BufferNotNull"); UtTest_Add(HS_ValidateXCTable_Test_ResourceTypeNotValid, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateXCTable_Test_ResourceTypeNotValid"); UtTest_Add(HS_ValidateXCTable_Test_EntryGood, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateXCTable_Test_EntryGood"); UtTest_Add(HS_ValidateXCTable_Test_Null, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateXCTable_Test_Null"); #endif UtTest_Add(HS_ValidateMATable_Test_UnusedTableEntry, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateMATable_Test_UnusedTableEntry"); UtTest_Add(HS_ValidateMATable_Test_InvalidEnableState, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateMATable_Test_InvalidEnableState"); UtTest_Add(HS_ValidateMATable_Test_MessageIDTooHigh, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateMATable_Test_MessageIDTooHigh"); UtTest_Add(HS_ValidateMATable_Test_LengthTooHigh, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateMATable_Test_LengthTooHigh"); UtTest_Add(HS_ValidateMATable_Test_EntryGood, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateMATable_Test_EntryGood"); UtTest_Add(HS_ValidateMATable_Test_Null, HS_Test_Setup, HS_Test_TearDown, "HS_ValidateMATable_Test_Null"); UtTest_Add(HS_SetCDSData_Test, HS_Test_Setup, HS_Test_TearDown, "HS_SetCDSData_Test"); } /* end HS_Monitors_Test_AddTestCases */ /************************/ /* End of File Comment */ /************************/ <|start_filename|>fsw/unit_test/hs_utils_test.c<|end_filename|> /************************************************************************* ** File: hs_utils_test.c ** ** NASA Docket No. GSC-18,476-1, and identified as "Core Flight System ** (cFS) Health and Safety (HS) Application version 2.3.2” ** ** Copyright © 2020 United States Government as represented by the ** Administrator of the National Aeronautics and Space Administration. ** All Rights Reserved. ** ** 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. ** ** Purpose: ** This file contains unit test cases for the functions contained in ** the file hs_utils.c ** *************************************************************************/ /* * Includes */ #include "hs_monitors_test.h" #include "hs_app.h" #include "hs_msg.h" #include "hs_msgdefs.h" #include "hs_msgids.h" #include "hs_events.h" #include "hs_version.h" #include "hs_test_utils.h" #include "ut_osapi_stubs.h" #include "ut_cfe_sb_stubs.h" #include "ut_cfe_es_stubs.h" #include "ut_cfe_es_hooks.h" #include "ut_cfe_evs_stubs.h" #include "ut_cfe_evs_hooks.h" #include "ut_cfe_time_stubs.h" #include "ut_cfe_psp_memutils_stubs.h" #include "ut_cfe_psp_watchdog_stubs.h" #include "ut_cfe_psp_timer_stubs.h" #include "ut_cfe_tbl_stubs.h" #include "ut_cfe_fs_stubs.h" #include "ut_cfe_time_stubs.h" #include <sys/fcntl.h> #include <unistd.h> #include <stdlib.h> /* * Function Definitions */ void HS_VerifyMsgLength_Test_Nominal(void) { HS_NoArgsCmd_t CmdPacket; boolean Result; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_CPUHOG_CC); /* Execute the function being tested */ Result = HS_VerifyMsgLength((CFE_SB_MsgPtr_t)&CmdPacket, sizeof(HS_NoArgsCmd_t)); /* Verify results */ UtAssert_True (Result == TRUE, "Result == TRUE"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_VerifyMsgLength_Test_Nominal */ void HS_VerifyMsgLength_Test_LengthErrorHK(void) { HS_NoArgsCmd_t CmdPacket; boolean Result; CFE_SB_InitMsg (&CmdPacket, HS_SEND_HK_MID, 1, TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, 0); /* Execute the function being tested */ Result = HS_VerifyMsgLength((CFE_SB_MsgPtr_t)&CmdPacket, sizeof(HS_NoArgsCmd_t)); /* Verify results */ UtAssert_True (Result == FALSE, "Result == FALSE"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_HKREQ_LEN_ERR_EID, CFE_EVS_ERROR, "Invalid HK request msg length: ID = 0x18AF, CC = 0, Len = 1, Expected = 8"), "Invalid HK request msg length: ID = 0x18AF, CC = 0, Len = 1, Expected = 8"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_VerifyMsgLength_Test_LengthErrorHK */ void HS_VerifyMsgLength_Test_LengthErrorNonHK(void) { HS_NoArgsCmd_t CmdPacket; boolean Result; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, 1, TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, 0); /* Execute the function being tested */ Result = HS_VerifyMsgLength((CFE_SB_MsgPtr_t)&CmdPacket, sizeof(HS_NoArgsCmd_t)); /* Verify results */ UtAssert_True (Result == FALSE, "Result == FALSE"); UtAssert_True (HS_AppData.CmdErrCount == 1, "HS_AppData.CmdErrCount == 1"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_LEN_ERR_EID, CFE_EVS_ERROR, "Invalid msg length: ID = 0x18AE, CC = 0, Len = 1, Expected = 8"), "Invalid msg length: ID = 0x18AE, CC = 0, Len = 1, Expected = 8"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_VerifyMsgLength_Test_LengthErrorNonHK */ void HS_AMTActionIsValid_Valid(void) { uint16 Action = (HS_AMT_ACT_LAST_NONMSG + HS_MAX_MSG_ACT_TYPES); boolean Result = HS_AMTActionIsValid(Action); UtAssert_True(Result == TRUE, "Result == TRUE"); } void HS_AMTActionIsValid_Invalid(void) { uint16 Action = (HS_AMT_ACT_LAST_NONMSG + HS_MAX_MSG_ACT_TYPES + 1); boolean Result = HS_AMTActionIsValid(Action); UtAssert_True(Result == FALSE, "Result == FALSE"); } void HS_EMTActionIsValid_Valid(void) { uint16 Action = (HS_EMT_ACT_LAST_NONMSG + HS_MAX_MSG_ACT_TYPES); boolean Result = HS_EMTActionIsValid(Action); UtAssert_True(Result == TRUE, "Result == TRUE"); } void HS_EMTActionIsValid_Invalid(void) { uint16 Action = (HS_EMT_ACT_LAST_NONMSG + HS_MAX_MSG_ACT_TYPES + 1); boolean Result = HS_EMTActionIsValid(Action); UtAssert_True(Result == FALSE, "Result == FALSE"); } void HS_Utils_Test_AddTestCases(void) { UtTest_Add(HS_VerifyMsgLength_Test_Nominal, HS_Test_Setup, HS_Test_TearDown, "HS_VerifyMsgLength_Test_Nominal"); UtTest_Add(HS_VerifyMsgLength_Test_LengthErrorHK, HS_Test_Setup, HS_Test_TearDown, "HS_VerifyMsgLength_Test_LengthErrorHK"); UtTest_Add(HS_VerifyMsgLength_Test_LengthErrorNonHK, HS_Test_Setup, HS_Test_TearDown, "HS_VerifyMsgLength_Test_LengthErrorNonHK"); UtTest_Add(HS_AMTActionIsValid_Valid, HS_Test_Setup, HS_Test_TearDown, "HS_AMTActionIsValid_Valid"); UtTest_Add(HS_AMTActionIsValid_Invalid, HS_Test_Setup, HS_Test_TearDown, "HS_AMTActionIsValid_Invalid"); UtTest_Add(HS_EMTActionIsValid_Valid, HS_Test_Setup, HS_Test_TearDown, "HS_EMTActionIsValid_Valid"); UtTest_Add(HS_EMTActionIsValid_Invalid, HS_Test_Setup, HS_Test_TearDown, "HS_EMTActionIsValid_Invalid"); } <|start_filename|>fsw/tables/hs_amt.c<|end_filename|> /************************************************************************ ** File: hs_amt.c ** ** NASA Docket No. GSC-18,476-1, and identified as "Core Flight System ** (cFS) Health and Safety (HS) Application version 2.3.2” ** ** Copyright © 2020 United States Government as represented by the ** Administrator of the National Aeronautics and Space Administration. ** All Rights Reserved. ** ** 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. ** ** Purpose: ** The CFS Health and Safety (HS) Applications Monitor Table Definition ** *************************************************************************/ /************************************************************************ ** Includes *************************************************************************/ #include "cfe.h" #include "hs_tbl.h" #include "hs_tbldefs.h" #include "cfe_tbl_filedef.h" static CFE_TBL_FileDef_t CFE_TBL_FileDef __attribute__((__used__)) = { "HS_Default_AppMon_Tbl", HS_APP_NAME ".AppMon_Tbl", "HS AppMon Table", "hs_amt.tbl", (sizeof(HS_AMTEntry_t) * HS_MAX_MONITORED_APPS) }; HS_AMTEntry_t HS_Default_AppMon_Tbl[HS_MAX_MONITORED_APPS] = { /* AppName NullTerm CycleCount ActionType */ /* 0 */ { "CFE_ES", 0, 10, HS_AMT_ACT_NOACT }, /* 1 */ { "CFE_EVS", 0, 10, HS_AMT_ACT_NOACT }, /* 2 */ { "CFE_TIME", 0, 10, HS_AMT_ACT_NOACT }, /* 3 */ { "CFE_TBL", 0, 10, HS_AMT_ACT_NOACT }, /* 4 */ { "CFE_SB", 0, 10, HS_AMT_ACT_NOACT }, /* 5 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 6 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 7 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 8 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 9 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 10 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 11 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 12 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 13 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 14 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 15 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 16 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 17 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 18 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 19 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 20 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 21 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 22 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 23 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 24 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 25 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 26 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 27 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 28 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 29 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 30 */ { "", 0, 10, HS_AMT_ACT_NOACT }, /* 31 */ { "", 0, 10, HS_AMT_ACT_NOACT }, }; /************************/ /* End of File Comment */ /************************/ <|start_filename|>fsw/src/hs_app.c<|end_filename|> /************************************************************************ ** File: hs_app.c ** ** NASA Docket No. GSC-18,476-1, and identified as "Core Flight System ** (cFS) Health and Safety (HS) Application version 2.3.2” ** ** Copyright © 2020 United States Government as represented by the ** Administrator of the National Aeronautics and Space Administration. ** All Rights Reserved. ** ** 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. ** ** Purpose: ** The CFS Health and Safety (HS) provides several utilities including ** application monitoring, event monitoring, cpu utilization monitoring, ** aliveness indication, and watchdog servicing. ** ** *************************************************************************/ /************************************************************************ ** Includes *************************************************************************/ #include "hs_app.h" #include "hs_events.h" #include "hs_msgids.h" #include "hs_perfids.h" #include "hs_monitors.h" #include "hs_custom.h" #include "hs_version.h" #include "hs_cmds.h" #include "hs_verify.h" /************************************************************************ ** Macro Definitions *************************************************************************/ /************************************************************************ ** HS global data *************************************************************************/ HS_AppData_t HS_AppData; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* HS application entry point and main process loop */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void HS_AppMain(void) { int32 Status = CFE_SUCCESS; uint32 RunStatus = CFE_ES_RunStatus_APP_RUN; /* ** Performance Log, Start */ CFE_ES_PerfLogEntry(HS_APPMAIN_PERF_ID); /* ** Register this application with Executive Services */ Status = CFE_ES_RegisterApp(); /* ** Perform application specific initialization */ if (Status == CFE_SUCCESS) { Status = HS_AppInit(); } /* ** If no errors were detected during initialization, then wait for everyone to start */ if (Status == CFE_SUCCESS) { CFE_ES_WaitForStartupSync(HS_STARTUP_SYNC_TIMEOUT); /* ** Enable and set the watchdog timer */ CFE_PSP_WatchdogSet(HS_WATCHDOG_TIMEOUT_VALUE); CFE_PSP_WatchdogService(); CFE_PSP_WatchdogEnable(); CFE_PSP_WatchdogService(); /* ** Subscribe to Event Messages */ if (HS_AppData.CurrentEventMonState == HS_STATE_ENABLED) { Status = CFE_SB_SubscribeEx(CFE_EVS_LONG_EVENT_MSG_MID, HS_AppData.EventPipe, CFE_SB_Default_Qos, HS_EVENT_PIPE_DEPTH); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_SUB_EVS_ERR_EID, CFE_EVS_EventType_ERROR, "Error Subscribing to Events,RC=0x%08X",(unsigned int)Status); } } } if (Status != CFE_SUCCESS) { /* ** Set run status to terminate main loop */ RunStatus = CFE_ES_RunStatus_APP_ERROR; } /* ** Application main loop */ while(CFE_ES_RunLoop(&RunStatus) == true ) { /* ** Performance Log, Stop */ CFE_ES_PerfLogExit(HS_APPMAIN_PERF_ID); /* ** Task Delay for a configured timeout */ #if HS_POST_PROCESSING_DELAY != 0 OS_TaskDelay(HS_POST_PROCESSING_DELAY); #endif /* ** Task Delay for a configured timeout */ Status = CFE_SB_RcvMsg(&HS_AppData.MsgPtr, HS_AppData.WakeupPipe, HS_WAKEUP_TIMEOUT); /* ** Performance Log, Start */ CFE_ES_PerfLogEntry(HS_APPMAIN_PERF_ID); /* ** Process the software bus message */ if ((Status == CFE_SUCCESS) || (Status == CFE_SB_NO_MESSAGE) || (Status == CFE_SB_TIME_OUT)) { Status = HS_ProcessMain(); } /* ** Note: If there were some reason to exit the task ** normally (without error) then we would set ** RunStatus = CFE_ES_APP_EXIT */ if (Status != CFE_SUCCESS) { /* ** Set request to terminate main loop */ RunStatus = CFE_ES_RunStatus_APP_ERROR; } } /* end CFS_ES_RunLoop while */ /* ** Check for "fatal" process error... */ if (Status != CFE_SUCCESS) { /* ** Send an event describing the reason for the termination */ CFE_EVS_SendEvent(HS_APP_EXIT_EID, CFE_EVS_EventType_CRITICAL, "Application Terminating, err = 0x%08X", (unsigned int)Status); /* ** In case cFE Event Services is not working */ CFE_ES_WriteToSysLog("HS App: Application Terminating, ERR = 0x%08X\n", (unsigned int)Status); } HS_CustomCleanup(); /* ** Performance Log, Stop */ CFE_ES_PerfLogExit(HS_APPMAIN_PERF_ID); /* ** Exit the application */ CFE_ES_ExitApp(RunStatus); } /* end HS_AppMain */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* HS initialization */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int32 HS_AppInit(void) { int32 Status = CFE_SUCCESS; /* ** Initialize operating data to default states... */ CFE_PSP_MemSet(&HS_AppData, 0, sizeof(HS_AppData_t)); HS_AppData.ServiceWatchdogFlag = HS_STATE_ENABLED; HS_AppData.RunStatus = CFE_ES_RunStatus_APP_RUN; HS_AppData.CurrentAppMonState = HS_APPMON_DEFAULT_STATE; HS_AppData.CurrentEventMonState = HS_EVENTMON_DEFAULT_STATE; HS_AppData.CurrentAlivenessState = HS_ALIVENESS_DEFAULT_STATE; HS_AppData.CurrentCPUHogState = HS_CPUHOG_DEFAULT_STATE; #if HS_MAX_EXEC_CNT_SLOTS != 0 HS_AppData.ExeCountState = HS_STATE_ENABLED; #else HS_AppData.ExeCountState = HS_STATE_DISABLED; #endif HS_AppData.MsgActsState = HS_STATE_ENABLED; HS_AppData.AppMonLoaded = HS_STATE_ENABLED; HS_AppData.EventMonLoaded = HS_STATE_ENABLED; HS_AppData.CDSState = HS_STATE_ENABLED; HS_AppData.MaxCPUHoggingTime = HS_UTIL_HOGGING_TIMEOUT; /* ** Register for event services... */ Status = CFE_EVS_Register (NULL, 0, CFE_EVS_EventFilter_BINARY); if (Status != CFE_SUCCESS) { CFE_ES_WriteToSysLog("HS App: Error Registering For Event Services, RC = 0x%08X\n", (unsigned int)Status); return (Status); } /* ** Create Critical Data Store */ Status = CFE_ES_RegisterCDS(&HS_AppData.MyCDSHandle, sizeof(HS_CDSData_t), HS_CDSNAME); if (Status == CFE_ES_CDS_ALREADY_EXISTS) { /* ** Critical Data Store already existed, we need to get a ** copy of its current contents to see if we can use it */ Status = CFE_ES_RestoreFromCDS(&HS_AppData.CDSData, HS_AppData.MyCDSHandle); if (Status == CFE_SUCCESS) { if((HS_AppData.CDSData.ResetsPerformed != (uint16) ~HS_AppData.CDSData.ResetsPerformedNot) || (HS_AppData.CDSData.MaxResets != (uint16) ~HS_AppData.CDSData.MaxResetsNot)) { /* ** Report error restoring data */ CFE_EVS_SendEvent(HS_CDS_CORRUPT_ERR_EID, CFE_EVS_EventType_ERROR, "Data in CDS was corrupt, initializing resets data"); /* ** If data was corrupt, initialize data */ HS_SetCDSData(0, HS_MAX_RESTART_ACTIONS); } } else { /* ** Report error restoring data */ CFE_EVS_SendEvent(HS_CDS_RESTORE_ERR_EID, CFE_EVS_EventType_ERROR, "Failed to restore data from CDS (Err=0x%08x), initializing resets data", (unsigned int)Status); /* ** If data could not be retrieved, initialize data */ HS_SetCDSData(0, HS_MAX_RESTART_ACTIONS); } Status = CFE_SUCCESS; } else if (Status == CFE_SUCCESS) { /* ** If CDS did not previously exist, initialize data */ HS_SetCDSData(0, HS_MAX_RESTART_ACTIONS); } else { /* ** Disable saving to CDS */ HS_AppData.CDSState = HS_STATE_DISABLED; /* ** Initialize values anyway (they will not be saved) */ HS_SetCDSData(0, HS_MAX_RESTART_ACTIONS); } /* ** Set up the HS Software Bus */ Status = HS_SbInit(); if(Status != CFE_SUCCESS) { return (Status); } /* ** Register The HS Tables */ Status = HS_TblInit(); if(Status != CFE_SUCCESS) { return (Status); } /* ** Perform custom initialization (for cpu utilization monitoring) */ Status = HS_CustomInit(); if(Status != CFE_SUCCESS) { CFE_EVS_SendEvent (HS_CUSTOM_INIT_ERR_EID, CFE_EVS_EventType_ERROR, "Error in custom initialization, RC=0x%08X", Status); return (Status); } /* ** Application initialization event */ CFE_EVS_SendEvent (HS_INIT_EID, CFE_EVS_EventType_INFORMATION, "HS Initialized. Version %d.%d.%d.%d", HS_MAJOR_VERSION, HS_MINOR_VERSION, HS_REVISION, HS_MISSION_REV); return (Status); } /* end HS_AppInit */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Initialize the software bus interface */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int32 HS_SbInit(void) { int32 Status = CFE_SUCCESS; /* Initialize housekeeping packet */ CFE_SB_InitMsg(&HS_AppData.HkPacket,HS_HK_TLM_MID,sizeof(HS_HkPacket_t),true ); /* Create Command Pipe */ Status = CFE_SB_CreatePipe (&HS_AppData.CmdPipe,HS_CMD_PIPE_DEPTH,HS_CMD_PIPE_NAME); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_CR_CMD_PIPE_ERR_EID, CFE_EVS_EventType_ERROR, "Error Creating SB Command Pipe,RC=0x%08X",(unsigned int)Status); return (Status); } /* Create Event Pipe */ Status = CFE_SB_CreatePipe (&HS_AppData.EventPipe,HS_EVENT_PIPE_DEPTH,HS_EVENT_PIPE_NAME); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_CR_EVENT_PIPE_ERR_EID, CFE_EVS_EventType_ERROR, "Error Creating SB Event Pipe,RC=0x%08X",(unsigned int)Status); return (Status); } /* Create Wakeup Pipe */ Status = CFE_SB_CreatePipe (&HS_AppData.WakeupPipe,HS_WAKEUP_PIPE_DEPTH,HS_WAKEUP_PIPE_NAME); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_CR_WAKEUP_PIPE_ERR_EID, CFE_EVS_EventType_ERROR, "Error Creating SB Wakeup Pipe,RC=0x%08X",(unsigned int)Status); return (Status); } /* Subscribe to Housekeeping Request */ Status = CFE_SB_Subscribe(HS_SEND_HK_MID,HS_AppData.CmdPipe); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_SUB_REQ_ERR_EID, CFE_EVS_EventType_ERROR, "Error Subscribing to HK Request,RC=0x%08X",(unsigned int)Status); return (Status); } /* Subscribe to HS ground commands */ Status = CFE_SB_Subscribe(HS_CMD_MID,HS_AppData.CmdPipe); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_SUB_CMD_ERR_EID, CFE_EVS_EventType_ERROR, "Error Subscribing to Gnd Cmds,RC=0x%08X",(unsigned int)Status); return (Status); } /* Subscribe to HS Wakeup Message */ Status = CFE_SB_Subscribe(HS_WAKEUP_MID,HS_AppData.WakeupPipe); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_SUB_WAKEUP_ERR_EID, CFE_EVS_EventType_ERROR, "Error Subscribing to Wakeup,RC=0x%08X",(unsigned int)Status); return (Status); } /* ** Event message subscription delayed until after startup synch */ return(Status); } /* End of HS_SbInit() */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Initialize the table interface */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int32 HS_TblInit(void) { uint32 TableSize = 0; uint32 TableIndex = 0; int32 Status = CFE_SUCCESS; /* Register The HS Applications Monitor Table */ TableSize = HS_MAX_MONITORED_APPS * sizeof (HS_AMTEntry_t); Status = CFE_TBL_Register (&HS_AppData.AMTableHandle, HS_AMT_TABLENAME, TableSize, CFE_TBL_OPT_DEFAULT, HS_ValidateAMTable); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_AMT_REG_ERR_EID, CFE_EVS_EventType_ERROR, "Error Registering AppMon Table,RC=0x%08X",(unsigned int)Status); return (Status); } /* Register The HS Events Monitor Table */ TableSize = HS_MAX_MONITORED_EVENTS * sizeof (HS_EMTEntry_t); Status = CFE_TBL_Register (&HS_AppData.EMTableHandle, HS_EMT_TABLENAME, TableSize, CFE_TBL_OPT_DEFAULT, HS_ValidateEMTable); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_EMT_REG_ERR_EID, CFE_EVS_EventType_ERROR, "Error Registering EventMon Table,RC=0x%08X",(unsigned int)Status); return (Status); } /* Register The HS Message Actions Table */ TableSize = HS_MAX_MSG_ACT_TYPES * sizeof (HS_MATEntry_t); Status = CFE_TBL_Register (&HS_AppData.MATableHandle, HS_MAT_TABLENAME, TableSize, CFE_TBL_OPT_DEFAULT, HS_ValidateMATable); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_MAT_REG_ERR_EID, CFE_EVS_EventType_ERROR, "Error Registering MsgActs Table,RC=0x%08X",(unsigned int)Status); return (Status); } #if HS_MAX_EXEC_CNT_SLOTS != 0 /* Register The HS Execution Counters Table */ TableSize = HS_MAX_EXEC_CNT_SLOTS * sizeof (HS_XCTEntry_t); Status = CFE_TBL_Register (&HS_AppData.XCTableHandle, HS_XCT_TABLENAME, TableSize, CFE_TBL_OPT_DEFAULT, HS_ValidateXCTable); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_XCT_REG_ERR_EID, CFE_EVS_EventType_ERROR, "Error Registering ExeCount Table,RC=0x%08X",(unsigned int)Status); return (Status); } /* Load the HS Execution Counters Table */ Status = CFE_TBL_Load (HS_AppData.XCTableHandle, CFE_TBL_SRC_FILE, (const void *) HS_XCT_FILENAME); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_XCT_LD_ERR_EID, CFE_EVS_EventType_ERROR, "Error Loading ExeCount Table,RC=0x%08X",(unsigned int)Status); HS_AppData.ExeCountState = HS_STATE_DISABLED; for (TableIndex = 0; TableIndex < HS_MAX_EXEC_CNT_SLOTS; TableIndex++) { /* HS 8005.1 Report 0xFFFFFFFF for all entries */ HS_AppData.HkPacket.ExeCounts[TableIndex] = HS_INVALID_EXECOUNT; } } #endif /* Load the HS Applications Monitor Table */ Status = CFE_TBL_Load (HS_AppData.AMTableHandle, CFE_TBL_SRC_FILE, (const void *) HS_AMT_FILENAME); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_AMT_LD_ERR_EID, CFE_EVS_EventType_ERROR, "Error Loading AppMon Table,RC=0x%08X",(unsigned int)Status); HS_AppData.CurrentAppMonState = HS_STATE_DISABLED; CFE_EVS_SendEvent (HS_DISABLE_APPMON_ERR_EID, CFE_EVS_EventType_ERROR, "Application Monitoring Disabled due to Table Load Failure"); HS_AppData.AppMonLoaded = HS_STATE_DISABLED; } /* Load the HS Events Monitor Table */ Status = CFE_TBL_Load (HS_AppData.EMTableHandle, CFE_TBL_SRC_FILE, (const void *) HS_EMT_FILENAME); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_EMT_LD_ERR_EID, CFE_EVS_EventType_ERROR, "Error Loading EventMon Table,RC=0x%08X",(unsigned int)Status); HS_AppData.CurrentEventMonState = HS_STATE_DISABLED; CFE_EVS_SendEvent (HS_DISABLE_EVENTMON_ERR_EID, CFE_EVS_EventType_ERROR, "Event Monitoring Disabled due to Table Load Failure"); HS_AppData.EventMonLoaded = HS_STATE_DISABLED; } /* Load the HS Message Actions Table */ Status = CFE_TBL_Load (HS_AppData.MATableHandle, CFE_TBL_SRC_FILE, (const void *) HS_MAT_FILENAME); if (Status != CFE_SUCCESS) { CFE_EVS_SendEvent(HS_MAT_LD_ERR_EID, CFE_EVS_EventType_ERROR, "Error Loading MsgActs Table,RC=0x%08X",(unsigned int)Status); HS_AppData.MsgActsState = HS_STATE_DISABLED; } /* ** Get pointers to table data */ HS_AcquirePointers(); return CFE_SUCCESS; } /* End of HS_TblInit() */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Main Processing Loop */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int32 HS_ProcessMain(void) { int32 Status = CFE_SUCCESS; const char *AliveString = HS_CPU_ALIVE_STRING; uint32 i = 0; /* ** Get Tables */ HS_AcquirePointers(); /* ** Decrement Cooldowns for Message Actions */ for(i = 0; i < HS_MAX_MSG_ACT_TYPES; i++) { if(HS_AppData.MsgActCooldown[i] != 0) { HS_AppData.MsgActCooldown[i]--; } } /* ** Monitor Applications */ if (HS_AppData.CurrentAppMonState == HS_STATE_ENABLED) { HS_MonitorApplications(); } /* ** Monitor CPU Utilization */ HS_CustomMonitorUtilization(); /* ** Output Aliveness */ if (HS_AppData.CurrentAlivenessState == HS_STATE_ENABLED) { HS_AppData.AlivenessCounter++; if (HS_AppData.AlivenessCounter >= HS_CPU_ALIVE_PERIOD) { OS_printf("%s", AliveString); HS_AppData.AlivenessCounter = 0; } } /* ** Check for Commands, Events, and HK Requests */ Status = HS_ProcessCommands(); /* ** Service the Watchdog */ if (HS_AppData.ServiceWatchdogFlag == HS_STATE_ENABLED) { CFE_PSP_WatchdogService(); } return(Status); } /* End of HS_ProcessMain() */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Process any Commands and Event Messages received this cycle */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int32 HS_ProcessCommands(void) { int32 Status = CFE_SUCCESS; /* ** Event Message Pipe (done first so EventMon does not get enabled without table checking) */ if (HS_AppData.CurrentEventMonState == HS_STATE_ENABLED) { while (Status == CFE_SUCCESS) { Status = CFE_SB_RcvMsg(&HS_AppData.MsgPtr, HS_AppData.EventPipe, CFE_SB_POLL); if ((Status == CFE_SUCCESS) && (HS_AppData.MsgPtr != NULL)) { /* ** Pass Events to Event Monitor */ HS_AppData.EventsMonitoredCount++; HS_MonitorEvent(HS_AppData.MsgPtr); } } } if (Status == CFE_SB_NO_MESSAGE) { /* ** It's Good to not get a message -- we are polling */ Status = CFE_SUCCESS; } /* ** Command and HK Requests Pipe */ while (Status == CFE_SUCCESS) { /* ** Process pending Commands or HK Reqs */ Status = CFE_SB_RcvMsg(&HS_AppData.MsgPtr, HS_AppData.CmdPipe, CFE_SB_POLL); if ((Status == CFE_SUCCESS) && (HS_AppData.MsgPtr != NULL)) { /* ** Pass Commands/HK Req to AppPipe Processing */ HS_AppPipe(HS_AppData.MsgPtr); } } if (Status == CFE_SB_NO_MESSAGE) { /* ** It's Good to not get a message -- we are polling */ Status = CFE_SUCCESS; } return(Status); } /* End of HS_ProcessCommands() */ /************************/ /* End of File Comment */ /************************/ <|start_filename|>fsw/src/hs_utils.c<|end_filename|> /************************************************************************ ** File: hs_utils.c ** ** NASA Docket No. GSC-18,476-1, and identified as "Core Flight System ** (cFS) Health and Safety (HS) Application version 2.3.2" ** ** Copyright © 2020 United States Government as represented by the ** Administrator of the National Aeronautics and Space Administration. ** All Rights Reserved. ** ** 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. ** ** Purpose: ** Utility functions for the CFS Health and Safety (HS) application. ** *************************************************************************/ /************************************************************************ ** Includes *************************************************************************/ #include "hs_app.h" #include "hs_utils.h" #include "hs_custom.h" #include "hs_monitors.h" #include "hs_msgids.h" #include "hs_events.h" #include "hs_version.h" /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Verify message packet length */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ bool HS_VerifyMsgLength(CFE_SB_MsgPtr_t msg, uint16 ExpectedLength) { bool result = true ; uint16 CommandCode = 0; uint16 ActualLength = 0; CFE_SB_MsgId_t MessageID = 0; /* ** Verify the message packet length... */ ActualLength = CFE_SB_GetTotalMsgLength(msg); if (ExpectedLength != ActualLength) { MessageID = CFE_SB_GetMsgId(msg); CommandCode = CFE_SB_GetCmdCode(msg); if (MessageID == HS_SEND_HK_MID) { /* ** For a bad HK request, just send the event. We only increment ** the error counter for ground commands and not internal messages. */ CFE_EVS_SendEvent(HS_HKREQ_LEN_ERR_EID, CFE_EVS_EventType_ERROR, "Invalid HK request msg length: ID = 0x%04X, CC = %d, Len = %d, Expected = %d", MessageID, CommandCode, ActualLength, ExpectedLength); } else { /* ** All other cases, increment error counter */ CFE_EVS_SendEvent(HS_LEN_ERR_EID, CFE_EVS_EventType_ERROR, "Invalid msg length: ID = 0x%04X, CC = %d, Len = %d, Expected = %d", MessageID, CommandCode, ActualLength, ExpectedLength); HS_AppData.CmdErrCount++; } result = false ; } return(result); } /* End of HS_VerifyMsgLength */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Verify AMT Action Type */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ bool HS_AMTActionIsValid(uint16 ActionType) { bool IsValid = true ; if(ActionType < HS_AMT_ACT_NOACT) { IsValid = false ; } else if (ActionType > (HS_AMT_ACT_LAST_NONMSG + HS_MAX_MSG_ACT_TYPES)) { /* HS allows for HS_AMT_ACT_LAST_NONMSG actions by default and HS_MAX_MSG_ACT_TYPES message actions defined in the Message Action Table. */ IsValid = false ; } else { IsValid = true ; } return IsValid; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Verify EMT Action Type */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ bool HS_EMTActionIsValid(uint16 ActionType) { bool IsValid = true ; if(ActionType < HS_EMT_ACT_NOACT) { IsValid = false ; } else if (ActionType > (HS_EMT_ACT_LAST_NONMSG + HS_MAX_MSG_ACT_TYPES)) { /* HS allows for HS_EMT_ACT_LAST_NONMSG actions by default and HS_MAX_MSG_ACT_TYPES message actions defined in the Message Action Table. */ IsValid = false ; } else { IsValid = true ; } return IsValid; } <|start_filename|>fsw/unit_test/hs_cmds_test.c<|end_filename|> /************************************************************************* ** File: hs_cmds_test.c ** ** NASA Docket No. GSC-18,476-1, and identified as "Core Flight System ** (cFS) Health and Safety (HS) Application version 2.3.2” ** ** Copyright © 2020 United States Government as represented by the ** Administrator of the National Aeronautics and Space Administration. ** All Rights Reserved. ** ** 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. ** ** Purpose: ** This file contains unit test cases for the functions contained in ** the file hs_cmds.c ** *************************************************************************/ /* * Includes */ #include "hs_cmds_test.h" #include "hs_app.h" #include "hs_cmds.h" #include "hs_msg.h" #include "hs_msgdefs.h" #include "hs_msgids.h" #include "hs_events.h" #include "hs_version.h" #include "hs_utils.h" #include "hs_test_utils.h" #include "ut_osapi_stubs.h" #include "ut_cfe_sb_stubs.h" #include "ut_cfe_es_stubs.h" #include "ut_cfe_es_hooks.h" #include "ut_cfe_evs_stubs.h" #include "ut_cfe_evs_hooks.h" #include "ut_cfe_time_stubs.h" #include "ut_cfe_psp_memutils_stubs.h" #include "ut_cfe_psp_watchdog_stubs.h" #include "ut_cfe_psp_timer_stubs.h" #include "ut_cfe_tbl_stubs.h" #include "ut_cfe_fs_stubs.h" #include "ut_cfe_time_stubs.h" #include <sys/fcntl.h> #include <unistd.h> #include <stdlib.h> /* * Function Definitions */ int32 HS_CMDS_TEST_CFE_ES_GetTaskInfoHook(CFE_ES_TaskInfo_t *TaskInfo, uint32 TaskId) { TaskInfo->ExecutionCounter = 5; return CFE_SUCCESS; } void HS_AppPipe_Test_SendHK(void) { HS_NoArgsCmd_t CmdPacket; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_AppData.EMTablePtr = EMTable; CFE_SB_InitMsg (&CmdPacket, HS_SEND_HK_MID, sizeof(HS_NoArgsCmd_t), TRUE); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_AppPipe_Test_SendHK */ void HS_AppPipe_Test_Noop(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_NOOP_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_Noop */ void HS_AppPipe_Test_Reset(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_RESET_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_Reset */ void HS_AppPipe_Test_EnableAppMon(void) { HS_NoArgsCmd_t CmdPacket; HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_APPMON_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_EnableAppMon */ void HS_AppPipe_Test_DisableAppMon(void) { HS_NoArgsCmd_t CmdPacket; HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_DISABLE_APPMON_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_DisableAppMon */ void HS_AppPipe_Test_EnableEventMon(void) { HS_NoArgsCmd_t CmdPacket; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_AppData.EMTablePtr = EMTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_EVENTMON_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_EnableEventMon */ void HS_AppPipe_Test_DisableEventMon(void) { HS_NoArgsCmd_t CmdPacket; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_AppData.EMTablePtr = EMTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_DISABLE_EVENTMON_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_DisableEventMon */ void HS_AppPipe_Test_EnableAliveness(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_ALIVENESS_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_EnableAliveness */ void HS_AppPipe_Test_DisableAliveness(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_DISABLE_ALIVENESS_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_DisableAliveness */ void HS_AppPipe_Test_ResetResetsPerformed(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_RESET_RESETS_PERFORMED_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_ResetResetsPerformed */ void HS_AppPipe_Test_SetMaxResets(void) { HS_SetMaxResetsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_SetMaxResetsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_SET_MAX_RESETS_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_SetMaxResets */ void HS_AppPipe_Test_EnableCPUHog(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_CPUHOG_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_EnableCPUHog */ void HS_AppPipe_Test_DisableCPUHog(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_DISABLE_CPUHOG_CC); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); /* Generates 1 message we don't care about in this test */ } /* end HS_AppPipe_Test_DisableCPUHog */ void HS_AppPipe_Test_InvalidCC(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, 99); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdErrCount == 1, "HS_AppData.CmdErrCount == 1"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_CC_ERR_EID, CFE_EVS_ERROR, "Invalid command code: ID = 0x18AE, CC = 99"), "Invalid command code: ID = 0x18AE, CC = 99"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_AppPipe_Test_InvalidCC */ void HS_AppPipe_Test_InvalidMID(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, 255, sizeof(HS_NoArgsCmd_t), TRUE); /* Execute the function being tested */ HS_AppPipe((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdErrCount == 1, "HS_AppData.CmdErrCount == 1"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_MID_ERR_EID, CFE_EVS_ERROR, "Invalid command pipe message ID: 0x00FF"), "Invalid command pipe message ID: 0x00FF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_AppPipe_Test_InvalidMID */ void HS_HousekeepingReq_Test_InvalidEventMon(void) { HS_NoArgsCmd_t CmdPacket; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; uint32 TableIndex; HS_AppData.EMTablePtr = EMTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_EVENTMON_CC); HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_NOACT + 1; /* Satisfies condition "if (Status == CFE_ES_ERR_APPNAME)" */ Ut_CFE_ES_SetReturnCode(UT_CFE_ES_GETAPPIDBYNAME_INDEX, CFE_ES_ERR_APPNAME, 1); HS_AppData.CmdCount = 1; HS_AppData.CmdErrCount = 2; HS_AppData.CurrentAppMonState = 3; HS_AppData.CurrentEventMonState = 4; HS_AppData.CurrentAlivenessState = 5; HS_AppData.CurrentCPUHogState = 6; HS_AppData.CDSData.ResetsPerformed = 7; HS_AppData.CDSData.MaxResets = 8; HS_AppData.EventsMonitoredCount = 9; HS_AppData.MsgActExec = 10; for(TableIndex = 0; TableIndex <= ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE); TableIndex++) { HS_AppData.AppMonEnables[TableIndex] = TableIndex; } /* Execute the function being tested */ HS_HousekeepingReq((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.HkPacket.CmdCount == 1, "HS_AppData.HkPacket.CmdCount == 1"); UtAssert_True (HS_AppData.HkPacket.CmdErrCount == 2, "HS_AppData.HkPacket.CmdErrCount == 2"); UtAssert_True (HS_AppData.HkPacket.CurrentAppMonState == 3, "HS_AppData.HkPacket.CurrentAppMonState == 3"); UtAssert_True (HS_AppData.HkPacket.CurrentEventMonState == 4, "HS_AppData.HkPacket.CurrentEventMonState == 4"); UtAssert_True (HS_AppData.HkPacket.CurrentAlivenessState == 5, "HS_AppData.HkPacket.CurrentAlivenessState == 5"); UtAssert_True (HS_AppData.HkPacket.CurrentCPUHogState == 6, "HS_AppData.HkPacket.CurrentCPUHogState == 6"); UtAssert_True (HS_AppData.HkPacket.ResetsPerformed == 7, "HS_AppData.HkPacket.ResetsPerformed == 7"); UtAssert_True (HS_AppData.HkPacket.MaxResets == 8, "HS_AppData.HkPacket.MaxResets == 8"); UtAssert_True (HS_AppData.HkPacket.EventsMonitoredCount == 9, "HS_AppData.HkPacket.EventsMonitoredCount == 9"); UtAssert_True (HS_AppData.HkPacket.MsgActExec == 10, "HS_AppData.HkPacket.MsgActExec == 10"); UtAssert_True (HS_AppData.HkPacket.InvalidEventMonCount == 1, "HS_AppData.HkPacket.InvalidEventMonCount == 1"); /* Check first, middle, and last element */ UtAssert_True (HS_AppData.HkPacket.AppMonEnables[0] == 0, "HS_AppData.HkPacket.AppMonEnables[0] == 0"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[(HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_HousekeepingReq_Test_InvalidEventMon */ #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_HousekeepingReq_Test_AllFlagsEnabled(void) { HS_NoArgsCmd_t CmdPacket; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_XCTEntry_t XCTable[HS_MAX_EXEC_CNT_SLOTS]; uint8 ExpectedStatusFlags = 0; int i; for(i = 0; i < HS_MAX_EXEC_CNT_SLOTS; i++) { XCTable[i].ResourceType = HS_XCT_TYPE_NOTYPE; } HS_AppData.EMTablePtr = EMTable; HS_AppData.XCTablePtr = XCTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_EVENTMON_CC); HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_NOACT; HS_AppData.CmdCount = 1; HS_AppData.CmdErrCount = 2; HS_AppData.CurrentAppMonState = 3; HS_AppData.CurrentEventMonState = 4; HS_AppData.CurrentAlivenessState = 5; HS_AppData.CurrentCPUHogState = 6; HS_AppData.CDSData.ResetsPerformed = 7; HS_AppData.CDSData.MaxResets = 8; HS_AppData.EventsMonitoredCount = 9; HS_AppData.MsgActExec = 10; HS_AppData.ExeCountState = HS_STATE_ENABLED; HS_AppData.MsgActsState = HS_STATE_ENABLED; HS_AppData.AppMonLoaded = HS_STATE_ENABLED; HS_AppData.EventMonLoaded = HS_STATE_ENABLED; HS_AppData.CDSState = HS_STATE_ENABLED; ExpectedStatusFlags |= HS_LOADED_XCT; ExpectedStatusFlags |= HS_LOADED_MAT; ExpectedStatusFlags |= HS_LOADED_AMT; ExpectedStatusFlags |= HS_LOADED_EMT; ExpectedStatusFlags |= HS_CDS_IN_USE; /* Execute the function being tested */ HS_HousekeepingReq((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.HkPacket.CmdCount == 1, "HS_AppData.HkPacket.CmdCount == 1"); UtAssert_True (HS_AppData.HkPacket.CmdErrCount == 2, "HS_AppData.HkPacket.CmdErrCount == 2"); UtAssert_True (HS_AppData.HkPacket.CurrentAppMonState == 3, "HS_AppData.HkPacket.CurrentAppMonState == 3"); UtAssert_True (HS_AppData.HkPacket.CurrentEventMonState == 4, "HS_AppData.HkPacket.CurrentEventMonState == 4"); UtAssert_True (HS_AppData.HkPacket.CurrentAlivenessState == 5, "HS_AppData.HkPacket.CurrentAlivenessState == 5"); UtAssert_True (HS_AppData.HkPacket.CurrentCPUHogState == 6, "HS_AppData.HkPacket.CurrentCPUHogState == 6"); UtAssert_True (HS_AppData.HkPacket.ResetsPerformed == 7, "HS_AppData.HkPacket.ResetsPerformed == 7"); UtAssert_True (HS_AppData.HkPacket.MaxResets == 8, "HS_AppData.HkPacket.MaxResets == 8"); UtAssert_True (HS_AppData.HkPacket.EventsMonitoredCount == 9, "HS_AppData.HkPacket.EventsMonitoredCount == 9"); UtAssert_True (HS_AppData.HkPacket.MsgActExec == 10, "HS_AppData.HkPacket.MsgActExec == 10"); UtAssert_True (HS_AppData.HkPacket.InvalidEventMonCount == 0, "HS_AppData.HkPacket.InvalidEventMonCount == 0"); UtAssert_True (HS_AppData.HkPacket.StatusFlags == ExpectedStatusFlags, "HS_AppData.HkPacket.StatusFlags == ExpectedStatusFlags"); /* Check first, middle, and last element */ UtAssert_True (HS_AppData.HkPacket.AppMonEnables[0] == 0, "HS_AppData.HkPacket.AppMonEnables[0] == 0"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[(HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_HousekeepingReq_Test_AllFlagsEnabled */ #endif #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_HousekeepingReq_Test_ResourceTypeAppMain(void) { HS_NoArgsCmd_t CmdPacket; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_XCTEntry_t XCTable[HS_MAX_EXEC_CNT_SLOTS]; uint32 TableIndex; int i; for(i = 0; i < HS_MAX_EXEC_CNT_SLOTS; i++) { XCTable[i].ResourceType = HS_XCT_TYPE_APP_MAIN; } HS_AppData.EMTablePtr = EMTable; HS_AppData.XCTablePtr = XCTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_EVENTMON_CC); HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_NOACT; HS_AppData.CmdCount = 1; HS_AppData.CmdErrCount = 2; HS_AppData.CurrentAppMonState = 3; HS_AppData.CurrentEventMonState = 4; HS_AppData.CurrentAlivenessState = 5; HS_AppData.CurrentCPUHogState = 6; HS_AppData.CDSData.ResetsPerformed = 7; HS_AppData.CDSData.MaxResets = 8; HS_AppData.EventsMonitoredCount = 9; HS_AppData.MsgActExec = 10; for(TableIndex = 0; TableIndex <= ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE); TableIndex++) { HS_AppData.AppMonEnables[TableIndex] = TableIndex; } HS_AppData.ExeCountState = HS_STATE_ENABLED; HS_AppData.XCTablePtr[0].ResourceType = HS_XCT_TYPE_APP_MAIN; /* Causes line "Status = CFE_ES_GetTaskInfo(&TaskInfo, TaskId)" to be reached */ Ut_OSAPI_SetReturnCode(UT_OSAPI_TASKGETIDBYNAME_INDEX, OS_SUCCESS, 1); /* Sets TaskInfo.ExecutionCounter to 5, returns CFE_SUCCESS, goes to line "ExeCount = TaskInfo.ExecutionCounter" */ Ut_CFE_ES_SetFunctionHook(UT_CFE_ES_GETTASKINFO_INDEX, &HS_CMDS_TEST_CFE_ES_GetTaskInfoHook); /* Execute the function being tested */ HS_HousekeepingReq((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.HkPacket.CmdCount == 1, "HS_AppData.HkPacket.CmdCount == 1"); UtAssert_True (HS_AppData.HkPacket.CmdErrCount == 2, "HS_AppData.HkPacket.CmdErrCount == 2"); UtAssert_True (HS_AppData.HkPacket.CurrentAppMonState == 3, "HS_AppData.HkPacket.CurrentAppMonState == 3"); UtAssert_True (HS_AppData.HkPacket.CurrentEventMonState == 4, "HS_AppData.HkPacket.CurrentEventMonState == 4"); UtAssert_True (HS_AppData.HkPacket.CurrentAlivenessState == 5, "HS_AppData.HkPacket.CurrentAlivenessState == 5"); UtAssert_True (HS_AppData.HkPacket.CurrentCPUHogState == 6, "HS_AppData.HkPacket.CurrentCPUHogState == 6"); UtAssert_True (HS_AppData.HkPacket.ResetsPerformed == 7, "HS_AppData.HkPacket.ResetsPerformed == 7"); UtAssert_True (HS_AppData.HkPacket.MaxResets == 8, "HS_AppData.HkPacket.MaxResets == 8"); UtAssert_True (HS_AppData.HkPacket.EventsMonitoredCount == 9, "HS_AppData.HkPacket.EventsMonitoredCount == 9"); UtAssert_True (HS_AppData.HkPacket.MsgActExec == 10, "HS_AppData.HkPacket.MsgActExec == 10"); UtAssert_True (HS_AppData.HkPacket.InvalidEventMonCount == 0, "HS_AppData.HkPacket.InvalidEventMonCount == 0"); /* Check first, middle, and last element */ UtAssert_True (HS_AppData.HkPacket.AppMonEnables[0] == 0, "HS_AppData.HkPacket.AppMonEnables[0] == 0"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[(HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE"); UtAssert_True (HS_AppData.HkPacket.ExeCounts[0] == 5, "HS_AppData.HkPacket.ExeCounts[0] == 5"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_HousekeepingReq_Test_ResourceTypeAppMain */ #endif #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_HousekeepingReq_Test_ResourceTypeAppChild(void) { HS_NoArgsCmd_t CmdPacket; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_XCTEntry_t XCTable[HS_MAX_EXEC_CNT_SLOTS]; uint32 TableIndex; int i; for(i = 0; i < HS_MAX_EXEC_CNT_SLOTS; i++) { XCTable[i].ResourceType = HS_XCT_TYPE_APP_CHILD; } HS_AppData.EMTablePtr = EMTable; HS_AppData.XCTablePtr = XCTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_EVENTMON_CC); HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_NOACT; HS_AppData.CmdCount = 1; HS_AppData.CmdErrCount = 2; HS_AppData.CurrentAppMonState = 3; HS_AppData.CurrentEventMonState = 4; HS_AppData.CurrentAlivenessState = 5; HS_AppData.CurrentCPUHogState = 6; HS_AppData.CDSData.ResetsPerformed = 7; HS_AppData.CDSData.MaxResets = 8; HS_AppData.EventsMonitoredCount = 9; HS_AppData.MsgActExec = 10; for(TableIndex = 0; TableIndex <= ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE); TableIndex++) { HS_AppData.AppMonEnables[TableIndex] = TableIndex; } HS_AppData.ExeCountState = HS_STATE_ENABLED; HS_AppData.XCTablePtr[0].ResourceType = HS_XCT_TYPE_APP_CHILD; /* Causes line "Status = CFE_ES_GetTaskInfo(&TaskInfo, TaskId)" to be reached */ Ut_OSAPI_SetReturnCode(UT_OSAPI_TASKGETIDBYNAME_INDEX, OS_SUCCESS, 1); /* Sets TaskInfo.ExecutionCounter to 5, returns CFE_SUCCESS, goes to line "ExeCount = TaskInfo.ExecutionCounter" */ Ut_CFE_ES_SetFunctionHook(UT_CFE_ES_GETTASKINFO_INDEX, &HS_CMDS_TEST_CFE_ES_GetTaskInfoHook); /* Execute the function being tested */ HS_HousekeepingReq((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.HkPacket.CmdCount == 1, "HS_AppData.HkPacket.CmdCount == 1"); UtAssert_True (HS_AppData.HkPacket.CmdErrCount == 2, "HS_AppData.HkPacket.CmdErrCount == 2"); UtAssert_True (HS_AppData.HkPacket.CurrentAppMonState == 3, "HS_AppData.HkPacket.CurrentAppMonState == 3"); UtAssert_True (HS_AppData.HkPacket.CurrentEventMonState == 4, "HS_AppData.HkPacket.CurrentEventMonState == 4"); UtAssert_True (HS_AppData.HkPacket.CurrentAlivenessState == 5, "HS_AppData.HkPacket.CurrentAlivenessState == 5"); UtAssert_True (HS_AppData.HkPacket.CurrentCPUHogState == 6, "HS_AppData.HkPacket.CurrentCPUHogState == 6"); UtAssert_True (HS_AppData.HkPacket.ResetsPerformed == 7, "HS_AppData.HkPacket.ResetsPerformed == 7"); UtAssert_True (HS_AppData.HkPacket.MaxResets == 8, "HS_AppData.HkPacket.MaxResets == 8"); UtAssert_True (HS_AppData.HkPacket.EventsMonitoredCount == 9, "HS_AppData.HkPacket.EventsMonitoredCount == 9"); UtAssert_True (HS_AppData.HkPacket.MsgActExec == 10, "HS_AppData.HkPacket.MsgActExec == 10"); UtAssert_True (HS_AppData.HkPacket.InvalidEventMonCount == 0, "HS_AppData.HkPacket.InvalidEventMonCount == 0"); /* Check first, middle, and last element */ UtAssert_True (HS_AppData.HkPacket.AppMonEnables[0] == 0, "HS_AppData.HkPacket.AppMonEnables[0] == 0"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[(HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE"); UtAssert_True (HS_AppData.HkPacket.ExeCounts[0] == 5, "HS_AppData.HkPacket.ExeCounts[0] == 5"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_HousekeepingReq_Test_ResourceTypeAppChild */ #endif #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_HousekeepingReq_Test_ResourceTypeDevice(void) { HS_NoArgsCmd_t CmdPacket; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_XCTEntry_t XCTable[HS_MAX_EXEC_CNT_SLOTS]; uint32 TableIndex; int i; for(i = 0; i < HS_MAX_EXEC_CNT_SLOTS; i++) { XCTable[i].ResourceType = HS_XCT_TYPE_DEVICE; } HS_AppData.EMTablePtr = EMTable; HS_AppData.XCTablePtr = XCTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_EVENTMON_CC); HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_NOACT; HS_AppData.CmdCount = 1; HS_AppData.CmdErrCount = 2; HS_AppData.CurrentAppMonState = 3; HS_AppData.CurrentEventMonState = 4; HS_AppData.CurrentAlivenessState = 5; HS_AppData.CurrentCPUHogState = 6; HS_AppData.CDSData.ResetsPerformed = 7; HS_AppData.CDSData.MaxResets = 8; HS_AppData.EventsMonitoredCount = 9; HS_AppData.MsgActExec = 10; for(TableIndex = 0; TableIndex <= ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE); TableIndex++) { HS_AppData.AppMonEnables[TableIndex] = TableIndex; } HS_AppData.ExeCountState = HS_STATE_ENABLED; HS_AppData.XCTablePtr[0].ResourceType = HS_XCT_TYPE_DEVICE; /* Execute the function being tested */ HS_HousekeepingReq((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.HkPacket.CmdCount == 1, "HS_AppData.HkPacket.CmdCount == 1"); UtAssert_True (HS_AppData.HkPacket.CmdErrCount == 2, "HS_AppData.HkPacket.CmdErrCount == 2"); UtAssert_True (HS_AppData.HkPacket.CurrentAppMonState == 3, "HS_AppData.HkPacket.CurrentAppMonState == 3"); UtAssert_True (HS_AppData.HkPacket.CurrentEventMonState == 4, "HS_AppData.HkPacket.CurrentEventMonState == 4"); UtAssert_True (HS_AppData.HkPacket.CurrentAlivenessState == 5, "HS_AppData.HkPacket.CurrentAlivenessState == 5"); UtAssert_True (HS_AppData.HkPacket.CurrentCPUHogState == 6, "HS_AppData.HkPacket.CurrentCPUHogState == 6"); UtAssert_True (HS_AppData.HkPacket.ResetsPerformed == 7, "HS_AppData.HkPacket.ResetsPerformed == 7"); UtAssert_True (HS_AppData.HkPacket.MaxResets == 8, "HS_AppData.HkPacket.MaxResets == 8"); UtAssert_True (HS_AppData.HkPacket.EventsMonitoredCount == 9, "HS_AppData.HkPacket.EventsMonitoredCount == 9"); UtAssert_True (HS_AppData.HkPacket.MsgActExec == 10, "HS_AppData.HkPacket.MsgActExec == 10"); UtAssert_True (HS_AppData.HkPacket.InvalidEventMonCount == 0, "HS_AppData.HkPacket.InvalidEventMonCount == 0"); /* Check first, middle, and last element */ UtAssert_True (HS_AppData.HkPacket.AppMonEnables[0] == 0, "HS_AppData.HkPacket.AppMonEnables[0] == 0"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[(HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE"); UtAssert_True (HS_AppData.HkPacket.ExeCounts[0] == HS_INVALID_EXECOUNT, "HS_AppData.HkPacket.ExeCounts[0] == HS_INVALID_EXECOUNT"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_HousekeepingReq_Test_ResourceTypeDevice */ #endif #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_HousekeepingReq_Test_ResourceTypeISR(void) { HS_NoArgsCmd_t CmdPacket; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_XCTEntry_t XCTable[HS_MAX_EXEC_CNT_SLOTS]; uint32 TableIndex; int i; for(i = 0; i < HS_MAX_EXEC_CNT_SLOTS; i++) { XCTable[i].ResourceType = HS_XCT_TYPE_ISR; } HS_AppData.EMTablePtr = EMTable; HS_AppData.XCTablePtr = XCTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_EVENTMON_CC); HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_NOACT; HS_AppData.CmdCount = 1; HS_AppData.CmdErrCount = 2; HS_AppData.CurrentAppMonState = 3; HS_AppData.CurrentEventMonState = 4; HS_AppData.CurrentAlivenessState = 5; HS_AppData.CurrentCPUHogState = 6; HS_AppData.CDSData.ResetsPerformed = 7; HS_AppData.CDSData.MaxResets = 8; HS_AppData.EventsMonitoredCount = 9; HS_AppData.MsgActExec = 10; for(TableIndex = 0; TableIndex <= ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE); TableIndex++) { HS_AppData.AppMonEnables[TableIndex] = TableIndex; } HS_AppData.ExeCountState = HS_STATE_ENABLED; HS_AppData.XCTablePtr[0].ResourceType = HS_XCT_TYPE_ISR; /* Execute the function being tested */ HS_HousekeepingReq((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.HkPacket.CmdCount == 1, "HS_AppData.HkPacket.CmdCount == 1"); UtAssert_True (HS_AppData.HkPacket.CmdErrCount == 2, "HS_AppData.HkPacket.CmdErrCount == 2"); UtAssert_True (HS_AppData.HkPacket.CurrentAppMonState == 3, "HS_AppData.HkPacket.CurrentAppMonState == 3"); UtAssert_True (HS_AppData.HkPacket.CurrentEventMonState == 4, "HS_AppData.HkPacket.CurrentEventMonState == 4"); UtAssert_True (HS_AppData.HkPacket.CurrentAlivenessState == 5, "HS_AppData.HkPacket.CurrentAlivenessState == 5"); UtAssert_True (HS_AppData.HkPacket.CurrentCPUHogState == 6, "HS_AppData.HkPacket.CurrentCPUHogState == 6"); UtAssert_True (HS_AppData.HkPacket.ResetsPerformed == 7, "HS_AppData.HkPacket.ResetsPerformed == 7"); UtAssert_True (HS_AppData.HkPacket.MaxResets == 8, "HS_AppData.HkPacket.MaxResets == 8"); UtAssert_True (HS_AppData.HkPacket.EventsMonitoredCount == 9, "HS_AppData.HkPacket.EventsMonitoredCount == 9"); UtAssert_True (HS_AppData.HkPacket.MsgActExec == 10, "HS_AppData.HkPacket.MsgActExec == 10"); UtAssert_True (HS_AppData.HkPacket.InvalidEventMonCount == 0, "HS_AppData.HkPacket.InvalidEventMonCount == 0"); /* Check first, middle, and last element */ UtAssert_True (HS_AppData.HkPacket.AppMonEnables[0] == 0, "HS_AppData.HkPacket.AppMonEnables[0] == 0"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[(HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE"); UtAssert_True (HS_AppData.HkPacket.ExeCounts[0] == HS_INVALID_EXECOUNT, "HS_AppData.HkPacket.ExeCounts[0] == HS_INVALID_EXECOUNT"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_HousekeepingReq_Test_ResourceTypeISR */ #endif #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_HousekeepingReq_Test_ResourceTypeUnknown(void) { HS_NoArgsCmd_t CmdPacket; HS_EMTEntry_t EMTable[HS_MAX_MONITORED_EVENTS]; HS_XCTEntry_t XCTable[HS_MAX_EXEC_CNT_SLOTS]; uint8 ExpectedStatusFlags = 0; int i; /* Set the XCTable Resource type to something invalid */ for(i = 0; i < HS_MAX_EXEC_CNT_SLOTS; i++) { XCTable[i].ResourceType = (HS_XCT_TYPE_ISR * 2); } HS_AppData.EMTablePtr = EMTable; HS_AppData.XCTablePtr = XCTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_EVENTMON_CC); HS_AppData.EMTablePtr[0].ActionType = HS_EMT_ACT_NOACT; HS_AppData.CmdCount = 1; HS_AppData.CmdErrCount = 2; HS_AppData.CurrentAppMonState = 3; HS_AppData.CurrentEventMonState = 4; HS_AppData.CurrentAlivenessState = 5; HS_AppData.CurrentCPUHogState = 6; HS_AppData.CDSData.ResetsPerformed = 7; HS_AppData.CDSData.MaxResets = 8; HS_AppData.EventsMonitoredCount = 9; HS_AppData.MsgActExec = 10; HS_AppData.ExeCountState = HS_STATE_ENABLED; HS_AppData.MsgActsState = HS_STATE_ENABLED; HS_AppData.AppMonLoaded = HS_STATE_ENABLED; HS_AppData.EventMonLoaded = HS_STATE_ENABLED; HS_AppData.CDSState = HS_STATE_ENABLED; ExpectedStatusFlags |= HS_LOADED_XCT; ExpectedStatusFlags |= HS_LOADED_MAT; ExpectedStatusFlags |= HS_LOADED_AMT; ExpectedStatusFlags |= HS_LOADED_EMT; ExpectedStatusFlags |= HS_CDS_IN_USE; /* Execute the function being tested */ HS_HousekeepingReq((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.HkPacket.CmdCount == 1, "HS_AppData.HkPacket.CmdCount == 1"); UtAssert_True (HS_AppData.HkPacket.CmdErrCount == 2, "HS_AppData.HkPacket.CmdErrCount == 2"); UtAssert_True (HS_AppData.HkPacket.CurrentAppMonState == 3, "HS_AppData.HkPacket.CurrentAppMonState == 3"); UtAssert_True (HS_AppData.HkPacket.CurrentEventMonState == 4, "HS_AppData.HkPacket.CurrentEventMonState == 4"); UtAssert_True (HS_AppData.HkPacket.CurrentAlivenessState == 5, "HS_AppData.HkPacket.CurrentAlivenessState == 5"); UtAssert_True (HS_AppData.HkPacket.CurrentCPUHogState == 6, "HS_AppData.HkPacket.CurrentCPUHogState == 6"); UtAssert_True (HS_AppData.HkPacket.ResetsPerformed == 7, "HS_AppData.HkPacket.ResetsPerformed == 7"); UtAssert_True (HS_AppData.HkPacket.MaxResets == 8, "HS_AppData.HkPacket.MaxResets == 8"); UtAssert_True (HS_AppData.HkPacket.EventsMonitoredCount == 9, "HS_AppData.HkPacket.EventsMonitoredCount == 9"); UtAssert_True (HS_AppData.HkPacket.MsgActExec == 10, "HS_AppData.HkPacket.MsgActExec == 10"); UtAssert_True (HS_AppData.HkPacket.InvalidEventMonCount == 0, "HS_AppData.HkPacket.InvalidEventMonCount == 0"); UtAssert_True (HS_AppData.HkPacket.StatusFlags == ExpectedStatusFlags, "HS_AppData.HkPacket.StatusFlags == ExpectedStatusFlags"); /* Check first, middle, and last element */ UtAssert_True (HS_AppData.HkPacket.AppMonEnables[0] == 0, "HS_AppData.HkPacket.AppMonEnables[0] == 0"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[(HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == (HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == HS_MAX_EXEC_CNT_SLOTS, "Ut_CFE_EVS_GetEventQueueDepth() == 32"); } /* end HS_HousekeepingReq_Test_AllFlagsEnabled */ #endif void HS_Noop_Test(void) { HS_NoArgsCmd_t CmdPacket; char Message[CFE_EVS_MAX_MESSAGE_LENGTH]; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_NOOP_CC); /* Execute the function being tested */ HS_NoopCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); sprintf(Message, "No-op command: Version %d.%d.%d.%d", HS_MAJOR_VERSION, HS_MINOR_VERSION, HS_REVISION, HS_MISSION_REV); UtAssert_True (Ut_CFE_EVS_EventSent(HS_NOOP_INF_EID, CFE_EVS_INFORMATION, Message), Message); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_Noop_Test */ void HS_ResetCmd_Test(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_RESET_CC); /* Execute the function being tested */ HS_ResetCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 0, "HS_AppData.CmdCount == 0"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_RESET_DBG_EID, CFE_EVS_DEBUG, "Reset counters command"), "Reset counters command"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ResetCmd_Test */ void HS_ResetCounters_Test(void) { /* No setup required for this test */ /* Execute the function being tested */ HS_ResetCounters(); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 0, "HS_AppData.CmdCount == 0"); UtAssert_True (HS_AppData.CmdErrCount == 0, "HS_AppData.CmdErrCount == 0"); UtAssert_True (HS_AppData.EventsMonitoredCount == 0, "HS_AppData.EventsMonitoredCount == 0"); UtAssert_True (HS_AppData.MsgActExec == 0, "HS_AppData.MsgActExec == 0"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_ResetCounters_Test */ void HS_EnableAppMonCmd_Test(void) { HS_NoArgsCmd_t CmdPacket; HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_APPMON_CC); /* Execute the function being tested */ HS_EnableAppMonCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (HS_AppData.CurrentAppMonState == HS_STATE_ENABLED, "HS_AppData.CurrentAppMonState == HS_STATE_ENABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_ENABLE_APPMON_DBG_EID, CFE_EVS_DEBUG, "Application Monitoring Enabled"), "Application Monitoring Enabled"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_EnableAppMonCmd_Test */ void HS_DisableAppMonCmd_Test(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_DISABLE_APPMON_CC); /* Execute the function being tested */ HS_DisableAppMonCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (HS_AppData.CurrentAppMonState == HS_STATE_DISABLED, "HS_AppData.CurrentAppMonState == HS_STATE_DISABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_DISABLE_APPMON_DBG_EID, CFE_EVS_DEBUG, "Application Monitoring Disabled"), "Application Monitoring Disabled"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_DisableAppMonCmd_Test */ void HS_EnableEventMonCmd_Test_Disabled(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_EVENTMON_CC); HS_AppData.CurrentEventMonState = HS_STATE_DISABLED; /* Execute the function being tested */ HS_EnableEventMonCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (HS_AppData.CurrentEventMonState == HS_STATE_ENABLED, "HS_AppData.CurrentEventMonState == HS_STATE_ENABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_ENABLE_EVENTMON_DBG_EID, CFE_EVS_DEBUG, "Event Monitoring Enabled"), "Event Monitoring Enabled"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_EnableEventMonCmd_Test_Disabled */ void HS_EnableEventMonCmd_Test_AlreadyEnabled(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_EVENTMON_CC); HS_AppData.CurrentEventMonState = HS_STATE_ENABLED; /* Execute the function being tested */ HS_EnableEventMonCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (HS_AppData.CurrentEventMonState == HS_STATE_ENABLED, "HS_AppData.CurrentEventMonState == HS_STATE_ENABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_ENABLE_EVENTMON_DBG_EID, CFE_EVS_DEBUG, "Event Monitoring Enabled"), "Event Monitoring Enabled"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_EnableEventMonCmd_Test_AlreadyEnabled */ void HS_EnableEventMonCmd_Test_SubscribeError(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_EVENTMON_CC); HS_AppData.CurrentEventMonState = HS_STATE_DISABLED; Ut_CFE_SB_SetReturnCode(UT_CFE_SB_SUBSCRIBEEX_INDEX, -1, 1); /* Causes event message HS_EVENTMON_SUB_EID to be generated */ /* Execute the function being tested */ HS_EnableEventMonCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdErrCount == 1, "HS_AppData.CmdErrCount == 1"); UtAssert_True (HS_AppData.CurrentEventMonState == HS_STATE_DISABLED, "HS_AppData.CurrentEventMonState == HS_STATE_DISABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_SUB_EID, CFE_EVS_ERROR, "Event Monitor Enable: Error Subscribing to Events,RC=0xFFFFFFFF"), "Event Monitor Enable: Error Subscribing to Events,RC=0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_EnableEventMonCmd_Test_SubscribeError */ void HS_DisableEventMonCmd_Test_Enabled(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_DISABLE_EVENTMON_CC); HS_AppData.CurrentEventMonState = HS_STATE_ENABLED; /* Execute the function being tested */ HS_DisableEventMonCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (HS_AppData.CurrentEventMonState == HS_STATE_DISABLED, "HS_AppData.CurrentEventMonState == HS_STATE_DISABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_DISABLE_EVENTMON_DBG_EID, CFE_EVS_DEBUG, "Event Monitoring Disabled"), "Event Monitoring Disabled"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_DisableEventMonCmd_Test_Enabled */ void HS_DisableEventMonCmd_Test_AlreadyDisabled(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_DISABLE_EVENTMON_CC); HS_AppData.CurrentEventMonState = HS_STATE_DISABLED; /* Execute the function being tested */ HS_DisableEventMonCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (HS_AppData.CurrentEventMonState == HS_STATE_DISABLED, "HS_AppData.CurrentEventMonState == HS_STATE_DISABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_DISABLE_EVENTMON_DBG_EID, CFE_EVS_DEBUG, "Event Monitoring Disabled"), "Event Monitoring Disabled"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_DisableEventMonCmd_Test_AlreadyDisabled */ void HS_DisableEventMonCmd_Test_UnsubscribeError(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_DISABLE_EVENTMON_CC); HS_AppData.CurrentEventMonState = HS_STATE_ENABLED; Ut_CFE_SB_SetReturnCode(UT_CFE_SB_UNSUBSCRIBE_INDEX, -1, 1); /* Causes event message HS_EVENTMON_UNSUB_EID to be generated */ /* Execute the function being tested */ HS_DisableEventMonCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdErrCount == 1, "HS_AppData.CmdErrCount == 1"); UtAssert_True (HS_AppData.CurrentEventMonState == HS_STATE_ENABLED, "HS_AppData.CurrentEventMonState == HS_STATE_ENABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_UNSUB_EID, CFE_EVS_ERROR, "Event Monitor Disable: Error Unsubscribing from Events,RC=0xFFFFFFFF"), "Event Monitor Disable: Error Unsubscribing from Events,RC=0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_DisableEventMonCmd_Test_UnsubscribeError */ void HS_EnableAlivenessCmd_Test(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_ALIVENESS_CC); HS_AppData.CurrentAlivenessState = HS_STATE_DISABLED; /* Execute the function being tested */ HS_EnableAlivenessCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (HS_AppData.CurrentAlivenessState == HS_STATE_ENABLED, "HS_AppData.CurrentAlivenessState == HS_STATE_ENABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_ENABLE_ALIVENESS_DBG_EID, CFE_EVS_DEBUG, "Aliveness Indicator Enabled"), "Aliveness Indicator Enabled"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_EnableAlivenessCmd_Test */ void HS_DisableAlivenessCmd_Test(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_DISABLE_ALIVENESS_CC); HS_AppData.CurrentAlivenessState = HS_STATE_ENABLED; /* Execute the function being tested */ HS_DisableAlivenessCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (HS_AppData.CurrentAlivenessState == HS_STATE_DISABLED, "HS_AppData.CurrentAlivenessState == HS_STATE_DISABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_DISABLE_ALIVENESS_DBG_EID, CFE_EVS_DEBUG, "Aliveness Indicator Disabled"), "Aliveness Indicator Disabled"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_DisableAlivenessCmd_Test */ void HS_EnableCPUHogCmd_Test(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_ENABLE_CPUHOG_CC); HS_AppData.CurrentCPUHogState = HS_STATE_DISABLED; /* Execute the function being tested */ HS_EnableCPUHogCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (HS_AppData.CurrentCPUHogState == HS_STATE_ENABLED, "HS_AppData.CurrentCPUHogState == HS_STATE_ENABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_ENABLE_CPUHOG_DBG_EID, CFE_EVS_DEBUG, "CPU Hogging Indicator Enabled"), "CPU Hogging Indicator Enabled"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_EnableCPUHogCmd_Test */ void HS_DisableCPUHogCmd_Test(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_DISABLE_CPUHOG_CC); HS_AppData.CurrentCPUHogState = HS_STATE_ENABLED; /* Execute the function being tested */ HS_DisableCPUHogCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (HS_AppData.CurrentCPUHogState == HS_STATE_DISABLED, "HS_AppData.CurrentCPUHogState == HS_STATE_DISABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_DISABLE_CPUHOG_DBG_EID, CFE_EVS_DEBUG, "CPU Hogging Indicator Disabled"), "CPU Hogging Indicator Disabled"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_DisableCPUHogCmd_Test */ void HS_ResetResetsPerformedCmd_Test(void) { HS_NoArgsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_NoArgsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_RESET_RESETS_PERFORMED_CC); /* Execute the function being tested */ HS_ResetResetsPerformedCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_RESET_RESETS_DBG_EID, CFE_EVS_DEBUG, "Processor Resets Performed by HS Counter has been Reset"), "Processor Resets Performed by HS Counter has been Reset"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_ResetResetsPerformedCmd_Test */ void HS_SetMaxResetsCmd_Test(void) { HS_SetMaxResetsCmd_t CmdPacket; CFE_SB_InitMsg (&CmdPacket, HS_CMD_MID, sizeof(HS_SetMaxResetsCmd_t), TRUE); CFE_SB_SetCmdCode((CFE_SB_MsgPtr_t)&CmdPacket, HS_SET_MAX_RESETS_CC); CmdPacket.MaxResets = 5; /* Execute the function being tested */ HS_SetMaxResetsCmd((CFE_SB_MsgPtr_t)&CmdPacket); /* Verify results */ UtAssert_True (HS_AppData.CmdCount == 1, "HS_AppData.CmdCount == 1"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_SET_MAX_RESETS_DBG_EID, CFE_EVS_DEBUG, "Max Resets Performable by HS has been set to 5"), "Max Resets Performable by HS has been set to 5"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 1, "Ut_CFE_EVS_GetEventQueueDepth() == 1"); } /* end HS_SetMaxResetsCmd_Test */ #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_AcquirePointers_Test_Nominal(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; HS_AppData.AMTablePtr = AMTable; /* Satisfies all instances of (Status == CFE_TBL_INFO_UPDATED), skips all (Status < CFE_SUCCESS) blocks */ Ut_CFE_TBL_SetReturnCode(UT_CFE_TBL_GETADDRESS_INDEX, CFE_TBL_INFO_UPDATED, 1); Ut_CFE_TBL_ContinueReturnCodeAfterCountZero(UT_CFE_TBL_GETADDRESS_INDEX); /* Execute the function being tested */ HS_AcquirePointers(); /* Verify results */ UtAssert_True (HS_AppData.AppMonLoaded == HS_STATE_ENABLED, "HS_AppData.AppMonLoaded == HS_STATE_ENABLED"); UtAssert_True (HS_AppData.EventMonLoaded == HS_STATE_ENABLED, "HS_AppData.EventMonLoaded == HS_STATE_ENABLED"); UtAssert_True (HS_AppData.MsgActsState == HS_STATE_ENABLED, "HS_AppData.MsgActsState == HS_STATE_ENABLED"); UtAssert_True (HS_AppData.ExeCountState == HS_STATE_ENABLED, "HS_AppData.ExeCountState == HS_STATE_ENABLED"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_AcquirePointers_Test_Nominal */ #endif #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_AcquirePointers_Test_ErrorsWithAppMonLoadedAndEventMonLoadedEnabled(void) { HS_AppData.AppMonLoaded = HS_STATE_ENABLED; HS_AppData.EventMonLoaded = HS_STATE_ENABLED; HS_AppData.CurrentAppMonState = HS_STATE_DISABLED; HS_AppData.CurrentEventMonState = HS_STATE_DISABLED; HS_AppData.MsgActsState = HS_STATE_ENABLED; HS_AppData.ExeCountState = HS_STATE_ENABLED; /* Causes to enter all (Status < CFE_SUCCESS) blocks */ Ut_CFE_TBL_SetReturnCode(UT_CFE_TBL_GETADDRESS_INDEX, -1, 1); Ut_CFE_TBL_ContinueReturnCodeAfterCountZero(UT_CFE_TBL_GETADDRESS_INDEX); /* Execute the function being tested */ HS_AcquirePointers(); /* Verify results */ UtAssert_True (HS_AppData.CurrentAppMonState == HS_STATE_DISABLED, "HS_AppData.CurrentAppMonState == HS_STATE_DISABLED"); UtAssert_True (HS_AppData.AppMonLoaded == HS_STATE_DISABLED, "HS_AppData.AppMonLoaded == HS_STATE_DISABLED"); UtAssert_True (HS_AppData.CurrentEventMonState == HS_STATE_DISABLED, "HS_AppData.CurrentEventMonState == HS_STATE_DISABLED"); UtAssert_True (HS_AppData.EventMonLoaded == HS_STATE_DISABLED , "HS_AppData.EventMonLoaded == HS_STATE_DISABLED"); UtAssert_True (HS_AppData.MsgActsState == HS_STATE_DISABLED , "HS_AppData.MsgActsState == HS_STATE_DISABLED"); UtAssert_True (HS_AppData.ExeCountState == HS_STATE_DISABLED , "HS_AppData.ExeCountState == HS_STATE_DISABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_APPMON_GETADDR_ERR_EID, CFE_EVS_ERROR, "Error getting AppMon Table address, RC=0xFFFFFFFF, Application Monitoring Disabled"), "Error getting AppMon Table address, RC=0xFFFFFFFF, Application Monitoring Disabled"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_GETADDR_ERR_EID, CFE_EVS_ERROR, "Error getting EventMon Table address, RC=0xFFFFFFFF, Event Monitoring Disabled"), "Error getting EventMon Table address, RC=0xFFFFFFFF, Event Monitoring Disabled"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_MSGACTS_GETADDR_ERR_EID, CFE_EVS_ERROR, "Error getting MsgActs Table address, RC=0xFFFFFFFF"), "Error getting MsgActs Table address, RC=0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_EXECOUNT_GETADDR_ERR_EID, CFE_EVS_ERROR, "Error getting ExeCount Table address, RC=0xFFFFFFFF"), "Error getting ExeCount Table address, RC=0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 4, "Ut_CFE_EVS_GetEventQueueDepth() == 4"); } /* end HS_AcquirePointers_Test_ErrorsWithAppMonLoadedAndEventMonLoadedEnabled */ #endif #if HS_MAX_EXEC_CNT_SLOTS != 0 void HS_AcquirePointers_Test_ErrorsWithCurrentAppMonAndCurrentEventMonEnabled(void) { HS_AppData.AppMonLoaded = HS_STATE_DISABLED; HS_AppData.EventMonLoaded = HS_STATE_DISABLED; HS_AppData.CurrentAppMonState = HS_STATE_ENABLED; HS_AppData.CurrentEventMonState = HS_STATE_ENABLED; HS_AppData.MsgActsState = HS_STATE_ENABLED; HS_AppData.ExeCountState = HS_STATE_ENABLED; /* Causes to enter all (Status < CFE_SUCCESS) blocks */ Ut_CFE_TBL_SetReturnCode(UT_CFE_TBL_GETADDRESS_INDEX, -1, 1); Ut_CFE_TBL_ContinueReturnCodeAfterCountZero(UT_CFE_TBL_GETADDRESS_INDEX); /* Causes event message HS_BADEMT_UNSUB_EID to be generated */ Ut_CFE_SB_SetReturnCode(UT_CFE_SB_UNSUBSCRIBE_INDEX, -1, 1); /* Execute the function being tested */ HS_AcquirePointers(); /* Verify results */ UtAssert_True (HS_AppData.CurrentAppMonState == HS_STATE_DISABLED, "HS_AppData.CurrentAppMonState == HS_STATE_DISABLED"); UtAssert_True (HS_AppData.AppMonLoaded == HS_STATE_DISABLED, "HS_AppData.AppMonLoaded == HS_STATE_DISABLED"); UtAssert_True (HS_AppData.CurrentEventMonState == HS_STATE_DISABLED, "HS_AppData.CurrentEventMonState == HS_STATE_DISABLED"); UtAssert_True (HS_AppData.EventMonLoaded == HS_STATE_DISABLED , "HS_AppData.EventMonLoaded == HS_STATE_DISABLED"); UtAssert_True (HS_AppData.MsgActsState == HS_STATE_DISABLED , "HS_AppData.MsgActsState == HS_STATE_DISABLED"); UtAssert_True (HS_AppData.ExeCountState == HS_STATE_DISABLED , "HS_AppData.ExeCountState == HS_STATE_DISABLED"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_APPMON_GETADDR_ERR_EID, CFE_EVS_ERROR, "Error getting AppMon Table address, RC=0xFFFFFFFF, Application Monitoring Disabled"), "Error getting AppMon Table address, RC=0xFFFFFFFF, Application Monitoring Disabled"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_EVENTMON_GETADDR_ERR_EID, CFE_EVS_ERROR, "Error getting EventMon Table address, RC=0xFFFFFFFF, Event Monitoring Disabled"), "Error getting EventMon Table address, RC=0xFFFFFFFF, Event Monitoring Disabled"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_BADEMT_UNSUB_EID, CFE_EVS_ERROR, "Error Unsubscribing from Events,RC=0xFFFFFFFF"), "Error Unsubscribing from Events,RC=0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_MSGACTS_GETADDR_ERR_EID, CFE_EVS_ERROR, "Error getting MsgActs Table address, RC=0xFFFFFFFF"), "Error getting MsgActs Table address, RC=0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_EventSent(HS_EXECOUNT_GETADDR_ERR_EID, CFE_EVS_ERROR, "Error getting ExeCount Table address, RC=0xFFFFFFFF"), "Error getting ExeCount Table address, RC=0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 5, "Ut_CFE_EVS_GetEventQueueDepth() == 5"); } /* end HS_AcquirePointers_Test_ErrorsWithCurrentAppMonAndCurrentEventMonEnabled */ #endif void HS_AppMonStatusRefresh_Test_CycleCountZero(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; uint32 i; HS_AppData.AMTablePtr = AMTable; for (i = 0; i <= ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE); i++ ) { HS_AppData.AppMonEnables[i] = 1 + i; } for (i = 0; i < HS_MAX_MONITORED_APPS; i++ ) { HS_AppData.AMTablePtr[i].CycleCount = 0; } /* Execute the function being tested */ HS_AppMonStatusRefresh(); /* Verify results */ /* Check first, middle, and last element */ UtAssert_True (HS_AppData.HkPacket.AppMonEnables[0] == 0, "HS_AppData.HkPacket.AppMonEnables[0] == 0"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == 0, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == 0"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[(HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == 0, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == 0"); UtAssert_True (HS_AppData.AppMonLastExeCount[0] == 0, "HS_AppData.AppMonLastExeCount[0] == 0"); UtAssert_True (HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS / 2] == 0, "HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS / 2] == 0"); UtAssert_True (HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS] == 0, "HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS] == 0"); UtAssert_True (HS_AppData.AppMonCheckInCountdown[0] == 0, "HS_AppData.AppMonCheckInCountdown[0] == 0"); UtAssert_True (HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS / 2] == 0, "HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS / 2] == 0"); UtAssert_True (HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS] == 0, "HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS] == 0"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_AppMonStatusRefresh_Test_CycleCountZero */ void HS_AppMonStatusRefresh_Test_ActionTypeNOACT(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; uint32 i; HS_AppData.AMTablePtr = AMTable; for (i = 0; i <= ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE); i++ ) { HS_AppData.AppMonEnables[i] = 1 + i; } for (i = 0; i < HS_MAX_MONITORED_APPS; i++ ) { HS_AppData.AMTablePtr[i].ActionType = HS_AMT_ACT_NOACT; } /* Execute the function being tested */ HS_AppMonStatusRefresh(); /* Verify results */ /* Check first, middle, and last element */ UtAssert_True (HS_AppData.HkPacket.AppMonEnables[0] == 0, "HS_AppData.HkPacket.AppMonEnables[0] == 0"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == 0, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE) / 2] == 0"); UtAssert_True (HS_AppData.HkPacket.AppMonEnables[(HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == 0, "((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE] == 0"); UtAssert_True (HS_AppData.AppMonLastExeCount[0] == 0, "HS_AppData.AppMonLastExeCount[0] == 0"); UtAssert_True (HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS / 2] == 0, "HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS / 2] == 0"); UtAssert_True (HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS] == 0, "HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS] == 0"); UtAssert_True (HS_AppData.AppMonCheckInCountdown[0] == 0, "HS_AppData.AppMonCheckInCountdown[0] == 0"); UtAssert_True (HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS / 2] == 0, "HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS / 2] == 0"); UtAssert_True (HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS] == 0, "HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS] == 0"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_AppMonStatusRefresh_Test_ActionTypeNOACT */ void HS_AppMonStatusRefresh_Test_ElseCase(void) { HS_AMTEntry_t AMTable[HS_MAX_MONITORED_APPS]; uint32 i; HS_AppData.AMTablePtr = AMTable; for (i = 0; i <= ((HS_MAX_MONITORED_APPS -1) / HS_BITS_PER_APPMON_ENABLE); i++ ) { HS_AppData.AppMonEnables[i] = 1 + i; } for (i = 0; i < HS_MAX_MONITORED_APPS; i++ ) { HS_AppData.AMTablePtr[i].CycleCount = 1 + i; HS_AppData.AMTablePtr[i].ActionType = 99; } /* Execute the function being tested */ HS_AppMonStatusRefresh(); /* Verify results */ UtAssert_True (HS_AppData.AppMonLastExeCount[0] == 0, "HS_AppData.AppMonLastExeCount[0] == 0"); UtAssert_True (HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS / 2] == 0, "HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS / 2] == 0"); UtAssert_True (HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS] == 0, "HS_AppData.AppMonLastExeCount[HS_MAX_MONITORED_APPS] == 0"); UtAssert_True (HS_AppData.AppMonCheckInCountdown[0] == 1, "HS_AppData.AppMonCheckInCountdown[0] == 1"); UtAssert_True (HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS / 2] == (HS_MAX_MONITORED_APPS / 2) + 1, "HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS / 2] == (HS_MAX_MONITORED_APPS / 2) + 1"); UtAssert_True (HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS - 1] == (HS_MAX_MONITORED_APPS - 1) + 1, "HS_AppData.AppMonCheckInCountdown[HS_MAX_MONITORED_APPS] == (HS_MAX_MONITORED_APPS - 1) + 1"); /* Check first, middle, and last element */ UtAssert_True (HS_AppData.AppMonEnables[0] == 0xFFFFFFFF, "HS_AppData.AppMonEnables[0] == 0xFFFFFFFF"); UtAssert_True (HS_AppData.AppMonEnables[(((HS_MAX_MONITORED_APPS - 1) / HS_BITS_PER_APPMON_ENABLE)+1) / 2] == 0xFFFFFFFF, "HS_AppData.AppMonEnables[(((HS_MAX_MONITORED_APPS - 1) / HS_BITS_PER_APPMON_ENABLE)+1) / 2] == 0xFFFFFFFF"); UtAssert_True (HS_AppData.AppMonEnables[(((HS_MAX_MONITORED_APPS - 1) / HS_BITS_PER_APPMON_ENABLE)+1) - 1] == 0xFFFFFFFF, "HS_AppData.AppMonEnables[(((HS_MAX_MONITORED_APPS - 1) / HS_BITS_PER_APPMON_ENABLE)+1) - 1] == 0xFFFFFFFF"); UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_AppMonStatusRefresh_Test_ElseCase */ void HS_MsgActsStatusRefresh_Test(void) { uint32 i; for (i = 0; i < HS_MAX_MSG_ACT_TYPES; i++ ) { HS_AppData.MsgActCooldown[i] = 1 + i; } /* Execute the function being tested */ HS_MsgActsStatusRefresh(); /* Verify results */ for (i = 0; i < HS_MAX_MSG_ACT_TYPES; i++ ) { /* Check first, middle, and last element */ UtAssert_True (HS_AppData.MsgActCooldown[0] == 0, "HS_AppData.MsgActCooldown[0] == 0"); UtAssert_True (HS_AppData.MsgActCooldown[HS_MAX_MSG_ACT_TYPES / 2] == 0, "HS_AppData.MsgActCooldown[HS_MAX_MSG_ACT_TYPES / 2] == 0"); UtAssert_True (HS_AppData.MsgActCooldown[HS_MAX_MSG_ACT_TYPES - 1] == 0, "HS_AppData.MsgActCooldown[HS_MAX_MSG_ACT_TYPES -1] == 0"); } UtAssert_True (Ut_CFE_EVS_GetEventQueueDepth() == 0, "Ut_CFE_EVS_GetEventQueueDepth() == 0"); } /* end HS_MsgActsStatusRefresh_Test */ void HS_Cmds_Test_AddTestCases(void) { UtTest_Add(HS_AppPipe_Test_SendHK, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_SendHK"); UtTest_Add(HS_AppPipe_Test_Noop, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_Noop"); UtTest_Add(HS_AppPipe_Test_Reset, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_Reset"); UtTest_Add(HS_AppPipe_Test_EnableAppMon, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_EnableAppMon"); UtTest_Add(HS_AppPipe_Test_DisableAppMon, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_DisableAppMon"); UtTest_Add(HS_AppPipe_Test_EnableEventMon, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_EnableEventMon"); UtTest_Add(HS_AppPipe_Test_DisableEventMon, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_DisableEventMon"); UtTest_Add(HS_AppPipe_Test_EnableAliveness, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_EnableAliveness"); UtTest_Add(HS_AppPipe_Test_DisableAliveness, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_DisableAliveness"); UtTest_Add(HS_AppPipe_Test_ResetResetsPerformed, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_ResetResetsPerformed"); UtTest_Add(HS_AppPipe_Test_SetMaxResets, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_SetMaxResets"); UtTest_Add(HS_AppPipe_Test_EnableCPUHog, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_EnableCPUHog"); UtTest_Add(HS_AppPipe_Test_DisableCPUHog, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_DisableCPUHog"); UtTest_Add(HS_AppPipe_Test_InvalidCC, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_InvalidCC"); UtTest_Add(HS_AppPipe_Test_InvalidMID, HS_Test_Setup, HS_Test_TearDown, "HS_AppPipe_Test_InvalidMID"); UtTest_Add(HS_HousekeepingReq_Test_InvalidEventMon, HS_Test_Setup, HS_Test_TearDown, "HS_HousekeepingReq_Test_InvalidEventMon"); #if HS_MAX_EXEC_CNT_SLOTS != 0 UtTest_Add(HS_HousekeepingReq_Test_AllFlagsEnabled, HS_Test_Setup, HS_Test_TearDown, "HS_HousekeepingReq_Test_AllFlagsEnabled"); UtTest_Add(HS_HousekeepingReq_Test_ResourceTypeAppMain, HS_Test_Setup, HS_Test_TearDown, "HS_HousekeepingReq_Test_ResourceTypeAppMain"); UtTest_Add(HS_HousekeepingReq_Test_ResourceTypeAppChild, HS_Test_Setup, HS_Test_TearDown, "HS_HousekeepingReq_Test_ResourceTypeAppChild"); UtTest_Add(HS_HousekeepingReq_Test_ResourceTypeDevice, HS_Test_Setup, HS_Test_TearDown, "HS_HousekeepingReq_Test_ResourceTypeDevice"); UtTest_Add(HS_HousekeepingReq_Test_ResourceTypeISR, HS_Test_Setup, HS_Test_TearDown, "HS_HousekeepingReq_Test_ResourceTypeISR"); UtTest_Add(HS_HousekeepingReq_Test_ResourceTypeUnknown, HS_Test_Setup, HS_Test_TearDown, "HS_HousekeepingReq_Test_ResourceTypeAppMain"); #endif UtTest_Add(HS_Noop_Test, HS_Test_Setup, HS_Test_TearDown, "HS_Noop_Test"); UtTest_Add(HS_ResetCmd_Test, HS_Test_Setup, HS_Test_TearDown, "HS_ResetCmd_Test"); UtTest_Add(HS_ResetCounters_Test, HS_Test_Setup, HS_Test_TearDown, "HS_ResetCounters_Test"); UtTest_Add(HS_EnableAppMonCmd_Test, HS_Test_Setup, HS_Test_TearDown, "HS_EnableAppMonCmd_Test"); UtTest_Add(HS_DisableAppMonCmd_Test, HS_Test_Setup, HS_Test_TearDown, "HS_DisableAppMonCmd_Test"); UtTest_Add(HS_EnableEventMonCmd_Test_Disabled, HS_Test_Setup, HS_Test_TearDown, "HS_EnableEventMonCmd_Test_Disabled"); UtTest_Add(HS_EnableEventMonCmd_Test_AlreadyEnabled, HS_Test_Setup, HS_Test_TearDown, "HS_EnableEventMonCmd_Test_AlreadyEnabled"); UtTest_Add(HS_EnableEventMonCmd_Test_SubscribeError, HS_Test_Setup, HS_Test_TearDown, "HS_EnableEventMonCmd_Test_SubscribeError"); UtTest_Add(HS_DisableEventMonCmd_Test_Enabled, HS_Test_Setup, HS_Test_TearDown, "HS_DisableEventMonCmd_Test_Enabled"); UtTest_Add(HS_DisableEventMonCmd_Test_AlreadyDisabled, HS_Test_Setup, HS_Test_TearDown, "HS_DisableEventMonCmd_Test_AlreadyDisabled"); UtTest_Add(HS_DisableEventMonCmd_Test_UnsubscribeError, HS_Test_Setup, HS_Test_TearDown, "HS_DisableEventMonCmd_Test_UnsubscribeError"); UtTest_Add(HS_EnableAlivenessCmd_Test, HS_Test_Setup, HS_Test_TearDown, "HS_EnableAlivenessCmd_Test"); UtTest_Add(HS_DisableAlivenessCmd_Test, HS_Test_Setup, HS_Test_TearDown, "HS_DisableAlivenessCmd_Test"); UtTest_Add(HS_EnableCPUHogCmd_Test, HS_Test_Setup, HS_Test_TearDown, "HS_EnableCPUHogCmd_Test"); UtTest_Add(HS_DisableCPUHogCmd_Test, HS_Test_Setup, HS_Test_TearDown, "HS_DisableCPUHogCmd_Test"); UtTest_Add(HS_ResetResetsPerformedCmd_Test, HS_Test_Setup, HS_Test_TearDown, "HS_ResetResetsPerformedCmd_Test"); UtTest_Add(HS_SetMaxResetsCmd_Test, HS_Test_Setup, HS_Test_TearDown, "HS_SetMaxResetsCmd_Test"); #if HS_MAX_EXEC_CNT_SLOTS != 0 UtTest_Add(HS_AcquirePointers_Test_Nominal, HS_Test_Setup, HS_Test_TearDown, "HS_AcquirePointers_Test_Nominal"); UtTest_Add(HS_AcquirePointers_Test_ErrorsWithAppMonLoadedAndEventMonLoadedEnabled, HS_Test_Setup, HS_Test_TearDown, "HS_AcquirePointers_Test_ErrorsWithAppMonLoadedAndEventMonLoadedEnabled"); UtTest_Add(HS_AcquirePointers_Test_ErrorsWithCurrentAppMonAndCurrentEventMonEnabled, HS_Test_Setup, HS_Test_TearDown, "HS_AcquirePointers_Test_ErrorsWithCurrentAppMonAndCurrentEventMonEnabled"); #endif UtTest_Add(HS_AppMonStatusRefresh_Test_CycleCountZero, HS_Test_Setup, HS_Test_TearDown, "HS_AppMonStatusRefresh_Test_CycleCountZero"); UtTest_Add(HS_AppMonStatusRefresh_Test_ActionTypeNOACT, HS_Test_Setup, HS_Test_TearDown, "HS_AppMonStatusRefresh_Test_ActionTypeNOACT"); UtTest_Add(HS_AppMonStatusRefresh_Test_ElseCase, HS_Test_Setup, HS_Test_TearDown, "HS_AppMonStatusRefresh_Test_ElseCase"); UtTest_Add(HS_MsgActsStatusRefresh_Test, HS_Test_Setup, HS_Test_TearDown, "HS_MsgActsStatusRefresh_Test"); } /* end HS_Cmds_Test_AddTestCases */ /************************/ /* End of File Comment */ /************************/
greck2908/HS
<|start_filename|>Dockerfile<|end_filename|> FROM certbot/certbot RUN mkdir /certs-dir && apk update && apk add bash curl ADD ./letsencrypt-to-vault /usr/bin EXPOSE 80 443 VOLUME /webroot-dir ENTRYPOINT [ "letsencrypt-to-vault" ]
ket4yii/letsencrypt-to-vault
<|start_filename|>src/adventure-export.js<|end_filename|> import Helpers from "./common.js"; export default class AdventureModuleExport extends FormApplication { /** @override */ static get defaultOptions() { return mergeObject(super.defaultOptions, { id: "adventure-export", classes: ["adventure-import-export"], title: "Adventure Exporter", template: "modules/adventure-import-export/templates/adventure-export.html" }); } /** @override */ async getData() { let data = {}; // Get lists of all data. Helpers.logger.log(`Retrieving current game data.`); data.scenes = game.scenes.map(scene => { return { key : scene.data._id, name : scene.name } }); data.actors = game.actors.map(actor => { return { key : actor.data._id, name : actor.name } }); data.items = game.items.map(item => { return { key : item.data._id, name : item.name } }); data.journals = game.journal.map(entry => { return { key : entry.data._id, name : entry.name } }); data.tables = game.tables.map(table => { return { key : table.data._id, name : table.name } }); data.playlists = game.playlists.map(playlist => { return { key : playlist.data._id, name : playlist.name } }); data.compendiums = game.packs.map(pack => { if(pack.metadata.package === "world") { return { key : `${pack.metadata.package}.${pack.metadata.name}`, name : pack.metadata.label } } }); data.macros = game.macros.map(macro => { return { key : macro.data._id, name : macro.name } }) let warnings = []; let isTooDeep = game.folders.filter(folder => { return folder.depth === 3 }).length > 0; if(isTooDeep) { warnings.push(`There are folders at the max depth, if you wish to retain the folder structure be sure to check the option.`); } return { data, cssClass : "aie-exporter-window", hasWarnings : warnings.length > 0, warnings }; } /** @override */ activateListeners(html) { html.find(".aie-accordion input").click(ev => { ev.stopPropagation(); const parent = $(ev.target).parent(); const panel = $(parent).next()[0]; $(panel).find("input[type='checkbox']").prop("checked", $(ev.target).prop("checked")); }) html.find(".aie-accordion").click(ev => { $(ev.target).toggleClass("active"); const panel = $(ev.target).next()[0]; if (panel.style.maxHeight) { panel.style.maxHeight = null; } else { panel.style.maxHeight = (panel.scrollHeight) + "px"; } }); html.find("button.dialog-button").on("click",this._exportData.bind(this)); } async _exportData(event) { event.preventDefault(); $(".import-progress").toggleClass("import-hidden"); $(".aie-overlay").toggleClass("import-invalid"); const name = $("#adventure_name").val().length === 0 ? `Adventure ${(new Date()).getTime()}` : $("#adventure_name").val(); let filename = `${Helpers.sanitizeFilename(name)}.fvttadv`; const controls = $(".aie-exporter-window input[type='checkbox'][data-type]:checked"); var zip = new JSZip(); let totalcount = controls.length; let currentcount = 0; CONFIG.AIE.TEMPORARY = {}; for(let i = 0; i < controls.length; i+=1) { let id = $(controls[i]).val(); let type = $(controls[i]).data("type"); try { let obj; let data; switch(type) { case "scene" : obj = await game.scenes.get(id); Helpers.logger.log(`Exporting ${type} : ${obj.name}`); this._updateProgress(totalcount, currentcount, `${type}-${obj.name}`); const sceneData = JSON.parse(JSON.stringify(obj.data)); totalcount += sceneData.tokens.length + sceneData.sounds.length + sceneData.notes.length + sceneData.tiles.length; await Helpers.asyncForEach(sceneData.tokens, async token => { token.img = await Helpers.exportImage(token.img, type, token._id, zip, "tokenimage"); }) await Helpers.asyncForEach(sceneData.sounds, async sound => { sound.path = await Helpers.exportImage(sound.path, type, sound._id, zip, "scenesound"); }) await Helpers.asyncForEach(sceneData.notes, async note => { note.icon = await Helpers.exportImage(note.icon, type, note._id, zip, "scenenote"); }); await Helpers.asyncForEach(sceneData.tiles, async tile => { tile.img = await Helpers.exportImage(tile.img, type, tile._id, zip, "tileimage"); }); sceneData.img = await Helpers.exportImage(sceneData.img, type, id, zip); if(sceneData.thumb) { sceneData.thumb = await Helpers.exportImage(sceneData.thumb, type, id, zip, "thumb"); } if(sceneData?.token?.img) { sceneData.token.img = await Helpers.exportImage(sceneData.token.img, type, id, zip, "token"); } data = Helpers.exportToJSON(sceneData); break; case "actor" : obj = await game.actors.get(id); Helpers.logger.log(`Exporting ${type} : ${obj.name}`); this._updateProgress(totalcount, currentcount, `${type}-${obj.name}`); break; case "item" : obj = await game.items.get(id); Helpers.logger.log(`Exporting ${type} : ${obj.name}`); this._updateProgress(totalcount, currentcount, `${type}-${obj.name}`); break; case "journal": obj = await game.journal.get(id); Helpers.logger.log(`Exporting ${type} : ${obj.name}`); this._updateProgress(totalcount, currentcount, `${type}-${obj.name}`); break; case "table" : obj = await game.tables.get(id); Helpers.logger.log(`Exporting ${type} : ${obj.name}`); this._updateProgress(totalcount, currentcount, `${type}-${obj.name}`); const tableData = JSON.parse(JSON.stringify(obj.data)); totalcount += tableData.results.length; await Helpers.asyncForEach(tableData.results, async (result) => { result.img = await Helpers.exportImage(result.img, type, result._id, zip, "table"); currentcount +=1; this._updateProgress(totalcount, currentcount, `${type}-${obj.name}`); }); data = Helpers.exportToJSON(tableData) break; case "playlist" : obj = await game.playlists.get(id); const playlistData = JSON.parse(JSON.stringify(obj.data)); totalcount += playlistData.sounds.length; Helpers.logger.log(`Exporting ${type} : ${obj.name}`); this._updateProgress(totalcount, currentcount, `${type}-${obj.name}`); await Helpers.asyncForEach(playlistData.sounds, async (sound) => { sound.path = await Helpers.exportImage(sound.path, type, sound._id, zip, "sounds"); currentcount +=1; this._updateProgress(totalcount, currentcount, `${type}-${obj.name}-${sound.name}`); }); data = Helpers.exportToJSON(playlistData) break; case "compendium" : obj = await game.packs.get(id); Helpers.logger.log(`Exporting ${type} : ${obj.name}`); this._updateProgress(totalcount, currentcount, `${type}-${obj.name}`); let content = await obj.getContent(); const compendiumData = JSON.parse(JSON.stringify(content)); totalcount += compendiumData.length; await Helpers.asyncForEach(compendiumData, async (item) => { item.img = await Helpers.exportImage(item.img, type, item._id, zip); if(item.thumb) { item.thumb = await Helpers.exportImage(item.thumb, type, item._id, zip); } if(item?.token?.img) { item.token.img = await Helpers.exportImage(item.token.img, type, item._id, zip); } if(item?.items?.length) { // we need to export images associated to owned items. await Helpers.asyncForEach(item.items, async i => { i.img = await Helpers.exportImage(i.img, type, item._id, zip); }); } currentcount +=1; this._updateProgress(totalcount, currentcount, `${type}-${obj.name}`); }) data = Helpers.exportToJSON({ info : obj.metadata, items : compendiumData }); break; case "macro": obj = await game.macros.get(id); Helpers.logger.log(`Exporting ${type} : ${obj.name}`) break; } if(type !== "compendium" && type !== "playlist" && type !== "table" && type !== "scene") { const exportData = JSON.parse(JSON.stringify(obj.data)); exportData.img = await Helpers.exportImage(exportData.img, type, id, zip); if(exportData.thumb) { exportData.thumb = await Helpers.exportImage(exportData.thumb, type, id, zip, "thumb"); } if(exportData?.token?.img) { if(exportData?.token?.randomImg) { // If it starts with http, we can't browse an http URL as a directory so just skip this if (!exportData.token.img.startsWith("http")) { // we need to grab all images that match the string. const imgFilepaths = exportData.token.img.split("/"); const imgFilename = (imgFilepaths.reverse())[0]; const imgFilepath = exportData.token.img.replace(imgFilename, ""); let wildcard = false; let extensions = []; if(imgFilename.includes("*")) { wildcard = true; if(imgFilename.includes("*.")) { extensions.push(imgFilename.replace("*.", ".")); } } const filestoexport = Helpers.BrowseFiles("data", exportData.token.img, {bucket:null, extensions, wildcard}); Helpers.logger.debug(`Found wildcard token image for ${exportData.name}, uploading ${filestoexport.files.length} files`); exportData.token.img = `${type}/token/${id}/${imgFilename}`; totalcount += filestoexport.files.length; await Helpers.asyncForEach(filestoexport.files, async (file) => { await Helpers.exportImage(file, type, id, zip, "token"); currentcount += 1; this._updateProgress(totalcount, currentcount, `${type}-${obj.name}`); }); } else { // We cannot support random images for remote URLs to just default to what the avatar image is since this will be // better than no token image at all! exportData.token.img = exportData.img; } } else { exportData.token.img = await Helpers.exportImage(exportData.token.img, type, id, zip, "token"); } } if (type === "journal" && exportData?.content) { console.log("Yup") const journalImages = Helpers.reMatchAll(/(src|href)="(?!http(?:s*):\/\/)([\w0-9\-._~%!$&'()*+,;=:@/]*)"/, exportData.content); if (journalImages) { await Helpers.asyncForEach(journalImages, async (result) => { const path = await Helpers.exportImage(result[2], type, id, zip); exportData.content = exportData.content.replace(result[0], `${result[1]}="${path}"`); }) } } if(type === "actor" && exportData?.items?.length) { // we need to export images associated to owned items. await Helpers.asyncForEach(exportData.items, async item => { item.img = await Helpers.exportImage(item.img, type, id, zip); }); } data = Helpers.exportToJSON(exportData) } zip.folder(type).file(`${id}.json`, data); } catch (err) { Helpers.logger.error(`Error during main export ${id} - ${type}`) } currentcount +=1; this._updateProgress(totalcount, currentcount, `${type}`); } let folderData = []; Helpers.logger.log(`Exporting ${game.folders.length} folders`) this._updateProgress(totalcount, currentcount, `folders`); await game.folders.forEach(folder => { let f = JSON.parse(JSON.stringify(folder.data)); f.flags.importid = f._id; folderData.push(f); }) zip.file("folders.json", Helpers.exportToJSON(folderData)); Helpers.logger.log(`Adventure Metadata`) this._updateProgress(totalcount, currentcount, `adventure metadata`); const descriptor = { id: randomID(), name, description : $("#adventure_description").val(), system : game.data.system.data.name, modules : game.data.modules.filter(module => { return module.active; }).map(module => { return module.data.title }), version : CONFIG.AIE.schemaVersion, options : { folders : $(".aie-exporter-window input[type='checkbox'][value='directories']:checked").length > 0 ? true : false } } zip.file("adventure.json", Helpers.exportToJSON(descriptor)); Helpers.logger.log(`Building and preparing adventure file for download`) this._updateProgress(totalcount, currentcount, `building and preparing adventure file for download`); try { const blob = await zip.generateAsync({type:"blob"}); saveAs(blob, filename); // const base64 = await zip.generateAsync({type:"base64"}); // const blob = "data:application/zip;base64," + base64; // let a = document.createElement('a'); // a.href = blob; // a.download = filename; // a.dispatchEvent(new MouseEvent("click", {bubbles: true, cancelable: true, view: window})); // setTimeout(() => window.URL.revokeObjectURL(a.href), 100); } catch (err) { Helpers.logger.error(err); } $(".aie-overlay").toggleClass("import-invalid"); CONFIG.AIE.TEMPORARY = {}; this.close(); } _updateProgress(total, count, type) { $(".import-progress-bar").width(`${Math.trunc((count / total) * 100)}%`).html(`<span>${game.i18n.localize("AIE.Working")}(${type})...</span>`); } } <|start_filename|>lang/en.json<|end_filename|> { "AIE.Scene" : "Scene", "AIE.Scenes" : "Scenes", "AIE.Actor" : "Actor", "AIE.Actors" : "Actors", "AIE.Item" : "Item", "AIE.Items" : "Items", "AIE.JournalEntry" : "JournalEntry", "AIE.Journals" : "Journals", "AIE.Rolltable" : "Roll Table", "AIE.Rolltables" : "Roll Tables", "AIE.Playlist" : "Playlist", "AIE.Playlists" : "Playlists", "AIE.Compendium" : "Compendium", "AIE.Compendiums" : "Compendiums", "AIE.AdventureName" : "Adventure Name", "AIE.Export" : "Export Assets", "AIE.Import" : "Import Adventure", "AIE.Working" : "Working", "AIE.ActiveModules" : "The following modules were active:", "AIE.ExportOptions" : "Export Options", "AIE.References" : "Updating References", "AIE.RollTable" : "Roll Table", "AIE.Macros" : "Macros" } <|start_filename|>templates/adventure-import.html<|end_filename|> <form class="{{cssClass}}" autocomplete="off" onsubmit="event.preventDefault();"> <div class="import-file-selector"> <p class="notes">You may select an adventure file manually</p> <p class="notes">uploaded within data directory (use this</p> <p class="notes">if file is larger that 500 mb) or select</p> <p class="notes">a file to import from your client.</p> <div> <select style="text-align:center" name="import-file" id="import-file"> <option></option> {{#each files}} <option value="{{this.path}}">{{this.name}}</option> {{/each}} </select> </div> <div> <div class="form-group"> <input type="file" name="data" accept=".fvttadv"/> </div> </div> <div class="import-progress import-hidden"> <div class="import-progress-bar" style="width: 0%"></div> </div> <div> <button class="dialog-button" data-button="import"> <i class="fas fa-check"></i> {{localize "AIE.Import"}} </button> </div> </div> <div class="aie-overlay import-invalid"> <div class="aie-working import-hidden"><i class="fas fa-cog"></i><div style="font-size: 15px; text-align: center;">Updating References...</div></div> </div> </form> <|start_filename|>lang/pt-BR.json<|end_filename|> { "AIE.Scene" : "Cena", "AIE.Scenes" : "Cenas", "AIE.Actor" : "Ator", "AIE.Actors" : "Atores", "AIE.Item" : "Item", "AIE.Items" : "Itens", "AIE.JournalEntry" : "EntradaDiario", "AIE.Journals" : "Diário", "AIE.Rolltable" : "Tabela de Rolagem", "AIE.Rolltables" : "Tabelas de Rolagens", "AIE.Playlist" : "Lista de Reprodução", "AIE.Playlists" : "Lista de Reproduções", "AIE.Compendium" : "Compêndio", "AIE.Compendiums" : "Compêndium", "AIE.AdventureName" : "Nome da Aventura", "AIE.Export" : "Exportar Assets", "AIE.Import" : "Importar Aventura", "AIE.Working" : "Executando", "AIE.ActiveModules" : "Os seguintes módulos estão ativos:", "AIE.ExportOptions" : "Opções de exportação", "AIE.References" : "Atualizando referências", "AIE.RollTable" : "Tabela de Rolagens", "AIE.Macros" : "Macros" }
p4535992/adventure-import-export
<|start_filename|>generators/eventAggregate/templates/handler/_server.go<|end_filename|> package handler import ( "context" "fmt" "<%=repoUrl%>/db" pb "<%=repoUrl%>/proto/event_aggregate" ) // Server 事件驱动服务间流程控制方法,提供基本的数据库操作方法 type Server struct { pb.EventAggregateServiceServer } // CreateAggregate 新建聚合,返回聚合Id func (s *Server) CreateAggregate(ctx context.Context, req *pb.CreateAggregateRequest) (*pb.CreateAggregateResponse, error) { stmt, _ := db.Db.Prepare(`INSERT INTO aggregate (aggregate_type, data) VALUES (?, ?)`) defer stmt.Close() ret, err := stmt.Exec(req.GetAggregateType(), req.GetData()) if err != nil { fmt.Printf("insert data error: %v\n", err) return nil, err } LastInsertId, _ := ret.LastInsertId() return &pb.CreateAggregateResponse{Id: LastInsertId}, nil } // CreateEvent 新建Event的方法,需要提供聚合Id func (s *Server) CreateEvent(ctx context.Context, req *pb.CreateEventRequest) (*pb.CreateEventResponse, error) { stmt, _ := db.Db.Prepare(`INSERT INTO event (aggregate_id, event_type, data) VALUES (?, ?, ?)`) defer stmt.Close() ret, err := stmt.Exec(req.GetAggregateId(), req.GetEventType(), req.GetData()) if err != nil { fmt.Printf("insert data error: %v\n", err) return nil, err } LastInsertId, _ := ret.LastInsertId() return &pb.CreateEventResponse{EventId: LastInsertId}, nil } <|start_filename|>generators/java_app/templates/grpc-server/src/main/java/grpc/Server.java<|end_filename|> package grpc; import grpc.service.HelloServiceImpl; import io.grpc.ServerBuilder; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import com.mikudos.grpcclient.Client; import com.mikudos.broker.Broker; public class Server { public Map config; public Server() throws FileNotFoundException { this.init(); System.out.println("server"); } private void init() throws FileNotFoundException { //初始化Yaml解析器 Yaml yaml = new Yaml(); File f=new File("config/default.yaml"); //读入文件 this.config = yaml.load(new FileInputStream(f)); new Client().clientEcho(); new Broker().echo(); } public void start() throws IOException, InterruptedException { io.grpc.Server server = ServerBuilder.forPort((int) this.config.get("port")) .addService(new HelloServiceImpl()) .build(); System.out.println("Starting server..."); server.start(); System.out.printf("Server started at %s!\n",this.config.get("port")); server.awaitTermination(); } } <|start_filename|>generators/node_service/templates/service/index.js<|end_filename|> const { Application, Service } = require('mikudos-node-app'); const HandlerClass = require('./<%=serviceNameSnake%>.class'); const methodMap = require('./<%=serviceNameSnake%>.map'); const hooks = require('./<%=serviceNameSnake%>.hooks'); module.exports = function (app) { let handler = new HandlerClass({}, app); const service = new Service(handler, methodMap, '<%=serviceName%>'); app.register(service.name, service, hooks); }; <|start_filename|>generators/node_app/templates/src/grpc_clients/index.js<|end_filename|> const greeterClient = require('./greeter.client'); module.exports = function (app) { app.context.grpcClients = {} greeterClient(app); } <|start_filename|>generators/golang_app/templates/handler/_server.go<|end_filename|> package handler import ( "context" "fmt" "<%=goModuleName%>/db" pb "<%=goModuleName%>/proto/<%=proto%>" ) // Server 事件驱动服务间流程控制方法,提供基本的数据库操作方法 type Server struct { pb.<%=protoCamelCapitalize%>Server } // CreateAggregate 新建聚合,返回聚合Id func (s *Server) CreateAggregate(ctx context.Context, req *pb.CreateAggregateRequest) (*pb.CreateAggregateResponse, error) { stmt, _ := db.Db.Prepare(`INSERT INTO aggregate (aggregate_type, data) VALUES (?, ?)`) defer stmt.Close() ret, err := stmt.Exec(req.GetAggregateType(), req.GetData()) if err != nil { fmt.Printf("insert data error: %v\n", err) return nil, err } LastInsertId, _ := ret.LastInsertId() return &pb.CreateAggregateResponse{Id: LastInsertId}, nil } // CreateEvent 新建Event的方法,需要提供聚合Id func (s *Server) CreateEvent(ctx context.Context, req *pb.CreateEventRequest) (*pb.CreateEventResponse, error) { stmt, _ := db.Db.Prepare(`INSERT INTO event (aggregate_id, event_type, data) VALUES (?, ?, ?)`) defer stmt.Close() ret, err := stmt.Exec(req.GetAggregateId(), req.GetEventType(), req.GetData()) if err != nil { fmt.Printf("insert data error: %v\n", err) return nil, err } LastInsertId, _ := ret.LastInsertId() return &pb.CreateEventResponse{EventId: LastInsertId}, nil } <|start_filename|>generators/gather_protos/index.js<|end_filename|> const Generator = require('../../lib'); const fs = require('fs'); const yaml = require('js-yaml'); const _ = require('lodash'); const { ProtoInfo } = require('../../lib/proto'); module.exports = class extends Generator { // The name `constructor` is important here constructor(args, opts) { // Calling the super constructor is important so our generator is correctly set up super(args, opts); this.option("protoList", { type: Array, required: false }) } async initializing() { this.protoInfos = {} // list all proto names if (!this.options["protoList"]) { this.protos = fs.readdirSync(this.destinationPath("./proto")) this.protos = this.protos.filter(p => !fs.statSync(this.destinationPath(`./proto/${p}`)).isFile()) this.log("the following proto list will be include to be scanning: \n", this.protos.join("\n")) } } async prompting() { let format = await this.prompt({ type: "list", name: "format", message: "Select the format that you want to generate to:", choices: [{ name: "YAML" }, { name: "JSON" }] }) this.format = format.format } async configuring() { // scanning all protos for (const proto of this.protos) { this.protoInfos[proto] = []; let tempProtoInfo = await new ProtoInfo(`./proto/${proto}/${proto}.proto`).init(); for (const key in tempProtoInfo.methodsList) { let list = tempProtoInfo.methodsList[key]; list = list.map(method => { return { file: proto, package: tempProtoInfo.packageName, service: tempProtoInfo.serviceList[key], path: `${tempProtoInfo.packageName}.${tempProtoInfo.serviceList[key]}.${method.name}`, ...method } }) this.protoInfos[proto] = _.concat(this.protoInfos[proto], list); } } } async default() { } async writing() { if (this.format === "YAML") { this.fs.write(this.destinationPath("./proto/proto_info.yml"), yaml.safeDump(this.protoInfos)) } else if (this.format === "JSON") { this.fs.writeJSON(this.destinationPath("./proto/proto_info.json"), this.protoInfos) } } async conflicts() { } async install() { } async end() { } }; <|start_filename|>generators/schedule/templates/broker/_broker.go<|end_filename|> package broker import ( "fmt" "log" "strings" "github.com/Shopify/sarama" "<%=repoUrl%>/config" ) // BrokerInstance faaa var BrokerInstance Broker // Broker aaa type Broker struct { producer sarama.AsyncProducer Client sarama.ConsumerGroup } // Msg aaa type Msg struct { Topic string Key string Message string } var ( brokers = config.RuntimeViper.GetString("brokers.endPoints") version = config.RuntimeViper.GetString("brokers.version") group = config.RuntimeViper.GetString("brokers.group") topics = config.RuntimeViper.GetString("brokers.topics") ) // Send 发送消息 func (b *Broker) Send(m Msg) { msg := &sarama.ProducerMessage{ Topic: m.Topic, Key: sarama.StringEncoder(m.Key), } for { fmt.Scanln(&m.Message) msg.Value = sarama.ByteEncoder(m.Message) fmt.Printf("input [%s]\n", m.Message) // // send to chain BrokerInstance.producer.Input() <- msg select { case suc := <-BrokerInstance.producer.Successes(): fmt.Printf("offset: %d, timestamp: %s", suc.Offset, suc.Timestamp.String()) case fail := <-BrokerInstance.producer.Errors(): fmt.Printf("err: %s\n", fail.Err.Error()) } } } func init() { config := sarama.NewConfig() config.Producer.RequiredAcks = sarama.WaitForAll config.Producer.Partitioner = sarama.NewRandomPartitioner config.Producer.Return.Successes = true config.Producer.Return.Errors = true config.Version = sarama.V0_11_0_2 config.Consumer.Group.Rebalance.Strategy = sarama.BalanceStrategyRoundRobin config.Consumer.Offsets.Initial = sarama.OffsetOldest BrokerInstance = Broker{} var err error BrokerInstance.producer, err = sarama.NewAsyncProducer(strings.Split(brokers, ","), config) if err != nil { fmt.Printf("producer_test create producer error :%s\n", err.Error()) return } BrokerInstance.Client, err = sarama.NewConsumerGroup(strings.Split(brokers, ","), group, config) if err != nil { log.Panicf("Error creating consumer group client: %v", err) } defer BrokerInstance.producer.AsyncClose() } <|start_filename|>generators/python_ai/templates/Dockerfile<|end_filename|> FROM ubuntu:16.04 WORKDIR /root # Pick up some TF dependencies RUN apt-get update \ && apt-get install -y --no-install-recommends \ build-essential \ curl \ pkg-config \ rsync \ software-properties-common \ unzip \ git \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* # Install miniconda RUN curl -LO http://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh \ && bash Miniconda-latest-Linux-x86_64.sh -p /miniconda -b \ && rm Miniconda-latest-Linux-x86_64.sh ENV PATH /miniconda/bin:$PATH # Create a conda environment ENV CONDA_ENV_NAME iris-predictor COPY environment.yml ./environment.yml RUN conda env create -f environment.yml -n $CONDA_ENV_NAME ENV PATH /miniconda/envs/${CONDA_ENV_NAME}/bin:$PATH # cleanup tarballs and downloaded package files RUN conda clean -tp -y \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* # gRPC EXPOSE 50052 # REST EXPOSE 5000 # Environment variables ENV MAX_WORKERS 1 ENV PORT 50052 COPY . /root/ CMD python server.py --max_workers ${MAX_WORKERS} --port ${PORT} <|start_filename|>generators/eventAggregate/templates/db/_db.go<|end_filename|> package db import ( "database/sql" "fmt" "log" "<%=repoUrl%>/config" _ "github.com/go-sql-driver/mysql" ) var ( username = "root" password = "<PASSWORD>" dbName = "events" // Db 数据库链接 Db *sql.DB ) // ConnectDb init DB instance func ConnectDb() error { Db, _ = sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", config.RuntimeViper.GetString("mysql.username"), config.RuntimeViper.GetString("mysql.password"), config.RuntimeViper.GetString("mysql.service"), config.RuntimeViper.GetInt("mysql.port"), config.RuntimeViper.GetString("mysql.dbName"))) log.Println("begin connect DB") //设置数据库最大连接数 Db.SetConnMaxLifetime(100) //设置上数据库最大闲置连接数 Db.SetMaxIdleConns(10) //验证连接 if err := Db.Ping(); err != nil { log.Fatalf("open database fail %v", err) return err } log.Println("DB connected") return nil } func init() { ConnectDb() } <|start_filename|>generators/eventAggregate/index.js<|end_filename|> const Generator = require('../../lib'); const fs = require('fs'); const path = require('path'); const mkdir = require('mkdirp'); const _ = require('lodash'); module.exports = class extends Generator { // The name `constructor` is important here constructor(args, opts) { // Calling the super constructor is important so our generator is correctly set up super(args, opts); // Next, add your custom code this.option('babel'); // This method adds support for a `--babel` flag } async initializing() { return this.log("Generate EventAggregate is currently not suported!") } async prompting() { // this.answers = await this.prompt([ // { // type: "input", // name: "projectName", // message: "Your Golang project name", // default: this.appname // Default to current folder name // }, // { // type: "input", // name: "serviceName", // message: "Your Golang micro service name", // default: this.appname // Default to current folder name // }, // { // type: "confirm", // name: "cool", // message: "Would you like to enable the Cool feature?" // } // ]); // this.answers.projectName = _.snakeCase(this.answers["projectName"]); // this.answers.serviceName = _.snakeCase(this.answers["serviceName"]); // let repoUrl = await this.prompt([ // { // type: 'input', // name: 'repoUrl', // message: 'What is your repository URL?', // default: `github.com/${this.answers["projectName"]}/${this.answers["serviceName"]}.git` // } // ]) // this.answers.repoUrl = repoUrl["repoUrl"].replace(/^https:\/\//, '').toLowerCase(); } async configuring() { } async default() { } async writing() { // this.log("app serviceName", this.answers.serviceName); // this.log("app repoUrl", this.answers.repoUrl); // this.log("cool feature", this.answers.cool); // let dirs = {} // dirs.configsDir = 'config'; // dirs.brokerDir = 'broker'; // dirs.clientsDir = 'clients'; // dirs.deploymentDir = 'deployment'; // dirs.servicesDir = 'handler'; // dirs.dbDir = 'db'; // dirs.modelsDir = 'models'; // var configObj = { // appName: this.answers.projectName, // serviceName: this.answers.serviceName, // repoUrl: this.answers.repoUrl // } // for (const key in dirs) { // if (dirs.hasOwnProperty(key)) { // const element = dirs[key]; // mkdir.sync(this.destinationPath(element)); // let files = fs.readdirSync(this.templatePath(element)) // this.log("element:", this.templatePath(element)) // this.log("files:", files) // } // } // var rootFiles = ['.dockerignore', 'Dockerfile', 'crons.yaml', 'LICENSE', 'update_proto.sh'] // var rootTemplate = ['Makefile', 'README.md', '_.gitignore', '_main.go', '_go.mod'] // rootFiles.map(fname => { // this.fs.copy( // this.templatePath(fname), // path.join("./", fname) // ) // }) // rootTemplate.map(fname => { // let fName = fname.replace(/^_/, "") // this.fs.copyTpl( // this.templatePath(fname), // path.join("./", fName), // configObj // ) // }) } async conflicts() { } async install() { } async end() { // add exicute right to the bash file // fs.chmodSync(path.join("./", 'update_proto.sh'), 755) } }; <|start_filename|>generators/ts_app/templates/Makefile<|end_filename|> IP:=$(shell /sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:") NAME := <%=serviceName%>_srv SERVICE_VERSION := <%=version%> PORT := 50051 .PHONY: proto-js proto-js: protoc --js_out=./proto/users proto/users/users.proto protoc --js_out=./proto/editors proto/editors/editors.proto protoc --js_out=./proto/managers proto/managers/managers.proto protoc --js_out=./proto/orders proto/orders/orders.proto protoc --js_out=./proto/puzzle_games proto/puzzle_games/puzzle_games.proto .PHONY:server server: yarn install npm start .PHONY:docker docker: yarn install yarn run compile docker build . -t asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) .PHONY:run-docker run-docker: docker run -p 3030:3030 asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) .PHONY:push push: # docker tag asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) docker push asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) .PHONY:istio istio: istioctl kube-inject -f deployment/frontend_deployment.yaml -o deployment/frontend_deployment-injected.yaml .PHONY:deploy deploy: kubectl apply -f deployment/frontend_deployment-injected.yaml .PHONY:istio-deploy istio-deploy: kubectl apply -f <(istioctl kube-inject -f deployment/frontend_deployment.yaml) .PHONY: run-client run-client: grpcc --proto ./proto/rbac/rbac.proto --address $(IP):$(PORT) -i # let ee = client.sayHello({name:"yue"}, printReply) <|start_filename|>generators/java_app/templates/grpc-server/src/main/java/grpc/methods/Greeting.java<|end_filename|> package grpc.methods; public class Greeting { } <|start_filename|>meta.js<|end_filename|> module.exports = { project: 'Create a new Mikudos project in the current folder', protos: 'Create a protos project with a proto folder which contains all your proto files', app: 'Create a Mikudos service in the current folder', java_app: 'Create a Mikudos service with JAVA in the current folder', cpp_app: 'Create a Mikudos service with C++ in the current folder', golang_app: 'Create a Mikudos service with GoLang in the current folder', golang_service: 'not support yet', cs_app: 'Create a Mikudos service with C# in the current folder', node_app: 'Create a Mikudos service with NodeJs in the current folder', node_service: 'not support yet', ruby_app: 'Create a Mikudos service with Ruby in the current folder', ts_app: 'Create a Mikudos service with Typescript in the current folder', python_app: 'Create a Mikudos service with Python in the current folder', python_service: 'not support yet', python_ai: 'Create a Mikudos service with Python for AI in the current folder', deployment: 'Create a Mikudos deployment template in the current folder', eventAggregate: 'Create a Mikudos eventAggregate service in the current folder', message_pusher: "Create a Mikudos message_pusher service in the current folder", ts_service: 'Generate a new methods implementation', schedule: 'Create a Mikudos schedule service within your project', gate: 'Create a Mikudos gate server within your project', rbac: 'Create a Mikudos RBAC service in the current folder', }; <|start_filename|>lib/index.js<|end_filename|> const Generator = require('yeoman-generator'); const fs = require('fs'); const cp = require('child_process'); const path = require('path'); const mkdir = require('mkdirp'); module.exports = class extends Generator { async gatherProtofiles() { // gather all the protos, and select one for generate service if (!fs.existsSync(this.destinationPath("./proto")) || !fs.statSync(this.destinationPath("./proto")).isDirectory()) return; this.protos = fs.readdirSync(this.destinationPath("./proto")) this.protos = this.protos.filter(p => !fs.statSync(this.destinationPath(`./proto/${p}`)).isFile()) } async _copyEveryFile(parentPath, dirs, configObj) { for (const key in dirs) { if (dirs.hasOwnProperty(key)) { let element = dirs[key]; let eleWithName; if (this.options["name"]) eleWithName = this.answers.serviceName + "/" + element; mkdir.sync(this.destinationPath(eleWithName || element)); let files = fs.readdirSync(this.templatePath(element)) let childDirs = []; for (let index = 0; index < files.length; index++) { const f = files[index]; let fPath = this.templatePath(`${element}/${f}`) if (fs.statSync(fPath).isFile()) { let fName = f.replace(/^_/, "") this.fs.copyTpl( this.templatePath(`${element}/${f}`), path.join("./", `${eleWithName || element}/${fName}`), configObj ) } else { childDirs.push(`${element}/${f}`) } } await this._copyEveryFile("./", childDirs, configObj) } } } async _copyRootFile(rootFiles, rootTemplate, configObj) { for (let index = 0; index < rootFiles.length; index++) { let fname = rootFiles[index]; this.fs.copy( this.templatePath(fname), path.join("./", this.options["name"] ? this.answers.serviceName + "/" + fname : fname) ) } for (let index = 0; index < rootTemplate.length; index++) { let fname = rootTemplate[index]; let fName = fname.replace(/^_/, "") if (this.options["name"]) { fName = this.answers.serviceName + "/" + fName; } this.fs.copyTpl( this.templatePath(fname), path.join("./", fName), configObj ) } } async addExecuteRight(type) { switch (type) { case 'update_proto': // add exicute right to the bash file cp.exec(`chmod 755 ${path.join("./", this.options["name"] ? this.answers.serviceName + "/" + 'update_proto.sh' : 'update_proto.sh')}`); break; default: break; } } } <|start_filename|>generators/java_app/templates/grpc-server/src/main/java/grpc/service/HelloServiceImpl.java<|end_filename|> package grpc.service; import greeter.GreetingServiceGrpc; import greeter.HelloRequest; import greeter.HelloResponse; import io.grpc.stub.StreamObserver; public class HelloServiceImpl extends GreetingServiceGrpc.GreetingServiceImplBase { @Override public void greeting(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { System.out.println(request); String greeting = "Hello there, " + request.getName(); HelloResponse response = HelloResponse.newBuilder().setGreeting(greeting).build(); responseObserver.onNext(response); responseObserver.onCompleted(); } } <|start_filename|>generators/node_app/templates/src/index.js<|end_filename|> const app = require('./app'); function main() { app.start(`0.0.0.0:${app.config.get('port')}`); console.log(`${app.config.get('app')} is started at Port: ${app.ports}`); } main(); <|start_filename|>generators/python_ai/templates/Makefile<|end_filename|> ENV_NAME := <%=serviceName%> NAME := <%=serviceName%>_service SERVICE_VERSION := 0.0.1 ENV_FILE := environment.yml .PHONY: update-proto update-proto: ./update_proto.sh # .PHONY: proto # proto: update-proto # protoc --python_out=. proto/ai/ai.proto .PHONY: proto-py proto-py: update-proto <% protos.forEach(function(item){ %> python -m grpc_tools.protoc -I. --python_out=. --python_grpc_out=. ./proto/<%=item%>/*.proto <% }); %> .PHONY: init-env init-env: clean-env echo "create conda env $(ENV_NAME)" conda env create -f $(ENV_FILE) -n $(ENV_NAME) conda env list .PHONY: env env: conda activate $(ENV_NAME) .PHONY: env-update env-update: conda env update -n $(ENV_NAME) --file $(ENV_FILE) --prune .PHONY: clean-env clean-env: conda env remove -y -n $(ENV_NAME) .PHONY: server server: proto-py python server.py .PHONY: client client: python client.py .PHONY: docker docker: docker build . -t $(NAME):$(SERVICE_VERSION) .PHONY: docker-run docker-run: docker run --rm -p 50052:50052 --env PYTHON_ENV=development --name $(NAME) $(NAME):$(SERVICE_VERSION) <|start_filename|>generators/java_app/templates/Makefile<|end_filename|> IP:=$(shell /sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:") NAME := <%=serviceName%>_srv SERVICE_VERSION := 0.0.1 PORT := 50051 .PHONY: update-proto update-proto: ./update_proto.sh .PHONY:clean clean: mvn clean .PHONY:install install: clean mvn install .PHONY:run-server run-server: java -jar grpc-server/target/grpc-server-1.0-SNAPSHOT.jar .PHONY:server server: install run-server .PHONY:docker docker: docker build . -t asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) .PHONY:run-docker run-docker: echo $(IP) docker run -p $(PORT):$(PORT) --env BROKER_ADDRESSES=192.168.199.185:9092 asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) .PHONY:push push: docker push asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) .PHONY:istio istio: istioctl kube-inject -f deployment/learn_service_deploy.yaml -o deployment/user_service_deploy-injected.yaml .PHONY:istio-deploy istio-deploy: kubectl apply -f <(istioctl kube-inject -f deployment/user_service_deploy.yaml) .PHONY: run-client run-client: grpcc --proto ./proto/users/users.proto --address 127.0.0.1:$(PORT) -i # let ee = client.sayHello({name:"yue"}, printReply) <|start_filename|>generators/node_app/templates/src/grpc_clients/greeter.client.js<|end_filename|> const path = require('path') const caller = require('grpc-caller') module.exports = function (app) { const file = path.resolve(__dirname, '../../proto/greeter/greeter.proto') const load = { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true } app.context.grpcClients.greeterClient = caller('mikudos_greeter_service:50051', { file, load }, 'GreeterService') }; <|start_filename|>generators/java_app/templates/broker/src/main/java/com/mikudos/broker/Broker.java<|end_filename|> package com.mikudos.broker; public class Broker { public void echo() { System.out.println("broker echo"); } } <|start_filename|>generators/node_app/templates/src/app.js<|end_filename|> const { Application } = require('mikudos-node-app'); const path = require('path'); const mongoose = require('./mongoose'); const middleware = require('./middleware'); const models = require('./models'); const grpc_clients = require('./grpc_clients'); const services = require('./services'); const PROTO_PATH = path.resolve( __dirname, '../proto/helloworld/helloworld.proto' ); const app = new Application(PROTO_PATH); app.configure(mongoose); app.configure(models); // app.configure(broker) app.configure(grpc_clients); app.configure(middleware); app.configure(services); module.exports = app; <|start_filename|>generators/schedule/templates/handler/_init.go<|end_filename|> package handler import ( "encoding/json" "io/ioutil" "log" "github.com/robfig/cron/v3" "<%=repoUrl%>/config" pb "<%=repoUrl%>/proto/schedule" "<%=repoUrl%>/schedule" "gopkg.in/yaml.v2" ) func startAllPersistCron(persistData map[string]map[cron.EntryID]schedule.CronModel) (err error) { for _, model := range persistData["CronJobs"] { var ( grpc pb.GrpcCall event pb.BrokerEvent sche pb.Schedule ) err = json.Unmarshal([]byte(model.Grpc), &grpc) err = json.Unmarshal([]byte(model.BrokerEvent), &event) err = json.Unmarshal([]byte(model.Schedule), &sche) if grpc.GetClientName() != "" { id, err := AddGrpcCron(sche.GetPeriod(), &grpc, &sche, false) if err != nil { log.Println(err) } else { log.Println("cron id:", id) } } else if event.GetMessage() != "" { id, err := AddBrokerCron(sche.GetPeriod(), &event, &sche, false) if err != nil { log.Println(err) } else { log.Println("cron id:", id) } } } for _, model := range persistData["OneTimeJobs"] { var ( grpc pb.GrpcCall event pb.BrokerEvent sche pb.Schedule ) err = json.Unmarshal([]byte(model.Grpc), &grpc) err = json.Unmarshal([]byte(model.BrokerEvent), &event) err = json.Unmarshal([]byte(model.Schedule), &sche) if grpc.GetClientName() != "" { id, err := AddGrpcCron(sche.GetPeriod(), &grpc, &sche, true) if err != nil { log.Println(err) } else { log.Println("cron id:", id) } } else if event.GetMessage() != "" { id, err := AddBrokerCron(sche.GetPeriod(), &event, &sche, true) if err != nil { log.Println(err) } else { log.Println("cron id:", id) } } } return err } func test() { id, err := AddGrpcCron("@every 5s", &pb.GrpcCall{ ClientName: "ai", MethodName: "SayHello", PayloadStr: "{\"name\":\"<NAME>\",\"age\":12}", }, &pb.Schedule{ Period: "@every 5s", ScheduleName: "测试 ai.SayHello 任务", ScheduleComment: "每隔5秒钟调用一次ai.SayHello", }, false) if err != nil { log.Println(err) } else { log.Println("cron id:", id) } } func init() { // test() // read persistence file, init all persistence CRONS buf, err := ioutil.ReadFile(config.RuntimeViper.GetString("persistentFile")) if err != nil { log.Fatalln("persistence File read Error!") } persistData := map[string]map[cron.EntryID]schedule.CronModel{} if err := yaml.Unmarshal(buf, &persistData); err != nil { log.Fatalln("persistence Data has Error!") } // log.Printf("CronJobs: %+v", persistData["CronJobs"]) // log.Printf("OneTimeJobs: %+v", persistData["OneTimeJobs"]) if err := startAllPersistCron(persistData); err != nil { log.Fatalln("start persistence CRONS Error!") } } <|start_filename|>generators/java_app/templates/grpc-server/src/main/java/Main.java<|end_filename|> import grpc.Server; import java.io.FileNotFoundException; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException, InterruptedException { new Server().start(); } } <|start_filename|>generators/node_app/templates/src/middleware/logger.js<|end_filename|> function logger(format) { format = format || ':name [:type]' return async function (ctx, next) { const str = format .replace(':name', ctx.name) .replace(':type', ctx.type) console.log(str) await next() } } module.exports = logger; <|start_filename|>generators/python_service/index.js<|end_filename|> const Generator = require('../../lib'); module.exports = class extends Generator { // The name `constructor` is important here constructor(args, opts) { // Calling the super constructor is important so our generator is correctly set up super(args, opts); // Next, add your custom code this.option('babel'); // This method adds support for a `--babel` flag } async initializing() { return this.log("Generate Python Serivce method is currently not suported!") } async prompting() { // this.answers = await this.prompt([ // { // type: "input", // name: "name", // message: "Your Python service name", // default: this.appname // Default to current folder name // }, // { // type: "confirm", // name: "cool", // message: "Would you like to enable the Cool feature?" // } // ]); } async configuring() { } async default() { } async writing() { // this.log("app name", this.answers.name); // this.log("cool feature", this.answers.cool); } async conflicts() { } async install() { } async end() { } }; <|start_filename|>generators/schedule/templates/schedule/_persistence.go<|end_filename|> package schedule import ( "io/ioutil" "log" cron "github.com/robfig/cron/v3" "<%=repoUrl%>/config" "gopkg.in/yaml.v2" ) func persistence() { Cron.AddFunc(config.RuntimeViper.GetString("persistentWritePeriod"), func() { out, err := yaml.Marshal(map[string]map[cron.EntryID]CronModel{"CronJobs": CronJobs, "OneTimeJobs": OneTimeJobs}) if err != nil { } if err := ioutil.WriteFile(config.RuntimeViper.GetString("persistentFile"), out, 0644); err != nil { log.Println("persistence File Write fail!") } }) } <|start_filename|>generators/protos/index.js<|end_filename|> const Generator = require('../../lib'); const _ = require('lodash'); const path = require('path'); const mkdir = require('mkdirp'); module.exports = class extends Generator { // The name `constructor` is important here constructor(args, opts) { // Calling the super constructor is important so our generator is correctly set up super(args, opts); this.option("projectName", { type: String, required: false }) this.option("folder", { type: String, required: false }) this.option("name", { type: String, required: false }) this.option("withSchedule", { type: Boolean }) this.option("withEvAgg", { type: Boolean }) this.option("withMessage", { type: Boolean }) } _method1() { this.log(this.options, this.destinationPath(this.options["name"] + "/proto/" + "users")); } async _srvProto(srvName, protoName = "proto") { let serviceProtoPath = this.options["name"] ? `${this.options["name"]}/proto/${srvName}` : `proto/${srvName}`; mkdir.sync(this.destinationPath(serviceProtoPath)); this.fs.copyTpl( this.templatePath(`_${protoName}.proto`), path.join(`${serviceProtoPath}/${srvName}.proto`), this.configObj ) } async initializing() { } async prompting() { let protos = [], proto; if (!this.options["name"]) { let conf = await this.prompt([ { type: "input", name: "name", message: "Your protos project name:", default: this.appname // Default to current folder name }, { type: "checkbox", name: "services", message: "Please select available service protos", choices: ['schedule', 'event_aggregate', 'messages'] } ]) protos = _.uniq(_.concat(protos, conf["services"])); } do { proto = await this.prompt([ { type: "input", name: "protoName", message: "Add proto for micro_service with name:", default: "" // Default to current folder name } ]); if (proto["protoName"]) protos = _.uniq(_.concat(protos, proto["protoName"])) } while (proto["protoName"]); this.answers = await this.prompt([ { type: "confirm", name: "confirm", message: `Do you want to generate all proto file for micro_service within ${JSON.stringify(protos)}` } ]) if (this.answers.confirm) { this.answers.protos = protos for (const proto of this.answers.protos) { this.configObj = { appName: this.answers.projectName, proto: _.snakeCase(proto), protoCamel: _.camelCase(proto), protoCamelCapitalize: _.camelCase(proto).replace(/^[a-z]/g, (L) => L.toUpperCase()), } await this._srvProto(proto) } } if (this.options["withSchedule"]) { await this._srvProto("schedule", "schedule") } if (this.options["withEvAgg"]) { await this._srvProto("event_aggregate", "event_aggregate") } if (this.options["withMessage"]) { await this._srvProto("messages", "messages") } } async configuring() { } async default() { } async writing() { this.log("confirm:", JSON.stringify(this.answers.protos)) await this._copyEveryFile("./", { proto: 'proto' }, this.configObj) } async conflicts() { } async install() { } async end() { } }; <|start_filename|>generators/node_app/templates/src/mongoose.js<|end_filename|> const mongoose = require('mongoose'); module.exports = function (app) { mongoose.connect(app.config.get('mongodb'), { useUnifiedTopology: true, useNewUrlParser: true }); mongoose.Promise = global.Promise; app.mongooseClient = mongoose; app.context.models = {}; } <|start_filename|>generators/node_service/templates/service/_method.map.js<|end_filename|> export = { <% methods.forEach(function(item, index){ %> <%=item.name%>: '<%=item.name%>'<% if (index<methods.length-1) { %>,<% } }); %> }; <|start_filename|>generators/message_pusher/templates/server/init.go<|end_filename|> package server import ( "encoding/json" "log" "github.com/mikudos/mikudos-message-pusher/db" pb "github.com/mikudos/mikudos-message-pusher/proto/message-pusher" ) // Handler Server instance var Handler Server func init() { Handler = Server{Mode: "group", Recv: make(chan *pb.Message), Returned: make(map[string]map[uint32]chan *pb.Response), GroupRecv: make(map[string]chan *pb.Message), EveryRecv: make(map[uint32]chan *pb.Message), SaveMsg: make(chan *pb.Message)} db.InitConfig() storage, err := db.InitStorage() if err != nil { log.Fatalf("InitStorage err: %v\n", err) } Handler.Storage = *storage initReadRoutine() } func initReadRoutine() { for index := 0; index < 1; index++ { go ReadSaveMsg(&Handler) } } // ReadSaveMsg ReadSaveMsg method func ReadSaveMsg(h *Server) { for { msg := <-h.SaveMsg Handler.Storage.SaveChannel(msg.GetChannelId(), json.RawMessage(msg.GetMsg()), msg.GetMsgId(), uint(msg.GetExpire())) } } <|start_filename|>generators/rbac/templates/Makefile<|end_filename|> IP:=$(shell /sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:") NAME := <%=serviceName%>_srv SERVICE_VERSION := 0.0.1 PORT := 50051 .PHONY:server server: yarn install npm start .PHONY:docker docker: yarn install yarn run compile docker build . -t asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) .PHONY:run-docker run-docker: docker run -p 3030:3030 asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) .PHONY:push push: # docker tag asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) docker push asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) .PHONY:istio istio: istioctl kube-inject -f deployment/frontend_deployment.yaml -o deployment/frontend_deployment-injected.yaml .PHONY:deploy deploy: kubectl apply -f deployment/frontend_deployment-injected.yaml .PHONY:istio-deploy istio-deploy: kubectl apply -f <(istioctl kube-inject -f deployment/frontend_deployment.yaml) <|start_filename|>generators/node_app/templates/src/broker.js<|end_filename|> const BROKER_ADDRESSES = process.env.BROKER_ADDRESSES ? String(process.env.BROKER_ADDRESSES).split(',') : null; const { Kafka } = require('kafkajs'); const run = async (consumer) => { await consumer.subscribe({ topic: 'test-topic', fromBeginning: true }) await consumer.run({ eachMessage: async ({ topic, partition, message }) => { console.log({ partition, offset: message.offset, value: message.value.toString(), }) }, }) } module.exports = function (app) { if (BROKER_ADDRESSES) app.config.brokers = BROKER_ADDRESSES const kafka = new Kafka({ clientId: app.config.get('app'), brokers: app.config.get('brokers') }) const producer = kafka.producer() const ProducerConnectPromise = producer.connect() const consumer = kafka.consumer({ groupId: app.config.get('consumer_group') }) const ConsumerConnectPromise = consumer.connect() ProducerConnectPromise.then(() => { app.context.broker = producer; }) ConsumerConnectPromise.then(() => { app.context.consumer = consumer; run(consumer) }) } <|start_filename|>generators/rbac/templates/Dockerfile<|end_filename|> FROM mhart/alpine-node:12 WORKDIR /app COPY . . # RUN apk add --no-cache make gcc g++ python RUN npm install --prod # ENV NODE_ENV production EXPOSE 50051 CMD ["npm", "run", "prod"] <|start_filename|>generators/eventAggregate/templates/Makefile<|end_filename|> GOPATH:=$(shell go env GOPATH) NAME := <%=serviceName%>-srv SERVICE_VERSION := 0.0.1 PORT := 50051 .PHONY: update-proto update-proto: ./update_proto.sh .PHONY: proto proto: update-proto protoc --proto_path=${GOPATH}/src:. --go_out=plugins=grpc:. proto/event_aggregate/event_aggregate.proto .PHONY: proto-js proto-js: protoc --js_out=./proto/event_aggregate proto/event_aggregate/event_aggregate.proto .PHONY: proto-py proto-py: protoc --python_out=. proto/event_aggregate/event_aggregate.proto .PHONY: build build: proto go build -o $(NAME) main.go .PHONY: docker docker: docker build . -t asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) .PHONY: run-docker run-docker: docker run --rm -p $(PORT):$(PORT) --name $(NAME) asia.gcr.io/kubenetes-test-project-249803/$(NAME):$(SERVICE_VERSION) .PHONY: run-client run-client: grpcc --proto ./proto/event_aggregate/event_aggregate.proto --address 127.0.0.1:$(PORT) -i <|start_filename|>generators/eventAggregate/templates/models/_event.go<|end_filename|> package models type Event struct { EventId int64 `sql:",unique"` AggregateId int64 `` EventType string Data string } <|start_filename|>generators/node_app/templates/Dockerfile<|end_filename|> FROM mhart/alpine-node:12 WORKDIR /app COPY . . # RUN apk add --no-cache make gcc g++ python RUN npm install --prod EXPOSE 50051 CMD ["npm", "start"] <|start_filename|>generators/node_service/templates/service/_method.class.js<|end_filename|> /* eslint-disable no-unused-vars */ exports.<%=className%> = class <%=className%> { constructor(options = {}, app) { this.options = options; this.app = app; } async enter(ctx) { ctx.res = { message: 'Hello '.concat(ctx.req.name) } await ctx.broker.send({ topic: 'test-topic', messages: [ { value: 'Hello '.concat(ctx.req.name) }, ], }) } }; <|start_filename|>generators/schedule/index.js<|end_filename|> const Generator = require('../../lib'); const fs = require('fs'); const cp = require('child_process'); const path = require('path'); const _ = require('lodash'); module.exports = class extends Generator { // The name `constructor` is important here constructor(args, opts) { // Calling the super constructor is important so our generator is correctly set up super(args, opts); // Next, add your custom code this.option('babel'); // This method adds support for a `--babel` flag this.option("projectName", { type: String, required: false }) this.option("name", { type: String, required: false }) this.option("folder", { type: String, required: false }) } async initializing() { // gather all the protos, and select one for generate service this.protos = fs.readdirSync(this.destinationPath(`./${this.options["name"] ? this.options["name"] + "_service/" : ""}proto`)) } async prompting() { this.answers = await this.prompt([ { type: "input", name: "projectName", message: "(schedule)Your Project name", default: this.options["projectName"] || path.basename(path.resolve("../")) // Default to parent folder name }, { type: "input", name: "serviceName", message: "(schedule)Your micro Schedule service name", default: (this.options["name"] ? (this.options["name"] + "_service") : null) || this.appname // Default to current folder name }, { type: "list", name: "proto", message: "Select for your service definition a proto file", choices: this.protos.map(proto => { return { name: `${proto}.proto`, value: proto } }) }, { type: "input", name: "version", message: "(schedule)Your micro Schedule service version", default: "0.0.1" }, { type: "confirm", name: "cool", message: "Would you like to enable the Cool feature?" } ]); this.answers.projectName = _.snakeCase(this.answers["projectName"]); this.answers.serviceName = _.snakeCase(this.answers["serviceName"]); let repoUrl = await this.prompt([ { type: 'input', name: 'repoUrl', message: 'What is your repository URL?', default: `github.com/${this.answers["projectName"]}/${this.answers["serviceName"]}.git` } ]) this.answers.repoUrl = repoUrl["repoUrl"].replace(/^https:\/\//, '').toLowerCase(); } async configuring() { } async default() { } async writing() { this.log("app serviceName", this.answers.serviceName); this.log("app repoUrl", this.answers.repoUrl); this.log("cool feature", this.answers.cool); let dirs = {} dirs.configsDir = 'config'; dirs.brokerDir = 'broker'; dirs.clientsDir = 'clients'; dirs.deploymentDir = 'deployment'; dirs.servicesDir = 'handler'; dirs.scheduleDir = 'schedule'; var rootFiles = ['.dockerignore', 'Dockerfile', 'crons.yaml', 'LICENSE'] var rootTemplate = ['Makefile', 'README.md', '_.gitignore', '_main.go', '_go.mod', 'update_proto.sh'] var configObj = { appName: this.answers.projectName, serviceName: this.answers.serviceName, repoUrl: this.answers.repoUrl, version: this.answers.version, protos: this.protos, proto: this.answers.proto } await this._copyEveryFile("./", dirs, configObj) await this._copyRootFile(rootFiles, rootTemplate, configObj) } async conflicts() { } async install() { } async end() { // add exicute right to the bash file cp.exec(`chmod 755 ${path.join("./", this.options["name"] ? this.answers.serviceName + "/" + 'update_proto.sh' : 'update_proto.sh')}`) } }; <|start_filename|>generators/schedule/templates/schedule/_schedule.go<|end_filename|> package schedule import ( "log" cron "github.com/robfig/cron/v3" ) // Cron aaaa var ( Cron *cron.Cron CronJobs = map[cron.EntryID]CronModel{} OneTimeJobs = map[cron.EntryID]CronModel{} ) // CronModel CronModel type CronModel struct { Schedule string `json:"schedule"` Grpc string `json:"grpc"` BrokerEvent string `json:"brokerevent:"` } // StartCron aaa func StartCron() { defer log.Fatalln("Cron server stoped, need restart!") defer Cron.Stop() Cron.Start() log.Println("Cron server started, should never stop!~") select {} } func init() { Cron = cron.New() go StartCron() persistence() } <|start_filename|>generators/eventAggregate/templates/models/_aggregate.go<|end_filename|> package models type Aggregate struct { ID int64 AggregateType string Data string } <|start_filename|>generators/cpp_app/index.js<|end_filename|> const Generator = require('../../lib'); <|start_filename|>lib/transform/index.js<|end_filename|> const j = require('jscodeshift'); // Adding a method to all Identifiers j.registerMethods({ logNames: function () { return this.forEach(function (path) { console.log(path.node.name); }); } }, j.Identifier); // Adding a method to all collections j.registerMethods({ findIdentifiers: function () { return this.find(j.Identifier); }, insertLastInFunction(code) { let fe = this.find(j.FunctionExpression) let es = this.find(j.ExpressionStatement) fe.find(j.BlockStatement).forEach(node => { const { body } = node.value; const es = j(code).find(j.ExpressionStatement).get().value; body.push(es); }); // es.forEach(function (path) { // console.log(path.node); // }); // console.log("FunctionExpression:", this.find(j.FunctionExpression)); // console.log("ExpressionStatement:", this.find(j.ExpressionStatement)); return this; } }); module.exports = j; <|start_filename|>generators/app/index.js<|end_filename|> const Generator = require('../../lib'); const yosay = require('yosay'); const _ = require('lodash'); const fs = require('fs'); const path = require('path'); const mkdir = require('mkdirp'); const cp = require('child_process'); const SpecialParams = ["project", "protos", "deployment", "schedule", "gate"] const ParamEnum = ["app", "service"] const genName = "mikudos:" module.exports = class extends Generator { // The name `constructor` is important here constructor(args, opts) { // Calling the super constructor is important so our generator is correctly set up super(args, opts); // Next, add your custom code this.option('babel'); // This method adds support for a `--babel` flag this.argument("name", { type: String, required: false }) let all = _.concat(SpecialParams, ParamEnum) this.log(`params surport value in ${all} as params`) this.options.name = this.options.name || "app" if (all.indexOf(this.options.name) == -1) { this.log(`params Error, only surport value in ${all} as params`) } } async _genNormal(genName) { this.answers = await this.prompt([ { type: "list", name: "lang", message: "Select your programming language", choices: [ { name: "Node.js", value: 1 }, { name: "Node.js with Typescript", value: 2 }, { name: "Golang", value: 3 }, { name: "Python3.7", value: 4, short: "python" }, { name: "Ruby", value: 5 }, { name: "Java", value: 6 }, { name: "c++", value: 7 }, { name: "c#", value: 8 } ] } ]); switch (this.answers["lang"]) { case 1: genName += "node" break; case 2: genName += "ts" break; case 3: genName += "golang" break; case 4: genName += "python" break; case 5: genName += "ruby" break; case 6: genName += "java" break; case 7: genName += "cpp" break; case 8: genName += "cs" break; } return genName; } async _createProjectProtos() { this.answers = await this.prompt([ { type: "input", name: "projectName", message: "Your Project name", default: this.appname // Default to current folder name } ]); this.answers.projectName = _.snakeCase(this.answers["projectName"]); mkdir.sync(this.destinationPath(this.answers.projectName + "_protos")); let genName = "mikudos:"; await this.composeWith(`${genName}protos`, { name: this.answers.projectName + "_protos", folder: this.answers.projectName + "/" + this.answers.projectName + "_protos", withSchedule: this.confirm["schedule"], withEvAgg: this.confirm["eventAggregate"], withMessage: this.confirm["message"] }); } async _configureProtos() { // get all the protos project list let directories = fs.readdirSync(this.destinationPath(this.answers.projectName + "_protos/proto")) // create subproject folder for (const proto of directories) { if (fs.statSync(this.destinationPath(this.answers.projectName + "_protos/proto/" + proto)).isFile()) continue; mkdir.sync(this.destinationPath(`${this.answers.projectName}_${proto}_service/proto`)); } } async _syncProtoFiles() { // get all the protos project list let directories = fs.readdirSync(this.destinationPath(this.answers.projectName + "_protos/proto")) if (this.confirm['schedule']) { directories.push('schedule') } // copy proto files let command = "" for (const proto of directories) { command += `cp -r ${this.destinationPath(this.answers.projectName + "_protos")}/proto/* ${this.destinationPath(`${this.answers.projectName}_${proto}_service`)}/proto | ` } command = command.replace(/ \| $/, "") cp.exec(command) } async initializing() { this.log(yosay('Welcome to the MIKUDOS Project Generator!')); if (this.options.name == 'project') { this.confirm = await this.prompt([ { type: "confirm", name: "schedule", message: `Do you want to generate a schedule service within your project?` }, { type: "confirm", name: "eventAggregate", message: `Do you want to generate a event aggregate service within your project?` }, { type: "confirm", name: "gate", message: `Do you want to generate a gate service with socketIO server within your project?` } ]) } } async prompting() { if (this.options.name == 'project') { await this._createProjectProtos() } else if (SpecialParams.includes(this.options.name)) { this.composeWith(`${genName}${this.options.name}`, {}); } else if (ParamEnum.includes(this.options.name)) { let genNameNew = await this._genNormal(genName) this.composeWith(`${genNameNew}_${this.options.name}`, {}); } } async configuring() { } async default() { } async writing() { if (SpecialParams.includes(this.options.name)) return } async conflicts() { } async install() { if (this.options.name == "project") { await this._syncProtoFiles() // copy all proto files to all services } } async end() { if (this.options.name == "project") { await this._configureProtos() if (this.confirm['schedule']) { this.composeWith(`${genName}schedule`, { projectName: this.appname, name: this.appname + "_schedule", folder: `${this.appname}/${this.appname}_schedule` }); } if (this.confirm['eventAggregate']) { this.composeWith(`${genName}eventAggregate`, { projectName: this.appname, name: this.appname + "_event_aggregate", folder: `${this.appname}/${this.appname}_event_aggregate` }); } if (this.confirm['gate']) { this.composeWith(`${genName}gate`, { projectName: this.appname, name: this.appname + "_gate", folder: `${this.appname}/${this.appname}_gate` }); } } } }; <|start_filename|>generators/ts_service/index.js<|end_filename|> const Generator = require('../../lib'); const { ProtoInfo } = require('../../lib/proto'); const fs = require('fs'); const mkdir = require('mkdirp'); const _ = require('lodash'); module.exports = class extends Generator { // The name `constructor` is important here constructor(args, opts) { // Calling the super constructor is important so our generator is correctly set up super(args, opts); } async initializing() { this.proto = this.options['proto']; if (this.proto) { this.protoInfo = await new ProtoInfo(`./proto/${this.proto}/${this.proto}.proto`).init(); } if (this.options['client']) { // gather all the protos this.protos = fs.readdirSync(this.destinationPath(`./${this.options["name"] ? this.options["name"] + "_service/" : ""}proto`)) this.protos = this.protos.filter(p => !fs.statSync(this.destinationPath(`./proto/${p}`)).isFile()) if (this.protos.includes(this.proto)) { this.protos.splice(this.protos.indexOf(this.proto), 1) } } } async prompting() { this.answers = {} if (this.proto) { // prepare for generate serive files let confirm = await this.prompt({ type: "confirm", name: "confirm", message: "Do you want to generate implementation for all Services?" }) if (confirm.confirm) { this.answers['serviceList'] = this.protoInfo.serviceList.map((name, index) => index) } else { this.answers = await this.prompt([ { type: "checkbox", name: "serviceList", message: "Select the service Name that you want to generate for:", choices: this.protoInfo.serviceList.map((name, index) => { return { name, value: index } }) } ]) } } if (this.options['client']) { let clientList = await this.prompt([ { type: "checkbox", name: "clientList", message: "Select the proto folder for the Clients that you want to generate for:", choices: this.protos.map((name, index) => { return { name, value: index } }) } ]) this.answers['clientList'] = clientList['clientList']; } if (!this.options['clientFolder']) { let folder = await this.prompt({ type: "input", name: "folder", message: "Please write the folder name which located in src folder, and under that you want to generate your client implementation files.", default: this.options['clientFolder'] || "grpc_clients" }) this.options['clientFolder'] = folder.folder; } } async configuring() { } async default() { } async writing() { if (this.proto) { // generate files for implementation all methods for each service for (const key in this.answers['serviceList']) { const serviceIndex = this.answers['serviceList'][key]; let serviceName = this.protoInfo.serviceList[serviceIndex]; mkdir.sync(this.destinationPath(`./src/services/${_.snakeCase(serviceName)}`)); let files = fs.readdirSync(this.templatePath('_method')); for (let index = 0; index < files.length; index++) { const f = files[index]; let fPath = this.templatePath(`_method/${f}`) if (fs.statSync(fPath).isFile()) { let fName = f.replace(/^_method/, _.snakeCase(serviceName)) this.fs.copyTpl( this.templatePath(`_method/${f}`), this.destinationPath(`./src/services/${_.snakeCase(serviceName)}/${fName}`), { serviceName, serviceNameSnake: _.snakeCase(serviceName), methods: this.protoInfo.methodsList[serviceIndex], serviceObj: this.protoInfo.packageObject[this.protoInfo.packageName][serviceName] } ) } } } // handle the service configure this.fs.copyTpl( this.templatePath(`index.ts`), this.destinationPath(`./src/services/index.ts`), { serviceNames: this.answers['serviceList'].map(serviceIndex => { return { camelCase: this.protoInfo.serviceList[serviceIndex], snakeCase: _.snakeCase(this.protoInfo.serviceList[serviceIndex]) } }) } ) } if (this.options['client']) { // generate all client implementation for (const key in this.answers['clientList']) { let tempProto = this.protos[this.answers['clientList'][key]]; let tempProtoInfo = await new ProtoInfo(`./proto/${tempProto}/${tempProto}.proto`).init(); this.fs.copyTpl( this.templatePath(`grpc_clients/_impl.client.ts`), this.destinationPath(`./src/${this.options['clientFolder']}/${_.snakeCase(tempProtoInfo.packageName)}.client.ts`), { proto: tempProto, protoCamel: _.camelCase(tempProto), serviceNames: tempProtoInfo.serviceList, serviceNamesSnake: tempProtoInfo.serviceList.map(name => _.snakeCase(name)), methods: tempProtoInfo.methodsList } ) } // handle the clients configure this.fs.copyTpl( this.templatePath(`grpc_clients/index.ts`), this.destinationPath(`./src/${this.options['clientFolder']}/index.ts`), { protos: this.answers['clientList'].map(index => this.protos[index]), protosCamel: this.answers['clientList'].map(index => _.camelCase(this.protos[index])) } ) } } async conflicts() { } async install() { } async end() { } } <|start_filename|>generators/node_app/templates/src/models/index.js<|end_filename|> const games = require('./game.model'); module.exports = function (app) { app.context.models.games = games(app); } <|start_filename|>generators/node_service/templates/service/_method.hooks.js<|end_filename|> module.exports = { before: [ async function (ctx, next) { // TransactionManager.beginTransaction(hook, skipPath) await next() } ], after: [ async function (ctx, next) { // TransactionManager.commitTransaction await next() } ] } <|start_filename|>lib/proto/index.js<|end_filename|> const protoLoader = require('@grpc/proto-loader'); const grpcLibrary = require('@grpc/grpc-js'); const _ = require('lodash'); // let protoFileName = "./proto/rbac/rbac.proto" let options = { keepCase: true } class ProtoInfo { constructor(protoFileName) { this.protoFileName = protoFileName; } async init() { let packageDefinition = await protoLoader.load(this.protoFileName, options); this.packageObject = grpcLibrary.loadPackageDefinition(packageDefinition); this.packageName = Object.keys(packageDefinition)[0].split('.')[0]; this.serviceList = []; this.methodsList = []; for (const i in this.packageObject[this.packageName]) { const item = this.packageObject[this.packageName][i]; if (item.service) { this.serviceList.push(i); // console.log('item', item.service); this.methodsList.push(Object.keys(item.service).map(name => { let type = _.at(item.service[name], ['requestStream', 'responseStream']) return { name, type: type[0] && type[1] ? 'duplex' : (type[0] ? 'requestStream' : (type[1] ? 'responseStream' : 'unary')) } })); } } return this; } } module.exports = { ProtoInfo }
mikudos/generator-mikudos
<|start_filename|>Core/hkAssetManagementUtil.cpp<|end_filename|> /* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2014 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #include "hkAssetManagementUtil.h" #include <Common/Base/System/Io/IStream/hkIStream.h> #define NEED_PLATFORM_SPECIFIC_EXTENSION const char* hkAssetManagementUtil::getFileEnding(hkStringBuf& e, hkStructureLayout::LayoutRules rules) { hkStructureLayout l; e.printf("_L%d%d%d%d", rules.m_bytesInPointer, rules.m_littleEndian? 1 : 0, rules.m_reusePaddingOptimization? 1 : 0, rules.m_emptyBaseClassOptimization? 1 : 0); return e; } static bool _fileExists( const char* filename ) { // Open hkIfstream file( filename ); // Check if (file.isOk()) { // Dummy read char ch; file.read( &ch , 1); return file.isOk(); } return false; } const char* HK_CALL hkAssetManagementUtil::getFilePath( hkStringBuf& filename, hkStructureLayout::LayoutRules rules ) { #ifdef NEED_PLATFORM_SPECIFIC_EXTENSION if (! _fileExists( filename ) ) { // Try platform extension int extn = filename.lastIndexOf('.'); if (extn != -1) { hkStringBuf fe; getFileEnding(fe, rules); filename.insert(extn, fe); } } #endif #ifdef HK_DEBUG { int a0 = filename.lastIndexOf('\\'); int a1 = filename.lastIndexOf('/'); int aLen = filename.getLength() - 1; // last index int mD0 = a0 >= 0? a0 : 0; int mD1 = a1 >= 0? a1 : 0; int maxSlash = mD0 > mD1? mD0 : mD1; if ( (aLen - maxSlash) > 42 ) { hkStringBuf w; w.printf("Your file name [%s] is longer than 42 characters. May have issues on some consoles (like Xbox360).", filename.cString() ); HK_WARN(0x04324, w.cString() ); } } #endif return filename; } const char* hkAssetManagementUtil::getFilePath( hkStringBuf& filename ) { return getFilePath( filename, hkStructureLayout::HostLayoutRules ); } const char* HK_CALL hkAssetManagementUtil::getFilePath( const char* pathIn, hkStringBuf& pathOut) { pathOut = pathIn; return getFilePath( pathOut, hkStructureLayout::HostLayoutRules ); } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907) * * Confidential Information of Havok. (C) Copyright 1999-2014 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */ <|start_filename|>Core/MathHelper.h<|end_filename|> #include <iostream> #include <cmath> #define _USE_MATH_DEFINES #include <math.h> using namespace std; double rad2deg(double rad) { return rad*180.0/M_PI; }
Lunaretic/fbxinterop
<|start_filename|>packages/plugin-graphql/test/unit/common.spec.js<|end_filename|> const expect = require('chai').expect; const { getQueryHash } = require('../../src/core/common.server'); describe('Unit Test: Data', function() { describe('Common', function() { describe('getQueryHash', function() { it('should return the expected hash for a standard graph query', function () { // __typename is added by server.js const query = ` query { graph { id, title, route, path, filename, template, __typename } } `; const hash = getQueryHash(query); expect(hash).to.be.equal('380713565'); }); it('should return the expected hash for a custom graph query with custom data', function () { const query = ` query { graph { title, route, data { date, image } } } `; const hash = getQueryHash(query); expect(hash).to.be.equal('1136154652'); }); it('should return the expected hash for a children query with a variable', function () { const query = ` query($parent: String!) { children(parent: $parent) { id, title, route, path, filename, template } } `; const hash = getQueryHash(query, { parent: '/docs/' }); expect(hash).to.be.equal('1696894039'); }); }); }); }); <|start_filename|>packages/plugin-graphql/src/core/common.server.js<|end_filename|> // https://gist.github.com/hyamamoto/fd435505d29ebfa3d9716fd2be8d42f0#gistcomment-2775538 function hashString(queryKeysString) { let h = 0; for (let i = 0; i < queryKeysString.length; i += 1) { h = Math.imul(31, h) + queryKeysString.charCodeAt(i) | 0; // eslint-disable-line no-bitwise } return Math.abs(h).toString(); } function getQueryHash(query, variables = {}) { const queryKeys = query; const variableValues = Object.keys(variables).length > 0 ? `_${Object.values(variables).join('').replace(/\//g, '')}` // handle / which will translate to filepaths : ''; return hashString(`${queryKeys}${variableValues}`); } module.exports = { getQueryHash }; <|start_filename|>packages/plugin-import-commonjs/package.json<|end_filename|> { "name": "@greenwood/plugin-import-commonjs", "version": "0.17.0", "description": "A plugin for loading CommonJS based modules in the browser using ESM (import / export) syntax.", "repository": "https://github.com/ProjectEvergreen/greenwood/tree/master/packages/plugin-import-commonjs", "author": "<NAME> <<EMAIL>>", "license": "MIT", "keywords": [ "Greenwood", "CommonJS", "Static Site Generator", "NodeJS" ], "main": "src/index.js", "files": [ "src/" ], "publishConfig": { "access": "public" }, "peerDependencies": { "@greenwood/cli": "^0.4.0" }, "dependencies": { "@rollup/plugin-commonjs": "^21.0.0", "@rollup/stream": "^2.0.0", "cjs-module-lexer": "^1.0.0" }, "devDependencies": { "@greenwood/cli": "^0.17.0", "lodash": "^4.17.20" } } <|start_filename|>packages/cli/src/commands/develop.js<|end_filename|> const generateCompilation = require('../lifecycles/compile'); const { ServerInterface } = require('../lib/server-interface'); const { devServer } = require('../lifecycles/serve'); module.exports = runDevServer = async () => { return new Promise(async (resolve, reject) => { try { const compilation = await generateCompilation(); const { port } = compilation.config.devServer; devServer(compilation).listen(port, () => { console.info(`Started local development server at localhost:${port}`); const servers = [...compilation.config.plugins.filter((plugin) => { return plugin.type === 'server'; }).map((plugin) => { const provider = plugin.provider(compilation); if (!(provider instanceof ServerInterface)) { console.warn(`WARNING: ${plugin.name}'s provider is not an instance of ServerInterface.`); } return provider; })]; return Promise.all(servers.map(async (server) => { return server.start(); })); }); } catch (err) { reject(err); } }); }; <|start_filename|>packages/cli/test/cases/build.default.workspace-assets/build.default.workspace-assets.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with custom assets directory * * User Result * Should generate a Greenwood build with a public asset folder containing contents of assets directory * * User Command * greenwood build * * Default Config * * Default Workspace */ const expect = require('chai').expect; const fs = require('fs'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'A Custom Assets Folder'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Assets folder', function() { it('should create a new assets directory', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'assets'))).to.be.true; }); it('should contain files from the asset directory', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'assets', './brand.png'))).to.be.true; }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.plugins.context/greenwood.config.js<|end_filename|> // shared with another test develop.plugins.context const myThemePackPlugin = require('./theme-pack-context-plugin'); module.exports = { plugins: [ ...myThemePackPlugin() ] }; <|start_filename|>www/components/header/header.js<|end_filename|> import { css, html, LitElement, unsafeCSS } from 'lit'; import client from '@greenwood/plugin-graphql/core/client'; import MenuQuery from '@greenwood/plugin-graphql/queries/menu'; import '@evergreen-wc/eve-container'; import headerCss from './header.css?type=css'; import '../social-icons/social-icons.js'; class HeaderComponent extends LitElement { static get properties() { return { navigation: { type: Array } }; } static get styles() { return css` ${unsafeCSS(headerCss)} `; } constructor() { super(); this.navigation = []; } async connectedCallback() { super.connectedCallback(); const response = await client.query({ query: MenuQuery, variables: { name: 'navigation', order: 'index_asc' } }); this.navigation = response.data.menu.children.map(item => item.item); } /* eslint-disable indent */ render() { const { navigation } = this; return html` <header class="header"> <eve-container fluid> <div class="head-wrap"> <div class="brand"> <a href="https://projectevergreen.github.io" target="_blank" rel="noopener noreferrer"> <img src="../../assets/evergreen.svg" alt="Greenwood logo"/> </a> <div class="project-name"> <a href="/">Greenwood</a> </div> </div> <nav> <ul> ${navigation.map((item) => { return html` <li><a href="${item.route}" title="Click to visit the ${item.label} page">${item.label}</a></li> `; })} </ul> </nav> <app-social-icons></app-social-icons> </div> </eve-container> </header> `; /* eslint-enable */ } } customElements.define('app-header', HeaderComponent); <|start_filename|>packages/cli/test/cases/build.default.workspace-templates-empty/build.default.workspace-templates-empty.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with no config and custom page templates to ensure Greenwood * can build various "states" of in development HTML files. * https://github.com/ProjectEvergreen/greenwood/issues/627 * * User Result * Should generate a Greenwood build with custom page templates. * * User Command * greenwood build * * User Config * None (Greenwood Default) * * User Workspace * src/ * pages/ * index.html * no-body.html * no-head.html * shell.html * scripts/ * main.js * styles/ * main.css */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Default Greenwood Configuration and Workspace w/Custom Page Templates for HTML "forgiveness"'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Custom Page Templates', function() { describe('Standard page with <html>, <head>, and <body> tags using pages/index.html', function() { let dom; let scriptTags; let linkTags; let headingTags; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); before(function() { scriptTags = dom.window.document.querySelectorAll('head > script'); linkTags = dom.window.document.querySelectorAll('head > link[rel="stylesheet"'); headingTags = dom.window.document.querySelectorAll('body > h1'); }); it('should have 1 <script> tags in the <head>', function() { expect(scriptTags.length).to.equal(1); }); it('should have 1 <link> tags in the <head>', function() { expect(linkTags.length).to.equal(1); }); it('should have the expected heading tags in the body', function() { expect(headingTags.length).to.equal(1); }); it('should have the expected content in the heading tag', function() { expect(headingTags[0].textContent).to.equal('This is the home page.'); }); }); describe('Standard page with <html> and <head> tags but NO <body> tag, using pages/no-body.html', function() { let dom; let scriptTags; let linkTags; let bodyTags; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'no-body/index.html')); }); before(function() { scriptTags = dom.window.document.querySelectorAll('head > script'); linkTags = dom.window.document.querySelectorAll('head > link[rel="stylesheet"'); bodyTags = dom.window.document.querySelectorAll('body'); }); it('should have 1 <script> tags in the <head>', function() { expect(scriptTags.length).to.equal(1); }); it('should have 1 <link> tags in the <head>', function() { expect(linkTags.length).to.equal(1); }); it('should have the expected content in the <body> tag', function() { expect(bodyTags[0].textContent.replace(/\n/g, '').trim()).to.equal(''); }); }); describe('Standard page with <html> and <body> tags but NO <head> tag, using pages/no-head.html', function() { let dom; let scriptTags; let linkTags; let bodyTags; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'no-head/index.html')); }); before(function() { scriptTags = dom.window.document.querySelectorAll('head > script'); linkTags = dom.window.document.querySelectorAll('head > link[rel="stylesheet"'); bodyTags = dom.window.document.querySelectorAll('body'); }); it('should have 0 <script> tags in the <head>', function() { expect(scriptTags.length).to.equal(0); }); it('should have 0 <link> tags in the <head>', function() { expect(linkTags.length).to.equal(0); }); it('should have the expected content in the <body> tag', function() { expect(bodyTags[0].textContent.replace(/\n/g, '').trim()).to.equal('This is the no head page.'); }); }); describe('Standard page with <html> tag but NO <body> and <head> tags, using pages/shell.html', function() { let dom; let scriptTags; let linkTags; let bodyTags; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'shell/index.html')); }); before(async function() { scriptTags = dom.window.document.querySelectorAll('head > script'); linkTags = dom.window.document.querySelectorAll('head > link[rel="stylesheet"'); bodyTags = dom.window.document.querySelectorAll('body'); }); it('should have 0 <script> tags in the <head>', function() { expect(scriptTags.length).to.equal(0); }); it('should have 0 <link> tags in the <head>', function() { expect(linkTags.length).to.equal(0); }); it('should have the expected content in the <body> tag', function() { expect(bodyTags[0].textContent.replace(/\n/g, '').trim()).to.equal(''); }); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>www/styles/page.css<|end_filename|> h3 { color: #2d3d3a; padding-top: 4rem; font-size: 1.8rem !important; } h2 { font-size: 2rem; } h4, h5, h6 { font-size: 1.2rem; } h1, h2, h3, h4, h5 { line-height: 1.8rem; color: #2d3d3a; } h3 > a > span.icon { width: 28px; height: 24px; float: left; padding: 2px; background-image: url(/assets/link.png); background-size: 20px 20px; background-repeat: no-repeat; background-position-y: center; &:hover:focus { filter: invert(0.4); } } .gwd-content-wrapper { display: flex; @media (max-width: 768px) { flex-direction: column; } } .gwd-sidebar { width: 300px; background-color: white; height: 100%; overflow: auto; padding: 2rem; position: sticky; top: 0; border-right: 1px solid #ededed; @media (max-width: 768px) { width: 100%; height: 100%; padding: 0; position: relative; border-right: 0; border-bottom: 3px solid #ededed; } } .gwd-content { max-width: 100ch; height: 100%; min-height: calc(100vh - (70px + 6rem)); overflow: scroll; margin: auto; background-color: white; font-size: 1.2rem; padding: 2rem; @media (max-width: 768px) { padding: 0; } #github-edit-button { padding: 1rem; background-color: black; color: white; margin-top: 2rem; border-radius: 0.5rem; } #github-edit-button-container { display: flex; justify-content: flex-end; margin-right: 15px; } & h3 { font-size: 2rem; margin: 5px 0; } & a { color: #1d337a; } & img { width: 100%; } & blockquote { margin: 0.5em; padding: 15px; background-color: #dcf9ca !important; border-left: 6px solid #192a27; } @media (max-width: 768px) { width: 100%; height: 100%; } } table { border: 1px solid #020202; width: 100%; text-align: left; margin-bottom: 20px; } table td:first-child { min-width: 100px; white-space: nowrap; padding: 0 5px; } table th { background-color: #f9e7ca; text-decoration: underline; } iframe.stackblitz { width: 100%; height: 800px; display: none; @media (min-width: 768px) { display: block; } } <|start_filename|>packages/plugin-graphql/src/core/server.js<|end_filename|> const { ApolloServer } = require('apollo-server'); module.exports = (compilation) => { const { config, graph, context } = compilation; const schema = require('../schema/schema')(compilation); const createCache = require('./cache'); const server = new ApolloServer({ schema, playground: { endpoint: '/graphql', settings: { 'editor.theme': 'light' } }, context: async (integrationContext) => { const { req } = integrationContext; if (req.query.q !== 'internal') { await createCache(req, context); } return { config, graph }; } }); return server; }; <|start_filename|>packages/cli/src/plugins/resource/plugin-standard-css.js<|end_filename|> /* * * Manages web standard resource related operations for CSS. * This is a Greenwood default plugin. * */ const fs = require('fs'); const cssnano = require('cssnano'); const path = require('path'); const postcss = require('postcss'); const { ResourceInterface } = require('../../lib/resource-interface'); class StandardCssResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['.css']; this.contentType = 'text/css'; } async serve(url) { return new Promise(async (resolve, reject) => { try { const css = await fs.promises.readFile(url, 'utf-8'); resolve({ body: css, contentType: this.contentType }); } catch (e) { reject(e); } }); } async shouldOptimize(url) { const isValidCss = path.extname(url) === this.extensions[0] && this.compilation.config.optimization !== 'none'; return Promise.resolve(isValidCss); } async optimize(url, body) { return new Promise(async (resolve, reject) => { try { const { outputDir, userWorkspace } = this.compilation.context; const workspaceUrl = url.replace(outputDir, userWorkspace); const css = (await postcss([cssnano]).process(body, { from: workspaceUrl })).css; resolve(css); } catch (e) { reject(e); } }); } } module.exports = { type: 'resource', name: 'plugin-standard-css', provider: (compilation, options) => new StandardCssResource(compilation, options) }; <|start_filename|>packages/cli/test/cases/build.config.error-workspace/greenwood.config.js<|end_filename|> module.exports = { workspace: 123 }; <|start_filename|>packages/plugin-google-analytics/test/cases/error-analytics-id/error-analytics-id.spec.js<|end_filename|> /* * Use Case * Run Greenwood with Google Analytics composite plugin. * * Uaer Result * Should generate an error when not passing in a valid analyticsId. * * User Command * greenwood build * * User Config * const googleAnalyticsPlugin = require('@greenwod/plugin-google-analytics'); * * { * plugins: [{ * googleAnalyticsPlugin() * }] * * } * * User Workspace * Greenwood default (src/) */ const expect = require('chai').expect; const path = require('path'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe('Google Analytics Plugin with a bad value for analyticsId', function() { it('should throw an error that analyticsId must be a string', async function() { try { await runner.setup(outputPath); await runner.runCommand(cliPath, 'build'); } catch (err) { expect(err).to.contain('Error: analyticsId should be of type string. got "undefined" instead.'); } }); }); after(function() { runner.teardown(); }); }); <|start_filename|>packages/plugin-typescript/src/index.js<|end_filename|> /* * * Enables using JavaScript to import TypeScript files, using ESM syntax. * */ const rollupPluginTypescript = require('@rollup/plugin-typescript'); const fs = require('fs').promises; const path = require('path'); const { ResourceInterface } = require('@greenwood/cli/src/lib/resource-interface'); const tsc = require('typescript'); const defaultcompilerOptions = { target: 'es2020', module: 'es2020', moduleResolution: 'node', sourceMap: true }; function getCompilerOptions (projectDirectory, extendConfig) { const customOptions = extendConfig ? require(path.join(projectDirectory, 'tsconfig.json')) : { compilerOptions: {} }; return compilerOptions = { ...defaultcompilerOptions, ...customOptions.compilerOptions }; } class TypeScriptResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['.ts']; this.contentType = 'text/javascript'; } async serve(url) { return new Promise(async (resolve, reject) => { try { const { projectDirectory } = this.compilation.context; const source = await fs.readFile(url, 'utf-8'); const compilerOptions = getCompilerOptions(projectDirectory, this.options.extendConfig); // https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API const result = tsc.transpileModule(source, { compilerOptions }); resolve({ body: result.outputText, contentType: this.contentType }); } catch (e) { reject(e); } }); } } module.exports = (options = {}) => { return [{ type: 'resource', name: 'plugin-import-typescript:resource', provider: (compilation) => new TypeScriptResource(compilation, options) }, { type: 'rollup', name: 'plugin-import-typescript:rollup', provider: (compilation) => { const compilerOptions = getCompilerOptions(compilation.context.projectDirectory, options.extendConfig); return [ rollupPluginTypescript(compilerOptions) ]; } }]; }; <|start_filename|>packages/cli/src/plugins/copy/plugin-copy-assets.js<|end_filename|> const fs = require('fs'); const path = require('path'); module.exports = [{ type: 'copy', name: 'plugin-copy-assets', provider: (compilation) => { const { context } = compilation; const fromAssetsDir = path.join(context.userWorkspace, 'assets'); const assets = []; if (fs.existsSync(fromAssetsDir)) { assets.push({ from: fromAssetsDir, to: path.join(context.outputDir, 'assets') }); } return assets; } }]; <|start_filename|>packages/plugin-import-commonjs/test/cases/default/default.spec.js<|end_filename|> /* * Use Case * Run Greenwood with pluginImportCommonjs plugin with default options. * * Uaer Result * Should generate a bare bones Greenwood build without erroring on a CommonJS module. * * User Command * greenwood build * * User Config * const pluginImportCommonjs = require('@greenwod/plugin-import-commonjs'); * * { * plugins: [{ * ...pluginImportCommonjs() * }] * } * * User Workspace * src/ * pages/ * index.html * scripts/ * main.js */ const expect = require('chai').expect; const glob = require('glob-promise'); const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getDependencyFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Import CommonJs Plugin with default options'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { const lodashLibs = await getDependencyFiles( `${process.cwd()}/node_modules/lodash/lodash.js`, `${outputPath}/node_modules/lodash/` ); const lodashLibsPackageJson = await getDependencyFiles( `${process.cwd()}/node_modules/lodash/package.json`, `${outputPath}/node_modules/lodash/` ); await runner.setup(outputPath, [ ...getSetupFiles(outputPath), ...lodashLibs, ...lodashLibsPackageJson ]); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Script tag in the <head> tag', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have one <script> tag for main.js loaded in the <head> tag', function() { const scriptTags = dom.window.document.querySelectorAll('head > script'); const mainScriptTag = Array.prototype.slice.call(scriptTags).filter(script => { return (/main.*.js/).test(script.src); }); expect(mainScriptTag.length).to.be.equal(1); }); it('should have the expected main.js file in the output directory', async function() { expect(await glob.promise(path.join(this.context.publicDir, 'main.*.js'))).to.have.lengthOf(1); }); it('should have the expected output from main.js (lodash) in the page output', async function() { const spanTags = dom.window.document.querySelectorAll('body > span'); expect(spanTags.length).to.be.equal(1); expect(spanTags[0].textContent).to.be.equal('import from lodash {"a":1,"b":2}'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.default/build.config.default.spec.js<|end_filename|> /* * Use Case * Run Greenwood with empty config object and default workspace. * * Uaer Result * Should generate a bare bones Greenwood build. (same as build.default.spec.js) * * User Command * greenwood build * * User Config * {} * * User Workspace * Greenwood default (src/) */ const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Empty Configuration and Default Workspace'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.workspace-custom/build.config.workspace-custom.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with custom workspace directory (absolute path) and custom pages. * * User Result * Should generate a Greenwood build from www directory with about and index pages. * * User Command * greenwood build * * User Config * { * workspace: path.join(__dirname, 'www') * } * * User Workspace * www/ * pages/ * about.md * index.md */ const expect = require('chai').expect; const fs = require('fs'); const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Custom Configuration for Workspace (www) and Default Greenwood configuration'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Custom About page', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'about', './index.html')); }); it('should output an index.html file within the custom about page directory', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'about', './index.html'))).to.be.true; }); it('should have the expected heading text within the custom about page in the about directory', function() { const heading = dom.window.document.querySelector('h3').textContent; expect(heading).to.equal('Nested Custom About Page'); }); it('should have the expected paragraph text within the custom about page in the about directory', function() { let paragraph = dom.window.document.querySelector('p').textContent; expect(paragraph).to.equal('This is a custom about page built by Greenwood.'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.workspace-custom/greenwood.config.js<|end_filename|> const path = require('path'); module.exports = { workspace: path.join(__dirname, 'www') }; <|start_filename|>greenwood.config.js<|end_filename|> const path = require('path'); const pluginGraphQL = require('@greenwood/plugin-graphql'); const pluginImportCss = require('@greenwood/plugin-import-css'); const pluginImportJson = require('@greenwood/plugin-import-json'); const pluginPolyfills = require('@greenwood/plugin-polyfills'); const pluginPostCss = require('@greenwood/plugin-postcss'); const rollupPluginAnalyzer = require('rollup-plugin-analyzer'); const META_DESCRIPTION = 'A modern and performant static site generator supporting Web Component based development'; const FAVICON_HREF = '/assets/favicon.ico'; module.exports = { workspace: path.join(__dirname, 'www'), mode: 'mpa', optimization: 'inline', title: 'Greenwood', meta: [ { name: 'description', content: META_DESCRIPTION }, { name: 'twitter:site', content: '@PrjEvergreen' }, { property: 'og:title', content: 'Greenwood' }, { property: 'og:type', content: 'website' }, { property: 'og:url', content: 'https://www.greenwoodjs.io' }, { property: 'og:image', content: 'https://www.greenwoodjs.io/assets/greenwood-logo-300w.png' }, { property: 'og:description', content: META_DESCRIPTION }, { rel: 'shortcut icon', href: FAVICON_HREF }, { rel: 'icon', href: FAVICON_HREF }, { name: 'google-site-verification', content: '4rYd8k5aFD0jDnN0CCFgUXNe4eakLP4NnA18mNnK5P0' } ], plugins: [ ...pluginGraphQL(), ...pluginPolyfills(), pluginPostCss(), ...pluginImportJson(), ...pluginImportCss(), { type: 'rollup', name: 'rollup-plugin-analyzer', provider: () => { return [ rollupPluginAnalyzer({ summaryOnly: true, filter: (module) => { return !module.id.endsWith('.html'); } }) ]; } } ], markdown: { plugins: [ '@mapbox/rehype-prism', 'rehype-slug', 'rehype-autolink-headings', 'remark-github' ] } }; <|start_filename|>packages/plugin-google-analytics/src/index.js<|end_filename|> const path = require('path'); const { ResourceInterface } = require('@greenwood/cli/src/lib/resource-interface'); class GoogleAnalyticsResource extends ResourceInterface { constructor(compilation, options = {}) { super(compilation, options); const { analyticsId } = options; if (!analyticsId || typeof analyticsId !== 'string') { throw new Error(`Error: analyticsId should be of type string. got "${typeof analyticsId}" instead.`); } } async shouldOptimize(url) { return Promise.resolve(path.extname(url) === '.html'); } async optimize(url, body) { const { analyticsId, anonymous } = this.options; const trackAnon = typeof anonymous === 'boolean' ? anonymous : true; return new Promise((resolve, reject) => { try { const newHtml = body.replace('</head>', ` <link rel="preconnect" href="https://www.google-analytics.com/"> <script async src="https://www.googletagmanager.com/gtag/js?id=${analyticsId}"></script> <script> var getOutboundLink = function(url) { gtag('event', 'click', { 'event_category': 'outbound', 'event_label': url, 'transport_type': 'beacon' }); } window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${analyticsId}', { 'anonymize_ip': ${trackAnon} }); </script> </head> `); resolve(newHtml); } catch (e) { reject(e); } }); } } module.exports = (options = {}) => { return { type: 'resource', name: 'plugin-google-analytics', provider: (compilation) => new GoogleAnalyticsResource(compilation, options) }; }; <|start_filename|>packages/plugin-graphql/test/unit/schema/config.spec.js<|end_filename|> const expect = require('chai').expect; const MOCK_CONFIG = require('../mocks/config'); const { configResolvers } = require('../../../src/schema/config'); describe('Unit Test: Data', function() { describe('Schema', function() { describe('Config', function() { let config = {}; before(async function() { config = await configResolvers.Query.config(undefined, {}, MOCK_CONFIG); }); describe('Dev Server', function() { const { devServer } = MOCK_CONFIG.config; it('should have the expected devServer.port', function() { expect(config.devServer.port).to.equal(devServer.port); }); }); describe('Meta', function() { const { meta } = MOCK_CONFIG.config; it('should have the expected name meta in the first indexx', function() { const nameMeta = config.meta[0]; expect(nameMeta.name).to.equal(meta[0].name); }); it('should have the expected rel meta in the second index', function() { const relMeta = config.meta[1]; expect(relMeta.rel).to.equal(meta[1].rel); }); }); describe('Mode', function() { it('should have a default mode setting of mode', function() { expect(config.mode).to.equal(MOCK_CONFIG.config.mode); }); }); describe('Optimization', function() { it('should have a default optimization setting of default', function() { expect(config.optimization).to.equal(MOCK_CONFIG.config.optimization); }); }); describe('Prerender', function() { it('should have a default prerender setting of false', function() { expect(config.optimization).to.equal(MOCK_CONFIG.config.prerender); }); }); describe('Title', function() { const { title } = MOCK_CONFIG.config; it('should have the expected title', function() { expect(title).to.equal(config.title); }); }); describe('Workspace', function() { const { workspace } = MOCK_CONFIG.config; it('should have the expected title', function() { expect(workspace).to.equal(config.workspace); }); }); }); }); }); <|start_filename|>packages/cli/test/cases/build.default.markdown/greenwood.config.js<|end_filename|> module.exports = { title: 'this is the title from the config' }; <|start_filename|>packages/cli/src/plugins/server/plugin-livereload.js<|end_filename|> const fs = require('fs'); const livereload = require('livereload'); const path = require('path'); const { ResourceInterface } = require('../../lib/resource-interface'); const { ServerInterface } = require('../../lib/server-interface'); class LiveReloadServer extends ServerInterface { constructor(compilation, options = {}) { super(compilation, options); } async start() { const { userWorkspace } = this.compilation.context; const standardPluginsPath = path.join(__dirname, '../', 'resource'); const standardPluginsExtensions = fs.readdirSync(standardPluginsPath) .filter(filename => filename.indexOf('plugin-standard') === 0) .map((filename) => { return require(`${standardPluginsPath}/${filename}`); }) .map((plugin) => { // assume that if it is an array, the second item is a rollup plugin const instance = plugin.length ? plugin[0].provider(this.compilation) : plugin.provider(this.compilation); return instance.extensions.flat(); }) .flat(); const customPluginsExtensions = this.compilation.config.plugins .filter((plugin) => plugin.type === 'resource') .map((plugin) => { return plugin.provider(this.compilation).extensions.flat(); }).flat(); // filter out wildcards or otherwise undesired values and remove any . since livereload likes them that way const allExtensions = [ ...standardPluginsExtensions, ...customPluginsExtensions, ...this.compilation.config.devServer.extensions ] .filter((ext) => ext !== '*' || ext !== '') .map((ext) => ext.replace('.', '')); const liveReloadServer = livereload.createServer({ exts: allExtensions.filter((ext, idx) => idx === allExtensions.indexOf(ext)), applyCSSLive: false // https://github.com/napcs/node-livereload/issues/33#issuecomment-693707006 }); liveReloadServer.watch(userWorkspace, () => { console.info(`Now watching directory "${userWorkspace}" for changes.`); return Promise.resolve(true); }); } } class LiveReloadResource extends ResourceInterface { async shouldIntercept(url, body, headers) { const { accept } = headers.request; return Promise.resolve(accept && accept.indexOf('text/html') >= 0 && process.env.__GWD_COMMAND__ === 'develop'); // eslint-disable-line no-underscore-dangle } async intercept(url, body) { return new Promise((resolve, reject) => { try { const contents = body.replace('</head>', ` <script src="http://localhost:35729/livereload.js?snipver=1"></script> </head> `); resolve({ body: contents }); } catch (e) { reject(e); } }); } } module.exports = [{ type: 'server', name: 'plugin-live-reload:server', provider: (compilation) => new LiveReloadServer(compilation) }, { type: 'resource', name: 'plugin-live-reload:resource', provider: (compilation) => new LiveReloadResource(compilation) }]; <|start_filename|>packages/cli/src/plugins/resource/plugin-standard-html.js<|end_filename|> /* * * Manages web standard resource related operations for HTML and markdown. * This is a Greenwood default plugin. * */ const frontmatter = require('front-matter'); const fs = require('fs'); const htmlparser = require('node-html-parser'); const path = require('path'); const rehypeStringify = require('rehype-stringify'); const rehypeRaw = require('rehype-raw'); const remarkFrontmatter = require('remark-frontmatter'); const remarkParse = require('remark-parse'); const remarkRehype = require('remark-rehype'); const { ResourceInterface } = require('../../lib/resource-interface'); const unified = require('unified'); function getCustomPageTemplates(contextPlugins, templateName) { return contextPlugins .map(plugin => plugin.templates) .flat() .filter((templateDir) => { return templateName && fs.existsSync(path.join(templateDir, `${templateName}.html`)); }); } const getPageTemplate = (barePath, templatesDir, template, contextPlugins = []) => { const pageIsHtmlPath = `${barePath.substring(0, barePath.lastIndexOf(`${path.sep}index`))}.html`; const customPluginDefaultPageTemplates = getCustomPageTemplates(contextPlugins, 'page'); const customPluginPageTemplates = getCustomPageTemplates(contextPlugins, template); if (template && customPluginPageTemplates.length > 0 || fs.existsSync(`${templatesDir}/${template}.html`)) { // use a custom template, usually from markdown frontmatter contents = customPluginPageTemplates.length > 0 ? fs.readFileSync(`${customPluginPageTemplates[0]}/${template}.html`, 'utf-8') : fs.readFileSync(`${templatesDir}/${template}.html`, 'utf-8'); } else if (fs.existsSync(`${barePath}.html`) || fs.existsSync(pageIsHtmlPath)) { // if the page is already HTML, use that as the template const indexPath = fs.existsSync(pageIsHtmlPath) ? pageIsHtmlPath : `${barePath}.html`; contents = fs.readFileSync(indexPath, 'utf-8'); } else if (customPluginDefaultPageTemplates.length > 0 || fs.existsSync(`${templatesDir}/page.html`)) { // else look for default page template from the user contents = customPluginDefaultPageTemplates.length > 0 ? fs.readFileSync(`${customPluginDefaultPageTemplates[0]}/page.html`, 'utf-8') : fs.readFileSync(`${templatesDir}/page.html`, 'utf-8'); } else { // fallback to using Greenwood's stock page template contents = fs.readFileSync(path.join(__dirname, '../../templates/page.html'), 'utf-8'); } return contents; }; const getAppTemplate = (contents, templatesDir, customImports = [], contextPlugins) => { function sliceTemplate(template, pos, needle, replacer) { return template.slice(0, pos) + template.slice(pos).replace(needle, replacer); } const userAppTemplatePath = `${templatesDir}app.html`; const customAppTemplates = getCustomPageTemplates(contextPlugins, 'app'); let appTemplateContents = customAppTemplates.length > 0 ? fs.readFileSync(`${customAppTemplates[0]}/app.html`, 'utf-8') : fs.existsSync(userAppTemplatePath) ? fs.readFileSync(userAppTemplatePath, 'utf-8') : fs.readFileSync(path.join(__dirname, '../../templates/app.html'), 'utf-8'); const root = htmlparser.parse(contents, { script: true, style: true, noscript: true, pre: true }); const body = root.querySelector('body') ? root.querySelector('body').innerHTML : ''; const headScripts = root.querySelectorAll('head script'); const headLinks = root.querySelectorAll('head link'); const headMeta = root.querySelectorAll('head meta'); const headStyles = root.querySelectorAll('head style'); const headTitle = root.querySelector('head title'); appTemplateContents = appTemplateContents.replace(/<page-outlet><\/page-outlet>/, body); if (headTitle) { appTemplateContents = appTemplateContents.replace(/<title>(.*)<\/title>/, `<title>${headTitle.rawText}</title>`); } headScripts.forEach((script) => { const matchNeedle = '</script>'; const matchPos = appTemplateContents.lastIndexOf(matchNeedle); if (script.text === '') { if (matchPos > 0) { appTemplateContents = sliceTemplate(appTemplateContents, matchPos, matchNeedle, `</script>\n <script ${script.rawAttrs}></script>\n `); } else { appTemplateContents = appTemplateContents.replace('</head>', ` <script ${script.rawAttrs}></script>\n </head> `); } } if (script.text !== '') { const attributes = script.rawAttrs !== '' ? ` ${script.rawAttrs}` : ''; const source = script.text .replace(/\$/g, '$$$'); // https://github.com/ProjectEvergreen/greenwood/issues/656 if (matchPos > 0) { appTemplateContents = sliceTemplate(appTemplateContents, matchPos, matchNeedle, `</script>\n <script${attributes}> ${source} </script>\n `); } else { appTemplateContents = appTemplateContents.replace('</head>', ` <script${attributes}> ${source} </script>\n </head> `); } } }); headLinks.forEach((link) => { const matchNeedle = /<link .*/g; const matches = appTemplateContents.match(matchNeedle); const lastLink = matches && matches.length && matches.length > 0 ? matches[matches.length - 1] : '<head>'; appTemplateContents = appTemplateContents.replace(lastLink, `${lastLink}\n <link ${link.rawAttrs}/> `); }); headStyles.forEach((style) => { const matchNeedle = '</style>'; const matchPos = appTemplateContents.lastIndexOf(matchNeedle); if (style.rawAttrs === '') { if (matchPos > 0) { appTemplateContents = sliceTemplate(appTemplateContents, matchPos, matchNeedle, `</style>\n <style> ${style.text} </style>\n `); } else { appTemplateContents = appTemplateContents.replace('<head>', ` <head> \n <style> ${style.text} </style>\n `); } } }); headMeta.forEach((meta) => { appTemplateContents = appTemplateContents.replace('<head>', ` <head> <meta ${meta.rawAttrs}/> `); }); customImports.forEach((customImport) => { const extension = path.extname(customImport); switch (extension) { case '.js': appTemplateContents = appTemplateContents.replace('</head>', ` <script src="${customImport}" type="module"></script> </head> `); break; case '.css': appTemplateContents = appTemplateContents.replace('</head>', ` <link rel="stylesheet" href="${customImport}"></link> </head> `); break; default: break; } }); return appTemplateContents; }; const getUserScripts = (contents, context) => { // polyfill chromium for WC support // https://lit.dev/docs/tools/requirements/#polyfills if (process.env.__GWD_COMMAND__ === 'build') { // eslint-disable-line no-underscore-dangle const { projectDirectory, userWorkspace } = context; const dependencies = fs.existsSync(path.join(userWorkspace, 'package.json')) // handle monorepos first ? JSON.parse(fs.readFileSync(path.join(userWorkspace, 'package.json'), 'utf-8')).dependencies : fs.existsSync(path.join(projectDirectory, 'package.json')) ? JSON.parse(fs.readFileSync(path.join(projectDirectory, 'package.json'), 'utf-8')).dependencies : {}; const litPolyfill = dependencies && dependencies.lit ? '<script src="/node_modules/lit/polyfill-support.js"></script>\n' : ''; contents = contents.replace('<head>', ` <head> ${litPolyfill} <script src="/node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script> `); } return contents; }; const getMetaContent = (url, config, contents) => { const existingTitleMatch = contents.match(/<title>(.*)<\/title>/); const existingTitleCheck = !!(existingTitleMatch && existingTitleMatch[1] && existingTitleMatch[1] !== ''); const title = existingTitleCheck ? existingTitleMatch[1] : config.title; const metaContent = config.meta.map(item => { let metaHtml = ''; for (const [key, value] of Object.entries(item)) { const isOgUrl = item.property === 'og:url' && key === 'content'; const hasTrailingSlash = isOgUrl && value[value.length - 1] === '/'; const contextualValue = isOgUrl ? hasTrailingSlash ? `${value}${url.replace('/', '')}` : `${value}${url === '/' ? '' : url}` : value; metaHtml += ` ${key}="${contextualValue}"`; } return item.rel ? `<link${metaHtml}/>` : `<meta${metaHtml}/>`; }).join('\n'); // add an empty <title> if it's not already there if (!existingTitleMatch) { contents = contents.replace('<head>', '<head><title></title>'); } contents = contents.replace(/<title>(.*)<\/title>/, `<title>${title}</title>`); contents = contents.replace('<meta-outlet></meta-outlet>', metaContent); return contents; }; class StandardHtmlResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['.html', '.md']; this.contentType = 'text/html'; } getRelativeUserworkspaceUrl(url) { return path.normalize(url.replace(this.compilation.context.userWorkspace, '')); } async shouldServe(url, headers) { const { pagesDir } = this.compilation.context; const relativeUrl = this.getRelativeUserworkspaceUrl(url); const isClientSideRoute = this.compilation.config.mode === 'spa' && (headers.request.accept || '').indexOf(this.contentType) >= 0; const barePath = relativeUrl.endsWith(path.sep) ? `${pagesDir}${relativeUrl}index` : `${pagesDir}${relativeUrl.replace('.html', '')}`; return Promise.resolve(this.extensions.indexOf(path.extname(relativeUrl)) >= 0 || path.extname(relativeUrl) === '') && (fs.existsSync(`${barePath}.html`) || barePath.substring(barePath.length - 5, barePath.length) === 'index') || fs.existsSync(`${barePath}.md`) || fs.existsSync(`${barePath.substring(0, barePath.lastIndexOf(`${path.sep}index`))}.md`) || isClientSideRoute; } async serve(url) { return new Promise(async (resolve, reject) => { try { const config = Object.assign({}, this.compilation.config); const { pagesDir, userTemplatesDir } = this.compilation.context; const { mode } = this.compilation.config; const normalizedUrl = this.getRelativeUserworkspaceUrl(url); let customImports; let body = ''; let template = null; let processedMarkdown = null; const barePath = normalizedUrl.endsWith(path.sep) ? `${pagesDir}${normalizedUrl}index` : `${pagesDir}${normalizedUrl.replace('.html', '')}`; const isMarkdownContent = fs.existsSync(`${barePath}.md`) || fs.existsSync(`${barePath.substring(0, barePath.lastIndexOf(`${path.sep}index`))}.md`) || fs.existsSync(`${barePath.replace(`${path.sep}index`, '.md')}`); if (isMarkdownContent) { const markdownPath = fs.existsSync(`${barePath}.md`) ? `${barePath}.md` : fs.existsSync(`${barePath.substring(0, barePath.lastIndexOf(`${path.sep}index`))}.md`) ? `${barePath.substring(0, barePath.lastIndexOf(`${path.sep}index`))}.md` : `${pagesDir}${url.replace(`${path.sep}index.html`, '.md')}`; const markdownContents = await fs.promises.readFile(markdownPath, 'utf-8'); const rehypePlugins = []; const remarkPlugins = []; config.markdown.plugins.forEach(plugin => { if (plugin.indexOf('rehype-') >= 0) { rehypePlugins.push(require(plugin)); } if (plugin.indexOf('remark-') >= 0) { remarkPlugins.push(require(plugin)); } }); const settings = config.markdown.settings || {}; const fm = frontmatter(markdownContents); processedMarkdown = await unified() .use(remarkParse, settings) // parse markdown into AST .use(remarkFrontmatter) // extract frontmatter from AST .use(remarkPlugins) // apply userland remark plugins .use(remarkRehype, { allowDangerousHtml: true }) // convert from markdown to HTML AST .use(rehypeRaw) // support mixed HTML in markdown .use(rehypePlugins) // apply userland rehype plugins .use(rehypeStringify) // convert AST to HTML string .process(markdownContents); // configure via frontmatter if (fm.attributes) { const { attributes } = fm; if (attributes.title) { config.title = `${config.title} - ${attributes.title}`; } if (attributes.template) { template = attributes.template; } if (attributes.imports) { customImports = attributes.imports; } } } // get context plugins const contextPlugins = this.compilation.config.plugins.filter((plugin) => { return plugin.type === 'context'; }).map((plugin) => { return plugin.provider(this.compilation); }); if (mode === 'spa') { body = fs.readFileSync(this.compilation.graph[0].path, 'utf-8'); } else { body = getPageTemplate(barePath, userTemplatesDir, template, contextPlugins); } body = getAppTemplate(body, userTemplatesDir, customImports, contextPlugins); body = getUserScripts(body, this.compilation.context); body = getMetaContent(normalizedUrl.replace(/\\/g, '/'), config, body); if (processedMarkdown) { const wrappedCustomElementRegex = /<p><[a-zA-Z]*-[a-zA-Z](.*)>(.*)<\/[a-zA-Z]*-[a-zA-Z](.*)><\/p>/g; const ceTest = wrappedCustomElementRegex.test(processedMarkdown.contents); if (ceTest) { const ceMatches = processedMarkdown.contents.match(wrappedCustomElementRegex); ceMatches.forEach((match) => { const stripWrappingTags = match .replace('<p>', '') .replace('</p>', ''); processedMarkdown.contents = processedMarkdown.contents.replace(match, stripWrappingTags); }); } body = body.replace(/\<content-outlet>(.*)<\/content-outlet>/s, processedMarkdown.contents); } // give the user something to see so they know it works, if they have no content if (body.indexOf('<content-outlet></content-outlet>') > 0) { body = body.replace('<content-outlet></content-outlet>', ` <h1>Welcome to Greenwood!</h1> `); } resolve({ body, contentType: this.contentType }); } catch (e) { reject(e); } }); } async shouldOptimize(url) { return Promise.resolve(path.extname(url) === '.html'); } async optimize(url, body) { return new Promise((resolve, reject) => { try { const hasHead = body.match(/\<head>(.*)<\/head>/s); if (hasHead && hasHead.length > 0) { let contents = hasHead[0]; contents = contents.replace(/<script src="(.*lit\/polyfill-support.js)"><\/script>/, ''); contents = contents.replace(/<script src="(.*webcomponents-bundle.js)"><\/script>/, ''); contents = contents.replace(/<script type="importmap-shim">.*?<\/script>/s, ''); contents = contents.replace(/<script defer="" src="(.*es-module-shims.js)"><\/script>/, ''); contents = contents.replace(/type="module-shim"/g, 'type="module"'); body = body.replace(/\<head>(.*)<\/head>/s, contents.replace(/\$/g, '$$$')); // https://github.com/ProjectEvergreen/greenwood/issues/656); } resolve(body); } catch (e) { reject(e); } }); } } module.exports = { type: 'resource', name: 'plugin-standard-html', provider: (compilation, options) => new StandardHtmlResource(compilation, options) }; <|start_filename|>packages/plugin-google-analytics/test/cases/default/default.spec.js<|end_filename|> /* * Use Case * Run Greenwood with Google Analytics composite plugin with default options. * * Uaer Result * Should generate a bare bones Greenwood build with Google Analytics tracking snippet injected into index.html. * * User Command * greenwood build * * User Config * const googleAnalyticsPlugin = require('@greenwod/plugin-google-analytics'); * * { * plugins: [{ * googleAnalyticsPlugin({ * analyticsId: 'UA-123456-1' * }) * }] * * } * * User Workspace * Greenwood default (src/) */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Google Analytics Plugin with default options and Default Workspace'; const mockAnalyticsId = 'UA-123456-1'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Initialization script', function() { let inlineScript = []; let scriptSrcTags = []; before(async function() { const dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); const scriptTags = dom.window.document.querySelectorAll('head script'); inlineScript = Array.prototype.slice.call(scriptTags).filter(script => { return !script.src && !script.getAttribute('data-state'); }); scriptSrcTags = Array.prototype.slice.call(scriptTags).filter(script => { return script.src && script.src.indexOf('google') >= 0; }); }); it('should be one inline <script> tag', function() { expect(inlineScript.length).to.be.equal(1); }); it('should have the expected code with users analyicsId', function() { const expectedContent = ` var getOutboundLink = function(url) { gtag('event', 'click', { 'event_category': 'outbound', 'event_label': url, 'transport_type': 'beacon' }); } window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${mockAnalyticsId}', { 'anonymize_ip': true }); `; expect(inlineScript[0].textContent).to.contain(expectedContent); }); it('should only have one external Google script tag', function() { expect(scriptSrcTags.length).to.be.equal(1); }); }); describe('Link Preconnect', function() { let linkTag; before(async function() { const dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); const linkTags = dom.window.document.querySelectorAll('head link'); linkTag = Array.prototype.slice.call(linkTags).filter(link => { return link.href === 'https://www.google-analytics.com/'; }); }); it('should have one <link> tag for prefetching from the Google Analytics domain', function() { expect(linkTag.length).to.be.equal(1); }); it('should have one <link> tag with rel preconnect attribute set', function() { expect(linkTag[0].rel).to.be.equal('preconnect'); }); }); describe('Tracking script', function() { let trackingScript; before(async function() { const dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); const scriptTags = dom.window.document.querySelectorAll('head script'); trackingScript = Array.prototype.slice.call(scriptTags).filter(script => { return script.src === `https://www.googletagmanager.com/gtag/js?id=${mockAnalyticsId}`; }); }); it('should have one <script> tag for loading the Google Analytics tracker', function() { expect(trackingScript.length).to.be.equal(1); }); it('should be an async <script> tag for loading the Google Analytics tracker', function() { const isAsync = trackingScript[0].async !== null; expect(isAsync).to.be.equal(true); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.optimization-inline/build.config-optimization-inline.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with inline setting for optimization * * User Result * Should generate a Greenwood build that inlines all JS and CSS <script> and <link> tags. * * User Command * greenwood build * * User Config * { * optimization: 'inline' * } * * Custom Workspace * src/ * components/ * header.js * pages/ * index.html * styles/ * theme.css */ const expect = require('chai').expect; const glob = require('glob-promise'); const { JSDOM } = require('jsdom'); const path = require('path'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Inline Optimization Configuration'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); describe('Output for JavaScript / CSS tags and files', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, './index.html')); }); it('should contain no link <tags> in the <head> tag', function() { const linkTags = dom.window.document.querySelectorAll('head link'); expect(linkTags.length).to.be.equal(0); }); describe('<script> tags and files', function() { it('should contain three <script> tags in the <head>', function() { const allScriptTags = dom.window.document.querySelectorAll('head script'); expect(allScriptTags.length).to.be.equal(3); }); it('should contain no <script> tags in the <head> with a src', function() { const allSrcScriptTags = dom.window.document.querySelectorAll('head script[src]'); expect(allSrcScriptTags.length).to.be.equal(0); }); it('should contain no Javascript files in the output directory', async function() { const jsFiles = await glob.promise(`${this.context.publicDir}**/**/*.js`); expect(jsFiles).to.have.lengthOf(0); }); }); // assume the first tag is for the header describe('Header', function() { it('should contain one <script> tag with the expected JS content inlined of type="module" for the header', function() { const scriptTag = dom.window.document.querySelectorAll('head script')[0]; expect(scriptTag.type).to.be.equal('module'); // eslint-disable-next-line max-len expect(scriptTag.textContent).to.be.contain('class e extends HTMLElement{constructor(){super(),this.root=this.attachShadow({mode:"open"}),this.root.innerHTML="\\n <header>This is the header component.</header>\\n "}}customElements.define("app-header",e);'); }); it('should contain the expected content from <app-header> in the <body>', function() { const header = dom.window.document.querySelectorAll('body header'); expect(header.length).to.be.equal(1); expect(header[0].textContent).to.be.equal('This is the header component.'); }); }); // assume the second tag is for FooBar // https://github.com/ProjectEvergreen/greenwood/issues/656 describe('Foobar', function() { it('should contain one <script> tag with the expected JS content inlined of type="module" for FooBar', function() { const scriptTag = dom.window.document.querySelectorAll('head script')[1]; expect(scriptTag.type).to.be.equal('module'); // eslint-disable-next-line max-len expect(scriptTag.textContent).to.be.contain('class t extends HTMLElement{constructor(){super(),this.list=[]}find(t){this.list.findIndex(e=>new RegExp(`^${t}$`).test(e.route))}}export{t as Foobar};'); }); }); // assume the third tag is for Baz // https://github.com/ProjectEvergreen/greenwood/issues/656 describe('Baz', function() { it('should contain one <script> tag with the expected JS content for the already inlined of type="module" for Baz', function() { const scriptTag = dom.window.document.querySelectorAll('head script')[2]; expect(scriptTag.type).to.be.equal('module'); // eslint-disable-next-line max-len expect(scriptTag.textContent).to.be.contain('class t extends HTMLElement{constructor(){super(),this.list=[]}find(t){this.list.findIndex(e=>new RegExp(`^${t}$`).test(e.route))}}console.log("1049249078-scratch");export{t as Baz};'); }); }); describe('<link> tags as <style> tags and file output', function() { it('should contain no CSS files in the output directory', async function() { const cssFiles = await glob.promise(`${this.context.publicDir}**/**/*.css`); expect(cssFiles).to.have.lengthOf(0); }); it('should contain one <style> tag with the expected CSS content inlined', function() { const styleTags = dom.window.document.querySelectorAll('head style'); // one for puppeteer expect(styleTags.length).to.be.equal(2); expect(styleTags[1].textContent).to.be.contain('*{margin:0;padding:0;font-family:Comic Sans,sans-serif}'); }); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-import-json/package.json<|end_filename|> { "name": "@greenwood/plugin-import-json", "version": "0.17.0", "description": "A Greenwood plugin to allow you to use ESM (import) syntax to load your JSON.", "repository": "https://github.com/ProjectEvergreen/greenwood/tree/master/packages/plugin-import-json", "author": "<NAME> <<EMAIL>>", "license": "MIT", "keywords": [ "Greenwood", "CommonJS", "Static Site Generator", "NodeJS", "JSON" ], "main": "src/index.js", "files": [ "src/" ], "publishConfig": { "access": "public" }, "peerDependencies": { "@greenwood/cli": "^0.12.3" }, "dependencies": { "@rollup/plugin-json": "^4.1.0" }, "devDependencies": { "@greenwood/cli": "^0.17.0" } } <|start_filename|>packages/cli/src/lifecycles/bundle.js<|end_filename|> const getRollupConfig = require('../config/rollup.config'); const rollup = require('rollup'); module.exports = bundleCompilation = async (compilation) => { return new Promise(async (resolve, reject) => { try { // https://rollupjs.org/guide/en/#differences-to-the-javascript-api if (compilation.graph.length > 0) { const rollupConfigs = await getRollupConfig(compilation); const bundle = await rollup.rollup(rollupConfigs[0]); await bundle.write(rollupConfigs[0].output); } resolve(); } catch (err) { reject(err); } }); }; <|start_filename|>packages/cli/test/cases/build.config.markdown-custom.plugins/build.config.markdown-custom.spec.js<|end_filename|> /* * Use Case * Run Greenwood with custom markdown preset in greenwood config. * * User Result * Should generate a bare bones Greenwood build. (same as build.default.spec.js) with custom markdown and rehype links * * User Command * greenwood build * * User Config * markdown: { * plugins: [ * '@mapbox/rehype-prism', * 'rehype-slug', * 'rehype-autolink-headings' * ] * } * * User Workspace * Greenwood default */ const { JSDOM } = require('jsdom'); const path = require('path'); const expect = require('chai').expect; const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Custom Markdown Configuration and Default Workspace'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Custom Markdown Plugins', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should use our custom rehype plugin to add syntax highlighting', function() { let pre = dom.window.document.querySelectorAll('body pre'); let code = dom.window.document.querySelectorAll('body pre code'); expect(pre.length).to.equal(1); expect(pre[0].getAttribute('class')).to.equal('language-js'); expect(code.length).to.equal(1); expect(code[0].getAttribute('class')).to.equal('language-js'); }); it('should use our custom markdown preset rehype-autolink-headings and rehype-slug plugins', function() { let heading = dom.window.document.querySelector('h1 > a'); expect(heading.getAttribute('href')).to.equal('#greenwood-markdown-syntax-highlighting-test'); }); it('should use our custom markdown preset rremark-TBD plugins', function() { let heading = dom.window.document.querySelector('h3 > a'); expect(heading.getAttribute('href')).to.equal('#lower-heading-test'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-google-analytics/test/cases/default/greenwood.config.js<|end_filename|> const googleAnalyticsPlugin = require('../../../src/index'); module.exports = { plugins: [ googleAnalyticsPlugin({ analyticsId: 'UA-123456-1' }) ] }; <|start_filename|>stylelint.config.js<|end_filename|> module.exports = { plugins: ['stylelint-a11y'], extends: [ 'stylelint-config-standard', 'stylelint-a11y/recommended' ], rules: { 'no-empty-source': null, 'declaration-empty-line-before': null, 'no-missing-end-of-source-newline': null, 'value-list-comma-newline-after': null, 'declaration-colon-newline-after': null, 'value-keyword-case': null, 'declaration-bang-space-before': null, 'selector-type-no-unknown': [true, { ignore: ['custom-elements'], ignoreTypes: ['/^app-/'] }] } }; <|start_filename|>packages/plugin-graphql/src/schema/schema.js<|end_filename|> const { makeExecutableSchema } = require('apollo-server-express'); const { configTypeDefs, configResolvers } = require('./config'); const { graphTypeDefs, graphResolvers } = require('./graph'); const fs = require('fs'); const gql = require('graphql-tag'); const path = require('path'); module.exports = (compilation) => { const { graph } = compilation; const uniqueCustomDataDefKeys = {}; const customSchemasPath = `${compilation.context.userWorkspace}/data/schema`; const customUserResolvers = []; const customUserDefs = []; let customDataDefsString = ''; try { // define custom data type definitions from user frontmatter graph.forEach((page) => { Object.keys(page.data).forEach(key => { uniqueCustomDataDefKeys[key] = 'String'; }); }); Object.keys(uniqueCustomDataDefKeys).forEach((key) => { customDataDefsString += ` ${key}: ${uniqueCustomDataDefKeys[key]} `; }); const customDataDefs = gql` type Data { noop: String ${customDataDefsString} } `; if (fs.existsSync(customSchemasPath)) { console.log('custom schemas directory detected, scanning...'); fs.readdirSync(customSchemasPath) .filter(file => path.extname(file) === '.js') .forEach(file => { const { customTypeDefs, customResolvers } = require(`${customSchemasPath}/${file}`); customUserDefs.push(customTypeDefs); customUserResolvers.push(customResolvers); }); } const mergedResolvers = Object.assign({}, { Query: { ...graphResolvers.Query, ...configResolvers.Query, ...customUserResolvers.reduce((resolvers, resolver) => { return { ...resolvers, ...resolver.Query }; }, {}) } }); const schema = makeExecutableSchema({ typeDefs: [ graphTypeDefs, configTypeDefs, customDataDefs, ...customUserDefs ], resolvers: [ mergedResolvers ] }); return schema; } catch (e) { console.error(e); } }; <|start_filename|>packages/cli/test/cases/theme-pack/my-theme-pack.js<|end_filename|> const packageJson = require('./package.json'); const path = require('path'); module.exports = (options = {}) => [{ type: 'context', name: `${packageJson.name}:context`, provider: (compilation) => { const templateLocation = options.__isDevelopment // eslint-disable-line no-underscore-dangle ? path.join(compilation.context.userWorkspace, 'layouts') : path.join(__dirname, 'dist/layouts'); return { templates: [ templateLocation ] }; } }]; <|start_filename|>packages/cli/test/cases/build.config.templates-directory/greenwood.config.js<|end_filename|> module.exports = { templatesDirectory: 'layouts' }; <|start_filename|>packages/cli/test/cases/build.default.workspace-template-app/build.default.workspace-template-app.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with no config and custom app template. * * User Result * Should generate a bare bones Greenwood build with custom app template. * * User Command * greenwood build * * User Config * None (Greenwood Default) * * User Workspace * src/ * templates/ * app.html */ const expect = require('chai').expect; const fs = require('fs'); const { JSDOM } = require('jsdom'); const path = require('path'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Default Greenwood Configuration and Workspace w/Custom App Template'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { let dom; before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Custom App Template', function() { before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should output a single index.html file using our custom app template', function() { expect(fs.existsSync(path.join(this.context.publicDir, './index.html'))).to.be.true; }); it('should have the specific element we added as part of our custom app template', function() { const customParagraph = dom.window.document.querySelector('body p').textContent; expect(customParagraph).to.equal('My Custom App Template'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/src/lifecycles/serve.js<|end_filename|> const fs = require('fs'); const path = require('path'); const Koa = require('koa'); const { ResourceInterface } = require('../lib/resource-interface'); function getDevServer(compilation) { const app = new Koa(); const compilationCopy = Object.assign({}, compilation); const resources = [ // Greenwood default standard resource and import plugins ...compilation.config.plugins.filter((plugin) => { return plugin.type === 'resource' && plugin.isGreenwoodDefaultPlugin; }).map((plugin) => { return plugin.provider(compilationCopy); }), // custom user resource plugins ...compilation.config.plugins.filter((plugin) => { return plugin.type === 'resource' && !plugin.isGreenwoodDefaultPlugin; }).map((plugin) => { const provider = plugin.provider(compilationCopy); if (!(provider instanceof ResourceInterface)) { console.warn(`WARNING: ${plugin.name}'s provider is not an instance of ResourceInterface.`); } return provider; }) ]; // resolve urls to paths first app.use(async (ctx, next) => { ctx.url = await resources.reduce(async (responsePromise, resource) => { const response = await responsePromise; const resourceShouldResolveUrl = await resource.shouldResolve(response); return resourceShouldResolveUrl ? resource.resolve(response) : Promise.resolve(response); }, Promise.resolve(ctx.url)); // bit of a hack to get these two bugs to play well together // https://github.com/ProjectEvergreen/greenwood/issues/598 // https://github.com/ProjectEvergreen/greenwood/issues/604 ctx.request.headers.originalUrl = ctx.originalUrl; await next(); }); // then handle serving urls app.use(async (ctx, next) => { const responseAccumulator = { body: ctx.body, contentType: ctx.response.contentType }; const reducedResponse = await resources.reduce(async (responsePromise, resource) => { const response = await responsePromise; const { url } = ctx; const { headers } = ctx.response; const shouldServe = await resource.shouldServe(url, { request: ctx.headers, response: headers }); if (shouldServe) { const resolvedResource = await resource.serve(url, { request: ctx.headers, response: headers }); return Promise.resolve({ ...response, ...resolvedResource }); } else { return Promise.resolve(response); } }, Promise.resolve(responseAccumulator)); ctx.set('Content-Type', reducedResponse.contentType); ctx.body = reducedResponse.body; await next(); }); // allow intercepting of urls (response) app.use(async (ctx) => { const responseAccumulator = { body: ctx.body, contentType: ctx.response.headers['content-type'] }; const reducedResponse = await resources.reduce(async (responsePromise, resource) => { const response = await responsePromise; const { url } = ctx; const { headers } = ctx.response; const shouldIntercept = await resource.shouldIntercept(url, response.body, { request: ctx.headers, response: headers }); if (shouldIntercept) { const interceptedResponse = await resource.intercept(url, response.body, { request: ctx.headers, response: headers }); return Promise.resolve({ ...response, ...interceptedResponse }); } else { return Promise.resolve(response); } }, Promise.resolve(responseAccumulator)); ctx.set('Content-Type', reducedResponse.contentType); ctx.body = reducedResponse.body; }); return app; } function getProdServer(compilation) { const app = new Koa(); const standardResources = compilation.config.plugins.filter((plugin) => { // html is intentionally omitted return plugin.isGreenwoodDefaultPlugin && plugin.type === 'resource' && plugin.name.indexOf('plugin-standard') >= 0 && plugin.name.indexOf('plugin-standard-html') < 0; }).map((plugin) => { return plugin.provider(compilation); }); app.use(async (ctx, next) => { const { outputDir } = compilation.context; const { mode } = compilation.config; const url = ctx.request.url.replace(/\?(.*)/, ''); // get rid of things like query string parameters if (url.endsWith('/') || url.endsWith('.html')) { const barePath = mode === 'spa' ? 'index.html' : url.endsWith('/') ? path.join(url, 'index.html') : url; const contents = await fs.promises.readFile(path.join(outputDir, barePath), 'utf-8'); ctx.set('content-type', 'text/html'); ctx.body = contents; } await next(); }); app.use(async (ctx, next) => { const url = ctx.request.url; if (compilation.config.devServer.proxy) { const proxyPlugin = compilation.config.plugins.filter((plugin) => { return plugin.name === 'plugin-dev-proxy'; }).map((plugin) => { return plugin.provider(compilation); })[0]; if (url !== '/' && await proxyPlugin.shouldServe(url)) { ctx.body = (await proxyPlugin.serve(url)).body; } } await next(); }); app.use(async (ctx) => { const responseAccumulator = { body: ctx.body, contentType: ctx.response.header['content-type'] }; const reducedResponse = await standardResources.reduce(async (responsePromise, resource) => { const response = await responsePromise; const url = ctx.url.replace(/\?(.*)/, ''); const { headers } = ctx.response; const outputPathUrl = path.join(compilation.context.outputDir, url); const shouldServe = await resource.shouldServe(outputPathUrl, { request: ctx.headers, response: headers }); if (shouldServe) { const resolvedResource = await resource.serve(outputPathUrl, { request: ctx.headers, response: headers }); return Promise.resolve({ ...response, ...resolvedResource }); } else { return Promise.resolve(response); } }, Promise.resolve(responseAccumulator)); ctx.set('content-type', reducedResponse.contentType); ctx.body = reducedResponse.body; }); return app; } module.exports = { devServer: getDevServer, prodServer: getProdServer }; <|start_filename|>packages/cli/test/cases/build.config.optimization-none/greenwood.config.js<|end_filename|> module.exports = { optimization: 'none' }; <|start_filename|>packages/cli/src/plugins/resource/plugin-standard-javascript.js<|end_filename|> /* * * Manages web standard resource related operations for JavaScript. * This is a Greenwood default plugin. * */ const fs = require('fs'); const { ResourceInterface } = require('../../lib/resource-interface'); const { terser } = require('rollup-plugin-terser'); class StandardJavaScriptResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['.js']; this.contentType = 'text/javascript'; } async serve(url) { return new Promise(async(resolve, reject) => { try { const body = await fs.promises.readFile(url, 'utf-8'); resolve({ body, contentType: this.contentType }); } catch (e) { reject(e); } }); } } module.exports = [{ type: 'resource', name: 'plugin-standard-javascript:resource', provider: (compilation, options) => new StandardJavaScriptResource(compilation, options) }, { type: 'rollup', name: 'plugin-standard-javascript:rollup', provider: (compilation) => { return compilation.config.optimization !== 'none' ? [terser()] : []; } }]; <|start_filename|>www/components/footer/footer.js<|end_filename|> import { css, html, LitElement, unsafeCSS } from 'lit'; import json from '../../package.json?type=json'; import footerCss from './footer.css?type=css'; class FooterComponent extends LitElement { static get styles() { return css` ${unsafeCSS(footerCss)} `; } render() { const { version } = json; return html` <footer class="footer"> <h4> <a href="https://github.com/ProjectEvergreen/greenwood/releases/tag/v${version}" target="_blank" rel="noopener noreferrer">Greenwood v${version}</a> <span class="separator">&#9672</span> <a href="https://www.netlify.com/">This site is powered by Netlify</a> </h4> </footer> `; } } customElements.define('app-footer', FooterComponent); <|start_filename|>packages/plugin-graphql/src/schema/config.js<|end_filename|> const gql = require('graphql-tag'); const getConfiguration = async (root, query, context) => { return context.config; }; // https://www.greenwoodjs.io/docs/configuration const configTypeDefs = gql` type DevServer { port: Int } type Meta { name: String, value: String, content: String, rel: String, property: String, href: String } type Config { devServer: DevServer, meta: [Meta], mode: String, optimization: String, prerender: Boolean, title: String, workspace: String } extend type Query { config: Config } `; const configResolvers = { Query: { config: getConfiguration } }; module.exports = { configTypeDefs, configResolvers }; <|start_filename|>packages/plugin-babel/package.json<|end_filename|> { "name": "@greenwood/plugin-babel", "version": "0.17.0", "description": "A Greenwood plugin for using Babel and applying it to your JavaScript.", "repository": "https://github.com/ProjectEvergreen/greenwood/tree/master/packages/plugin-babel", "author": "<NAME> <<EMAIL>>", "license": "MIT", "keywords": [ "Greenwood", "CommonJS", "Static Site Generator", "NodeJS", "Babel" ], "main": "src/index.js", "files": [ "src/" ], "publishConfig": { "access": "public" }, "peerDependencies": { "@babel/core": "^7.10.4", "@greenwood/cli": "^0.4.0" }, "dependencies": { "@babel/core": "^7.10.4", "@babel/plugin-transform-runtime": "^7.10.4", "@babel/preset-env": "^7.10.4", "@rollup/plugin-babel": "^5.3.0", "core-js": "^3.4.1" }, "devDependencies": { "@babel/plugin-proposal-class-properties": "^7.10.4", "@babel/plugin-proposal-private-methods": "^7.10.4", "@babel/runtime": "^7.10.4", "@greenwood/cli": "^0.17.0" } } <|start_filename|>packages/cli/test/cases/build.config.title/greenwood.config.js<|end_filename|> module.exports = { title: 'My Custom Greenwood App' }; <|start_filename|>packages/plugin-graphql/src/index.js<|end_filename|> const fs = require('fs'); const graphqlServer = require('./core/server'); const path = require('path'); const { ResourceInterface } = require('@greenwood/cli/src/lib/resource-interface'); const { ServerInterface } = require('@greenwood/cli/src/lib/server-interface'); const rollupPluginAlias = require('@rollup/plugin-alias'); class GraphQLResource extends ResourceInterface { constructor(compilation, options = {}) { super(compilation, options); this.extensions = ['.gql']; this.contentType = ['text/javascript']; } async serve(url) { return new Promise(async (resolve, reject) => { try { const js = await fs.promises.readFile(url, 'utf-8'); const body = ` export default \`${js}\`; `; resolve({ body, contentType: this.contentType }); } catch (e) { reject(e); } }); } async shouldIntercept(url, body, headers) { return Promise.resolve(headers.request.accept && headers.request.accept.indexOf('text/html') >= 0); } async intercept(url, body) { return new Promise(async (resolve, reject) => { try { // es-modules-shims breaks on dangling commas in an importMap :/ const danglingComma = body.indexOf('"imports": {}') > 0 ? '' : ','; const shimmedBody = body.replace('"imports": {', ` "imports": { "@greenwood/plugin-graphql/core/client": "/node_modules/@greenwood/plugin-graphql/src/core/client.js", "@greenwood/plugin-graphql/core/common": "/node_modules/@greenwood/plugin-graphql/src/core/common.client.js", "@greenwood/plugin-graphql/queries/children": "/node_modules/@greenwood/plugin-graphql/src/queries/children.gql", "@greenwood/plugin-graphql/queries/config": "/node_modules/@greenwood/plugin-graphql/src/queries/config.gql", "@greenwood/plugin-graphql/queries/graph": "/node_modules/@greenwood/plugin-graphql/src/queries/graph.gql", "@greenwood/plugin-graphql/queries/menu": "/node_modules/@greenwood/plugin-graphql/src/queries/menu.gql"${danglingComma} `); resolve({ body: shimmedBody }); } catch (e) { reject(e); } }); } async shouldOptimize(url) { return Promise.resolve(path.extname(url) === '.html'); } async optimize(url, body) { return new Promise((resolve, reject) => { try { body = body.replace('<head>', ` <script data-state="apollo"> window.__APOLLO_STATE__ = true; </script> <head> `); resolve(body); } catch (e) { reject(e); } }); } } class GraphQLServer extends ServerInterface { constructor(compilation, options = {}) { super(compilation, options); } async start() { return graphqlServer(this.compilation).listen().then((server) => { console.log(`GraphQLServer started at ${server.url}`); }); } } module.exports = (options = {}) => { return [{ type: 'server', name: 'plugin-graphql:server', provider: (compilation) => new GraphQLServer(compilation, options) }, { type: 'resource', name: 'plugin-graphql:resource', provider: (compilation) => new GraphQLResource(compilation, options) }, { type: 'rollup', name: 'plugin-graphql:rollup', provider: () => [ rollupPluginAlias({ entries: [ { find: '@greenwood/plugin-graphql/core/client', replacement: '@greenwood/plugin-graphql/src/core/client.js' }, { find: '@greenwood/plugin-graphql/core/common', replacement: '@greenwood/plugin-graphql/src/core/common.client.js' }, { find: '@greenwood/plugin-graphql/queries/menu', replacement: '@greenwood/plugin-graphql/src/queries/menu.gql' }, { find: '@greenwood/plugin-graphql/queries/config', replacement: '@greenwood/plugin-graphql/src/queries/config.gql' }, { find: '@greenwood/plugin-graphql/queries/children', replacement: '@greenwood/plugin-graphql/src/queries/children.gql' }, { find: '@greenwood/plugin-graphql/queries/graph', replacement: '@greenwood/plugin-graphql/src/queries/graph.gql' } ] }) ] }]; }; <|start_filename|>packages/cli/test/cases/develop.plugins.context/greenwood.config.js<|end_filename|> // shared from another test const myThemePackPlugin = require('../build.plugins.context/theme-pack-context-plugin'); const packageName = require('./package.json').name; const path = require('path'); const { ResourceInterface } = require('@greenwood/cli/src/lib/resource-interface'); class MyThemePackDevelopmentResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['*']; } async shouldResolve(url) { return Promise.resolve(url.indexOf(`/node_modules/${packageName}/`) >= 0); } async resolve(url) { return Promise.resolve(url.replace(`/node_modules/${packageName}/dist/`, path.join(process.cwd(), '/fixtures/'))); } } module.exports = { plugins: [ ...myThemePackPlugin(), { type: 'resource', name: 'my-theme-pack:resource', provider: (compilation, options) => new MyThemePackDevelopmentResource(compilation, options) } ] }; <|start_filename|>packages/plugin-postcss/src/index.js<|end_filename|> /* * * Enable using PostCSS process for CSS files. * */ const fs = require('fs'); const path = require('path'); const postcss = require('postcss'); const { ResourceInterface } = require('@greenwood/cli/src/lib/resource-interface'); function getConfig (compilation, extendConfig = false) { const { projectDirectory } = compilation.context; const configFile = 'postcss.config'; const defaultConfig = require(path.join(__dirname, configFile)); const userConfig = fs.existsSync(path.join(projectDirectory, `${configFile}.js`)) ? require(`${projectDirectory}/${configFile}`) : {}; let finalConfig = Object.assign({}, userConfig); if (userConfig && extendConfig) { finalConfig.plugins = Array.isArray(userConfig.plugins) ? [...defaultConfig.plugins, ...userConfig.plugins] : [...defaultConfig.plugins]; } return finalConfig; } class PostCssResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['.css']; this.contentType = ['text/css']; } isCssFile(url) { return path.extname(url) === '.css'; } async shouldIntercept(url) { return Promise.resolve(this.isCssFile(url)); } async intercept(url, body) { return new Promise(async(resolve, reject) => { try { const config = getConfig(this.compilation, this.options.extendConfig); const plugins = config.plugins || []; const css = plugins.length > 0 ? (await postcss(plugins).process(body, { from: url })).css : body; resolve({ body: css }); } catch (e) { reject(e); } }); } async shouldOptimize(url) { return Promise.resolve(this.isCssFile(url)); } async optimize(url, body) { const { outputDir, userWorkspace } = this.compilation.context; const workspaceUrl = url.replace(outputDir, userWorkspace); const config = getConfig(this.compilation, this.options.extendConfig); const plugins = config.plugins || []; plugins.push( require('cssnano') ); const css = plugins.length > 0 ? (await postcss(plugins).process(body, { from: workspaceUrl })).css : body; return Promise.resolve(css); } } module.exports = (options = {}) => { return { type: 'resource', name: 'plugin-postcss', provider: (compilation) => new PostCssResource(compilation, options) }; }; <|start_filename|>packages/cli/test/cases/build.config.error-pages-directory/greenwood.config.js<|end_filename|> module.exports = { pagesDirectory: {} }; <|start_filename|>packages/cli/test/cases/build.config.markdown-custom.settings/build.config.markdown-custom.settings.spec.js<|end_filename|> /* * Use Case * Run Greenwood with custom markdown settings in greenwood config. * * User Result * Should generate a bare bones Greenwood build. (same as build.default.spec.js) with custom markdown and rehype links * * User Command * greenwood build * * User Config * markdown: { * settings: { gfm: false } * } * * User Workspace * src/ * pages/ * index.md */ const { JSDOM } = require('jsdom'); const expect = require('chai').expect; const path = require('path'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Custom Markdown Configuration and Custom Workspace'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); describe('Custom Markdown Presets', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); // gfm: false disables things like fenced code blocks https://www.npmjs.com/package/remark-parse#optionsgfm it('should intentionally fail to compile code fencing using our custom markdown preset settings', async function() { let pre = dom.window.document.querySelector('pre > code'); expect(pre).to.equal(null); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.mode-mpa/greenwood.config.js<|end_filename|> module.exports = { mode: 'mpa' }; <|start_filename|>packages/cli/src/lifecycles/config.js<|end_filename|> const fs = require('fs'); const path = require('path'); // get and "tag" all plugins provided / maintained by the @greenwood/cli // and include as the default set, with all user plugins getting appended const greenwoodPluginsBasePath = path.join(__dirname, '../', 'plugins'); const greenwoodPlugins = [ path.join(greenwoodPluginsBasePath, 'copy'), path.join(greenwoodPluginsBasePath, 'resource'), path.join(greenwoodPluginsBasePath, 'server') ].map((pluginDirectory) => { return fs.readdirSync(pluginDirectory) .map((filename) => { const plugin = require(`${pluginDirectory}/${filename}`); return Array.isArray(plugin) ? plugin : [plugin]; }).flat(); }).flat() .map((plugin) => { return { isGreenwoodDefaultPlugin: true, ...plugin }; }); const modes = ['ssg', 'mpa', 'spa']; const optimizations = ['default', 'none', 'static', 'inline']; const pluginTypes = ['copy', 'context', 'resource', 'rollup', 'server']; const defaultConfig = { workspace: path.join(process.cwd(), 'src'), devServer: { port: 1984, extensions: [] }, mode: modes[0], optimization: optimizations[0], title: 'My App', meta: [], plugins: greenwoodPlugins, markdown: { plugins: [], settings: {} }, prerender: true, pagesDirectory: 'pages', templatesDirectory: 'templates' }; module.exports = readAndMergeConfig = async() => { // eslint-disable-next-line complexity return new Promise(async (resolve, reject) => { try { // deep clone of default config let customConfig = Object.assign({}, defaultConfig); if (fs.existsSync(path.join(process.cwd(), 'greenwood.config.js'))) { const userCfgFile = require(path.join(process.cwd(), 'greenwood.config.js')); const { workspace, devServer, title, markdown, meta, mode, optimization, plugins, prerender, pagesDirectory, templatesDirectory } = userCfgFile; // workspace validation if (workspace) { if (typeof workspace !== 'string') { reject('Error: greenwood.config.js workspace path must be a string'); } if (!path.isAbsolute(workspace)) { // prepend relative path with current directory customConfig.workspace = path.join(process.cwd(), workspace); } if (path.isAbsolute(workspace)) { // use the users provided path customConfig.workspace = workspace; } if (!fs.existsSync(customConfig.workspace)) { reject('Error: greenwood.config.js workspace doesn\'t exist! \n' + 'common issues to check might be: \n' + '- typo in your workspace directory name, or in greenwood.config.js \n' + '- if using relative paths, make sure your workspace is in the same cwd as _greenwood.config.js_ \n' + '- consider using an absolute path, e.g. path.join(__dirname, \'my\', \'custom\', \'path\') // <__dirname>/my/custom/path/ '); } } if (title) { if (typeof title !== 'string') { reject('Error: greenwood.config.js title must be a string'); } customConfig.title = title; } if (meta && meta.length > 0) { customConfig.meta = meta; } if (typeof mode === 'string' && modes.indexOf(mode.toLowerCase()) >= 0) { customConfig.mode = mode; } else if (mode) { reject(`Error: provided mode "${mode}" is not supported. Please use one of: ${modes.join(', ')}.`); } if (typeof optimization === 'string' && optimizations.indexOf(optimization.toLowerCase()) >= 0) { customConfig.optimization = optimization; } else if (optimization) { reject(`Error: provided optimization "${optimization}" is not supported. Please use one of: ${optimizations.join(', ')}.`); } if (plugins && plugins.length > 0) { plugins.forEach(plugin => { if (!plugin.type || pluginTypes.indexOf(plugin.type) < 0) { reject(`Error: greenwood.config.js plugins must be one of type "${pluginTypes.join(', ')}". got "${plugin.type}" instead.`); } if (!plugin.provider || typeof plugin.provider !== 'function') { const providerTypeof = typeof plugin.provider; reject(`Error: greenwood.config.js plugins provider must be a function. got ${providerTypeof} instead.`); } if (!plugin.name || typeof plugin.name !== 'string') { const nameTypeof = typeof plugin.name; reject(`Error: greenwood.config.js plugins must have a name. got ${nameTypeof} instead.`); } }); customConfig.plugins = customConfig.plugins.concat(plugins); } if (devServer && Object.keys(devServer).length > 0) { if (devServer.port) { // eslint-disable-next-line max-depth if (!Number.isInteger(devServer.port)) { reject(`Error: greenwood.config.js devServer port must be an integer. Passed value was: ${devServer.port}`); } else { customConfig.devServer.port = devServer.port; } } if (devServer.proxy) { customConfig.devServer.proxy = devServer.proxy; } if (devServer.extensions) { if (Array.isArray(devServer.extensions)) { customConfig.devServer.extensions = devServer.extensions; } else { reject('Error: provided extensions is not an array. Please provide an array like [\'.txt\', \'.foo\']'); } } } if (markdown && Object.keys(markdown).length > 0) { customConfig.markdown.plugins = markdown.plugins && markdown.plugins.length > 0 ? markdown.plugins : []; customConfig.markdown.settings = markdown.settings ? markdown.settings : {}; } if (prerender !== undefined) { if (typeof prerender === 'boolean') { customConfig.prerender = prerender; } else { reject(`Error: greenwood.config.js prerender must be a boolean; true or false. Passed value was typeof: ${typeof prerender}`); } } // SPA should _not_ prerender if user has specified prerender should be true if (prerender === undefined && mode === 'spa') { customConfig.prerender = false; } if (pagesDirectory && typeof pagesDirectory === 'string') { customConfig.pagesDirectory = pagesDirectory; } else if (pagesDirectory) { reject(`Error: provided pagesDirectory "${pagesDirectory}" is not supported. Please make sure to pass something like 'docs/'`); } if (templatesDirectory && typeof templatesDirectory === 'string') { customConfig.templatesDirectory = templatesDirectory; } else if (templatesDirectory) { reject(`Error: provided templatesDirectory "${templatesDirectory}" is not supported. Please make sure to pass something like 'layouts/'`); } } resolve({ ...defaultConfig, ...customConfig }); } catch (err) { reject(err); } }); }; <|start_filename|>www/components/footer/footer.css<|end_filename|> :host { grid-area: footer; & .footer { background-color: #192a27; min-height: 30px; padding-top: 10px; & h4 { width: 90%; margin: 0 auto!important; padding: 0; text-align: center; } & a { color: white; text-decoration: none; } & span.separator { color: white; } } } <|start_filename|>packages/cli/test/cases/build.plugins.context/theme-pack-context-plugin.js<|end_filename|> const os = require('os'); const path = require('path'); const packageJson = require('./package.json'); const { spawnSync } = require('child_process'); module.exports = () => [{ type: 'context', name: 'my-theme-pack:context', provider: () => { const { name } = packageJson; const baseDistDir = `node_modules/${name}/dist`; const command = os.platform() === 'win32' ? 'npm.cmd' : 'npm'; const ls = spawnSync(command, ['ls', name]); const isInstalled = ls.stdout.toString().indexOf('(empty)') < 0; const templateLocation = isInstalled ? path.join(__dirname, `${baseDistDir}/layouts`) : path.join(process.cwd(), 'fixtures/layouts'); return { templates: [ templateLocation ] }; } }]; <|start_filename|>packages/cli/test/cases/build.config.optimization-static/greenwood.config.js<|end_filename|> module.exports = { optimization: 'static' }; <|start_filename|>packages/cli/src/lifecycles/prerender.js<|end_filename|> const BrowserRunner = require('../lib/browser'); const fs = require('fs'); const path = require('path'); async function optimizePage(compilation, contents, route, outputDir) { const outputPath = `${outputDir}${route}index.html`; const optimizeResources = compilation.config.plugins.filter((plugin) => { return plugin.type === 'resource'; }).map((plugin) => { return plugin.provider(compilation); }).filter((provider) => { return provider.shouldOptimize && provider.optimize; }); const htmlOptimized = await optimizeResources.reduce(async (htmlPromise, resource) => { const html = await htmlPromise; const shouldOptimize = await resource.shouldOptimize(outputPath, html); return shouldOptimize ? resource.optimize(outputPath, html) : Promise.resolve(html); }, Promise.resolve(contents)); if (!fs.existsSync(path.join(outputDir, route))) { fs.mkdirSync(path.join(outputDir, route), { recursive: true }); } await fs.promises.writeFile(outputPath, htmlOptimized); } async function preRenderCompilation(compilation) { const browserRunner = new BrowserRunner(); const runBrowser = async (serverUrl, pages, outputDir) => { try { return Promise.all(pages.map(async(page) => { const { route } = page; console.info('prerendering page...', route); return await browserRunner .serialize(`${serverUrl}${route}`) .then(async (indexHtml) => { console.info(`prerendering complete for page ${route}.`); await optimizePage(compilation, indexHtml, route, outputDir); }); })); } catch (e) { // eslint-disable-next-line no-console console.error(err); return false; } }; // gracefully handle if puppeteer is not installed correctly // like may happen in a stackblitz environment and just reject early // otherwise we can feel confident attempating to prerender all pages // https://github.com/ProjectEvergreen/greenwood/discussions/639 try { await browserRunner.init(); } catch (e) { console.error(e); console.error('*******************************************************************'); console.error('*******************************************************************'); console.error('There was an error trying to initialize puppeteer for pre-rendering.'); console.info('To troubleshoot, please check your environment for any npm install or postinstall errors, as may be the case in a Stackblitz or other sandbox like environment.'); console.info('For more information please see this guide - https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md'); return Promise.reject(); } return new Promise(async (resolve, reject) => { try { const pages = compilation.graph; const port = compilation.config.devServer.port; const outputDir = compilation.context.scratchDir; const serverAddress = `http://127.0.0.1:${port}`; console.info(`Prerendering pages at ${serverAddress}`); console.debug('pages to render', `\n ${pages.map(page => page.path).join('\n ')}`); await runBrowser(serverAddress, pages, outputDir); console.info('done prerendering all pages'); browserRunner.close(); resolve(); } catch (err) { reject(err); } }); } async function staticRenderCompilation(compilation) { const pages = compilation.graph; const scratchDir = compilation.context.scratchDir; const htmlResource = compilation.config.plugins.filter((plugin) => { return plugin.name === 'plugin-standard-html'; }).map((plugin) => { return plugin.provider(compilation); })[0]; console.info('pages to generate', `\n ${pages.map(page => page.path).join('\n ')}`); await Promise.all(pages.map(async (page) => { const route = page.route; const response = await htmlResource.serve(route); await optimizePage(compilation, response.body, route, scratchDir); return Promise.resolve(); })); console.info('success, done generating all pages!'); } module.exports = { preRenderCompilation, staticRenderCompilation }; <|start_filename|>packages/plugin-graphql/test/cases/query-config/query-config.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with GraphQL calls to get data from the project configuration. * * User Result * Should generate a Greenwood build that dynamically serializes data from the config in the footer. * * User Command * greenwood build * * Default Config (+ plugin-graphql) * * Custom Workspace * greenwood.config.js * src/ * components/ * footer.js * pages/ * index.html */ const expect = require('chai').expect; const greenwoodConfig = require('./greenwood.config'); const glob = require('glob-promise'); const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getDependencyFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'ConfigQuery from GraphQL'; const apolloStateRegex = /window.__APOLLO_STATE__ = true/; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { const greenwoodGraphqlCoreLibs = await getDependencyFiles( `${process.cwd()}/packages/plugin-graphql/src/core/*.js`, `${outputPath}/node_modules/@greenwood/plugin-graphql/src/core/` ); const greenwoodGraphqlQueryLibs = await getDependencyFiles( `${process.cwd()}/packages/plugin-graphql/src/queries/*.gql`, `${outputPath}/node_modules/@greenwood/plugin-graphql/src/queries/` ); await runner.setup(outputPath, [ ...getSetupFiles(outputPath), ...greenwoodGraphqlCoreLibs, ...greenwoodGraphqlQueryLibs ]); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('displaying config title in the footer using ConfigQuery', function() { before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have a <footer> in the <body> with greenwoodConfig#title as the text value', function() { const footer = dom.window.document.querySelector('body footer'); expect(footer.innerHTML).to.be.equal(greenwoodConfig.title); }); it('should have one window.__APOLLO_STATE__ <script> with (approximated) expected state', function() { const scriptTags = dom.window.document.querySelectorAll('script'); const apolloScriptTags = Array.prototype.slice.call(scriptTags).filter(script => { return script.getAttribute('data-state') === 'apollo'; }); const innerHTML = apolloScriptTags[0].innerHTML; expect(apolloScriptTags.length).to.equal(1); expect(innerHTML).to.match(apolloStateRegex); }); it('should output a single (partial) *-cache.json file, one per each query made', async function() { expect(await glob.promise(path.join(this.context.publicDir, './*-cache.json'))).to.have.lengthOf(1); }); it('should output a (partial) *-cache.json files, one per each query made, that are all defined', async function() { const cacheFiles = await glob.promise(path.join(this.context.publicDir, './*-cache.json')); cacheFiles.forEach(file => { const cache = require(file); expect(cache).to.not.be.undefined; }); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.mode-spa/greenwood.config.js<|end_filename|> module.exports = { title: 'this is the wrong title', mode: 'spa' }; <|start_filename|>packages/cli/test/cases/build.default.workspace-template-page-and-app/build.default.workspace-template-page-and-app.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with no config and custom page (and app) template. * * User Result * Should generate a bare bones Greenwood build with custom page template. * * User Command * greenwood build * * User Config * None (Greenwood Default) * * User Workspace * src/ * scripts/ * app-template-one.js * app-template-two.js * page-template-one.js * page-template-two.js * styles/ * app-template-one.css * app-template-two.css * page-template-one.css * page-template-two.css * templates/ * app.html * page.html */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Default Greenwood Configuration and Workspace w/Custom App and Page Templates'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Custom App and Page Templates', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have the specific element we added as part of our custom page template', function() { const customElement = dom.window.document.querySelectorAll('div.owen-test'); expect(customElement.length).to.equal(1); }); describe('merge order for app and page template <head> tags', function() { let scriptTags; let linkTags; let styleTags; before(function() { scriptTags = dom.window.document.querySelectorAll('head > script'); linkTags = dom.window.document.querySelectorAll('head > link[rel="stylesheet"'); styleTags = dom.window.document.querySelectorAll('head > style'); }); it('should have 4 <script> tags in the <head>', function() { expect(scriptTags.length).to.equal(4); }); it('should have 4 <link> tags in the <head>', function() { expect(linkTags.length).to.equal(4); }); it('should have 5 <style> tags in the <head> (4 + one from Puppeteer)', function() { expect(styleTags.length).to.equal(5); }); it('should merge page template <script> tags after app template <script> tags', function() { expect(scriptTags[0].src).to.match(/app-template-one.*.js/); expect(scriptTags[1].src).to.match(/app-template-two.*.js/); expect(scriptTags[2].src).to.match(/page-template-one.*.js/); expect(scriptTags[3].src).to.match(/page-template-two.*.js/); scriptTags.forEach((scriptTag) => { expect(scriptTag.type).to.equal('module'); }); }); it('should merge page template <link> tags after app template <link> tags', function() { expect(linkTags[0].href).to.match(/app-template-one.*.css/); expect(linkTags[1].href).to.match(/app-template-two.*.css/); expect(linkTags[2].href).to.match(/page-template-one.*.css/); expect(linkTags[3].href).to.match(/page-template-two.*.css/); linkTags.forEach((linkTag) => { expect(linkTag.rel).to.equal('stylesheet'); }); }); it('should merge page template <style> tags after app template <style> tags', function() { // offset index by one since first <style> tag is from Puppeteer expect(styleTags[1].textContent).to.contain('app-template-one-style'); expect(styleTags[2].textContent).to.contain('app-template-two-style'); expect(styleTags[3].textContent).to.contain('page-template-one-style'); expect(styleTags[4].textContent).to.contain('page-template-two-style'); }); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.error-optimization/greenwood.config.js<|end_filename|> module.exports = { optimization: 'loremipsum' }; <|start_filename|>packages/cli/test/cases/build.default.workspace-template-page/build.default.workspace-template-page.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with no config and custom page template. * * User Result * Should generate a bare bones Greenwood build with custom page template. * * User Command * greenwood build * * User Config * None (Greenwood Default) * * User Workspace * src/ * scripts * main.js * styles/ * theme.css * templates/ * page.html */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Default Greenwood Configuration and Workspace w/Custom Page Template'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Custom Page Template', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); describe('correct merge order for default app and custom page template <head> tags', function() { let scriptTags; let linkTags; let styleTags; before(function() { scriptTags = dom.window.document.querySelectorAll('head > script'); linkTags = dom.window.document.querySelectorAll('head > link[rel="stylesheet"]'); styleTags = dom.window.document.querySelectorAll('head > style'); }); it('should have custom <meta> tag in the <head>', function() { const customMeta = Array.from(dom.window.document.querySelectorAll('head > meta')) .filter(meta => meta.getAttribute('property') === 'og:description'); expect(customMeta.length).to.be.equal(1); expect(customMeta[0].getAttribute('content')).to.be.equal('My custom meta content.'); }); it('should have 1 <script> tags in the <head>', function() { expect(scriptTags.length).to.equal(1); }); it('should have 1 <link> tags in the <head>', function() { expect(linkTags.length).to.equal(1); }); it('should have 2 <style> tags in the <head> (1 + one from Puppeteer)', function() { expect(styleTags.length).to.equal(2); }); it('should add one page template <script> tag', function() { expect(scriptTags[0].type).to.equal('module'); expect(scriptTags[0].src).to.match(/main.*.js/); }); it('should add one page template <link> tag', function() { expect(linkTags[0].rel).to.equal('stylesheet'); expect(linkTags[0].href).to.match(/styles\/theme.[a-z0-9]{8}.css/); }); it('should add one page template <style> tag', function() { // offset index by one since first <style> tag is from Puppeteer expect(styleTags[1].textContent).to.contain('.owen-test'); }); }); describe('custom inline <style> tag in the <head> of a page template', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have the specific element we added as part of our custom page template', function() { const customElement = dom.window.document.querySelectorAll('div.owen-test'); expect(customElement.length).to.equal(1); }); it('should have the color style for the .owen-test element in the page template that we added as part of our custom style', function() { const customElement = dom.window.document.querySelector('.owen-test'); const computedStyle = dom.window.getComputedStyle(customElement); expect(computedStyle.color).to.equal('blue'); }); it('should have the color styles for the h3 element that we defined as part of our custom style', function() { const customHeader = dom.window.document.querySelector('h3'); const computedStyle = dom.window.getComputedStyle(customHeader); expect(computedStyle.color).to.equal('green'); }); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>www/styles/theme.css<|end_filename|> @import url('../assets/fonts/source-sans-pro.css'); * { margin: 0; padding: 0; text-decoration: none; } html { background-color: white; } body { font-family: 'Source Sans Pro', sans-serif; line-height: 1.4; } img { width: 100%; } h2, h3, h4, h5 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; color: #201e2e; } ul, ol { padding-left: 20px; } p { margin: 20px 0; } ul > li { margin: 10px 0; } a { & .title { text-decoration: underline; } & .step { margin: 2px; } } p > code { color: #2d3d3a; font-weight: 800; } .gwd-wrapper { & .single-column { margin: inherit; color: #000; } } <|start_filename|>packages/cli/src/plugins/resource/plugin-standard-json.js<|end_filename|> /* * * Manages web standard resource related operations for JavaScript. * This is a Greenwood default plugin. * */ const fs = require('fs'); const { ResourceInterface } = require('../../lib/resource-interface'); class StandardJsonResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['.json']; this.contentType = 'application/json'; } async serve(url) { return new Promise(async (resolve, reject) => { try { const { scratchDir } = this.compilation.context; const filePath = url.indexOf('graph.json') >= 0 ? `${scratchDir}/graph.json` : url; const contents = await fs.promises.readFile(filePath, 'utf-8'); resolve({ body: JSON.parse(contents), contentType: this.contentType }); } catch (e) { reject(e); } }); } } module.exports = [{ type: 'resource', name: 'plugin-standard-json:resource', provider: (compilation, options) => new StandardJsonResource(compilation, options) }]; <|start_filename|>packages/cli/src/plugins/resource/plugin-standard-font.js<|end_filename|> /* * * Manages web standard resource related operations for JavaScript. * This is a Greenwood default plugin. * */ const fs = require('fs'); const path = require('path'); const { ResourceInterface } = require('../../lib/resource-interface'); class StandardFontResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['.woff2', '.woff', '.ttf']; } async serve(url) { return new Promise(async (resolve, reject) => { try { const contentType = path.extname(url).replace('.', ''); const body = await fs.promises.readFile(url); resolve({ body, contentType }); } catch (e) { reject(e); } }); } } module.exports = { type: 'resource', name: 'plugin-standard-font', provider: (compilation, options) => new StandardFontResource(compilation, options) }; <|start_filename|>packages/cli/src/commands/serve.js<|end_filename|> const generateCompilation = require('../lifecycles/compile'); const { prodServer } = require('../lifecycles/serve'); module.exports = runProdServer = async () => { return new Promise(async (resolve, reject) => { try { const compilation = await generateCompilation(); const port = 8080; prodServer(compilation).listen(port, () => { console.info(`Started production test server at localhost:${port}`); }); } catch (err) { reject(err); } }); }; <|start_filename|>packages/plugin-google-analytics/test/cases/error-analytics-id/greenwood.config.js<|end_filename|> const googleAnalyticsPlugin = require('../../../src/index'); module.exports = { plugins: [ googleAnalyticsPlugin() ] }; <|start_filename|>packages/cli/test/cases/build.default.workspace-templates-relative-paths/build.default.workspace-templates-relative-paths.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with no config and custom page (and app) templates using relative paths. * * User Result * Should generate the expected Greenwood build. * * User Command * greenwood build * * User Config * None (Greenwood Default) * * User Workspace * src/ * components/ * footer.js * greeting.js * header.js * styles/ * home.css * page.css * theme.css * pages/ * one/ * two/ * three/ * index.md * index.html * templates/ * app.html * page.html */ const expect = require('chai').expect; const glob = require('glob-promise'); const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getDependencyFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Default Greenwood Configuration and Workspace w/Custom App and Page Templates using relative paths'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { const prismCss = await getDependencyFiles( `${process.cwd()}/node_modules/prismjs/themes/prism-tomorrow.css`, `${outputPath}/node_modules/prismjs/themes/` ); await runner.setup(outputPath, [ ...getSetupFiles(outputPath), ...prismCss ]); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Custom App and Page Templates using relative paths', function() { let cssFiles; let scriptFiles; before(async function() { cssFiles = await glob(`${this.context.publicDir}/**/**/*.css`); scriptFiles = await glob(`${this.context.publicDir}/**/**/*.js`); }); describe('common styles and scripts file output', function() { it('should emit three javascript files (header, footer, greeting)', function() { expect(scriptFiles.length).to.be.equal(3); }); it('should emit one javascript file for the header', function() { const header = scriptFiles.filter(file => file.indexOf('/header') >= 0); expect(header.length).to.be.equal(1); }); it('should emit one javascript file for the footer', function() { const footer = scriptFiles.filter(file => file.indexOf('/footer') >= 0); expect(footer.length).to.be.equal(1); }); it('should emit four CSS files for styles and assets/', function() { const styles = cssFiles.filter((file) => file.indexOf('/styles') >= 0); const assets = cssFiles.filter(file => file.indexOf('/assets') >= 0); expect(cssFiles.length).to.be.equal(4); expect(styles.length).to.be.equal(3); expect(assets.length).to.be.equal(1); }); }); describe('top level index (home) page content', function() { let dom; let scriptTags; let linkTags; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); scriptTags = Array.from(dom.window.document.querySelectorAll('head > script')); linkTags = Array.from(dom.window.document.querySelectorAll('head > link[rel="stylesheet"')); }); it('should have one <script> tags in the <head> for the header', function() { const headerTag = scriptTags.filter((tag) => { return tag.src.indexOf('/header') >= 0 && tag.src.indexOf('..') < 0; }); expect(headerTag.length).to.be.equal(1); }); it('should have one <script> tags in the <head> for the footer', function() { const footerTag = scriptTags.filter((tag) => { return tag.src.indexOf('/footer') >= 0 && tag.src.indexOf('..') < 0; }); expect(footerTag.length).to.be.equal(1); }); it('should have one <link> tag in the <head> for theme.css', function() { const themeTag = linkTags.filter((tag) => { return tag.href.indexOf('/theme') >= 0 && tag.href.indexOf('..') < 0; }); expect(themeTag.length).to.be.equal(1); }); it('should have one <link> tag in the <head> for home.css', function() { const homeTag = linkTags.filter((tag) => { return tag.href.indexOf('/home') >= 0 && tag.href.indexOf('..') < 0; }); expect(homeTag.length).to.be.equal(1); }); it('should have content output for the <app-footer> component', function() { const footer = dom.window.document.querySelectorAll('body footer'); expect(footer.length).to.be.equal(1); expect(footer[0].textContent).to.be.equal('This is the footer component.'); }); it('should have content output for the <app-header> component', function() { const header = dom.window.document.querySelectorAll('body header'); expect(header.length).to.be.equal(1); expect(header[0].textContent).to.be.equal('This is the header component.'); }); it('should have content output for the page', function() { const content = dom.window.document.querySelectorAll('body > h1'); expect(content.length).to.be.equal(1); expect(content[0].textContent).to.be.equal('Home Page'); }); }); describe('three level deep nested page content', function() { let dom; let scriptTags; let linkTags; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'one/two/three', 'index.html')); scriptTags = Array.from(dom.window.document.querySelectorAll('head > script')); linkTags = Array.from(dom.window.document.querySelectorAll('head > link[rel="stylesheet"')); }); it('should emit one javascript file for the greeting component from frontmatter import', function() { const greeting = scriptFiles.filter(file => file.indexOf('/greeting') >= 0); expect(greeting.length).to.be.equal(1); }); it('should have one <script> tags in the <head> for the header', function() { const headerTag = scriptTags.filter((tag) => { return tag.src.indexOf('/header') >= 0 && tag.src.indexOf('..') < 0; }); expect(headerTag.length).to.be.equal(1); }); it('should have one <script> tags in the <head> for the footer', function() { const footerTag = scriptTags.filter((tag) => { return tag.src.indexOf('/footer') >= 0 && tag.src.indexOf('..') < 0; }); expect(footerTag.length).to.be.equal(1); }); it('should have one <script> tags in the <head> for the greeting from front matter import', function() { const greetingTag = scriptTags.filter((tag) => { return tag.src.indexOf('/greeting') >= 0 && tag.src.indexOf('..') < 0; }); expect(greetingTag.length).to.be.equal(1); }); it('should have one <link> tag in the <head> for theme.css', function() { const themeTag = linkTags.filter((tag) => { return tag.href.indexOf('/theme') >= 0 && tag.href.indexOf('..') < 0; }); expect(themeTag.length).to.be.equal(1); }); it('should have one <link> tag in the <head> for page.css', function() { const pageTag = linkTags.filter((tag) => { return tag.href.indexOf('/page') >= 0 && tag.href.indexOf('..') < 0; }); expect(pageTag.length).to.be.equal(1); }); it('should have content output for the <app-footer> component', function() { const footer = dom.window.document.querySelectorAll('body footer'); expect(footer.length).to.be.equal(1); expect(footer[0].textContent).to.be.equal('This is the footer component.'); }); it('should have content output for the <app-header> component', function() { const header = dom.window.document.querySelectorAll('body header'); expect(header.length).to.be.equal(1); expect(header[0].textContent).to.be.equal('This is the header component.'); }); it('should have content output for the page', function() { const content = dom.window.document.querySelectorAll('body > h1'); expect(content.length).to.be.equal(1); expect(content[0].textContent).to.be.equal('One Two Three'); }); it('should have content output for the x-greeting component from front matter import', function() { const content = dom.window.document.querySelectorAll('body > x-greeting > h3'); expect(content.length).to.be.equal(1); expect(content[0].textContent).to.be.equal('Hello from the greeting component!'); }); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.meta/build.config.meta.spec.js<|end_filename|> /* * Use Case * Run Greenwood with meta in Greenwood config and a default workspace with a nested route. * * User Result * Should generate a bare bones Greenwood build with one nested About page w/ custom meta data. * * User Command * greenwood build * * User Config * { * title: 'My Custom Greenwood App', * meta: [ * { property: 'og:site', content: 'The Greenhouse I/O' }, * { property: 'og:url', content: 'https://www.thegreenhouse.io' }, * { name: 'twitter:site', content: '@thegreenhouseio' } * { rel: 'shortcut icon', href: '/assets/images/favicon.ico' } * { rel: 'icon', href: '/assets/images/favicon.ico' } * ] * } * * User Workspace * Greenwood default w/ nested page * src/ * pages/ * about/ * index.md * hello.md * index.md */ const fs = require('fs'); const greenwoodConfig = require('./greenwood.config'); const { JSDOM } = require('jsdom'); const path = require('path'); const expect = require('chai').expect; const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Custom Meta Configuration and Nested Workspace'; const meta = greenwoodConfig.meta; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { const metaFilter = (metaKey) => { return meta.filter((item) => { if (item.property === metaKey || item.name === metaKey || item.rel === metaKey) { return item; } })[0]; }; before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Index (home) page with custom meta data', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, './index.html')); }); it('should have a <title> tag in the <head>', function() { const title = dom.window.document.querySelector('head title').textContent; expect(title).to.be.equal(greenwoodConfig.title); }); it('should have the expected heading text within the index page in the public directory', function() { const indexPageHeading = 'Greenwood'; const heading = dom.window.document.querySelector('h3').textContent; expect(heading).to.equal(indexPageHeading); }); it('should have the expected paragraph text within the index page in the public directory', function() { const indexPageBody = 'This is the home page built by Greenwood. Make your own pages in src/pages/index.js!'; const paragraph = dom.window.document.querySelector('p').textContent; expect(paragraph).to.equal(indexPageBody); }); it('should have a <meta> tag with custom og:site content in the <head>', function() { const ogSiteMeta = metaFilter('og:site'); const metaElement = dom.window.document.querySelector(`head meta[property="${ogSiteMeta.property}`); expect(metaElement.getAttribute('content')).to.be.equal(ogSiteMeta.content); }); it('should have a <meta> tag with custom og:url content in the <head>', function() { const ogUrlMeta = metaFilter('og:url'); const metaElement = dom.window.document.querySelector(`head meta[property="${ogUrlMeta.property}"]`); expect(metaElement.getAttribute('content')).to.be.equal(ogUrlMeta.content); }); it('should have a <meta> tag with custom twitter:site content in the <head>', function() { const twitterSiteMeta = metaFilter('twitter:site'); const metaElement = dom.window.document.querySelector(`head meta[name="${twitterSiteMeta.name}"]`); expect(metaElement.getAttribute('content')).to.be.equal(twitterSiteMeta.content); }); }); describe('Nested About page meta data', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'about', './index.html')); }); it('should output an index.html file within the about page directory', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'about', './index.html'))).to.be.true; }); it('should have a <meta> tag with custom og:site content in the <head>', function() { const ogSiteMeta = metaFilter('og:site'); const metaElement = dom.window.document.querySelector(`head meta[property="${ogSiteMeta.property}`); expect(metaElement.getAttribute('content')).to.be.equal(ogSiteMeta.content); }); it('should have custom config <meta> tag with og:url property in the <head>', function() { const ogUrlMeta = metaFilter('og:url'); const metaElement = dom.window.document.querySelector(`head meta[property="${ogUrlMeta.property}"]`); expect(metaElement.getAttribute('content')).to.be.equal(`${ogUrlMeta.content}/about/`); }); it('should have our custom config <meta> tag with twitter:site name in the <head>', function() { const twitterSiteMeta = metaFilter('twitter:site'); const metaElement = dom.window.document.querySelector(`head meta[name="${twitterSiteMeta.name}"]`); expect(metaElement.getAttribute('content')).to.be.equal(twitterSiteMeta.content); }); }); describe('favicon', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, './index.html')); }); it('should have our custom config <link> tag with shortcut icon in the <head>', function() { const shortcutIconLink = metaFilter('shortcut icon'); const linkElement = dom.window.document.querySelector(`head link[rel="${shortcutIconLink.rel}"]`); expect(linkElement.getAttribute('href')).to.be.equal(shortcutIconLink.href); }); it('should have our custom config <link> tag with icon in the <head>', function() { const iconLink = metaFilter('icon'); const linkElement = dom.window.document.querySelector(`head link[rel="${iconLink.rel}"]`); expect(linkElement.getAttribute('href')).to.be.equal(iconLink.href); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/src/lifecycles/graph.js<|end_filename|> #!/usr/bin/env node const fs = require('fs'); const fm = require('front-matter'); const path = require('path'); const toc = require('markdown-toc'); module.exports = generateGraph = async (compilation) => { return new Promise(async (resolve, reject) => { try { const { context, config } = compilation; const { pagesDir, userWorkspace } = context; let graph = [{ path: '/', route: '/', data: {} }]; const walkDirectoryForPages = function(directory, pages = []) { fs.readdirSync(directory).forEach((filename) => { const fullPath = path.normalize(`${directory}${path.sep}${filename}`); if (fs.statSync(fullPath).isDirectory()) { pages = walkDirectoryForPages(fullPath, pages); } else { const fileContents = fs.readFileSync(fullPath, 'utf8'); const { attributes } = fm(fileContents); const relativePagePath = fullPath.substring(pagesDir.length - 1, fullPath.length); const relativeWorkspacePath = directory.replace(process.cwd(), '').replace(path.sep, ''); const template = attributes.template || 'page'; const title = attributes.title || compilation.config.title || ''; const id = attributes.label || filename.split(path.sep)[filename.split(path.sep).length - 1].replace('.md', '').replace('.html', ''); const imports = attributes.imports || []; const label = id.split('-') .map((idPart) => { return `${idPart.charAt(0).toUpperCase()}${idPart.substring(1)}`; }).join(' '); let route = relativePagePath .replace('.md', '') .replace('.html', '') .replace(/\\/g, '/'); /* * check if additional nested directories exist to correctly determine route (minus filename) * examples: * - pages/index.{html,md} -> / * - pages/about.{html,md} -> /about/ * - pages/blog/index.{html,md} -> /blog/ * - pages/blog/some-post.{html,md} -> /blog/some-post/ */ if (relativePagePath.lastIndexOf(path.sep) > 0) { // https://github.com/ProjectEvergreen/greenwood/issues/455 route = id === 'index' || route.replace('/index', '') === `/${id}` ? route.replace('index', '') : `${route}/`; } else { route = route === '/index' ? '/' : `${route}/`; } // prune "reserved" attributes that are supported by Greenwood // https://www.greenwoodjs.io/docs/front-matter const customData = attributes; delete customData.label; delete customData.imports; delete customData.title; delete customData.template; /* Menu Query * Custom front matter - Variable Definitions * -------------------------------------------------- * menu: the name of the menu in which this item can be listed and queried * index: the index of this list item within a menu * linkheadings: flag to tell us where to add page's table of contents as menu items * tableOfContents: json object containing page's table of contents(list of headings) */ // set specific menu to place this page customData.menu = customData.menu || ''; // set specific index list priority of this item within a menu customData.index = customData.index || ''; // set flag whether to gather a list of headings on a page as menu items customData.linkheadings = customData.linkheadings || 0; customData.tableOfContents = []; if (customData.linkheadings > 0) { // parse markdown for table of contents and output to json customData.tableOfContents = toc(fileContents).json; customData.tableOfContents.shift(); // parse table of contents for only the pages user wants linked if (customData.tableOfContents.length > 0 && customData.linkheadings > 0) { customData.tableOfContents = customData.tableOfContents .filter((item) => item.lvl === customData.linkheadings); } } /* ---------End Menu Query-------------------- */ /* * Graph Properties (per page) *---------------------- * data: custom page frontmatter * filename: name of the file * id: filename without the extension * label: "pretty" text representation of the filename * imports: per page JS or CSS file imports to be included in HTML output * path: path to the file relative to the workspace * route: URL route for a given page on outputFilePath * template: page template to use as a base for a generated component * title: a default value that can be used for <title></title> */ pages.push({ data: customData || {}, filename, id, label, imports, path: route === '/' || relativePagePath.lastIndexOf(path.sep) === 0 ? `${relativeWorkspacePath}${filename}` : `${relativeWorkspacePath}${path.sep}${filename}`, route, template, title }); } }); return pages; }; if (config.mode === 'spa') { graph = [{ ...graph[0], path: `${userWorkspace}${path.sep}index.html` }]; } else { graph = fs.existsSync(pagesDir) ? walkDirectoryForPages(pagesDir) : graph; } compilation.graph = graph; if (!fs.existsSync(context.scratchDir)) { await fs.promises.mkdir(context.scratchDir); } await fs.promises.writeFile(`${context.scratchDir}/graph.json`, JSON.stringify(compilation.graph)); resolve(compilation); } catch (err) { reject(err); } }); }; <|start_filename|>packages/plugin-graphql/test/cases/query-menu/greenwood.config.js<|end_filename|> const pluginGraphQL = require('../../../src/index'); module.exports = { plugins: [ ...pluginGraphQL() ] }; <|start_filename|>packages/cli/test/cases/build.config.pages-directory/greenwood.config.js<|end_filename|> module.exports = { pagesDirectory: 'docs' }; <|start_filename|>packages/plugin-import-json/test/cases/develop.default/develop.default.spec.js<|end_filename|> /* * Use Case * Run Greenwood develop command with no config. * * User Result * Should start the development server and render a bare bones Greenwood build and return JSON file as ESM. * * User Command * greenwood develop * * User Config * Import JSON Plugin * * User Workspace * src/ * main.json * */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const path = require('path'); const request = require('request'); const Runner = require('gallinago').Runner; const runSmokeTest = require('../../../../../test/smoke-test'); describe('Develop Greenwood With: ', function() { const LABEL = 'Import JSON plugin for using ESM with .json files'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; const hostname = 'http://localhost'; const port = 1984; let runner; before(function() { this.context = { hostname: `${hostname}:${port}` }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath); return new Promise(async (resolve) => { setTimeout(() => { resolve(); }, 5000); await runner.runCommand(cliPath, 'develop'); }); }); runSmokeTest(['serve'], LABEL); describe('Develop command specific ESM .json behaviors', function() { let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get({ url: `http://127.0.0.1:${port}/main.json?type=json` }, (err, res, body) => { if (err) { reject(); } response = res; dom = new JSDOM(body); resolve(); }); }); }); it('should return a 200', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.equal('text/javascript'); done(); }); it('should return an ECMASCript module', function(done) { expect(response.body.replace(/\n/g, '')).to.equal('export default { "status": 200, "message": "got json"}'); done(); }); }); }); after(function() { runner.stopCommand(); runner.teardown([ path.join(outputPath, '.greenwood') ]); }); }); <|start_filename|>packages/cli/test/cases/serve.default/serve.default.spec.js<|end_filename|> /* * Use Case * Run Greenwood serve command with no config. * * User Result * Should start the production server and render a bare bones Greenwood build. * * User Command * greenwood serve * * User Config * None (Greenwood Default) * * User Workspace * Greenwood default (src/) */ const expect = require('chai').expect; const path = require('path'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const request = require('request'); const runSmokeTest = require('../../../../../test/smoke-test'); const Runner = require('gallinago').Runner; describe('Serve Greenwood With: ', function() { const LABEL = 'Default Greenwood Configuration and Workspace'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; const hostname = 'http://127.0.0.1:8080'; let runner; before(function() { this.context = { hostname }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); return new Promise(async (resolve) => { setTimeout(() => { resolve(); }, 10000); await runner.runCommand(cliPath, 'serve'); }); }); runSmokeTest(['serve'], LABEL); // proxies to analogstudios.net/api/events vis greenwood.config.js // ideally should find something else to avoid using something "live" in our tests describe('Serve command with dev proxy', function() { let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get(`${hostname}/api/albums?artistId=2`, (err, res, body) => { if (err) { reject(); } response = res; response.body = JSON.parse(body); resolve(); }); }); }); it('should return a 200 status', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.contain('application/json'); done(); }); it('should return the correct response body', function(done) { expect(response.body).to.have.lengthOf(1); done(); }); }); describe('Develop command with image (png) specific behavior', function() { const ext = 'png'; let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get(`${hostname}/assets/logo.${ext}`, (err, res, body) => { if (err) { reject(); } response = res; response.body = body; resolve(); }); }); }); it('should return a 200 status', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.equal(`image/${ext}`); done(); }); it('should return binary data', function(done) { expect(response.body).to.contain('PNG'); done(); }); }); describe('Develop command with image (ico) specific behavior', function() { let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get(`${hostname}/assets/favicon.ico`, (err, res, body) => { if (err) { reject(); } response = res; response.body = body; resolve(response); }); }); }); it('should return a 200 status', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.equal('image/x-icon'); done(); }); it('should return binary data', function(done) { expect(response.body).to.contain('\u0000'); done(); }); }); describe('Develop command with SVG specific behavior', function() { const ext = 'svg'; let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get(`${hostname}/assets/webcomponents.${ext}`, (err, res, body) => { if (err) { reject(); } response = res; response.body = body; resolve(); }); }); }); it('should return a 200 status', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.equal(`image/${ext}+xml`); done(); }); it('should return the correct response body', function(done) { expect(response.body.indexOf('<svg')).to.equal(0); done(); }); }); describe('Develop command with font specific (.woff) behavior', function() { const ext = 'woff'; let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get(`${hostname}/assets/source-sans-pro.woff?v=1`, (err, res, body) => { if (err) { reject(); } response = res; response.body = body; resolve(); }); }); }); it('should return a 200 status', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.equal(ext); done(); }); it('should return the correct response body', function(done) { expect(response.body).to.contain('wOFF'); done(); }); }); describe('Develop command with JSON specific behavior', function() { let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get(`${hostname}/assets/data.json`, (err, res, body) => { if (err) { reject(); } response = res; response.body = JSON.parse(body); resolve(); }); }); }); it('should return a 200 status', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.contain('application/json'); done(); }); it('should return the correct response body', function(done) { expect(response.body.name).to.equal('Marvin'); done(); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); runner.stopCommand(); }); }); <|start_filename|>packages/cli/test/cases/build.plugins.resource/greenwood.config.js<|end_filename|> const fs = require('fs'); const { ResourceInterface } = require('../../../src/lib/resource-interface'); class FooResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['.foo']; this.contentType = 'text/javascript'; } async serve(url) { return new Promise(async (resolve, reject) => { try { let body = await fs.promises.readFile(url, 'utf-8'); body = body.replace(/interface (.*){(.*)}/s, ''); resolve({ body, contentType: this.contentType }); } catch (e) { reject(e); } }); } } module.exports = { plugins: [{ type: 'resource', name: 'plugin-foo', provider: (compilation, options) => new FooResource(compilation, options) }] }; <|start_filename|>packages/cli/test/cases/build.default.workspace-template-page-bare-merging/build.default.workspace-template-page-bare-merging.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with no config and emplty page templates. * * User Result * Should generate a bare bones Greenwood build. * * User Command * greenwood build * * User Config * None (Greenwood Default) * * User Workspace * src/ * pages/ * index.md * templates/ * page.html */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Default Greenwood Configuration and Workspace for Quick Start'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Default output for index.html', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, './index.html')); }); describe('head section tags', function() { let metaTags; before(function() { metaTags = dom.window.document.querySelectorAll('head > meta'); }); it('should have a <title> tag in the <head>', function() { const title = dom.window.document.querySelector('head title').textContent; expect(title).to.be.equal('My App'); }); it('should have five default <meta> tags in the <head>', function() { expect(metaTags.length).to.be.equal(5); }); it('should have default mobile-web-app-capable <meta> tag', function() { const mwacMeta = metaTags[2]; expect(mwacMeta.getAttribute('name')).to.be.equal('mobile-web-app-capable'); expect(mwacMeta.getAttribute('content')).to.be.equal('yes'); }); it('should have default apple-mobile-web-app-capable <meta> tag', function() { const amwacMeta = metaTags[3]; expect(amwacMeta.getAttribute('name')).to.be.equal('apple-mobile-web-app-capable'); expect(amwacMeta.getAttribute('content')).to.be.equal('yes'); }); it('should have default apple-mobile-web-app-status-bar-style <meta> tag', function() { const amwasbsMeta = metaTags[4]; expect(amwasbsMeta.getAttribute('name')).to.be.equal('apple-mobile-web-app-status-bar-style'); expect(amwasbsMeta.getAttribute('content')).to.be.equal('black'); }); }); describe('expected content output in <body> tag', function() { it('should have expected h2 tag in the <body>', function() { const h1 = dom.window.document.querySelectorAll('body h1'); expect(h1.length).to.be.equal(1); expect(h1[0].textContent).to.be.equal('Page Template Heading'); }); it('should have expected h2 tag in the <body>', function() { const h2 = dom.window.document.querySelectorAll('body h2'); expect(h2.length).to.be.equal(1); expect(h2[0].textContent).to.be.equal('Quick Start'); }); it('should have expected content output tag in the <body>', function() { const p = dom.window.document.querySelectorAll('body p'); expect(p.length).to.be.equal(1); expect(p[0].textContent).to.be.equal('This is a test.'); }); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-polyfills/test/cases/default/default.spec.js<|end_filename|> /* * Use Case * Run Greenwood with Polyfills composite plugin with default options. * * Uaer Result * Should generate a bare bones Greenwood build with polyfills injected into index.html. * * User Command * greenwood build * * User Config * const polyfillsPlugin = require('@greenwod/plugin-polyfills'); * * { * plugins: [{ * ...polyfillsPlugin() * }] * * } * * User Workspace * Greenwood default (src/) */ const expect = require('chai').expect; const fs = require('fs'); const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; const expectedPolyfillFiles = [ 'webcomponents-loader.js', 'webcomponents-ce.js', 'webcomponents-ce.js.map', 'webcomponents-sd-ce-pf.js', 'webcomponents-sd-ce-pf.js.map', 'webcomponents-sd-ce.js', 'webcomponents-sd-ce.js.map', 'webcomponents-sd.js', 'webcomponents-sd.js.map' ]; describe('Build Greenwood With: ', function() { const LABEL = 'Polyfill Plugin with default options and Default Workspace'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, [...getSetupFiles(outputPath), ...expectedPolyfillFiles.map((file) => { const dir = file === 'webcomponents-loader.js' ? 'node_modules/@webcomponents/webcomponentsjs' : 'node_modules/@webcomponents/webcomponentsjs/bundles'; return { source: `${process.cwd()}/${dir}/${file}`, destination: `${outputPath}/${dir}/${file}` }; })]); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Script tag in the <head> tag', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have one <script> tag for polyfills loaded in the <head> tag', function() { const scriptTags = dom.window.document.querySelectorAll('head > script'); const polyfillScriptTags = Array.prototype.slice.call(scriptTags).filter(script => { // hyphen is used to make sure no other bundles get loaded by accident (#9) return script.src.indexOf('/webcomponents-') >= 0; }); expect(polyfillScriptTags.length).to.be.equal(1); }); it('should have the expected polyfill files in the output directory', function() { expectedPolyfillFiles.forEach((file) => { const dir = file === 'webcomponents-loader.js' ? '' : 'bundles/'; expect(fs.existsSync(path.join(this.context.publicDir, `${dir}${file}`))).to.be.equal(true); }); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-typescript/test/cases/default/default.spec.js<|end_filename|> /* * Use Case * Run Greenwood with TypeScript processing. * * User Result * Should generate a bare bones Greenwood build with the user's JavaScript files processed based on the pluygins default config. * * User Command * greenwood build * * User Config * const pluginTypeScript = require('@greenwod/plugin-typescript); * * { * plugins: [ * ...pluginTypeScript() * ] * } * * User Workspace * src/ * pages/ * index.html * scripts/ * main.ts * * Default Config * { * "compilerOptions": { * "target": "es2020", * "module": "es2020", * "moduleResolution": "node", * "sourceMap": true * } * } * */ const fs = require('fs'); const glob = require('glob-promise'); const path = require('path'); const expect = require('chai').expect; const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Default TypeScript configuration'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('TypeScript should process JavaScript that uses an interface', function() { it('should output correctly processed JavaScript without the interface', function() { // Rollup is giving different [hash] filenames for us in Windows vs Linux / macOS so cant do a to.equal here :/ // https://github.com/ProjectEvergreen/greenwood/pull/650#issuecomment-877614947 const expectedJavaScript = 'const o="Angela",l="Davis",s="Professor";console.log(`Hello ${s} ${o} ${l}!`);//# sourceMappingURL=main.ts.'; const jsFiles = glob.sync(path.join(this.context.publicDir, '*.js')); const javascript = fs.readFileSync(jsFiles[0], 'utf-8'); expect(jsFiles.length).to.equal(1); expect(javascript.replace(/\n/g, '')).to.contain(expectedJavaScript); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-postcss/test/cases/options.extend-config/options.extend-config.spec.js<|end_filename|> /* * Use Case * Run Greenwood with a custom PostCSS config * * User Result * Should generate a bare bones Greenwood build with the user's CSS file correctly un-nested and minified * * User Command * greenwood build * * User Config * const pluginPostCss = require('@greenwod/plugin-postcss'); * * { * plugins: [ * pluginPostCss() * ] * } * * User Workspace * src/ * pages/ * index.html * styles/ * main.css * * User postcss.config.js * module.exports = { * plugins: [ * require('postcss-nested') * ] * }; */ const fs = require('fs'); const glob = require('glob-promise'); const path = require('path'); const expect = require('chai').expect; const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Custom PostCSS configuration'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Page referencing external nested CSS file', function() { it('should output correctly processed nested CSS as non nested', function() { const expectedCss = 'body{color:red}body h1{color:#00f}'; const cssFiles = glob.sync(path.join(this.context.publicDir, 'styles', '*.css')); const css = fs.readFileSync(cssFiles[0], 'utf-8'); expect(cssFiles.length).to.equal(1); expect(css).to.equal(expectedCss); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/src/commands/eject.js<|end_filename|> const fs = require('fs'); const generateCompilation = require('../lifecycles/compile'); const path = require('path'); module.exports = ejectConfiguration = async () => { return new Promise(async (resolve, reject) => { try { const compilation = await generateCompilation(); const configFilePaths = fs.readdirSync(path.join(__dirname, '../config')); configFilePaths.forEach((configFile) => { const from = path.join(__dirname, '../config', configFile); const to = `${compilation.context.projectDirectory}/${configFile}`; fs.copyFileSync(from, to); console.log(`Ejected ${configFile} successfully.`); }); console.debug('all configuration files ejected.'); resolve(); } catch (err) { reject(err); } }); }; <|start_filename|>packages/cli/test/cases/build.config.error-templates-directory/build.config.error-templates-directory.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with a bad value for templatesDirectory in a custom config. * * User Result * Should throw an error. * * User Command * greenwood build * * User Config * { * templatesDirectory: {} * } * * User Workspace * Greenwood default */ const expect = require('chai').expect; const path = require('path'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe('Custom Configuration with a bad value for templatesDirectory', function() { it('should throw an error that templatesDirectory must be a string', async function() { try { await runner.setup(outputPath); await runner.runCommand(cliPath, 'build'); } catch (err) { expect(err).to.contain('Error: provided templatesDirectory "[object Object]" is not supported. Please make sure to pass something like \'layouts/\''); } }); }); }); <|start_filename|>packages/plugin-babel/src/babel.config.js<|end_filename|> module.exports = { // https://github.com/zloirock/core-js/blob/master/docs/2019-03-19-core-js-3-babel-and-a-look-into-the-future.md#babelpreset-env presets: [ [ // https://babeljs.io/docs/en/babel-preset-env '@babel/preset-env', { // https://babeljs.io/docs/en/babel-preset-env#usebuiltins useBuiltIns: 'entry', // https://babeljs.io/docs/en/babel-preset-env#modules // preserves ES Modules modules: false, // https://babeljs.io/docs/en/babel-preset-env#corejs corejs: { version: 3, proposals: true }, // https://babeljs.io/docs/en/babel-preset-env#configpath configPath: __dirname } ] ], // https://github.com/babel/babel/issues/8829#issuecomment-456524916 plugins: [ [ // https://babeljs.io/docs/en/babel-plugin-transform-runtime '@babel/plugin-transform-runtime', { regenerator: true, useESModules: true } ] ] }; <|start_filename|>packages/cli/test/cases/build.config.error-mode/greenwood.config.js<|end_filename|> module.exports = { mode: 'loremipsum' }; <|start_filename|>packages/cli/test/cases/build.default.markdown/build.default.markdown.spec.js<|end_filename|> /* * Use Case * Run Greenwood with custom markdown preset in greenwood config. * * User Result * Should generate a bare bones Greenwood build. (same as build.default.spec.js) with custom markdown and rehype links * * User Command * greenwood build * * User Config * { * title: 'a title to test correct title merging' * } * * User Workspace * Greenwood default */ const { JSDOM } = require('jsdom'); const path = require('path'); const expect = require('chai').expect; const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Markdown'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Markdown Rendering', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have custom <title> tag in the <head>', function() { const title = dom.window.document.querySelectorAll('head > title'); expect(title.length).to.be.equal(1); expect(title[0].textContent).to.be.equal('this is the title from the config - this is a custom markdown title'); }); it('should correctly rendering an <h3> tag', function() { const heading = dom.window.document.querySelectorAll('body h3'); expect(heading.length).to.equal(1); expect(heading[0].textContent).to.equal('Greenwood Markdown Test'); }); it('should correctly render a <p> tag', function() { const paragraph = dom.window.document.querySelectorAll('body p'); expect(paragraph.length).to.equal(1); expect(paragraph[0].textContent).to.be.equal('This is some markdown being rendered by Greenwood.'); }); it('should correctly render markdown with a <code> tag', function() { const code = dom.window.document.querySelectorAll('body pre code'); expect(code.length).to.equal(1); expect(code[0].textContent).to.contain('console.log(\'hello world\');'); }); it('should correctly render markdown with an HTML <img> tag in it', function() { const images = dom.window.document.querySelectorAll('body img'); const myImage = images[0]; expect(images.length).to.equal(1); expect(myImage.src).to.contain('my-image.png'); expect(myImage.alt).to.equal('just passing by'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.markdown-custom.settings/greenwood.config.js<|end_filename|> module.exports = { markdown: { settings: { gfm: false } } }; <|start_filename|>packages/plugin-babel/test/cases/default/default.spec.js<|end_filename|> /* * Use Case * Run Greenwood with Babel processing. * * User Result * Should generate a bare bones Greenwood build with the user's JavaScript files processed based on the default plugin babel.config.js. * * User Command * greenwood build * * User Config * const pluginBabel = require('@greenwod/plugin-babel'); * * { * plugins: [ * ...pluginBabel() * ] * } * * User Workspace * src/ * pages/ * index.html * scripts/ * main.js * */ const fs = require('fs'); const glob = require('glob-promise'); const path = require('path'); const expect = require('chai').expect; const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Default Babel configuration'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Babel should process JavaScript that reference private class members / methods', function() { it('should output correctly processed JavaScript without private members', function() { const expectedJavaScript = '#x'; const jsFiles = glob.sync(path.join(this.context.publicDir, '*.js')); const javascript = fs.readFileSync(jsFiles[0], 'utf-8'); expect(jsFiles.length).to.equal(1); expect(javascript).to.not.contain(expectedJavaScript); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-import-json/test/cases/default/default.spec.js<|end_filename|> /* * Use Case * Run Greenwood with pluginImportCss plugin with default options. * * Uaer Result * Should generate a bare bones Greenwood build without erroring when using ESM (import) with CSS. * * User Command * greenwood build * * User Config * const pluginImportCss = require('@greenwod/plugin-import-css'); * * { * plugins: [{ * ...pluginImportCss() * }] * } * * User Workspace * src/ * assets/ * data.json * pages/ * index.html * scripts/ * main.js */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Import JSON Plugin with default options'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('importing JSON using ESM (import)', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have the expected output from importing data.json in main.js', async function() { const scriptTagOneOutput = dom.window.document.querySelector('body > .output-json-import'); expect(scriptTagOneOutput.textContent).to.be.equal('got json via import, status is - 200'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-import-css/test/cases/default/default.spec.js<|end_filename|> /* * Use Case * Run Greenwood with pluginImportCss plugin with default options. * * Uaer Result * Should generate a bare bones Greenwood build without erroring when using ESM (import) with CSS. * * User Command * greenwood build * * User Config * const pluginImportCss = require('@greenwod/plugin-import-css'); * * { * plugins: [{ * ...pluginImportCss() * }] * } * * User Workspace * src/ * main.js * styles.css * pages/ * index.html */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Import Css Plugin with default options'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('importing CSS using ESM (import)', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have the expected output from main.js (lodash) in the page output', async function() { const spanTags = dom.window.document.querySelectorAll('body > span'); expect(spanTags.length).to.be.equal(1); expect(spanTags[0].textContent).to.be.equal('import from styles.css: p { color: red; }'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.title/build.config.title.spec.js<|end_filename|> /* * Use Case * Run Greenwood with string title in config and default workspace. * * User Result * Should generate a bare bones Greenwood build. (same as build.default.spec.js) with custom title in header * * User Command * greenwood build * * User Config * { * title: 'My Custom Greenwood App' * } * * User Workspace * Greenwood default * src/ * pages/ * index.md * hello.md */ const fs = require('fs'); const { JSDOM } = require('jsdom'); const path = require('path'); const expect = require('chai').expect; const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; const configTitle = require('./greenwood.config').title; describe('Build Greenwood With: ', function() { const LABEL = 'Custom Title Configuration and Default Workspace'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Custom Title from Configuration', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, './index.html')); }); it('should have our custom config <title> tag in the <head>', function() { const title = dom.window.document.querySelector('head title').textContent; expect(title).to.be.equal(configTitle); }); }); describe('Custom Front-Matter Title', function() { const pageTitle = 'About Page'; let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'about', './index.html')); }); it('should output an index.html file within the about page directory', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'about', './index.html'))).to.be.true; }); it('should have a overridden meta <title> tag in the <head> using markdown front-matter', function() { const title = dom.window.document.querySelector('head title').textContent; expect(title).to.be.equal(`${configTitle} - ${pageTitle}`); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.prerender/greenwood.config.js<|end_filename|> module.exports = { prerender: false }; <|start_filename|>packages/plugin-import-commonjs/test/cases/default/greenwood.config.js<|end_filename|> const pluginImportCommonJs = require('../../../src/index'); module.exports = { plugins: [ ...pluginImportCommonJs() ] }; <|start_filename|>packages/plugin-graphql/src/core/cache.js<|end_filename|> const { ApolloClient, InMemoryCache, HttpLink } = require('@apollo/client/core'); const fetch = require('node-fetch'); const fs = require('fs'); const { gql } = require('apollo-server'); const { getQueryHash } = require('./common.server'); /* Extract cache server-side */ module.exports = async (req, context) => { return new Promise(async(resolve, reject) => { try { const client = await new ApolloClient({ link: new HttpLink({ uri: 'http://localhost:4000?q=internal', /* internal flag to prevent looping cache on request */ fetch }), cache: new InMemoryCache() }); /* Take the same query from request, and repeat the query for our server side cache */ const { query, variables } = req.body; const { data } = await client.query({ query: gql`${query}`, variables }); if (data) { const { outputDir } = context; const cache = JSON.stringify(data); const queryHash = getQueryHash(query, variables); const hashFilename = `${queryHash}-cache.json`; const cachePath = `${outputDir}/${hashFilename}`; if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir); } if (!fs.existsSync(cachePath)) { fs.writeFileSync(cachePath, cache, 'utf8'); } } resolve(); } catch (err) { console.error('create cache error', err); reject(err); } }); }; <|start_filename|>packages/plugin-graphql/test/cases/query-menu/query-menu.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with GraphQL calls to get data about the projects graph using MenuQuery, simluting * a site navigation based on top level page routes. Also uses LitElement. * * User Result * Should generate a Greenwood build that dynamically serializes data from the graph from the header. * * User Command * greenwood build * * Default Config (+ plugin-graphql) * * Custom Workspace * src/ * components/ * header.js * pages/ * about.md * contact.md * index.md * templates/ * page.html */ const expect = require('chai').expect; const glob = require('glob-promise'); const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getDependencyFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', async function() { const LABEL = 'MenuQuery from GraphQL'; const apolloStateRegex = /window.__APOLLO_STATE__ = true/; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { const greenwoodGraphqlCoreLibs = await getDependencyFiles( `${process.cwd()}/packages/plugin-graphql/src/core/*.js`, `${outputPath}/node_modules/@greenwood/plugin-graphql/src/core/` ); const greenwoodGraphqlQueryLibs = await getDependencyFiles( `${process.cwd()}/packages/plugin-graphql/src/queries/*.gql`, `${outputPath}/node_modules/@greenwood/plugin-graphql/src/queries/` ); const lit = await getDependencyFiles( `${process.cwd()}/node_modules/lit/*.js`, `${outputPath}/node_modules/lit/` ); const litDecorators = await getDependencyFiles( `${process.cwd()}/node_modules/lit/decorators/*.js`, `${outputPath}/node_modules/lit/decorators/` ); const litDirectives = await getDependencyFiles( `${process.cwd()}/node_modules/lit/directives/*.js`, `${outputPath}/node_modules/lit/directives/` ); const litPackageJson = await getDependencyFiles( `${process.cwd()}/node_modules/lit/package.json`, `${outputPath}/node_modules/lit/` ); const litElement = await getDependencyFiles( `${process.cwd()}/node_modules/lit-element/*.js`, `${outputPath}/node_modules/lit-element/` ); const litElementPackageJson = await getDependencyFiles( `${process.cwd()}/node_modules/lit-element/package.json`, `${outputPath}/node_modules/lit-element/` ); const litElementDecorators = await getDependencyFiles( `${process.cwd()}/node_modules/lit-element/decorators/*.js`, `${outputPath}/node_modules/lit-element/decorators/` ); const litHtml = await getDependencyFiles( `${process.cwd()}/node_modules/lit-html/*.js`, `${outputPath}/node_modules/lit-html/` ); const litHtmlPackageJson = await getDependencyFiles( `${process.cwd()}/node_modules/lit-html/package.json`, `${outputPath}/node_modules/lit-html/` ); const litHtmlDirectives = await getDependencyFiles( `${process.cwd()}/node_modules/lit-html/directives/*.js`, `${outputPath}/node_modules/lit-html/directives/` ); // lit-html has a dependency on this // https://github.com/lit/lit/blob/main/packages/lit-html/package.json#L82 const trustedTypes = await getDependencyFiles( `${process.cwd()}/node_modules/@types/trusted-types/package.json`, `${outputPath}/node_modules/@types/trusted-types/` ); const litReactiveElement = await getDependencyFiles( `${process.cwd()}/node_modules/@lit/reactive-element/*.js`, `${outputPath}/node_modules/@lit/reactive-element/` ); const litReactiveElementDecorators = await getDependencyFiles( `${process.cwd()}/node_modules/@lit/reactive-element/decorators/*.js`, `${outputPath}/node_modules/@lit/reactive-element/decorators/` ); const litReactiveElementPackageJson = await getDependencyFiles( `${process.cwd()}/node_modules/@lit/reactive-element/package.json`, `${outputPath}/node_modules/@lit/reactive-element/` ); await runner.setup(outputPath, [ ...getSetupFiles(outputPath), ...greenwoodGraphqlCoreLibs, ...greenwoodGraphqlQueryLibs, ...lit, ...litPackageJson, ...litDirectives, ...litDecorators, ...litElementPackageJson, ...litElement, ...litElementDecorators, ...litHtmlPackageJson, ...litHtml, ...litHtmlDirectives, ...trustedTypes, ...litReactiveElement, ...litReactiveElementDecorators, ...litReactiveElementPackageJson ]); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Home Page navigation w/ MenuQuery', function() { before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have one window.__APOLLO_STATE__ <script> with (approximated) expected state', function() { const scriptTags = dom.window.document.querySelectorAll('script'); const apolloScriptTags = Array.prototype.slice.call(scriptTags).filter(script => { return script.getAttribute('data-state') === 'apollo'; }); const innerHTML = apolloScriptTags[0].innerHTML; expect(apolloScriptTags.length).to.equal(1); expect(innerHTML).to.match(apolloStateRegex); }); it('should output a single (partial) *-cache.json file, one per each query made', async function() { expect(await glob.promise(path.join(this.context.publicDir, './*-cache.json'))).to.have.lengthOf(1); }); it('should output a (partial) *-cache.json files, one per each query made, that are all defined', async function() { const cacheFiles = await glob.promise(path.join(this.context.publicDir, './*-cache.json')); cacheFiles.forEach(file => { const cache = require(file); expect(cache).to.not.be.undefined; }); }); it('should have a <header> in the <body>', function() { const headers = dom.window.document.querySelectorAll('body header'); expect(headers.length).to.be.equal(1); }); it('should have a expected navigation output in the <header> based on pages with menu: navigation frontmatter', function() { const listItems = dom.window.document.querySelectorAll('body header ul li'); const link1 = listItems[0].querySelector('a'); const link2 = listItems[1].querySelector('a'); expect(listItems.length).to.be.equal(2); expect(link1.href.replace('file://', '').replace(/\/[A-Z]:/, '')).to.be.equal('/about/'); expect(link1.title).to.be.equal('Click to visit the About page'); expect(link1.innerHTML).to.contain('About'); expect(link2.href.replace('file://', '').replace(/\/[A-Z]:/, '')).to.be.equal('/contact/'); expect(link2.title).to.be.equal('Click to visit the Contact page'); expect(link2.innerHTML).to.contain('Contact'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-babel/src/index.js<|end_filename|> /* * * Enable using Babel for processing JavaScript files. * */ const babel = require('@babel/core'); const fs = require('fs'); const path = require('path'); const { ResourceInterface } = require('@greenwood/cli/src/lib/resource-interface'); const rollupBabelPlugin = require('@rollup/plugin-babel').default; function getConfig (compilation, extendConfig = false) { const { projectDirectory } = compilation.context; const configFile = 'babel.config'; const defaultConfig = require(path.join(__dirname, configFile)); const userConfig = fs.existsSync(path.join(projectDirectory, `${configFile}.js`)) ? require(`${projectDirectory}/${configFile}`) : {}; let finalConfig = Object.assign({}, userConfig); if (extendConfig) { finalConfig.presets = Array.isArray(userConfig.presets) ? [...defaultConfig.presets, ...userConfig.presets] : [...defaultConfig.presets]; finalConfig.plugins = Array.isArray(userConfig.plugins) ? [...defaultConfig.plugins, ...userConfig.plugins] : [...defaultConfig.plugins]; } return finalConfig; } class BabelResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['.js']; this.contentType = ['text/javascript']; } async shouldIntercept(url) { return Promise.resolve(path.extname(url) === this.extensions[0] && url.indexOf('node_modules/') < 0); } async intercept(url, body) { return new Promise(async(resolve, reject) => { try { const config = getConfig(this.compilation, this.options.extendConfig); const result = await babel.transform(body, config); resolve({ body: result.code }); } catch (e) { reject(e); } }); } } module.exports = (options = {}) => { return [{ type: 'resource', name: 'plugin-babel:resource', provider: (compilation) => new BabelResource(compilation, options) }, { type: 'rollup', name: 'plugin-babel:rollup', provider: (compilation) => [ rollupBabelPlugin({ // https://github.com/rollup/plugins/tree/master/packages/babel#babelhelpers babelHelpers: options.extendConfig ? 'runtime' : 'bundled', ...getConfig(compilation, options.extendConfig) }) ] }]; }; <|start_filename|>www/components/banner/banner.js<|end_filename|> import { css, html, LitElement, unsafeCSS } from 'lit'; import bannerCss from './banner.css?type=css'; import buttonCss from './button.css?type=css'; import './eve-button.js'; import '@evergreen-wc/eve-container'; class Banner extends LitElement { constructor() { super(); this.currentProjectIndex = 0; this.animateState = 'on'; this.projectTypes = [ 'blog', 'portfolio', 'website', 'web app', 'marketing site', 'small business' ]; } static get styles() { return css` ${unsafeCSS(bannerCss)} `; } cycleProjectTypes() { this.currentProjectIndex = this.currentProjectIndex += 1; if (this.currentProjectIndex >= this.projectTypes.length) { this.currentProjectIndex = 0; } } firstUpdated() { setInterval(() => { this.animateState = 'off'; this.update(); setTimeout(() => { this.cycleProjectTypes(); this.animateState = 'on'; this.update(); }, 1000); }, 3000); } render() { const currentProjectType = this.projectTypes[this.currentProjectIndex]; return html` <div class='banner'> <eve-container> <div class='content'> <img src="../../assets/greenwood-logo-300w.png" alt="Greenwood Logo" srcset="../../assets/greenwood-logo-300w.png 1x, ../../assets/greenwood-logo-500w.png 2x, ../../assets/greenwood-logo-750w.png 3x, ../../assets/greenwood-logo-1000w.png 4x, ../../assets/greenwood-logo-1500w.png 5x"/> <h3>The static site generator for your. . . <br /><span class="${this.animateState}">${currentProjectType}.</span></h3> <eve-button size="md" href="/getting-started/" style="${buttonCss}">Get Started</eve-button> </div> </eve-container> </div> `; } } customElements.define('app-banner', Banner); <|start_filename|>packages/cli/src/index.js<|end_filename|> #!/usr/bin/env node /* eslint-disable no-underscore-dangle */ // https://github.com/ProjectEvergreen/greenwood/issues/141 process.setMaxListeners(0); const program = require('commander'); const runProductionBuild = require('./commands/build'); const runDevServer = require('./commands/develop'); const runProdServer = require('./commands/serve'); const ejectConfiguration = require('./commands/eject'); const greenwoodPackageJson = require('../package.json'); let cmdOption = {}; let command = ''; console.info('-------------------------------------------------------'); console.info(`Welcome to Greenwood (v${greenwoodPackageJson.version}) ♻️`); console.info('-------------------------------------------------------'); program .version(greenwoodPackageJson.version) .arguments('<script-mode>') .usage('<script-mode> [options]'); program .command('build') .description('Build a static site for production.') .action((cmd) => { command = cmd._name; }); program .command('develop') .description('Start a local development server.') .action((cmd) => { command = cmd._name; }); program .command('serve') .description('View a production build locally with a basic web server.') .action((cmd) => { command = cmd._name; }); program .command('eject') .option('-a, --all', 'eject all configurations including babel, postcss, browserslistrc') .description('Eject greenwood configurations.') .action((cmd) => { command = cmd._name; cmdOption.all = cmd.all; }); program.parse(process.argv); if (program.parse.length === 0) { program.help(); } const run = async() => { try { console.info(`Running Greenwood with the ${command} command.`); process.env.__GWD_COMMAND__ = command; switch (command) { case 'build': await runProductionBuild(); break; case 'develop': await runDevServer(); break; case 'serve': process.env.__GWD_COMMAND__ = 'build'; await runProductionBuild(); await runProdServer(); break; case 'eject': await ejectConfiguration(); break; default: console.warn(` Error: not able to detect command. try using the --help flag if you're encountering issues running Greenwood. Visit our docs for more info at https://www.greenwoodjs.io/docs/. `); break; } process.exit(0); // eslint-disable-line no-process-exit } catch (err) { console.error(err); process.exit(1); // eslint-disable-line no-process-exit } }; run(); <|start_filename|>packages/plugin-polyfills/test/cases/lit/lit.spec.js<|end_filename|> /* * Use Case * Run Greenwood with Polyfills composite plugin with default options and using Lit. * * Uaer Result * Should generate a bare bones Greenwood build with polyfills injected into index.html. * * User Command * greenwood build * * User Config * const polyfillsPlugin = require('@greenwod/plugin-polyfills'); * * { * plugins: [ * polyfillsPlugin() * ] * * } * * User Workspace * Greenwood default */ const expect = require('chai').expect; const fs = require('fs'); const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getDependencyFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; const expectedLitPolyfillFiles = [ 'polyfill-support.js' ]; const expectedPolyfillFiles = [ 'webcomponents-loader.js', 'webcomponents-ce.js', 'webcomponents-ce.js.map', 'webcomponents-sd-ce-pf.js', 'webcomponents-sd-ce-pf.js.map', 'webcomponents-sd-ce.js', 'webcomponents-sd-ce.js.map', 'webcomponents-sd.js', 'webcomponents-sd.js.map' ]; describe('Build Greenwood With: ', function() { const LABEL = 'Lit Polyfill Plugin with default options and Default Workspace'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { const lit = await getDependencyFiles( `${process.cwd()}/node_modules/lit/*.js`, `${outputPath}/node_modules/lit/` ); const litDecorators = await getDependencyFiles( `${process.cwd()}/node_modules/lit/decorators/*.js`, `${outputPath}/node_modules/lit/decorators/` ); const litDirectives = await getDependencyFiles( `${process.cwd()}/node_modules/lit/directives/*.js`, `${outputPath}/node_modules/lit/directives/` ); const litPackageJson = await getDependencyFiles( `${process.cwd()}/node_modules/lit/package.json`, `${outputPath}/node_modules/lit/` ); const litElement = await getDependencyFiles( `${process.cwd()}/node_modules/lit-element/*.js`, `${outputPath}/node_modules/lit-element/` ); const litElementPackageJson = await getDependencyFiles( `${process.cwd()}/node_modules/lit-element/package.json`, `${outputPath}/node_modules/lit-element/` ); const litElementDecorators = await getDependencyFiles( `${process.cwd()}/node_modules/lit-element/decorators/*.js`, `${outputPath}/node_modules/lit-element/decorators/` ); const litHtml = await getDependencyFiles( `${process.cwd()}/node_modules/lit-html/*.js`, `${outputPath}/node_modules/lit-html/` ); const litHtmlPackageJson = await getDependencyFiles( `${process.cwd()}/node_modules/lit-html/package.json`, `${outputPath}/node_modules/lit-html/` ); const litHtmlDirectives = await getDependencyFiles( `${process.cwd()}/node_modules/lit-html/directives/*.js`, `${outputPath}/node_modules/lit-html/directives/` ); // lit-html has a dependency on this // https://github.com/lit/lit/blob/main/packages/lit-html/package.json#L82 const trustedTypes = await getDependencyFiles( `${process.cwd()}/node_modules/@types/trusted-types/package.json`, `${outputPath}/node_modules/@types/trusted-types/` ); const litReactiveElement = await getDependencyFiles( `${process.cwd()}/node_modules/@lit/reactive-element/*.js`, `${outputPath}/node_modules/@lit/reactive-element/` ); const litReactiveElementDecorators = await getDependencyFiles( `${process.cwd()}/node_modules/@lit/reactive-element/decorators/*.js`, `${outputPath}/node_modules/@lit/reactive-element/decorators/` ); const litReactiveElementPackageJson = await getDependencyFiles( `${process.cwd()}/node_modules/@lit/reactive-element/package.json`, `${outputPath}/node_modules/@lit/reactive-element/` ); await runner.setup(outputPath, [ ...getSetupFiles(outputPath), ...expectedPolyfillFiles.map((file) => { const dir = file === 'webcomponents-loader.js' ? 'node_modules/@webcomponents/webcomponentsjs' : 'node_modules/@webcomponents/webcomponentsjs/bundles'; return { source: `${process.cwd()}/${dir}/${file}`, destination: `${outputPath}/${dir}/${file}` }; }), ...lit, // includes polyfill-support.js ...litPackageJson, ...litDirectives, ...litDecorators, ...litElementPackageJson, ...litElement, ...litElementDecorators, ...litHtmlPackageJson, ...litHtml, ...litHtmlDirectives, ...trustedTypes, ...litReactiveElement, ...litReactiveElementDecorators, ...litReactiveElementPackageJson ]); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Script tag in the <head> tag', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have one <script> tag for lit polyfills loaded in the <head> tag', function() { const scriptTags = dom.window.document.querySelectorAll('head > script'); const polyfillScriptTags = Array.prototype.slice.call(scriptTags).filter(script => { return script.src.indexOf('polyfill-support') >= 0; }); expect(polyfillScriptTags.length).to.be.equal(1); }); it('should have the expected lit polyfill files in the output directory', function() { expectedLitPolyfillFiles.forEach((file) => { expect(fs.existsSync(path.join(this.context.publicDir, file))).to.be.equal(true); }); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/theme-pack/theme-pack.develop.spec.js<|end_filename|> /* * Use Case * A theme pack _author_ creating a theme pack and using Greenwood for development and testing * following the guide published on the Greenwood website. (https://www.greenwoodjs.io/guides/theme-packs/) * * User Result * Should correctly validate the develop and build / serve commands work correctly using tge expected templates * being resolved correctly per the known work around needs as documented in the FAQ and tracked in a discussion. * https://github.com/ProjectEvergreen/greenwood/discussions/682 * * User Command * greenwood develop * * User Config * Mock Theme Pack Plugin (from fixtures) * * Plugin Author Workspace * src/ * components/ * header.js * layouts/ * blog-post.html * pages/ * index.md * styles/ * theme.css */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const packageJson = require('./package.json'); const path = require('path'); const request = require('request'); const Runner = require('gallinago').Runner; const runSmokeTest = require('../../../../../test/smoke-test'); describe('Develop Greenwood With: ', function() { const LABEL = 'Developement environment for a Theme Pack'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; const hostname = 'http://localhost'; const port = 1984; let runner; before(function() { this.context = { hostname: `${hostname}:${port}` }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath); return new Promise(async (resolve) => { setTimeout(() => { resolve(); }, 5000); await runner.runCommand(cliPath, 'develop'); }); }); runSmokeTest(['serve'], LABEL); describe('Develop command specific HTML behaviors', function() { let response = {}; let dom; before(async function() { return new Promise((resolve, reject) => { request.get({ url: `http://127.0.0.1:${port}`, headers: { accept: 'text/html' } }, (err, res, body) => { if (err) { reject(); } response = res; dom = new JSDOM(body); resolve(); }); }); }); it('should return a 200', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should have expected text from from a mock package layouts/blog-post.html in the users workspace', function(done) { const pageTemplateHeading = dom.window.document.querySelectorAll('body h1')[0]; expect(pageTemplateHeading.textContent).to.be.equal('This is the blog post template called from the layouts directory.'); done(); }); it('should have expected text from user workspace pages/index.md', function(done) { const heading = dom.window.document.querySelectorAll('body h2')[0]; const paragraph = dom.window.document.querySelectorAll('body p')[0]; expect(heading.textContent).to.be.equal('Title of blog post'); expect(paragraph.textContent).to.be.equal('Lorum Ipsum, this is a test.'); done(); }); }); describe('Custom Theme Pack internal logic for resolving theme.css for local development', function() { let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get({ url: `http://127.0.0.1:${port}/node_modules/${packageJson.name}/dist/styles/theme.css` }, (err, res, body) => { if (err) { reject(); } response = res; response.body = body; resolve(); }); }); }); it('should return a 200', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.equal('text/css'); done(); }); it('should correctly return CSS from the developers local files', function(done) { expect(response.body).to.equal(':root {\n --color-primary: #135;\n --color-secondary: #74b238;\n --font-family: \'Optima\', sans-serif;\n}'); done(); }); }); describe('Custom Theme Pack internal logic for resolving header.js for local development', function() { let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get({ url: `http://127.0.0.1:${port}/node_modules/${packageJson.name}/dist/components/header.js` }, (err, res, body) => { if (err) { reject(); } response = res; response.body = body; resolve(); }); }); }); it('should return a 200', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.equal('text/javascript'); done(); }); it('should correctly return JavaScript from the developers local files', function(done) { expect(response.body).to.contain('customElements.define(\'x-header\', HeaderComponent);'); done(); }); }); }); after(function() { runner.stopCommand(); runner.teardown([ path.join(outputPath, '.greenwood') ]); }); }); <|start_filename|>packages/cli/src/lib/browser.js<|end_filename|> /* * Rendertron - Modified * Repo: https://github.com/GoogleChrome/rendertron * License: Apache 2.0 */ /** * Wraps Puppeteer's interface to Headless Chrome to expose high level rendering * APIs that are able to handle web components and PWAs. */ const puppeteer = require('puppeteer'); class BrowserRunner { constructor() { this.browser = {}; this.renderer = {}; } async init() { this.browser = await puppeteer.launch({ args: ['--no-sandbox'] }); } async serialize(requestUrl) { const page = await this.browser.newPage(); let response = null; // Page may reload when setting isMobile // https://github.com/GoogleChrome/puppeteer/blob/v1.10.0/docs/api.md#pagesetviewportviewport page.evaluateOnNewDocument('customElements.forcePolyfill = true'); page.evaluateOnNewDocument('ShadyDOM = {force: true}'); page.evaluateOnNewDocument('ShadyCSS = {shimcssproperties: true}'); await page.setCacheEnabled(false); // https://github.com/ProjectEvergreen/greenwood/pull/699 await page.setRequestInterception(true); // only allow puppeteer to load necessary (local) scripts needed for pre-rendering of the site itself page.on('request', interceptedRequest => { const interceptedRequestUrl = interceptedRequest.url(); if ( interceptedRequestUrl.indexOf('http://127.0.0.1') >= 0 || interceptedRequestUrl.indexOf('localhost') >= 0 ) { interceptedRequest.continue(); } else { // console.warn('aborting request', interceptedRequestUrl); interceptedRequest.abort(); } }); try { // Navigate to page. Wait until there are no oustanding network requests. // https://pptr.dev/#?product=Puppeteer&version=v1.8.0&show=api-pagegotourl-options response = await page.goto(requestUrl, { waitUntil: 'networkidle0', timeout: 0 }); } catch (e) { console.error('browser error', e); } if (!response) { console.error('response does not exist'); // This should only occur when the page is about:blank. See // https://github.com/GoogleChrome/puppeteer/blob/v1.5.0/docs/api.md#pagegotourl-options. return { status: 400, content: '' }; } // Serialize page. const content = await page.content(); // console.debug('content????', content); await page.close(); return content; } close() { this.browser.close(); } } module.exports = BrowserRunner; <|start_filename|>packages/cli/src/lifecycles/compile.js<|end_filename|> const initConfig = require('./config'); const initContext = require('./context'); const generateGraph = require('./graph'); module.exports = generateCompilation = () => { return new Promise(async (resolve, reject) => { try { let compilation = { graph: [], context: {}, config: {} }; console.info('Initializing project config'); compilation.config = await initConfig(); // determine whether to use default template or user detected workspace console.info('Initializing project workspace contexts'); compilation.context = await initContext(compilation); // generate a graph of all pages / components to build console.info('Generating graph of workspace files...'); compilation = await generateGraph(compilation); resolve(compilation); } catch (err) { reject(err); } }); }; <|start_filename|>www/styles/home.css<|end_filename|> h3 { color: green; } .gwd-content { background-color: white; min-height: 300px; font-size: 1.2rem; & h3 { font-size: 2rem; margin: 5px 0; } & a { color: #201e2e; } } /* .cards { margin: 0 -15%; } */ .message { padding: 2rem; text-align: center; margin: 0 auto; & hr { margin-top: 4rem; } @media (max-width: 768px) { padding: 0; } } .quickstart { width: 90%; text-align: center; margin: 4rem auto; & p { max-width: 60ch; margin: auto; margin-top: 2rem; } } .cards { margin: 20px -0.25rem 3rem -0.25rem; display: flex; justify-content: space-around; flex-direction: row; width: 100%; @media (max-width: 1024px) { flex-direction: column; } } #gwd-message-wrapper { background-color: #504b65; & h2 { color: #fff; max-width: 60ch; margin: auto; @media (max-width: 768px) { padding-top: 2rem; } } } .mini-card { width: 200px; margin: 1.5rem; border: 0.5px solid #dddde1; border-radius: 20px; background-color: #fff; display: flex; align-items: center; padding: 2rem; box-shadow: 0 1.3px 2.7px rgba(0, 0, 0, 0.065), 0 3.4px 6.9px rgba(0, 0, 0, 0.093), 0 6.9px 14.2px rgba(0, 0, 0, 0.117), 0 14.2px 29.2px rgba(0, 0, 0, 0.145), 0 39px 80px rgba(0, 0, 0, 0.21); } .min-card-container { display: flex; justify-content: center; flex-wrap: wrap; max-width: 1200px; margin: auto; } app-card { margin: 1.5rem; padding: 2rem; border: 0.5px solid #dddde1; border-radius: 20px; box-shadow: 0 2px 3.6px rgba(0, 0, 0, 0.014), 0 5.6px 10px rgba(0, 0, 0, 0.02), 0 13.6px 24.1px rgba(0, 0, 0, 0.026), 0 45px 80px rgba(0, 0, 0, 0.04); } <|start_filename|>packages/cli/test/cases/build.config.error-prerender/greenwood.config.js<|end_filename|> module.exports = { prerender: {} }; <|start_filename|>packages/cli/test/cases/build.config.meta/greenwood.config.js<|end_filename|> module.exports = { title: 'My Custom Greenwood App', meta: [ { property: 'og:site', content: 'The Greenhouse I/O' }, { property: 'og:url', content: 'https://www.thegreenhouse.io' }, { name: 'twitter:site', content: '@thegreenhouseio' }, { rel: 'shortcut icon', href: '/assets/images/favicon.ico' }, { rel: 'icon', href: '/assets/images/favicon.ico' } ] }; <|start_filename|>packages/plugin-graphql/test/cases/query-custom-schema/query-custom-schema.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with GraphQL calls to get data about the projects graph using its own custom schema and query. * * User Result * Should generate a Greenwood build that tests basic output from the custom query. * * User Command * greenwood build * * Default Config * * Custom Workspace * src/ * data/ * queries/ * gallery.gql * schema/ * gallery.js * pages/ * index.html */ const expect = require('chai').expect; const glob = require('glob-promise'); const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getDependencyFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Custom Query from GraphQL'; const apolloStateRegex = /window.__APOLLO_STATE__ = true/; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { const greenwoodGraphqlCoreLibs = await getDependencyFiles( `${process.cwd()}/packages/plugin-graphql/src/core/*.js`, `${outputPath}/node_modules/@greenwood/plugin-graphql/src/core/` ); await runner.setup(outputPath, [ ...getSetupFiles(outputPath), ...greenwoodGraphqlCoreLibs ]); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Home Page output w/ (custom) GalleryQuery', function() { before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have one window.__APOLLO_STATE__ <script> with (approximated) expected state', function() { const scriptTags = dom.window.document.querySelectorAll('script'); const apolloScriptTags = Array.prototype.slice.call(scriptTags).filter(script => { return script.getAttribute('data-state') === 'apollo'; }); const innerHTML = apolloScriptTags[0].innerHTML; expect(apolloScriptTags.length).to.equal(1); expect(innerHTML).to.match(apolloStateRegex); }); it('should output a single (partial) *-cache.json file, one per each query made', async function() { expect(await glob.promise(path.join(this.context.publicDir, './*-cache.json'))).to.have.lengthOf(1); }); it('should output a (partial) *-cache.json files, one per each query made, that are all defined', async function() { const cacheFiles = await glob.promise(path.join(this.context.publicDir, './*-cache.json')); cacheFiles.forEach(file => { const cache = require(file); expect(cache).to.not.be.undefined; }); }); describe('<img> tag output from query', function() { const title = 'Home Page Logos'; let images; before(function() { images = dom.window.document.querySelectorAll('body img'); }); it('should have three <img> tags in the <body>', function() { expect(images.length).to.be.equal(3); }); it('should have a expected src attribute value for all three <img> tags', function() { images.forEach((image, i) => { const count = i += 1; expect(image.src).to.be.contain(`/assets/logo${count}.png`); }); }); it('should have a expected title attribute value for all three <img> tags', function() { images.forEach((image, i) => { const count = i += 1; expect(image.title).to.be.contain(`${title} - Logo #${count}`); }); }); it('should have a expected title content in the <h2> tag', function() { const h2 = dom.window.document.querySelectorAll('body h2'); expect(h2.length).to.be.equal(1); expect(h2[0].textContent).to.be.equal(title); }); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/src/plugins/copy/plugin-copy-graph-json.js<|end_filename|> const path = require('path'); module.exports = [{ type: 'copy', name: 'plugin-copy-graph-json', provider: (compilation) => { const { context } = compilation; return [{ from: path.join(context.scratchDir, 'graph.json'), to: path.join(context.outputDir, 'graph.json') }]; } }]; <|start_filename|>packages/cli/test/cases/build.default.workspace-top-level-pages/build.default.workspace-top-level-pages.spec.js<|end_filename|> /* * Use Case * Run Greenwood with default config and mixed HTML and markdown top level pages. * * Result * Test for correct page output and layout. * * Command * greenwood build * * User Config * None (Greenwood default) * * User Workspace * src/ * pages/ * about.html * contact.md * index.html */ const expect = require('chai').expect; const fs = require('fs'); const { JSDOM } = require('jsdom'); const path = require('path'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Default Greenwood Configuration and Default Workspace w/ Top Level Pages'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Home (index) Page', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have custom <meta> tag in the <head>', function() { const customMeta = Array.from(dom.window.document.querySelectorAll('head > meta')) .filter(meta => meta.getAttribute('property') === 'og:description'); expect(customMeta.length).to.be.equal(1); expect(customMeta[0].getAttribute('content')).to.be.equal('My custom meta content.'); }); it('should have the correct <title> for the home page', function() { const titleTags = dom.window.document.querySelectorAll('title'); expect(titleTags.length).to.equal(1); expect(titleTags[0].textContent).to.equal('Top Level Test'); }); it('should have the correct content for the home page', function() { const h1Tags = dom.window.document.querySelectorAll('h1'); expect(h1Tags.length).to.equal(1); expect(h1Tags[0].textContent).to.equal('Hello from the home page!!!!'); }); }); describe('About Page', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'about', 'index.html')); }); it('should create a top level about page with a directory and index.html', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'about', 'index.html'))).to.be.true; }); it('should have the correct content for the about page', function() { const h1Tags = dom.window.document.querySelectorAll('h1'); const pTags = dom.window.document.querySelectorAll('p'); expect(h1Tags.length).to.equal(1); expect(h1Tags[0].textContent).to.equal('Hello from about.html'); expect(pTags.length).to.equal(1); expect(pTags[0].textContent).to.equal('Lorum Ipsum'); }); }); describe('Contact Page', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'contact', 'index.html')); }); it('should create a top level contact page with a directory and index.html', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'contact', 'index.html'))).to.be.true; }); it('should have the correct content for the contact page', function() { const h3Tags = dom.window.document.querySelectorAll('h3'); const pTags = dom.window.document.querySelectorAll('p'); expect(h3Tags.length).to.equal(1); expect(h3Tags[0].textContent).to.equal('Contact Page'); expect(pTags.length).to.equal(1); expect(pTags[0].textContent).to.equal('Thanks for contacting us.'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/eject.default/eject.default.spec.js<|end_filename|> /* * Use Case * Run Greenwood eject command to copy core configuration files * * User Result * Should eject configuration files to working directory * * User Command * greenwood eject */ const fs = require('fs'); const path = require('path'); const expect = require('chai').expect; const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Eject Greenwood', function() { const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; let configFiles; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe('Default Eject', function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'eject'); configFiles = fs.readdirSync(__dirname) .filter((file) => path.extname(file) === '.js' && file.indexOf('spec.js') < 0); }); it('should output one config files to users project working directory', function() { expect(configFiles.length).to.equal(1); }); it('should output rollup config file', function() { expect(fs.existsSync(path.join(__dirname, 'rollup.config.js'))).to.be.true; }); after(function() { // remove test files configFiles.forEach(file => { fs.unlinkSync(path.join(__dirname, file)); }); }); }); describe('Eject and Build Ejected Config', function() { before(async function() { await runner.runCommand(cliPath, 'build'); await runner.runCommand(cliPath, 'eject'); }); runSmokeTest(['public', 'index'], 'Eject and Build Ejected Config'); }); after(function() { // remove test files configFiles.forEach(file => { fs.unlinkSync(path.join(__dirname, file)); }); runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-postcss/test/cases/options.extend-config/greenwood.config.js<|end_filename|> const pluginPostCss = require('../../../src/index'); module.exports = { plugins: [ pluginPostCss({ extendConfig: true }) ] }; <|start_filename|>packages/cli/test/cases/build.plugins.resource/build.config.plugins-resource.spec.js<|end_filename|> /* * Use Case * Run Greenwood with a custom resource plugin and default workspace. * * Uaer Result * Should generate a bare bones Greenwood build with expected custom file (.foo) behavior. * * User Command * greenwood build * * User Config * class FooResource extends ResourceInterface { * // see complete implementation in the greenwood.config.js file used for this spec * } * * { * plugins: [{ * type: 'resource', * name: 'plugin-foo', * provider: (compilation, options) => new FooResource(compilation, options) * }] * } * * Custom Workspace * src/ * pages/ * index.html * foo-files/ * my-custom-file.foo * my-other-custom-file.foo */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const path = require('path'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Custom FooResource Plugin and Default Workspace'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); describe('Transpiling and DOM Manipulation', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); }); it('should have expected text executed from my-custom-file.foo in the DOM', function() { const placeholder = dom.window.document.querySelector('body h6'); expect(placeholder.textContent).to.be.equal('hello from my-custom-file.foo'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/src/plugins/resource/plugin-optimization-mpa.js<|end_filename|> /* * * Manages web standard resource related operations for JavaScript. * This is a Greenwood default plugin. * */ const fs = require('fs'); const path = require('path'); const { ResourceInterface } = require('../../lib/resource-interface'); class OptimizationMPAResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['.html']; this.contentType = 'text/html'; this.libPath = '@greenwood/router/router.js'; } async shouldResolve(url) { return Promise.resolve(url.indexOf(this.libPath) >= 0); } async resolve() { return new Promise(async (resolve, reject) => { try { const routerUrl = path.join(__dirname, '../../', 'lib/router.js'); resolve(routerUrl); } catch (e) { reject(e); } }); } async shouldOptimize(url) { return Promise.resolve(path.extname(url) === '.html' && this.compilation.config.mode === 'mpa'); } async optimize(url, body) { return new Promise(async (resolve, reject) => { try { let currentTemplate; const { projectDirectory, scratchDir, outputDir } = this.compilation.context; const bodyContents = body.match(/<body>(.*)<\/body>/s)[0].replace('<body>', '').replace('</body>', ''); const outputBundlePath = path.normalize(`${outputDir}/_routes${url.replace(projectDirectory, '')}`) .replace(`.greenwood${path.sep}`, ''); const routeTags = this.compilation.graph.map((page) => { const template = path.extname(page.filename) === '.html' ? page.route : page.template; const key = page.route === '/' ? '' : page.route.slice(0, page.route.lastIndexOf('/')); if (url.replace(scratchDir, '') === `${page.route}index.html`) { currentTemplate = template; } return ` <greenwood-route data-route="${page.route}" data-template="${template}" data-key="/_routes${key}/index.html"></greenwood-route> `; }); if (!fs.existsSync(path.dirname(outputBundlePath))) { fs.mkdirSync(path.dirname(outputBundlePath), { recursive: true }); } await fs.promises.writeFile(outputBundlePath, bodyContents); body = body.replace('</head>', ` <script type="module" src="/node_modules/@greenwood/cli/src/lib/router.js"></script>\n <script> window.__greenwood = window.__greenwood || {}; window.__greenwood.currentTemplate = "${currentTemplate}"; </script> </head> `).replace(/<body>(.*)<\/body>/s, ` <body>\n <router-outlet> ${bodyContents.replace(/\$/g, '$$$')}\n </router-outlet> ${routeTags.join('\n')} </body> `); resolve(body); } catch (e) { reject(e); } }); } } module.exports = { type: 'resource', name: 'plugin-optimization-mpa', provider: (compilation, options) => new OptimizationMPAResource(compilation, options) }; <|start_filename|>packages/plugin-graphql/test/cases/query-custom-schema/src/data/schema/gallery.js<|end_filename|> const gql = require('graphql-tag'); const getGallery = async (root, query) => { if (query.name === 'logos') { return [{ name: 'logos', title: 'Home Page Logos', images: [{ path: '/assets/logo1.png' }, { path: '/assets/logo2.png' }, { path: '/assets/logo3.png' }] }]; } }; const galleryTypeDefs = gql` type Image { path: String } type Gallery { name: String, title: String, images: [Image] } extend type Query { gallery(name: String!): [Gallery] } `; const galleryResolvers = { Query: { gallery: getGallery } }; module.exports = { customTypeDefs: galleryTypeDefs, customResolvers: galleryResolvers }; <|start_filename|>packages/cli/src/lifecycles/copy.js<|end_filename|> const fs = require('fs'); const path = require('path'); async function rreaddir (dir, allFiles = []) { const files = (await fs.promises.readdir(dir)).map(f => path.join(dir, f)); allFiles.push(...files); await Promise.all(files.map(async f => ( await fs.promises.stat(f)).isDirectory() && rreaddir(f, allFiles ))); return allFiles; } // https://stackoverflow.com/a/30405105/417806 async function copyFile(source, target) { try { console.info(`copying file... ${source.replace(`${process.cwd()}/`, '')}`); const rd = fs.createReadStream(source); const wr = fs.createWriteStream(target); return await new Promise((resolve, reject) => { rd.on('error', reject); wr.on('error', reject); wr.on('finish', resolve); rd.pipe(wr); }); } catch (error) { console.error('ERROR', error); rd.destroy(); wr.end(); } } async function copyDirectory(from, to) { return new Promise(async(resolve, reject) => { try { console.info(`copying directory... ${from.replace(`${process.cwd()}/`, '')}`); const files = await rreaddir(from); if (files.length > 0) { if (!fs.existsSync(to)) { fs.mkdirSync(to); } await Promise.all(files.filter((asset) => { const target = asset.replace(from, to); const isDirectory = path.extname(target) === ''; if (isDirectory && !fs.existsSync(target)) { fs.mkdirSync(target); } else if (!isDirectory) { return asset; } }).map((asset) => { const target = asset.replace(from, to); return copyFile(asset, target); })); } resolve(); } catch (e) { reject(e); } }); } module.exports = copyAssets = (compilation) => { return new Promise(async (resolve, reject) => { try { const copyPlugins = compilation.config.plugins.filter(plugin => plugin.type === 'copy'); for (plugin of copyPlugins) { const locations = plugin.provider(compilation); for (location of locations) { const { from, to } = location; if (path.extname(from) === '') { // copy directory await copyDirectory(from, to); } else { // copy file await copyFile(from, to); } } } resolve(); } catch (err) { reject(err); } }); }; <|start_filename|>packages/plugin-graphql/test/unit/schema/graph.spec.js<|end_filename|> const expect = require('chai').expect; const MOCK_GRAPH = require('../mocks/graph'); const { graphResolvers } = require('../../../src/schema/graph'); describe('Unit Test: Data', function() { describe('Schema', function() { describe('Graph', function() { describe('getPagesFromGraph', function() { let pages = []; before(async function() { pages = await graphResolvers.Query.graph(undefined, {}, MOCK_GRAPH); }); it('should have 28 pages', function() { expect(pages.length).to.equal(28); }); it('should have all expected properties for each page', function() { pages.forEach(function(page) { expect(page.id).to.exist; expect(page.path).to.exist; expect(page.filename).to.exist; expect(page.template).to.exist; expect(page.title).to.exist; expect(page.route).to.exist; }); }); }); describe('getChildrenFromParentRoute for (mock) Getting Started', function() { let children = []; before(async function() { children = await graphResolvers.Query.children(undefined, { parent: 'getting-started' }, MOCK_GRAPH); }); it('should have 8 children', function() { // console.debug(children); expect(children.length).to.equal(7); }); it('should have the expected value for id for each child', function() { expect(children[0].id).to.equal('branding'); expect(children[1].id).to.equal('build-and-deploy'); expect(children[2].id).to.equal('creating-content'); expect(children[3].id).to.equal('key-concepts'); expect(children[4].id).to.equal('next-steps'); expect(children[5].id).to.equal('project-setup'); expect(children[6].id).to.equal('quick-start'); }); it('should have the expected route for each child', function() { children.forEach(function(child) { expect(child.route).to.equal(`/getting-started/${child.id}`); }); }); it('should have the expected label for each child', function() { expect(children[0].label).to.equal('Branding'); expect(children[1].label).to.equal('Build And Deploy'); expect(children[2].label).to.equal('Creating Content'); expect(children[3].label).to.equal('Key Concepts'); expect(children[4].label).to.equal('Next Steps'); expect(children[5].label).to.equal('Project Setup'); expect(children[6].label).to.equal('Quick Start'); }); it('should have the expected path for each child', function() { children.forEach(function(child) { expect(child.path).to.contain(`/getting-started/${child.id}.md`); }); }); it('should have "page" as the template for all children', function() { children.forEach(function(child) { expect(child.template).to.equal('page'); }); }); it('should have the expected title for each child', function() { expect(children[0].title).to.equal('Styles and Web Components'); expect(children[1].title).to.equal('Build and Deploy'); expect(children[2].title).to.equal('Creating Content'); expect(children[3].title).to.equal('Key Concepts'); expect(children[4].title).to.equal('Next Steps'); expect(children[5].title).to.equal('Project Setup'); expect(children[6].title).to.equal('Quick Start'); }); it('should have expected custom front matter data if it is set', function() { expect(children[0].data.menu).to.equal('side'); }); }); }); }); }); <|start_filename|>.mocharc.js<|end_filename|> const path = require('path'); module.exports = { spec: path.join(__dirname, 'packages/**/test/**/**/**/*.spec.js'), timeout: 30000 }; <|start_filename|>packages/cli/test/cases/develop.spa/develop.spa.spec.js<|end_filename|> /* * Use Case * Run Greenwood develop command with SPA mode setting. * * User Result * Should start the development server in SPA mode with client side routing support. * * User Command * greenwood develop * * User Config * { * mode: 'spa' * } * * User Workspace * src/ * index.html * */ const expect = require('chai').expect; const fs = require('fs'); const { JSDOM } = require('jsdom'); const path = require('path'); const request = require('request'); const Runner = require('gallinago').Runner; const runSmokeTest = require('../../../../../test/smoke-test'); function removeWhiteSpace(string = '') { return string .replace(/\n/g, '') .replace(/ /g, ''); } describe('Develop Greenwood With: ', function() { const LABEL = 'SPA Mode'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; const hostname = 'http://localhost'; const BODY_REGEX = /<body>(.*)<\/body>/s; const expected = removeWhiteSpace(fs.readFileSync(path.join(outputPath, 'src/index.html'), 'utf-8').match(BODY_REGEX)[0]); const port = 1984; let runner; before(function() { this.context = { hostname: `${hostname}:${port}` }; runner = new Runner(true); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath); return new Promise(async (resolve) => { setTimeout(() => { resolve(); }, 5000); await runner.runCommand(cliPath, 'develop'); }); }); runSmokeTest(['serve'], LABEL); describe('Develop command specific HTML behaviors for client side routing at root - /', function() { let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get({ url: `http://127.0.0.1:${port}/`, headers: { accept: 'text/html' } }, (err, res, body) => { if (err) { reject(); } response = res; dom = new JSDOM(body); resolve(); }); }); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.contain('text/html'); done(); }); it('should return a 200', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the expected body contents', function(done) { expect(removeWhiteSpace(response.body.match(BODY_REGEX)[0])).to.equal(expected); done(); }); }); describe('Develop command specific HTML behaviors for client side routing at 1 level route - /<resource>', function() { let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get({ url: `http://127.0.0.1:${port}/artists/`, headers: { accept: 'text/html' } }, (err, res, body) => { if (err) { reject(); } response = res; dom = new JSDOM(body); resolve(); }); }); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.contain('text/html'); done(); }); it('should return a 200', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the expected body contents', function(done) { expect(removeWhiteSpace(response.body.match(BODY_REGEX)[0])).to.equal(expected); done(); }); }); describe('Develop command specific HTML behaviors for client side routing at 1 level route - /<resource>/:id', function() { let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get({ url: `http://127.0.0.1:${port}/artists/1`, headers: { accept: 'text/html' } }, (err, res, body) => { if (err) { reject(); } response = res; dom = new JSDOM(body); resolve(); }); }); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.contain('text/html'); done(); }); it('should return a 200', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the expected body contents', function(done) { expect(removeWhiteSpace(response.body.match(BODY_REGEX)[0])).to.equal(expected); done(); }); }); }); after(function() { runner.stopCommand(); runner.teardown([ path.join(outputPath, '.greenwood') ]); }); }); <|start_filename|>packages/cli/test/cases/build.default.workspace-getting-started/build.default.workspace-getting-started.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command and reproduce building the Getting Started docs companion repo * https://github.com/ProjectEvergreen/greenwood-getting-started * * User Result * Should generate a Greenwood build that generally reproduces the Getting Started guide * * User Command * greenwood build * * Default Config * * Custom Workspace * src/ * assets/ * greenwood-logo.png * components/ * footer.js * header.js * pages/ * blog/ * first-post.md * second-post.md * index.md * styles/ * theme.css * templates/ * app.html * blog.html */ const expect = require('chai').expect; const fs = require('fs'); const glob = require('glob-promise'); const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; const { tagsMatch } = require('../../../../../test/utils'); describe('Build Greenwood With: ', function() { const LABEL = 'Custom Workspace based on the Getting Started guide and repo'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public'], LABEL); describe('Folder Structure and Home Page', function() { let dom; let html; before(async function() { const htmlPath = path.resolve(this.context.publicDir, 'index.html'); dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); html = await fs.promises.readFile(htmlPath, 'utf-8'); }); describe('document <html>', function() { it('should have an <html> tag with the DOCTYPE attribute', function() { expect(html.indexOf('<!DOCTYPE html>')).to.be.equal(0); }); it('should have a <head> tag with the lang attribute on it', function() { const htmlTag = dom.window.document.querySelectorAll('html'); expect(htmlTag.length).to.equal(1); expect(htmlTag[0].getAttribute('lang')).to.be.equal('en'); expect(htmlTag[0].getAttribute('prefix')).to.be.equal('og:http://ogp.me/ns#'); }); it('should have matching opening and closing <head> tags', function() { expect(tagsMatch('<html>', html)).to.be.equal(true); }); }); describe('head section tags', function() { let metaTags; before(function() { metaTags = dom.window.document.querySelectorAll('head > meta'); }); it('should have a <title> tag in the <head>', function() { const title = dom.window.document.querySelector('head title').textContent; expect(title).to.be.equal('My App'); }); it('should have five default <meta> tags in the <head>', function() { expect(metaTags.length).to.be.equal(5); }); it('should have default mobile-web-app-capable <meta> tag', function() { const mwacMeta = metaTags[2]; expect(mwacMeta.getAttribute('name')).to.be.equal('mobile-web-app-capable'); expect(mwacMeta.getAttribute('content')).to.be.equal('yes'); }); it('should have default apple-mobile-web-app-capable <meta> tag', function() { const amwacMeta = metaTags[3]; expect(amwacMeta.getAttribute('name')).to.be.equal('apple-mobile-web-app-capable'); expect(amwacMeta.getAttribute('content')).to.be.equal('yes'); }); it('should have default apple-mobile-web-app-status-bar-style <meta> tag', function() { const amwasbsMeta = metaTags[4]; expect(amwasbsMeta.getAttribute('name')).to.be.equal('apple-mobile-web-app-status-bar-style'); expect(amwasbsMeta.getAttribute('content')).to.be.equal('black'); }); }); describe('additional custom workspace output', function() { it('should create a new assets directory', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'assets'))).to.be.true; }); it('should contain files from the asset directory', async function() { expect(fs.existsSync(path.join(this.context.publicDir, 'assets', './greenwood-logo.png'))).to.be.true; }); it('should output two JS bundle files', async function() { expect(await glob.promise(path.join(this.context.publicDir, './*.js'))).to.have.lengthOf(2); }); it('should have two <script> tags in the <head>', async function() { const scriptTags = dom.window.document.querySelectorAll('head script'); expect(scriptTags.length).to.be.equal(2); }); it('should output one CSS file', async function() { expect(await glob.promise(`${path.join(this.context.publicDir, 'styles')}/theme.*.css`)).to.have.lengthOf(1); }); it('should output two <style> tag in the <head> (one from puppeteer)', async function() { const styleTags = dom.window.document.querySelectorAll('head style'); expect(styleTags.length).to.be.equal(2); }); it('should output one <link> tag in the <head>', async function() { const linkTags = dom.window.document.querySelectorAll('head link[rel="stylesheet"]'); expect(linkTags.length).to.be.equal(1); }); it('should have content in the <body>', function() { const h2 = dom.window.document.querySelector('body h2'); const p = dom.window.document.querySelector('body p'); const h3 = dom.window.document.querySelector('body h3'); expect(h2.textContent).to.be.equal('Home Page'); expect(p.textContent).to.be.equal('This is the Getting Started home page!'); expect(h3.textContent).to.be.equal('My Posts'); }); it('should have an unordered list of blog posts in the <body>', function() { const ul = dom.window.document.querySelectorAll('body ul'); const li = dom.window.document.querySelectorAll('body ul li'); const links = dom.window.document.querySelectorAll('body ul a'); expect(ul.length).to.be.equal(1); expect(li.length).to.be.equal(2); expect(links.length).to.be.equal(2); expect(links[0].href.replace('file://', '').replace(/\/[A-Z]:/, '')).to.be.equal('/blog/second-post/'); expect(links[0].textContent).to.be.equal('my-second-post'); expect(links[1].href.replace('file://', '').replace(/\/[A-Z]:/, '')).to.be.equal('/blog/first-post/'); expect(links[1].textContent).to.be.equal('my-first-post'); }); it('should have a <header> tag in the <body>', function() { const header = dom.window.document.querySelectorAll('body header'); expect(header.length).to.be.equal(1); expect(header[0].textContent).to.be.equal('This is the header component.'); }); it('should have a <footer> tag in the <body>', function() { const footer = dom.window.document.querySelectorAll('body footer'); expect(footer.length).to.be.equal(1); expect(footer[0].textContent).to.be.equal('This is the footer component.'); }); }); }); describe('First Blog Post', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'blog/first-post/index.html')); }); it('should create a blog directory', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'blog'))).to.be.true; }); it('should output an index.html file for first-post page', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'blog', 'first-post', './index.html'))).to.be.true; }); it('should have two <script> tags in the <head>', async function() { const scriptTags = dom.window.document.querySelectorAll('head script'); expect(scriptTags.length).to.be.equal(2); }); it('should output one <style> tag in the <head> (one from puppeteer)', async function() { const styleTags = dom.window.document.querySelectorAll('head style'); expect(styleTags.length).to.be.equal(1); }); it('should output one <link> tag in the <head>', async function() { const linkTags = dom.window.document.querySelectorAll('head link[rel="stylesheet"]'); expect(linkTags.length).to.be.equal(1); }); it('should have a <header> tag in the <body>', function() { const header = dom.window.document.querySelectorAll('body header'); expect(header.length).to.be.equal(1); expect(header[0].textContent).to.be.equal('This is the header component.'); }); it('should have an the expected content in the <body>', function() { const h1 = dom.window.document.querySelector('body h1'); const h2 = dom.window.document.querySelector('body h2'); const p = dom.window.document.querySelectorAll('body p'); expect(h1.textContent).to.be.equal('A Blog Post Page'); expect(h2.textContent).to.be.equal('My First Blog Post'); expect(p[0].textContent).to.be.equal('Lorem Ipsum'); expect(p[1].textContent).to.be.equal('back'); }); it('should have a <footer> tag in the <body>', function() { const footer = dom.window.document.querySelectorAll('body footer'); expect(footer.length).to.be.equal(1); expect(footer[0].textContent).to.be.equal('This is the footer component.'); }); it('should have the expected content for the first blog post', function() { const footer = dom.window.document.querySelectorAll('body footer'); expect(footer.length).to.be.equal(1); expect(footer[0].textContent).to.be.equal('This is the footer component.'); }); }); describe('Second Blog Post', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'blog/second-post/index.html')); }); it('should create a blog directory', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'blog'))).to.be.true; }); it('should output an index.html file for first-post page', function() { expect(fs.existsSync(path.join(this.context.publicDir, 'blog', 'second-post', './index.html'))).to.be.true; }); it('should have two <script> tags in the <head>', async function() { const scriptTags = dom.window.document.querySelectorAll('head script'); expect(scriptTags.length).to.be.equal(2); }); it('should output one <style> tag in the <head> (one from puppeteer)', async function() { const styleTags = dom.window.document.querySelectorAll('head style'); expect(styleTags.length).to.be.equal(1); }); it('should output one <link> tag in the <head>', async function() { const linkTags = dom.window.document.querySelectorAll('head link[rel="stylesheet"]'); expect(linkTags.length).to.be.equal(1); }); it('should have a <header> tag in the <body>', function() { const header = dom.window.document.querySelectorAll('body header'); expect(header.length).to.be.equal(1); expect(header[0].textContent).to.be.equal('This is the header component.'); }); it('should have an the expected content in the <body>', function() { const h1 = dom.window.document.querySelector('body h1'); const h2 = dom.window.document.querySelector('body h2'); const p = dom.window.document.querySelectorAll('body p'); expect(h1.textContent).to.be.equal('A Blog Post Page'); expect(h2.textContent).to.be.equal('My Second Blog Post'); expect(p[0].textContent).to.be.equal('Lorem Ipsum'); expect(p[1].textContent).to.be.equal('back'); }); it('should have a <footer> tag in the <body>', function() { const footer = dom.window.document.querySelectorAll('body footer'); expect(footer.length).to.be.equal(1); expect(footer[0].textContent).to.be.equal('This is the footer component.'); }); it('should have the expected content for the first blog post', function() { const footer = dom.window.document.querySelectorAll('body footer'); expect(footer.length).to.be.equal(1); expect(footer[0].textContent).to.be.equal('This is the footer component.'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.optimization-default/build.config-optimization-default.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with default setting for optimization * * User Result * Should generate a Greenwood build that preloads all <script> and <link> tags * * User Command * greenwood build * * Default Config * * Custom Workspace * src/ * components/ * header.js * pages/ * index.html * styles/ * theme.css */ const expect = require('chai').expect; const glob = require('glob-promise'); const { JSDOM } = require('jsdom'); const path = require('path'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Default Optimization Configuration'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); describe('Output for JavaScript / CSS tags and files', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, './index.html')); }); describe('<script> tag and preloading', function() { it('should contain one javasccript file in the output directory', async function() { expect(await glob.promise(path.join(this.context.publicDir, '*.js'))).to.have.lengthOf(1); }); it('should have the expected <script> tag in the <head>', function() { const scriptTags = dom.window.document.querySelectorAll('head script'); expect(scriptTags.length).to.be.equal(1); }); it('should have the expect modulepreload <link> tag for the same <script> tag src in the <head>', function() { const preloadScriptTags = Array .from(dom.window.document.querySelectorAll('head link[rel="modulepreload"]')) .filter(link => link.getAttribute('as') === 'script'); expect(preloadScriptTags.length).to.be.equal(1); expect(preloadScriptTags[0].href).to.match(/header.*.js/); }); it('should contain the expected content from <app-header> in the <body>', function() { const header = dom.window.document.querySelectorAll('body header'); expect(header.length).to.be.equal(1); expect(header[0].textContent).to.be.equal('This is the header component.'); }); }); describe('<link> tag and preloading', function() { it('should contain one style.css in the output directory', async function() { expect(await glob.promise(`${path.join(this.context.publicDir, 'styles')}/theme.*.css`)).to.have.lengthOf(1); }); it('should have the expected <link> tag in the <head>', function() { const linkTags = Array .from(dom.window.document.querySelectorAll('head link[rel="preload"]')) .filter(tag => tag.getAttribute('as') === 'style'); expect(linkTags.length).to.be.equal(1); }); it('should have the expect preload <link> tag for the same <link> tag href in the <head>', function() { const preloadLinkTags = Array .from(dom.window.document.querySelectorAll('head link[rel="preload"]')) .filter(link => link.getAttribute('as') === 'style'); expect(preloadLinkTags.length).to.be.equal(1); expect(preloadLinkTags[0].href).to.match(/\/styles\/theme.*.css/); expect(preloadLinkTags[0].getAttribute('crossorigin')).to.equal('anonymous'); }); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-graphql/test/cases/query-config/src/components/footer.js<|end_filename|> import client from '@greenwood/plugin-graphql/core/client'; import ConfigQuery from '@greenwood/plugin-graphql/queries/config'; class FooterComponent extends HTMLElement { constructor() { super(); this.root = this.attachShadow({ mode: 'open' }); } async connectedCallback() { await client.query({ query: ConfigQuery }).then((response) => { this.root.innerHTML = ` <footer>${response.data.config.title}</footer> `; }); } } customElements.define('app-footer', FooterComponent); <|start_filename|>packages/cli/test/cases/build.config.optimization-overrides/build.config-optimization-overrides.spec.js<|end_filename|> /* * Use Case * Run Greenwood build command with various override settings for optimization settings. * * User Result * Should generate a Greenwood build that respects optimization setting overrides for all <script> and <link> tags. * * User Command * greenwood build * * User Config * Default * * Custom Workspace * src/ * components/ * footer.js * header.js * pages/ * index.html * styles/ * theme.css */ const expect = require('chai').expect; const glob = require('glob-promise'); const { JSDOM } = require('jsdom'); const path = require('path'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Optimization Overrides'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(async function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); describe('Cumulative output based on all override settings', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, './index.html')); }); it('should emit no Javascript files to the output directory', async function() { const jsFiles = await glob.promise(path.join(this.context.publicDir, '**/*.js')); expect(jsFiles).to.have.lengthOf(0); }); it('should emit no CSS files to the output directory', async function() { const cssFiles = await glob.promise(path.join(this.context.publicDir, '**/*.css')); expect(cssFiles).to.have.lengthOf(0); }); it('should have one <script> tag in the <head>', function() { const scriptTags = dom.window.document.querySelectorAll('head script'); expect(scriptTags.length).to.be.equal(1); }); // one of these tags comes from puppeteer it('should have two <style> tags in the <head>', function() { const styleTags = dom.window.document.querySelectorAll('head style'); expect(styleTags.length).to.be.equal(2); }); it('should have no <link> tags in the <head>', function() { const linkTags = dom.window.document.querySelectorAll('head link'); expect(linkTags.length).to.be.equal(0); }); }); describe('JavaScript <script> tag and static optimization override for <app-header>', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, './index.html')); }); it('should contain no <link> tags in the <head>', function() { const headerLinkTags = Array.from(dom.window.document.querySelectorAll('head link')) .filter(link => link.getAttribute('href').indexOf('header') >= 0); expect(headerLinkTags.length).to.be.equal(0); }); it('should have no <script> tags in the <head>', function() { const headerScriptTags = Array.from(dom.window.document.querySelectorAll('head script')) .filter(script => script.getAttribute('src') && script.getAttribute('src').indexOf('header') >= 0); expect(headerScriptTags.length).to.be.equal(0); }); it('should contain the expected content from <app-header> in the <body>', function() { const headerScriptTags = dom.window.document.querySelectorAll('body header'); expect(headerScriptTags.length).to.be.equal(1); expect(headerScriptTags[0].textContent).to.be.equal('This is the header component.'); }); }); describe('JavaScript <script> tag and inline optimization override for <app-footer>', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, './index.html')); }); it('should contain no <link> tags in the <head>', function() { const footerLinkTags = Array.from(dom.window.document.querySelectorAll('head link')) .filter(link => link.getAttribute('href').indexOf('footer') >= 0); expect(footerLinkTags.length).to.be.equal(0); }); it('should have an inline <script> tag in the <head>', function() { const footerScriptTags = Array.from(dom.window.document.querySelectorAll('head script')) .filter((script) => { // eslint-disable-next-line max-len return script.textContent.indexOf('const e=document.createElement("template");e.innerHTML="<footer>This is the footer component.</footer>";class t extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.shadowRoot.appendChild(e.content.cloneNode(!0))}}customElements.define("app-footer",t);') >= 0 && !script.getAttribute('src'); }); expect(footerScriptTags.length).to.be.equal(1); }); it('should contain the expected content from <app-footer> in the <body>', function() { const footer = dom.window.document.querySelectorAll('body footer'); expect(footer.length).to.be.equal(1); expect(footer[0].textContent).to.be.equal('This is the footer component.'); }); }); describe('CSS <link> tag and inline optimization override for theme.css', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, './index.html')); }); it('should contain no <link> tags in the <head>', function() { const themeLinkTags = Array.from(dom.window.document.querySelectorAll('head link')) .filter(link => link.getAttribute('href').indexOf('theme') >= 0); expect(themeLinkTags.length).to.be.equal(0); }); it('should have an inline <style> tag in the <head>', function() { const themeStyleTags = Array.from(dom.window.document.querySelectorAll('head style')) .filter(style => style.textContent.indexOf('*{color:#00f}') >= 0); expect(themeStyleTags.length).to.be.equal(1); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-graphql/test/cases/query-config/greenwood.config.js<|end_filename|> const pluginGraphQL = require('../../../src/index'); module.exports = { title: 'GraphQL ConfigQuery Spec', plugins: [ ...pluginGraphQL() ] }; <|start_filename|>packages/cli/src/lib/node-modules-utils.js<|end_filename|> const fs = require('fs'); // defer to NodeJS to find where on disk a package is located using require.resolve // and return the root absolute location function getNodeModulesLocationForPackage(packageName) { let nodeModulesUrl; try { const packageEntryLocation = require.resolve(packageName).replace(/\\/g, '/'); // force / for consistency and path matching if (packageName.indexOf('@greenwood') === 0) { const subPackage = packageEntryLocation.indexOf('@greenwood') > 0 ? packageName // we are in the user's node modules : packageName.split('/')[1]; // else we are in our monorepo const packageRootPath = packageEntryLocation.indexOf('@greenwood') > 0 ? packageEntryLocation.split(packageName)[0] // we are in the user's node modules : packageEntryLocation.split(subPackage)[0]; // else we are in our monorepo nodeModulesUrl = `${packageRootPath}${subPackage}`; } else { const packageRootPath = packageEntryLocation.split(packageName)[0]; nodeModulesUrl = `${packageRootPath}${packageName}`; } } catch (e) { // require.resolve may fail in the event a package has no main in its package.json // so as a fallback, ask for node_modules paths and find its location manually // https://github.com/ProjectEvergreen/greenwood/issues/557#issuecomment-923332104 const locations = require.resolve.paths(packageName); for (const location in locations) { const nodeModulesPackageRoot = `${locations[location]}/${packageName}`; const packageJsonLocation = `${nodeModulesPackageRoot}/package.json`; if (fs.existsSync(packageJsonLocation)) { nodeModulesUrl = nodeModulesPackageRoot; } } if (!nodeModulesUrl) { console.debug(`Unable to look up ${packageName} using NodeJS require.resolve.`); } } return nodeModulesUrl; } // extract the package name from a URL like /node_modules/<some>/<package>/index.js function getPackageNameFromUrl(url) { const packagePathPieces = url.split('node_modules/')[1].split('/'); // double split to handle node_modules within nested paths let packageName = packagePathPieces.shift(); // handle scoped packages if (packageName.indexOf('@') === 0) { packageName = `${packageName}/${packagePathPieces.shift()}`; } return packageName; } module.exports = { getNodeModulesLocationForPackage, getPackageNameFromUrl }; <|start_filename|>packages/cli/test/cases/develop.plugins.context/develop.plugins.context.spec.js<|end_filename|> /* * Use Case * Develop with Greenwood when using a custom context plugin (e.g. installed via npm) that provides custom templates (app / page) and resources (JS / CSS); aka a "theme pack". * * User Result * Should start development server with expected templates being used from node_modules along with JS and CSS. * * User Command * greenwood develop * * User Config * Mock Theme Pack Plugin (from fixtures) * * Custom Workspace * src/ * pages/ * slides/ * index.md * index.md */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const packageJson = require('./package.json'); const path = require('path'); const request = require('request'); const Runner = require('gallinago').Runner; const runSmokeTest = require('../../../../../test/smoke-test'); describe('Develop Greenwood With: ', function() { const LABEL = 'Custom Context Plugin and Default Workspace (aka Theme Packs)'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; const hostname = 'http://localhost'; const port = 1984; let runner; before(function() { this.context = { hostname: `${hostname}:${port}` }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath); return new Promise(async (resolve) => { setTimeout(() => { resolve(); }, 5000); await runner.runCommand(cliPath, 'develop'); }); }); runSmokeTest(['serve'], LABEL); describe('Develop command specific HTML behaviors', function() { let response = {}; let dom; before(async function() { return new Promise((resolve, reject) => { request.get({ url: `http://127.0.0.1:${port}`, headers: { accept: 'text/html' } }, (err, res, body) => { if (err) { reject(); } response = res; dom = new JSDOM(body); resolve(); }); }); }); it('should return a 200', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should have expected text from from a mock package layout/app.html in node_modules/', function(done) { const pageTemplateHeading = dom.window.document.querySelectorAll('body h1')[0]; expect(pageTemplateHeading.textContent).to.be.equal('This is a custom app template from the custom layouts directory.'); done(); }); it('should have expected text from from a mock package layout/page.html in node_modules/', function(done) { const pageTemplateHeading = dom.window.document.querySelectorAll('body h2')[0]; expect(pageTemplateHeading.textContent).to.be.equal('This is a custom (default) page template from the custom layouts directory.'); done(); }); it('should have expected text from user workspace pages/index.md', function(done) { const pageHeadingPrimary = dom.window.document.querySelectorAll('body h3')[0]; const pageHeadingSecondary = dom.window.document.querySelectorAll('body h4')[0]; expect(pageHeadingPrimary.textContent).to.be.equal('Context Plugin Theme Pack Test'); expect(pageHeadingSecondary.textContent).to.be.equal('From user workspace pages/index.md'); done(); }); }); describe('Custom Theme Pack internal logic for resolving theme.css for local development', function() { let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get({ url: `http://127.0.0.1:${port}/node_modules/${packageJson.name}/dist/styles/theme.css` }, (err, res, body) => { if (err) { reject(); } response = res; response.body = body; resolve(); }); }); }); it('should return a 200', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.equal('text/css'); done(); }); it('should correctly return CSS from the developers local files', function(done) { expect(response.body).to.equal(':root {\n --color-primary: #135;\n}'); done(); }); }); describe('Custom Theme Pack internal logic for resolving greeting.js for local development', function() { let response = {}; before(async function() { return new Promise((resolve, reject) => { request.get({ url: `http://127.0.0.1:${port}/node_modules/${packageJson.name}/dist/components/greeting.js` }, (err, res, body) => { if (err) { reject(); } response = res; response.body = body; resolve(); }); }); }); it('should return a 200', function(done) { expect(response.statusCode).to.equal(200); done(); }); it('should return the correct content type', function(done) { expect(response.headers['content-type']).to.equal('text/javascript'); done(); }); it('should correctly return JavaScript from the developers local files', function(done) { expect(response.body).to.contain('customElements.define(\'x-greeting\', GreetingComponent);'); done(); }); }); }); after(function() { runner.stopCommand(); runner.teardown([ path.join(outputPath, '.greenwood') ]); }); }); <|start_filename|>packages/plugin-graphql/test/unit/mocks/config.js<|end_filename|> const MOCK_CONFIG = { config: { devServer: { port: 1984 }, meta: [ { name: 'twitter:site', content: '@PrjEvergreen' }, { rel: 'icon', href: '/assets/favicon.ico' } ], title: 'My App', workspace: 'src' } }; module.exports = MOCK_CONFIG; <|start_filename|>packages/cli/test/cases/theme-pack/greenwood.config.js<|end_filename|> const myThemePack = require('./my-theme-pack'); const packageName = require('./package.json').name; const path = require('path'); const { ResourceInterface } = require('@greenwood/cli/src/lib/resource-interface'); class MyThemePackDevelopmentResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['*']; } async shouldResolve(url) { // eslint-disable-next-line no-underscore-dangle return Promise.resolve(process.env.__GWD_COMMAND__ === 'develop' && url.indexOf(`/node_modules/${packageName}/`) >= 0); } async resolve(url) { return Promise.resolve(this.getBareUrlPath(url).replace(`/node_modules/${packageName}/dist/`, path.join(process.cwd(), '/src/'))); } } module.exports = { plugins: [ ...myThemePack({ __isDevelopment: true }), { type: 'resource', name: `${packageName}:resource`, provider: (compilation, options) => new MyThemePackDevelopmentResource(compilation, options) } ] }; <|start_filename|>packages/cli/src/plugins/resource/plugin-source-maps.js<|end_filename|> /* * * Detects and fully resolve requests to source map (.map) files. * */ const fs = require('fs'); const path = require('path'); const { ResourceInterface } = require('../../lib/resource-interface'); class SourceMapsResource extends ResourceInterface { constructor(compilation, options) { super(compilation, options); this.extensions = ['.map']; } async shouldServe(url) { return Promise.resolve(path.extname(url) === this.extensions[0] && fs.existsSync(url)); } async serve(url) { return new Promise(async (resolve, reject) => { try { const sourceMap = fs.readFileSync(url, 'utf-8'); resolve({ body: sourceMap, contentType: 'application/json' }); } catch (e) { reject(e); } }); } } module.exports = { type: 'resource', name: 'plugin-source-maps', provider: (compilation, options) => new SourceMapsResource(compilation, options) }; <|start_filename|>packages/cli/test/cases/develop.spa/greenwood.config.js<|end_filename|> module.exports = { mode: 'spa' }; <|start_filename|>packages/plugin-import-css/test/cases/develop.default/greenwood.config.js<|end_filename|> const pluginImportCss = require('../../../src/index'); module.exports = { plugins: [ ...pluginImportCss() ] }; <|start_filename|>packages/plugin-google-analytics/test/cases/option-anonymous/option-anonymous.spec.js<|end_filename|> /* * Use Case * Run Greenwood with Google Analytics composite plugin with IP anonymization set to false. * * Uaer Result * Should generate a bare bones Greenwood build with Google Analytics tracking snippet injected into index.html. * * User Command * greenwood build * * User Config * const googleAnalyticsPlugin = require('@greenwod/plugin-google-analytics'); * * { * plugins: [{ * googleAnalyticsPlugin({ * analyticsId: 'UA-123456-1', * anonymouse: false * }) * }] * * } * * User Workspace * Greenwood default (src/) */ const expect = require('chai').expect; const { JSDOM } = require('jsdom'); const path = require('path'); const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Google Analytics Plugin with IP Anonymization tracking set to false and Default Workspace'; const mockAnalyticsId = 'UA-123456-1'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Initialization script', function() { let inlineScript; before(async function() { const dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); const scriptTags = dom.window.document.querySelectorAll('head script'); inlineScript = Array.prototype.slice.call(scriptTags).filter(script => { return !script.src && !script.getAttribute('data-state'); }); }); it('should be one inline <script> tag', function() { expect(inlineScript.length).to.be.equal(1); }); it('should have the expected code with users analyicsId', function() { const expectedContent = ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${mockAnalyticsId}', { 'anonymize_ip': false }); `; expect(inlineScript[0].textContent).to.contain(expectedContent); }); }); describe('Tracking script', function() { let trackingScript; before(async function() { const dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, 'index.html')); const scriptTags = dom.window.document.querySelectorAll('head script'); trackingScript = Array.prototype.slice.call(scriptTags).filter(script => { return script.src === `https://www.googletagmanager.com/gtag/js?id=${mockAnalyticsId}`; }); }); it('should have one <script> tag for loading the Google Analytics tracker', function() { expect(trackingScript.length).to.be.equal(1); }); it('should be an async <script> tag for loading the Google Analytics tracker', function() { const isAsync = trackingScript[0].async !== null; expect(isAsync).to.be.equal(true); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/cli/test/cases/build.config.templates-directory/build.config.templates-directory.spec.js<|end_filename|> /* * Use Case * Run Greenwood with a custom name for templates directory. * * User Result * Should generate a bare bones Greenwood build. (same as build.default.spec.js) with custom title in header * * User Command * greenwood build * * User Config * { * templatesDirectory: 'layouts' * } * * User Workspace * Greenwood default * src/ * pages/ * index.md * layouts/ * page.html */ const fs = require('fs'); const { JSDOM } = require('jsdom'); const path = require('path'); const expect = require('chai').expect; const runSmokeTest = require('../../../../../test/smoke-test'); const { getSetupFiles, getOutputTeardownFiles } = require('../../../../../test/utils'); const Runner = require('gallinago').Runner; describe('Build Greenwood With: ', function() { const LABEL = 'Custom Pages Directory from Configuration'; const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js'); const outputPath = __dirname; let runner; before(function() { this.context = { publicDir: path.join(outputPath, 'public') }; runner = new Runner(); }); describe(LABEL, function() { before(async function() { await runner.setup(outputPath, getSetupFiles(outputPath)); await runner.runCommand(cliPath, 'build'); }); runSmokeTest(['public', 'index'], LABEL); describe('Page Content', function() { let dom; before(async function() { dom = await JSDOM.fromFile(path.resolve(this.context.publicDir, './index.html')); }); it('should output an index.html file for the home page', function() { expect(fs.existsSync(path.join(this.context.publicDir, './index.html'))).to.be.true; }); it('should have the correct page heading', function() { const heading = dom.window.document.querySelectorAll('head title')[0].textContent; expect(heading).to.be.equal('Custom Layout Page Template'); }); it('should have the correct page heading', function() { const heading = dom.window.document.querySelectorAll('body h1')[0].textContent; expect(heading).to.be.equal('Home Page'); }); it('should have the correct page heading', function() { const paragraph = dom.window.document.querySelectorAll('body p')[0].textContent; expect(paragraph).to.be.equal('A page using a page template from a custom layout directory.'); }); }); }); after(function() { runner.teardown(getOutputTeardownFiles(outputPath)); }); }); <|start_filename|>packages/plugin-import-css/test/cases/develop.default/src/main.css<|end_filename|> * { color: \'blue\'; background-image: url("/assets/background.jpg"); content: \"\"; font-family: 'Arial' }
ProjectEvergreen/greenwood
<|start_filename|>gatsby-node.js<|end_filename|> // Extend default Gatsby config with SVGR support, aliases and Webpack Bundle Analyzer const path = require('path') const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') exports.onCreateWebpackConfig = ({ getConfig, actions, stage }) => { const existingConfig = getConfig() const rules = existingConfig.module.rules.map(rule => { if (String(rule.test) === String(/\.(ico|svg|jpg|jpeg|png|gif|webp|avif)(\?.*)?$/)) { return { ...rule, exclude: path.resolve(__dirname, './src/icons'), } } return rule }) actions.replaceWebpackConfig({ ...existingConfig, module: { ...existingConfig.module, rules, }, }) actions.setWebpackConfig({ module: { rules: [ { test: /\.svg$/, include: path.resolve(__dirname, './src/icons'), issuer: /\.((j|t)sx?)$/, use: { loader: require.resolve(`@svgr/webpack`), options: { titleProp: true, }, }, }, ], }, plugins: stage === 'build-javascript' ? [ new BundleAnalyzerPlugin({ analyzerMode: 'static', defaultSizes: 'gzip', openAnalyzer: false, generateStatsFile: true, }), ] : [], resolve: { alias: { '@': path.resolve(__dirname, 'src'), }, }, }) } <|start_filename|>src/styles/base.css<|end_filename|> @layer base { html { @apply scroll-behaviour-smooth; } body { @apply body bg-purple-dark text-purple-light; } svg { fill: currentColor; } :focus:not(.focus-visible) { @apply outline-none; } :focus { @apply outline; } } <|start_filename|>src/styles/components.css<|end_filename|> @layer components { .body { @apply text-body-mobile md:text-body; } .h1 { @apply text-h1-mobile md:text-h1 font-bold; } .header { @apply text-header-mobile md:text-header font-bold; } .code { @apply py-2 px-4 md:py-4 md:px-8 bg-purple-light text-purple-dark rounded-md whitespace-nowrap overflow-x-auto max-w-full; } .code::before { content: '$ '; } } <|start_filename|>src/styles/utilities.css<|end_filename|> @layer utilities { .scroll-behaviour-smooth { scroll-behavior: smooth; } }
p1t1ch/gatsby-starter
<|start_filename|>Module 2/Chapter 6/detect insults - kaggle competitor version/java/Tagger.java<|end_filename|> import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.tartarus.snowball.SnowballStemmer; import org.tartarus.snowball.ext.englishStemmer; import com.fasterxml.jackson.databind.ObjectMapper; import edu.stanford.nlp.ling.CyclicCoreLabel; import edu.stanford.nlp.ling.HasWord; import edu.stanford.nlp.ling.TaggedWord; import edu.stanford.nlp.parser.lexparser.LexicalizedParser; import edu.stanford.nlp.tagger.maxent.MaxentTagger; import edu.stanford.nlp.trees.GrammaticalStructure; import edu.stanford.nlp.trees.GrammaticalStructureFactory; import edu.stanford.nlp.trees.PennTreebankLanguagePack; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.trees.TreebankLanguagePack; import edu.stanford.nlp.trees.TypedDependency; class Tagger { private MaxentTagger tagger; private SnowballStemmer stemmer; private LexicalizedParser lp; private GrammaticalStructureFactory gsf; private Tagger( MaxentTagger tagger, SnowballStemmer stemmer, LexicalizedParser lp, GrammaticalStructureFactory gsf) { this.tagger = tagger; this.stemmer = stemmer; this.lp = lp; this.gsf = gsf; } public static void main(String[] args) throws Exception { Tagger tagger = init(); String cmd = args[0]; String inFile = args[1]; String outFile = args[2]; System.out.println("Command: " + cmd + " inFile=" + inFile + " outFile=" + outFile); if ("train".equals(cmd)) { tagger.convertTrain(inFile, outFile); } else if ("test".equals(cmd)) { tagger.convertTest(inFile, outFile); } } private static Tagger init() throws Exception { MaxentTagger tagger = new MaxentTagger("dep/wsj-0-18-left3words.tagger"); SnowballStemmer stemmer = new englishStemmer(); LexicalizedParser lp = LexicalizedParser.loadModel( "edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz", "-maxLength", "80", "-retainTmpSubcategories"); TreebankLanguagePack tlp = new PennTreebankLanguagePack(); GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory(); return new Tagger(tagger, stemmer, lp, gsf); } public void convertTest(String fileName, String outFile) throws Exception { BufferedReader in = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(outFile)); String line; out.write(in.readLine()); // header out.newLine(); out.flush(); System.out.println("Process test."); int i = 0; while (null != (line = in.readLine())) { if (0 == ++i % 200) { System.out.println(" processed " + i + " lines."); } String fields[] = line.split(",", 2); String dt = fields[0]; String rawText = fields[1]; Row row = parse(rawText); ObjectMapper mapper = new ObjectMapper(); out.write(dt + "," + mapper.writeValueAsString(row) + "\n"); out.flush(); } out.close(); in.close(); } public void convertTrain(String fileName, String outFile) throws Exception { BufferedReader in = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(outFile)); String line; out.write(in.readLine()); // header out.newLine(); out.flush(); System.out.println("Process train."); int i = 0; while (null != (line = in.readLine())) { if (0 == ++i % 200) { System.out.println(" processed " + i + " lines."); } String fields[] = line.split(",", 3); String id = fields[0]; String rawText = fields[2]; Row row = parse(rawText); ObjectMapper mapper = new ObjectMapper(); out.write(id + "," + mapper.writeValueAsString(row) + "\n"); out.flush(); } out.close(); in.close(); } private Row parse(String text) { String normText = norm(text); List<List<HasWord>> taggedSentences = MaxentTagger.tokenizeText(new StringReader(normText)); Row row = new Row(); row.rawText = text; row.text = normText; for (List<HasWord> taggedSentence : taggedSentences) { Sen sentence = new Sen(); for (TaggedWord tok : tagger.tagSentence(taggedSentence)) { sentence.tokens.add( new Token(tok.word(), tok.tag(), stem(stemmer, tok.word()))); } if (taggedSentence.size() < 80) { Tree parse = lp.apply(taggedSentence); GrammaticalStructure gs = gsf.newGrammaticalStructure(parse); for (TypedDependency dep : gs.typedDependenciesCCprocessed()) { sentence.dependencies.add( new Dep( dep.reln().toString(), toDepWord(dep.gov().label()), toDepWord(dep.dep().label()))); } } else { System.err.println("long sentence: " + taggedSentence); } row.sentences.add(sentence); } return row; } private DepWord toDepWord(CyclicCoreLabel label) { return (0 == label.index()) ? new DepWord("$ROOT", "$ROOT", 0) : new DepWord(label.value(), stem(stemmer, label.value()), label.index()); } public static String norm(String s) { // strip('"') while (s.startsWith("\"")) s = s.substring(1); while (s.endsWith("\"")) s = s.substring(0, s.length() - 1); s = s.replaceAll("</?[a-zA-Z][^>]*>", " "); s = s.replaceAll("\\\\x[0-9a-zA-Z]{1,10}", " "); s = s.replaceAll("\\\\x[0-9a-zA-Z]{1,10}", " "); s = s.replaceAll("&[a-zA-Z]{1,10};", " "); s = s.replaceAll("&#[0-9a-zA-Z];", " "); s = s.replaceAll("\\\\[nrt]", " "); return s.trim(); } public static String stem(SnowballStemmer stemmer, String word) { stemmer.setCurrent(word); stemmer.stem(); return stemmer.getCurrent(); } } class Row { public List<Sen> sentences = new ArrayList<Sen>(); public String rawText = ""; public String text = ""; } class Sen { public List<Token> tokens = new ArrayList<Token>(); public List<Dep> dependencies = new ArrayList<Dep>(); } class Token { public Token(String word, String tag, String stem) { this.word = word; this.tag = tag; this.stem = stem; } public String word; public String tag; public String stem; } class Dep { public Dep(String rel, DepWord gov, DepWord dep) { this.rel = rel; this.gov = gov; this.dep = dep; } public String rel; public DepWord gov; public DepWord dep; } class DepWord { public DepWord(String word, String stem, int index) { this.word = word; this.stem = stem; this.index = index; } public String word; public String stem; public int index; }
saicharanabhishek/machinelearning_examples
<|start_filename|>ab-test.js<|end_filename|> /* * @license * ab-test v0.0.1 * (c) 2014 <NAME> http://daniellmb.com * License: MIT */ // shortcut to include both the a/b test service and directive modules angular.module('ab.test', ['ab.test.directive']); angular.module('ab.test.directive', ['ab.test.service', 'ngAnimate']) // create ab test service .factory('ab', function (abMfg) { return abMfg(); }) // ab-test directive controller .controller('abTestCtrl', ['$scope', 'ab', function abTestCtrl($scope, ab) { var ctrl = this, control = ctrl.control, variants = ctrl.variants = [], shown = $scope.shown || angular.noop, select = $scope.select || angular.noop; // register an a/b test variant ctrl.add = function add(variant) { // set in index on the variant variant.index = variants.length; variants.push(variant); // check if variant is the a/b test "control" if (variant.control) { ctrl.control = control = variant; } }; function getResultFromSelect() { var result = null; var toSelect = $scope.select(); angular.forEach(variants, function(elem) { if(elem.uid === toSelect || elem.uid === parseInt(toSelect)) { result = elem; } }); return result; } // run the ab test $scope.run = function run() { // hide active variant if (ctrl.variant) { ctrl.variant.active = false; } var result= null; // If user provides their own selection function, use that if($scope.select) { result = getResultFromSelect(); } if(!result) { result = ab.test(variants, $scope.frequency); } // check if there is a variant to show if (result) { // show variant returned result.active = true; ctrl.variant = result; // notify optional callback what was shown shown(result); } else if (control) { // no variant, show control instead control.active = true; ctrl.variant = control; // notify optional callback what was shown shown(control); } }; }]) // ab-test directive .directive('abTest', ['abTestLink', function abTest(abTestLink) { return { restrict: 'EA', replace: true, transclude: true, template: '<div ng-transclude></div>', controller: 'abTestCtrl', scope: { // (optional) two way binding run: '=?abRun', shown: '=?abShown', // (required) two way binding frequency: '=abFrequency', select: '=?abSelect' }, compile: function compile(elm, attrs) { // a/b test frequency required if (!angular.isDefined(attrs.abFrequency)) { throw new Error('ab-test: ab-frequency attribute required'); } // return post link method (see factory below) return abTestLink; } }; }]) // ab-test directive link function (separate so it can be easily mocked) .factory('abTestLink', function abTestLink() { return function link(scope, elm, attrs, ctrl) { var frequency = scope.frequency; // quick data sanity checks if (isNaN(frequency) || (frequency < 0.0001 || frequency > 1)) { throw new Error('ab-test: test frequency must be a float between 0.0001 and 1'); } if (ctrl.variants.length === 0) { throw new Error('ab-test: no variants found for the a/b test'); } // run the a/b test scope.run(); }; }) // ab-test variant directive .directive('abVariant', ['abVariantLink', function abVariant(abVariantLink) { return { require: '^abTest', restrict: 'EA', replace: true, transclude: true, template: '<div ng-transclude ng-show="active" class="ng-class:{\'ab-active\':active}; ab-animate"></div>', scope: { uid: '=abUid', // (optional) two way binding active: '=?abActive', control: '=?abControl', data: '=?abData' }, // empty controller so other directives can require being 'within' an ab-variant controller: angular.noop, link: abVariantLink // (see factory below) }; }]) // ab-variant directive link function (separate so it can be easily mocked) .factory('abVariantLink', function abVariantLink() { return function link(scope, elm, attrs, ctrl) { // register variant with ab-test parent directive ctrl.add(scope); }; }); <|start_filename|>gulpfile.js<|end_filename|> var gulp = require('gulp'), jshint = require('gulp-jshint'), complexity = require('gulp-complexity'), uglify = require('gulp-uglify'), rename = require('gulp-rename'), ngmin = require('gulp-ngmin'); gulp.task('default', function () { return gulp.src('ab-test.js') .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(jshint.reporter('fail')) .pipe(complexity({ cyclomatic: [8], halstead: [10], maintainability: [100] })) .pipe(rename('ab-test.min.js')) .pipe(ngmin()) .pipe(uglify({ preserveComments: 'some', outSourceMap: true })) .pipe(gulp.dest('.')); }); <|start_filename|>demo/js/app.js<|end_filename|> 'use strict'; var myapp = angular.module('myApp', [ 'myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'ab.test' //<= awesomesauce ]); // service to $broadcast 'run new a/b test' every 20 seconds. myapp.service('tictoc', function ($interval, $rootScope) { var count = 0, max = 20, title; $interval(function () { // old-school update the page title to avoid broadcasting on the rootScope every second if (!title) { title = document.getElementsByTagName('title')[0]; } title.innerHTML = (max - count) + ' seconds to next a/b test'; count += 1; // trigger a new a/b test if (count === max + 1) { $rootScope.$broadcast('toc'); count = 0; } }, 1000); }); // imperative A/B/n test that updates an element using ng-bind function HeadlinesCtrl($scope, ab, tictoc) { // setting the default value is need because it's bound one way with ng-bind $scope.headline = 'Include Your Children When Baking Cookies'; // define variants var list = [ 'Something Went Wrong in Jet Crash, Experts Say', 'Police Begin Campaign to Run Down Jaywalkers', 'Drunks Get Nine Months in Violin Case', 'Panda Mating Fails; Veterinarian Takes Over', 'Plane Too Close to Ground, Crash Probe Told', 'Miners Refuse to Work After Death', 'Juvenile Court to Try Shooting Defendant', 'Stolen Painting Found by Tree', 'Two Sisters Reunited after 18 Years in Checkout Counter', 'War Dims Hope for Peace', 'If Strike Isn\'t Settled Quickly, It May Last a While', 'New Study of Obesity Looks for Larger Test Group', 'Astronaut Takes Blame for Gas in Space', 'Kids Make Nutritious Snacks', 'Local High School Dropouts Cut in Half' ]; // listen for 'toc' event $scope.$on('toc', function () { // run new A/B/n test $scope.headline = ab.test(list, 1); }); } // declarative A/B/n test using the ab-test directive function ParagraphCtrl($scope) { $scope.onShow = function (variant) { // variant parameter === ab-variant scope //here you can call ab.log() to record a/b variant shown if (window.console && console.log) { console.log('variant ' + variant.index + '; is control ' + variant.control + '; data', variant.data); } }; // listen for 'toc' event $scope.$on('toc', function () { // run new A/B/n test $scope.runAgain(); }); } function TestimonialsCtrl($scope, $http, ab) { // set default values $scope.testimonial = 'It really saves me time and effort, ab-test is exactly what I have been looking for!'; $scope.name = '<NAME>.'; // load vatiants using JSON $http.get('data/testimonials.json') .then(function (res) { // listen for toc event $scope.$on('toc', function () { // A/B/n test it! var result = ab.test(res.data, 1); $scope.testimonial = result.text; $scope.name = result.by; }); }); } function SocialCtrl($scope, ab) { // setting the default value need because it's bound one way with ng-bind $scope.likes = '2.1M'; // listen for toc event $scope.$on('toc', function () { // A/B/n test it! $scope.likes = ab.test(['2', '99', '283', '5.7K', '3.6M', '9.1M'], 1); }); } function MediaCtrl($scope, ab) { // set the default value $scope.asSeenOn = 'http://i.imgur.com/VxsxKNe.jpg'; // listen for toc event $scope.$on('toc', function () { // A/B/n test it! $scope.asSeenOn = ab.test([ 'http://i.imgur.com/e9QC6wF.jpg', 'http://i.imgur.com/OBm9nh9.jpg', 'http://i.imgur.com/VxsxKNe.jpg' ], 1); }); } function ButtonsCtrl($scope, ab) { // set the default value $scope.style = 'btn-success'; // listen for toc event $scope.$on('toc', function () { // A/B/n test it! var cssClass = ab.test(['default', 'primary', 'success', 'info', 'warning', 'danger', 'link'], 1); // update ui $scope.style = 'btn-' + cssClass; }); } function ImagesCtrl($scope) { // coming soon, pull requests welcome :) } function AwardsCtrl($scope) { // coming soon, pull requests welcome :) } function PricingCtrl($scope) { // coming soon, pull requests welcome :) } function PromotionalCtrl($scope) { // coming soon, pull requests welcome :) } <|start_filename|>test/e2e/scenarios.js<|end_filename|> 'use strict'; /* See: https://github.com/angular/protractor/blob/master/docs/getting-started.md */ describe('my app', function () { describe('Headlines', function () { beforeEach(function () { browser.get('index.html'); }); it('should show the default value', function () { expect(element(by.binding('headline')).getText()).toEqual('Include Your Children When Baking Cookies'); }); }); describe('Paragraphs', function () { beforeEach(function () { browser.get('index.html'); }); it('should show only one of the test variants at a time', function () { var selector = '.paragraphs .ab-active', activeVariant = element.all(by.css(selector)); expect(activeVariant.count()).toEqual(1); }); // to do click "run again" and expect value to change }); describe('Testimonials', function () { beforeEach(function () { browser.get('index.html'); }); it('should show a testimonial', function () { var testimonial = element(by.binding('testimonial')); expect(testimonial.getText()).toBe('It really saves me time and effort, ab-test is exactly what I have been looking for!'); }); }); describe('Social', function () { beforeEach(function () { browser.get('index.html'); }); it('should show the number of likes', function () { var likes = element(by.binding('likes')); expect(likes.getText()).toBe('2.1M'); }); }); describe('Media', function () { beforeEach(function () { browser.get('index.html'); }); it('should show an as-seen-on media image', function () { var asSeenOn = element(by.css('.as-seen-on-media')); asSeenOn.getAttribute('src').then(function (attr) { expect(attr).toBe('http://i.imgur.com/VxsxKNe.jpg'); }); }); }); describe('Buttons', function () { beforeEach(function () { browser.get('index.html'); }); it('should a/b test the star this repo button', function () { var asSeenOn = element(by.css('#star-repo-btn')); asSeenOn.getAttribute('class').then(function (attr) { expect(attr).toMatch('btn-success'); }); }); }); }); <|start_filename|>test/unit/ab-variant.directive.js<|end_filename|> 'use strict'; describe('ab-variant directive', function () { var scope, compile, abSvc, MockABSvc = function () { this.test = jasmine.createSpy('test'); return this; }, validTemplate = '<ab-test ab-frequency="freq">' + '<ab-variant ab-data="data" ab-uid="a">A</ab-variant>' + '<ab-variant ab-active="active" ab-uid="b">B</ab-variant>' + '<ab-variant ab-control="true" ab-uid="c">C</ab-variant>' + '</ab-test>'; // Use to provide any mocks needed function _provide(callback) { // Execute callback with $provide module(function ($provide) { callback($provide); }); } // Use to create the directive under test function _create(template, data, active) { var elm; // Setup scope state scope.data = data; scope.freq = 0.5; scope.active = active; // Create directive elm = compile(template || validTemplate)(scope); // Return return elm; } // Inject dependencies function _inject() { inject(function ($rootScope, $compile) { scope = $rootScope.$new(); compile = $compile; }); } // Call this before each test, except where you are testing for edge-cases function _setup() { // Mock the expected values _provide(function (provide) { abSvc = new MockABSvc(); provide.value('ab', abSvc); }); // Inject the code under test _inject(); } beforeEach(function () { // Load the directive's module module('ab.test.directive'); }); describe('when created', function () { beforeEach(function () { // Inject with 'normal' setup _setup(); }); it('should throw error when not a child of an ab-test directive', function () { // arrange function invalidTemplate() { // act _create('<ab-variant></ab-variant>'); } // assert expect(invalidTemplate).toThrow(); }); it('should not throw error with a valid template', function () { // arrange function validTemplate() { // act _create(); } // assert expect(validTemplate).not.toThrow(); }); it('should accept optional ab-active attribute', function () { // arrange // act var elm = angular.element(_create(null, null, true).children()[1]); // assert expect(elm.isolateScope().active).toBe(true); }); it('should accept optional ab-control attribute', function () { // arrange // act var elm = angular.element(_create().children()[2]); // assert expect(elm.isolateScope().control).toBe(true); }); it('should accept optional ab-data attribute', function () { // arrange var data = 'foo'; // act var elm = angular.element(_create(null, data).children()[0]); // assert expect(elm.isolateScope().data).toBe(data); }); it('should show when active', function () { // arrange var elm = angular.element(_create().children()[0]); // act elm.isolateScope().active = true; scope.$apply(); // assert expect(elm.hasClass('ng-hide')).toBe(false); }); it('should hide when inactive', function () { // arrange var elm = angular.element(_create().children()[0]); // act elm.isolateScope().active = false; scope.$apply(); // assert expect(elm.hasClass('ng-hide')).toBe(true); }); }); // inject the directive link service to test hard-to-reach corners :) describe('when created', function () { var abVariantLink; // custom inject to control what gets passed to the directive link service beforeEach(function () { inject(function ($rootScope, $compile, _abVariantLink_) { scope = $rootScope.$new(); compile = $compile; abVariantLink = _abVariantLink_; }); }); it('should register the itself with ab-test', function () { // arrange scope.frequency = 1; var ctrl = { variants: [null], add: jasmine.createSpy('add') }; // act abVariantLink(scope, null, null, ctrl); // assert expect(ctrl.add).toHaveBeenCalled(); }); }); describe('when destroyed', function () { // Add specs }); }); <|start_filename|>test/lib/mock/ab.js<|end_filename|> MockABJS = function () { 'use strict'; // Methods this.test = jasmine.createSpy('test'); this.log = jasmine.createSpy('log'); return this; }; <|start_filename|>config/karma.conf.js<|end_filename|> // Karma configuration module.exports = function (config) { config.set({ basePath : '../', files : [ // deps 'test/lib/angular/angular.js', 'test/lib/angular/angular-*.js', 'test/lib/mock/*.js', // ab-test 'ab-test.js', // demo source 'demo/js/**/*.js', // specs 'test/unit/**/*.js' ], preprocessors: { 'ab-test.js': ['coverage'] }, exclude : [ 'test/lib/angular/angular-loader.js', 'test/lib/angular/*.min.js', 'test/lib/angular/angular-scenario.js' ], reporters: ['dots', 'coverage'], coverageReporter: { reporters: [{ type: 'text' }, { type: 'lcov', dir: 'coverage/' }] }, port: 9876, colors: true, autoWatch: true, singleRun: false, logLevel: config.LOG_INFO, frameworks: ['jasmine'], browsers : ['Firefox'], captureTimeout: 60000 }); // have travis publish to coveralls if (process.env.TRAVIS) { config.reporters.push('coveralls'); } }; <|start_filename|>test/unit/ab-variant.controller.js<|end_filename|> 'use strict'; describe('ab-variant controller', function () { // Add specs }); <|start_filename|>demo/data/testimonials.json<|end_filename|> [ { "text":"Million times better than other A/B testing tools!", "by":"<NAME>." }, { "text":"ab-test is better than using Visual Website Optimizer, Omniture, or Sitespect!", "by":"<NAME>." }, { "text":"ab-test is a great tool. We managed to find out the perfect combination of buttons on our pages.", "by":"<NAME>." }, { "text":"I can't say enough about ab-test. ab-test saved my business. Absolutely wonderful! Great work!", "by":"<NAME>." } ] <|start_filename|>test/unit/ab-test.controller.js<|end_filename|> 'use strict'; describe('ab-test controller', function () { var abTestCtrl, scope, abSvc, abSvcTestResult, MockABSvc = function () { this.test = function () { return abSvcTestResult; }; spyOn(this, 'test').andCallThrough(); return this; }; // Initialize the controller and scope beforeEach(function () { // Load the controller's module module('ab.test.directive'); // Provide any mocks needed module(function ($provide) { abSvc = new MockABSvc(); $provide.value('ab', abSvc); }); // Inject code under test inject(function ($controller) { scope = {}; abTestCtrl = $controller('abTestCtrl', { $scope: scope }); }); }); it('should exist', function () { expect(!!abTestCtrl).toBe(true); }); describe('when created', function () { it('should provide a variants array to the scope', function () { expect(abTestCtrl.variants instanceof Array).toBe(true); }); it('should provide an add method on the controller', function () { expect(typeof abTestCtrl.add).toBe('function'); }); it('should provide a run method on the scope', function () { expect(typeof scope.run).toBe('function'); }); }); describe('add method', function () { it('should add to the variants array', function () { // arrange expect(abTestCtrl.variants.length).toBe(0); // act abTestCtrl.add({}); // assert expect(abTestCtrl.variants.length).toBe(1); }); it('should set an index number on the variant', function () { // arrange var variant = {}; // act abTestCtrl.add(variant); // assert expect(abTestCtrl.variants[0].index).toBeDefined(); }); it('should set control on the scope if variant is the control', function () { // arrange expect(abTestCtrl.control).not.toBeDefined(); var variant = {control: true}; // act abTestCtrl.add(variant); // assert expect(abTestCtrl.control).toBe(variant); }); it('should not set control on the scope if variant isn\'t the control', function () { // arrange expect(abTestCtrl.control).not.toBeDefined(); // act abTestCtrl.add({}); // assert expect(abTestCtrl.control).not.toBeDefined(); }); }); describe('run method', function () { it('should reset the active variant', function () { // arrange abTestCtrl.variant = {active: true}; // act scope.run(); // assert expect(abTestCtrl.variant.active).toBe(false); }); it('should run an a/b test', function () { // arrange expect(abSvc.test.callCount).toBe(0); scope.frequency = -1; // act scope.run(); // assert expect(abSvc.test.callCount).toBe(1); expect(abSvc.test).toHaveBeenCalledWith(abTestCtrl.variants, scope.frequency); }); describe('when variant is returned', function () { it('should show the variant', function () { // arrange abSvcTestResult = {}; var control = {control: true, uid: 'control'}; abTestCtrl.add(control); // act scope.run(); // assert expect(abTestCtrl.variant).not.toBe(control); expect(abTestCtrl.variant).toBe(abSvcTestResult); }); it('should call abShown with the variant', function () { // arrange abSvcTestResult = {}; var control = {control: true, uid: 'control'}; abTestCtrl.add(control); // act scope.run(); // assert expect(abTestCtrl.variant).not.toBe(control); expect(abTestCtrl.variant).toBe(abSvcTestResult); }); it('should select a variant based on ab-select', function () { // arrange var variant1 = {uid: 'variant1'}; var variant2 = {uid: 'variant2'}; scope.select = function() {return 'variant2'}; abTestCtrl.add(variant1); abTestCtrl.add(variant2); // act scope.run(); // assert expect(abTestCtrl.variant).toBe(variant2); }); }); describe('when variant is not returned', function () { it('should show the control', function () { // arrange abSvcTestResult = null; var control = {control: true}; abTestCtrl.add(control); // act scope.run(); // assert expect(abTestCtrl.variant).toBe(control); }); it('should not show anything when no control', function () { // arrange abSvcTestResult = null; // act scope.run(); // assert expect(abTestCtrl.variant).not.toBeDefined(); expect(abTestCtrl.control).not.toBeDefined(); }); }); }); describe('when the model changes', function () { // Add specs }); describe('when destroyed', function () { // Add specs }); }); <|start_filename|>test/unit/ab-test.directive.js<|end_filename|> 'use strict'; describe('ab-test directive', function () { var scope, compile, abSvc, MockABSvc = function () { this.test = jasmine.createSpy('test'); this.log = jasmine.createSpy('log'); return this; }; // Use to provide any mocks needed function _provide(callback) { // Execute callback with $provide module(function ($provide) { callback($provide); }); } // Use to create the directive under test function _create(template) { var elm; // Create directive elm = compile(template)(scope); // Return return elm; } // Inject dependencies function _inject() { inject(function ($rootScope, $compile) { scope = $rootScope.$new(); compile = $compile; }); } // Call this before each test, except where you are testing for edge-cases function _setup() { // Mock the expected values _provide(function (provide) { abSvc = new MockABSvc(); provide.value('ab', abSvc); }); // Inject the code under test _inject(); } beforeEach(function () { // Load the directive's module module('ab.test.directive'); }); describe('when created', function () { beforeEach(function () { // Inject with 'normal' setup _setup(); }); it('should throw error when ab-frequency attribute not defined', function () { // arrange function invalidTemplate() { // act _create('<ab-test></ab-test>'); } // assert expect(invalidTemplate).toThrow(new Error('ab-test: ab-frequency attribute required')); }); it('should throw error when ab-frequency attribute value is not a number', function () { // arrange function invalidTemplate() { // act _create('<ab-test ab-frequency="foo"></ab-test>'); } // assert expect(invalidTemplate).toThrow(new Error('ab-test: test frequency must be a float between 0.0001 and 1')); }); it('should throw error when ab-frequency attribute value is less than 0.001', function () { // arrange function invalidTemplate() { // act _create('<ab-test ab-frequency="0.00009"></ab-test>'); } // assert expect(invalidTemplate).toThrow(new Error('ab-test: test frequency must be a float between 0.0001 and 1')); }); it('should not throw error when ab-frequency attribute value is 1', function () { // arrange function invalidTemplate() { // act _create('<ab-test ab-frequency="1"></ab-test>'); } // assert expect(invalidTemplate).not.toThrow(new Error('ab-test: test frequency must be a float between 0.0001 and 1')); }); it('should throw error when ab-frequency attribute value is more than 1', function () { // arrange function invalidTemplate() { // act _create('<ab-test ab-frequency="10"></ab-test>'); } // assert expect(invalidTemplate).toThrow(new Error('ab-test: test frequency must be a float between 0.0001 and 1')); }); it('should throw error when child variants are not found', function () { // arrange function invalidTemplate() { // act _create('<ab-test ab-frequency="0.1"></ab-test>'); } // assert expect(invalidTemplate).toThrow(new Error('ab-test: no variants found for the a/b test')); }); it('should not throw error with valid template', function () { // arrange function validTemplate() { // act _create('<ab-test ab-frequency="0.1"><ab-variant/></ab-test>'); } // assert expect(validTemplate).not.toThrow(); }); it('should accept optional ab-shown attribute', function () { // arrange scope.foo = jasmine.createSpy('foo'); // act var elm = angular.element(_create('<ab-test ab-frequency="0.1" ab-shown="foo"><ab-variant/></ab-test>')); // assert expect(elm.isolateScope().shown).toBe(scope.foo); }); it('should accept optional ab-run attribute', function () { // arrange // act // assert }); }); // inject the directive link service to test hard-to-reach corners :) describe('when created', function () { var abTestLink; // custom inject to control what gets passed to the directive link service beforeEach(function () { inject(function ($rootScope, $compile, _abTestLink_) { scope = $rootScope.$new(); compile = $compile; abTestLink = _abTestLink_; }); }); it('should call run on the scope', function () { // arrange scope.run = jasmine.createSpy('run'); scope.frequency = 1; var ctrl = {variants: [null]}; // act abTestLink(scope, null, null, ctrl); // assert expect(scope.run).toHaveBeenCalled(); }); }); describe('when the model changes', function () { // Add specs }); return describe('when destroyed', function () { // Add specs }); }); <|start_filename|>test/unit/ab-service.js<|end_filename|> 'use strict'; describe('ab-service', function () { var ab, mock = function () { return jasmine.createSpy('ab'); }; // Use to provide any mocks needed function _provide(callback) { // Execute callback with $provide module(function ($provide) { callback($provide); }); } // Use to inject the code under test function _inject() { inject(function (_ab_) { ab = _ab_; }); } // Call this before each test, except where you are testing for errors function _setup() { // Mock any expected data _provide(function (provide) { provide.value('abMfg', mock); }); // Inject the code under test _inject(); } beforeEach(function () { // Load the service's module module('ab.test.directive'); }); describe('the service', function () { beforeEach(function () { // Inject with expected values _setup(); }); it('should exist', function () { expect(!!ab).toBe(true); }); }); describe('when created', function () { it('should return an abMfg instance', function () { expect(ab.isSpy).toBe(true); }); }); describe('when destroyed', function () { // Add specs }); }); <|start_filename|>demo/index.html<|end_filename|> <!doctype html> <html lang="en" ng-app="myApp"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <title>ab-test demos</title> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/> <link rel="stylesheet" href="css/app.css"/> </head> <body> <div class="container"> <h1>AngularJS A/B Test Service & Directives <a name="top" href="#top"></a></h1> <p class="lead">The following examples are mix of <span class="label label-success">declarative</span> and <span class="label label-primary">imperative</span> A/B/n Tests that run every 20 seconds.</p> <ul> <li><a href="#Headlines">Headlines & Sub-Headlines</a></li> <li><a href="#Paragraph">Paragraph Text</a></li> <li><a href="#Testimonials">Testimonials</a></li> <li><a href="#Social">Social Proof</a></li> <li><a href="#Media">Media Mentions</a></li> <li><a href="#Buttons">Buttons (wording, size, color)</a></li> <li><a href="#Pricing">Product Pricing</a></li> <li><a href="#Promotional">Promotional Offers</a></li> <li><a href="#Images">Images (wording, size, color)</a></li> <li><a href="#Awards">Awards and Badges</a></li> </ul> <div class="row" ng-controller="HeadlinesCtrl"> <div class="col-md-12"> <h3><a name="Headlines" href="#"></a>Headlines & Sub-Headlines <a href="#top">&#8593;</a></h3> <p> One of the most common elements to A/B test on websites are headline variations. This example shows how to default an inline value that is updated with <code>ng-bind</code> (a one-way data binding from the $scope to view) once the A/B/n test is run.</p> <h1 ng-bind="headline">Include Your Children When Baking Cookies</h1> </div> </div> <hr> <div class="row" ng-controller="ParagraphCtrl"> <div class="col-md-12"> <h3> <a name="Paragraph" href="#"></a>Paragraph Text <button ng-click="runAgain()" type="button" class="btn btn-default"> <span class="glyphicon glyphicon-refresh"></span> </button> <a href="#top">&#8593;</a> </h3> <p>Changing a whole paragraph is probably more text than you want to maintain inside a JavaScript or JSON file. This example shows how how to use the <code>&lt;ab-test&gt;</code> and <code>&lt;ab-variant&gt;</code> to A/B test a large section of content.</p> <p class="lead paragraphs"> <ab-test ab-frequency="1" ab-run="runAgain" ab-shown="onShow"> <ab-variant ab-data="{foo:'optional arbitrary information'}"> Aliquam eget scelerisque ipsum. Suspendisse a mi pulvinar purus ultrices malesuada. Aliquam semper, odio scelerisque feugiat consequat, orci tortor dignissim sapien, id molestie libero ligula eget massa. Nullam pulvinar gravida eros vel sollicitudin. Nullam arcu orci, sagittis ut justo vitae, vulputate tristique leo. Curabitur condimentum, nisl et aliquam tempor, quam augue hendrerit nibh, ac convallis erat elit non sem. Quisque vestibulum dignissim arcu, non dictum eros tristique eget. </ab-variant> <ab-variant> Faucibus, mauris a vestibulum ultricies, turpis risus feugiat tellus, non porttitor tellus velit vel risus. Nulla condimentum lacus sed mauris sodales scelerisque. Nunc fermentum, lorem sed vulputate vulputate, enim est pulvinar arcu, ac molestie massa enim sed ligula. Quisque interdum lacinia lorem, non ullamcorper nisl ornare et. Nullam nec velit nec augue cursus aliquet eu ac magna. Sed consequat nulla id eros cursus, eget tincidunt enim dapibus. Mauris ultrices risus ac felis commodo condimentum. Curabitur diam tellus, mattis vel varius a, pharetra et quam. In hac habitasse platea dictumst. </ab-variant> <ab-variant> Curabitur gravida, dolor eget commodo egestas, enim ante ullamcorper nulla, quis semper enim mi id quam. Proin non varius quam. Maecenas tempus tincidunt egestas. Cras sollicitudin posuere neque, et lobortis dui volutpat dictum. Fusce imperdiet sapien sit amet massa dictum venenatis. In ultrices aliquam bibendum. Phasellus non ante et quam bibendum consectetur ut in lacus. Proin lacus metus, pellentesque at massa sed, consectetur faucibus odio. </ab-variant> <ab-variant ab-control="true"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tincidunt faucibus urna, id auctor tellus pretium eget. Vivamus tempor vitae lectus non hendrerit. Pellentesque iaculis fermentum ligula, vel volutpat sapien lacinia id. Donec nisi lorem, cursus nec mattis vitae, pulvinar ut massa. Maecenas rutrum convallis lacus. Fusce ullamcorper, arcu id interdum varius, sapien enim egestas nisl, a tempus urna odio eu ante. </ab-variant> </ab-test> </p> </div> </div> <hr> <div class="row" ng-controller="TestimonialsCtrl"> <div class="col-md-12"> <h3><a name="Testimonials" href="#"></a>Testimonials <a href="#top">&#8593;</a></h3> <p>This example shows how to A/B test using a more complex model than a simple string or number. In this case an external JSON file is used to hold the values for <code ng-non-bindable>{{testimonial}}</code> and <code ng-non-bindable>{{name}}</code>.</p> <blockquote> <p>{{testimonial}}</p> <footer>&#8212; {{name}}</footer> </blockquote> </div> </div> <hr> <div class="row" ng-controller="SocialCtrl"> <div class="col-md-12"> <h3><a name="Social" href="#"></a>Social Proof <a href="#top">&#8593;</a></h3> <p>Social proof, also known as informational social influence, is a psychological phenomenon where people assume the actions of others in an attempt to reflect correct behavior for a given situation. This example shows an example of A/B/n testing the impact of social media on conversion rates using <code ng-non-bindable>{{likes}}</code> to test different values.</p> <table class="fakebook"> <tr> <td>Wow, you should really&nbsp;</td> <td><div id="fake-like-rapper"><div class="fb-like" data-href="https://github.com/daniellmb" data-layout="button" data-action="like" data-show-faces="false" data-share="false"></div><div id="like-fake"><div class="connect_widget_button_count_including"><table class="uiGrid" cellspacing="0" cellpadding="0"><tbody><tr><td><div class="thumbs_up hidden_elem"></div></td><td><div class="undo hidden_elem"></div></td></tr><tr><td><div class="connect_widget_button_count_nub"><s></s><i></i></div></td><td><div class="connect_widget_button_count_count">{{likes}}</div></td></tr></tbody></table></div></div></div></td> <td>&nbsp;ab-test!</td> </tr> </table> </div> </div> <hr> <div class="row" ng-controller="MediaCtrl"> <div class="col-md-12"> <h3><a name="Media" href="#"></a>Media Mentions <a href="#top">&#8593;</a></h3> <p>A/B test the appeal of various media outlets on your target demographics. This example uses <code>ng-src</code> and the <code ng-non-bindable>{{asSeenOn}}</code> expression to A/B testing 3 different "as seen on" media images.</p> <h2>ab-test is super popular! <small>as seen on</small></h2> <img class="as-seen-on-media" ng-src="{{asSeenOn}}"> </div> </div> <hr> <div class="row" ng-controller="ButtonsCtrl"> <div class="col-md-12"> <h3><a name="Buttons" href="#"></a>Buttons <a href="#top">&#8593;</a></h3> <p>The presentation of "calls to action" have a massive impact on how effective they are! This example A/B tests the style of the button below from a list of 7 variants.</p> <button id="star-repo-btn" type="button" class="btn btn-lg {{style}}"> <span class="glyphicon glyphicon-star"></span> Star this Repository! </button> </div> </div> <hr> <div class="row" ng-controller="PricingCtrl"> <div class="col-md-12"> <h3><a name="Pricing" href="#"></a>Product Pricing <a href="#top">&#8593;</a></h3> <p>Coming soon, pull requests welcome :)</p> <!-- TODO --> </div> </div> <hr> <div class="row" ng-controller="PromotionalCtrl"> <div class="col-md-12"> <h3><a name="Promotional" href="#"></a>Promotional <a href="#top">&#8593;</a></h3> <p>Coming soon, pull requests welcome :)</p> <!-- TODO --> </div> </div> <hr> <div class="row" ng-controller="ImagesCtrl"> <div class="col-md-12"> <h3><a name="Images" href="#"></a>Images <a href="#top">&#8593;</a></h3> <p>Coming soon, pull requests welcome :)</p> <!-- TODO --> </div> </div> <hr> <div class="row" ng-controller="AwardsCtrl"> <div class="col-md-12"> <h3><a name="Awards" href="#"></a>Awards and Badges <a href="#top">&#8593;</a></h3> <p>Coming soon, pull requests welcome :)</p> <!-- TODO --> </div> </div> </div> <!-- load angular (from google so this page will work when hosted on GitHub.io) --> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular-animate.min.js"></script> <script src="js/demo-deps.js"></script> <script src="../ab-test.js"></script> <!-- load demo code --> <script src="js/app.js"></script> <script src="js/services.js"></script> <script src="js/controllers.js"></script> <script src="js/filters.js"></script> <script src="js/directives.js"></script> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=1401488693436528"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> </body> </html> <|start_filename|>demo/js/demo-deps.js<|end_filename|> // Bower is a much better way to manage these! Including dependencies here just for demo use on GitHub.io /* * @license * ab.js https://github.com/daniellmb/ab.js * (c) 2014 <NAME> http://daniellmb.com * License: MIT */ (function(c,a){c[a]=c[a]||{};c[a].test=function(a,e){var b=Math.random();if(1E-4<b&&(b=Math.random(),b<e)){try{var d=new Uint16Array(1);c.crypto.getRandomValues(d);b=d[0]/65536}catch(f){b=Math.random()}return a[Math.floor(b*a.length)]}return null}})(window,'AB'); /* * @license * ab-test-service https://github.com/daniellmb/ab-test-service * (c) 2014 <NAME> http://daniellmb.com * License: MIT */ angular.module("ab.test.service",[]).provider("abMfg",function(){this.$get=["AB",function(r){return function(t){t=t||{};var n=t.ab||r;if(!n)throw new Error("ab.js JavaScript library not provided");return{test:function(r,t){return n.test(r,t)},log:function(r,t,e){return n.log(r,t,e)}}}}]}).value("AB",window.AB);
daniellmb/ab-test
<|start_filename|>test/test.js<|end_filename|> 'use strict'; /** * This is an helper function to transform the input into a binary string. * The transformation is normaly handled by JSZip. * @param {String|ArrayBuffer} input the input to convert. * @return {String} the binary string. */ function toString(input) { var result = "", i, len, isArray = (typeof input !== "string"); if (isArray) { input = new Uint8Array(input); } for (i = 0, len = input.length; i < len; i++) { result += String.fromCharCode( (isArray ? input[i] : input.charCodeAt(i)) % 0xFF ); } return result; } QUnit.module("callback"); QUnit.test("JSZipUtils.getBinaryContent, text, 200 OK", function (assert) { var done = assert.async(); var p = JSZipUtils.getBinaryContent("ref/amount.txt", function (err, data) { assert.equal(err, null, "no error"); assert.equal(toString(data), "\xe2\x82\xac\x31\x35\x0a", "The content has been fetched"); done(); }); assert.strictEqual(p, undefined, 'not return promise'); }); QUnit.test("JSZipUtils.getBinaryContent, image, 200 OK", function (assert) { var done = assert.async(); var p = JSZipUtils.getBinaryContent("ref/smile.gif", function (err, data) { assert.equal(err, null, "no error"); assert.equal(toString(data).indexOf("\x47\x49\x46\x38\x37\x61"), 0, "The content has been fetched"); done(); }); assert.strictEqual(p, undefined, 'not return promise'); }); QUnit.test("JSZipUtils.getBinaryContent, 404 NOT FOUND", function (assert) { var done = assert.async(); var p = JSZipUtils.getBinaryContent("ref/nothing", function (err, data) { assert.equal(data, null, "no error"); assert.ok(err instanceof Error, "The error is an Error"); done(); }); assert.strictEqual(p, undefined, 'not return promise'); }); QUnit.module("options={callback}"); QUnit.test("JSZipUtils.getBinaryContent, text, 200 OK", function (assert) { var done = assert.async(); var p = JSZipUtils.getBinaryContent("ref/amount.txt", { callback: function (err, data) { assert.equal(err, null, "no error"); assert.equal(toString(data), "\xe2\x82\xac\x31\x35\x0a", "The content has been fetched"); done(); } }); assert.strictEqual(p, undefined, 'not return promise'); }); QUnit.test("JSZipUtils.getBinaryContent, image, 200 OK", function (assert) { var done = assert.async(); var p = JSZipUtils.getBinaryContent("ref/smile.gif", { callback: function (err, data) { assert.equal(err, null, "no error"); assert.equal(toString(data).indexOf("\x47\x49\x46\x38\x37\x61"), 0, "The content has been fetched"); done(); } }); assert.strictEqual(p, undefined, 'not return promise'); }); QUnit.test("JSZipUtils.getBinaryContent, 404 NOT FOUND", function (assert) { var done = assert.async(); var p = JSZipUtils.getBinaryContent("ref/nothing", { callback: function (err, data) { assert.equal(data, null, "no error"); assert.ok(err instanceof Error, "The error is an Error"); done(); } }); assert.strictEqual(p, undefined, 'not return promise'); }); // Guard Promise tests for IE if (typeof Promise === "undefined") { QUnit.module("Promises"); QUnit.skip("Skipping promise tests"); } else { QUnit.module("Promise (no parameters)"); QUnit.test("JSZipUtils.getBinaryContent amount, text, 200 OK", function (assert) { var done = assert.async(); JSZipUtils.getBinaryContent("ref/amount.txt").then(function (data) { assert.equal(toString(data), "\xe2\x82\xac\x31\x35\x0a", "The content has been fetched"); done(); }) .catch(function (err) { assert.equal(err, null, "no error"); done(); }); }); QUnit.test("JSZipUtils.getBinaryContent smile, image, 200 OK", function (assert) { var done = assert.async(); JSZipUtils.getBinaryContent("ref/smile.gif").then(function (data) { assert.equal(toString(data).indexOf("\x47\x49\x46\x38\x37\x61"), 0, "The content has been fetched"); done(); }).catch(function (err) { assert.equal(err, null, "no error"); done(); }); }); QUnit.test("JSZipUtils.getBinaryContent nothing, 404 NOT FOUND", function (assert) { var done = assert.async(); JSZipUtils.getBinaryContent("ref/nothing").then(function (data) { assert.equal(data, null, "no error"); done(); }).catch(function (err) { assert.ok(err instanceof Error, "The error is an Error"); done(); }); }); QUnit.module("Promise, options={}"); QUnit.test("JSZipUtils.getBinaryContent amount, text, 200 OK", function (assert) { var done = assert.async(); JSZipUtils.getBinaryContent("ref/amount.txt", {}).then(function (data) { assert.equal(toString(data), "\xe2\x82\xac\x31\x35\x0a", "The content has been fetched"); done(); }) .catch(function (err) { assert.equal(err, null, "no error"); done(); }); }); QUnit.test("JSZipUtils.getBinaryContent smile, image, 200 OK", function (assert) { var done = assert.async(); JSZipUtils.getBinaryContent("ref/smile.gif", {}).then(function (data) { assert.equal(toString(data).indexOf("\x47\x49\x46\x38\x37\x61"), 0, "The content has been fetched"); done(); }).catch(function (err) { assert.equal(err, null, "no error"); done(); }); }); QUnit.test("JSZipUtils.getBinaryContent nothing, 404 NOT FOUND", function (assert) { var done = assert.async(); JSZipUtils.getBinaryContent("ref/nothing", {}).then(function (data) { assert.equal(data, null, "no error"); done(); }).catch(function (err) { assert.ok(err instanceof Error, "The error is an Error"); done(); }); }); QUnit.module("Promise, options={progress}"); QUnit.test("JSZipUtils.getBinaryContent amount, text, 200 OK", function (assert) { var done = assert.async(); var progress = assert.async(); JSZipUtils.getBinaryContent("ref/amount.txt", { progress: function(e){ assert.ok(true, 'progress to be called'); assert.strictEqual(e.total, 6, 'total'); progress(); }}).then(function (data) { assert.equal(toString(data), "\xe2\x82\xac\x31\x35\x0a", "The content has been fetched"); done(); }) .catch(function (err) { assert.equal(err, null, "no error"); done(); }); }); QUnit.test("JSZipUtils.getBinaryContent smile, image, 200 OK", function (assert) { var done = assert.async(); var progress = assert.async(); JSZipUtils.getBinaryContent("ref/smile.gif", { progress: function(e){ assert.ok(true, 'progress to be called'); assert.strictEqual(e.total, 41, 'total'); progress(); }}).then(function (data) { assert.equal(toString(data).indexOf("\x47\x49\x46\x38\x37\x61"), 0, "The content has been fetched"); done(); }).catch(function (err) { assert.equal(err, null, "no error"); done(); }); }); QUnit.test("JSZipUtils.getBinaryContent nothing, 404 NOT FOUND", function (assert) { var done = assert.async(); JSZipUtils.getBinaryContent("ref/nothing", { progress: function(e){ }}).then(function (data) { assert.equal(data, null, "no error"); done(); }).catch(function (err) { assert.ok(err instanceof Error, "The error is an Error"); done(); }); }); } // Promise tests // enforcing Stuk's coding style // vim: set shiftwidth=4 softtabstop=4: <|start_filename|>bower.json<|end_filename|> { "name": "jszip-utils", "version": "0.1.0", "homepage": "https://github.com/Stuk/jszip-utils", "authors": [ "<NAME> <<EMAIL>>", "<NAME> <<EMAIL>>" ], "description": "A collection of cross-browser utilities to go along with JSZip.", "main": "dist/jszip-utils.js", "keywords": [ "JSZip", "ajax", "cross browser", "IE", "Internet Explorer" ], "license": "MIT or GPLv3", "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests" ] } <|start_filename|>Gruntfile.js<|end_filename|> /*jshint node: true */ "use strict"; module.exports = function(grunt) { // https://wiki.saucelabs.com/display/DOCS/Platform+Configurator // A lot of the browsers seem to time out with Saucelab's unit testing // framework. Here are the browsers that work that get enough coverage for our // needs. var browsers = [ {browserName: "chrome"}, {browserName: "firefox", platform: "Linux"}, {browserName: "internet explorer"} ]; var tags = []; if (process.env.TRAVIS_PULL_REQUEST && process.env.TRAVIS_PULL_REQUEST != "false") { tags.push("pr" + process.env.TRAVIS_PULL_REQUEST); } else if (process.env.TRAVIS_BRANCH) { tags.push(process.env.TRAVIS_BRANCH); } var postBundleWithLicense = function(err, src, done) { if (!err) { // add the license var license = require('fs').readFileSync('lib/license_header.js'); done(err, license + src); } else { done(err); } }; grunt.initConfig({ connect: { server: { options: { base: "", port: 8080 } } }, 'saucelabs-qunit': { all: { options: { urls: ["http://127.0.0.1:8080/test/index.html?hidepassed"], build: process.env.TRAVIS_JOB_ID, testname: "qunit tests", tags: tags, // Tests have statusCheckAttempts * pollInterval seconds to complete pollInterval: 2000, statusCheckAttempts: 15, "max-duration": 30, browsers: browsers, maxRetries: 2 } } }, jshint: { options: { jshintrc: "./.jshintrc" }, all: ['./lib/*.js', "Gruntfile.js"] }, browserify: { "utils": { files: { 'dist/jszip-utils.js': ['lib/index.js'] }, options: { standalone: 'JSZipUtils', postBundleCB: postBundleWithLicense } }, "utils-ie": { files: { 'dist/jszip-utils-ie.js': ['lib/index_IE.js'] }, options: { postBundleCB: postBundleWithLicense } } }, uglify: { options: { report: 'gzip', mangle: true, output: { comments: /^!/ } }, "jszip-utils": { src: 'dist/jszip-utils.js', dest: 'dist/jszip-utils.min.js' }, "jszip-utils-ie": { src: 'dist/jszip-utils-ie.js', dest: 'dist/jszip-utils-ie.min.js' } } }); grunt.loadNpmTasks("grunt-saucelabs"); grunt.loadNpmTasks("grunt-contrib-connect"); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); // A task to cause Grunt to sit and wait, keeping the test server running grunt.registerTask("wait", function() { this.async(); }); grunt.registerTask("test-local", ["build", "connect", "wait"]); grunt.registerTask("test-remote", ["build", "connect", "saucelabs-qunit"]); if (process.env.SAUCE_USERNAME && process.env.SAUCE_ACCESS_KEY) { grunt.registerTask("test", ["jshint", "test-remote"]); } else { grunt.registerTask("test", ["jshint", "test-local"]); } grunt.registerTask("build", ["browserify", "uglify"]); grunt.registerTask("default", ["jshint", "build"]); };
gmpovio/jszip-utils
<|start_filename|>scripts/vite.js<|end_filename|> const path = require('path'); const fs = require('fs-extra'); const minimist = require('minimist'); const prettier = require('prettier'); const prettierOpt = require('./../arco-design-pro-vite/.prettierrc.js'); const params = minimist(process.argv.slice(2)); const isSimple = params.simple; const templatePath = path.resolve(__dirname, '../arco-design-pro-vite'); const projectPath = params.projectPath || path.resolve(__dirname, '../examples/arco-design-pro-vite'); const maps = { 'src/api': 'src/api', 'src/assets': 'src/assets', 'src/components': 'src/components', 'src/config': 'src/config', 'src/hooks': 'src/hooks', 'src/layout': 'src/layout', 'src/locale': 'src/locale', 'src/mock': 'src/mock', 'src/router': 'src/router', 'src/store': 'src/store', 'src/types': 'src/types', 'src/utils': 'src/utils', 'src/views': 'src/views', '.eslintrc.js': '.eslintrc.js', '.eslintignore': '.eslintignore', '.stylelintrc.js': '.stylelintrc.js', '.prettierrc.js': '.prettierrc.js', 'tsconfig.json': 'tsconfig.json', }; fs.copySync(templatePath, projectPath, { filter: (src) => !src.startsWith(path.resolve(templatePath, 'node_modules')), }); const gitignorePath = path.resolve( __dirname, '../arco-design-pro-vite/gitignore' ); const gitignorePath2 = path.resolve( __dirname, '../arco-design-pro-vite/.gitignore' ); Object.keys(maps).forEach((src) => { if (typeof maps[src] === 'string') { fs.copySync( path.resolve(__dirname, '../arco-design-pro-vite', src), path.resolve(projectPath, maps[src]) ); } if (typeof maps[src] === 'object') { fs.copySync( path.resolve(__dirname, '../arco-design-pro-vite', src), path.resolve(projectPath, maps[src].dest), { filter: maps[src].filter } ); } if (fs.existsSync(gitignorePath)) { fs.copySync(gitignorePath, path.resolve(projectPath, '.gitignore')); } else if (fs.existsSync(gitignorePath2)) { fs.copySync(gitignorePath2, path.resolve(projectPath, '.gitignore')); } }); // simple mode const simpleOptions = [ { base: 'src/views', accurate: ['dashboard/monitor'], // Accurate to delete excludes: ['login', 'dashboard', 'not-found'], }, { base: 'src/api', excludes: ['dashboard', 'interceptor', 'user', 'message'], }, { base: 'src/router/routes/modules', excludes: ['index', 'dashboard'], }, ]; const regSum = /\/\*{2} simple( end)? \*\//g; const matchReg = /(\/\*{2} simple \*\/)(?:(?!\/\*{2} simple end \*\/).|\n)*?\/\*{2} simple end \*\//gm; const simplifyFiles = [ 'locale/en-US.ts', 'locale/zh-CN.ts', 'mock/index.ts', 'router/routes/modules/dashboard.ts', ]; const runSimpleMode = () => { deleteFiles(); simplifyFiles.forEach((el) => { const file = path.resolve(projectPath, path.join('src', el)); fs.readFile(file, 'utf8', (err, content) => { if (err) return console.error(err); const main = content.replace(matchReg, ''); const formatTxt = prettier.format(main, { ...prettierOpt, parser: 'babel', }); fs.writeFile(file, formatTxt, 'utf8', function (err) { if (err) return console.error(err); }); }); }); }; const deleteFiles = () => { simpleOptions.forEach((option) => { const baseDir = path.resolve(projectPath, option.base); fs.readdir(baseDir, (error, files) => { files.forEach((fileName) => { if ( option.excludes && option.excludes.find((name) => new RegExp(`^${name}(.(ts|js|vue|json|jsx|tsx))?$`).test(fileName) ) ) { return; } fs.remove(path.join(baseDir, fileName)); }); }); if (option.accurate) { option.accurate.forEach((el) => { fs.remove(path.join(baseDir, el)); }); } }); }; const runNormalMode = () => { simplifyFiles.forEach((el) => { const file = path.resolve(projectPath, path.join('src', el)); fs.readFile(file, 'utf8', (err, content) => { if (err) return console.error(err); const result = content.replace(regSum, ''); const formatTxt = prettier.format(result, { ...prettierOpt, parser: 'babel', }); fs.writeFile(file, formatTxt, 'utf8', function (err) { if (err) return console.error(err); }); }); }); }; if (isSimple) { runSimpleMode(); } else { runNormalMode(); }
deluxebear/arco-design-pro-vue
<|start_filename|>venv/Lib/site-packages/numpy/distutils/checks/cpu_sse.c<|end_filename|> #include <xmmintrin.h> int main(void) { __m128 a = _mm_add_ps(_mm_setzero_ps(), _mm_setzero_ps()); return (int)_mm_cvtss_f32(a); } <|start_filename|>venv/Lib/site-packages/numpy/distutils/checks/cpu_sse2.c<|end_filename|> #include <emmintrin.h> int main(void) { __m128i a = _mm_add_epi16(_mm_setzero_si128(), _mm_setzero_si128()); return _mm_cvtsi128_si32(a); } <|start_filename|>venv/Lib/site-packages/numpy/distutils/checks/cpu_ssse3.c<|end_filename|> #include <tmmintrin.h> int main(void) { __m128i a = _mm_hadd_epi16(_mm_setzero_si128(), _mm_setzero_si128()); return (int)_mm_cvtsi128_si32(a); } <|start_filename|>venv/Lib/site-packages/numpy/distutils/checks/cpu_avx512_knm.c<|end_filename|> #include <immintrin.h> int main(void) { __m512i a = _mm512_setzero_si512(); __m512 b = _mm512_setzero_ps(); /* 4FMAPS */ b = _mm512_4fmadd_ps(b, b, b, b, b, NULL); /* 4VNNIW */ a = _mm512_4dpwssd_epi32(a, a, a, a, a, NULL); /* VPOPCNTDQ */ a = _mm512_popcnt_epi64(a); a = _mm512_add_epi32(a, _mm512_castps_si512(b)); return _mm_cvtsi128_si32(_mm512_castsi512_si128(a)); } <|start_filename|>venv/Lib/site-packages/numpy/distutils/checks/cpu_fma3.c<|end_filename|> #include <xmmintrin.h> #include <immintrin.h> int main(void) { __m256 a = _mm256_fmadd_ps(_mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps()); return (int)_mm_cvtss_f32(_mm256_castps256_ps128(a)); } <|start_filename|>venv/Lib/site-packages/numpy/distutils/checks/cpu_f16c.c<|end_filename|> #include <emmintrin.h> #include <immintrin.h> int main(void) { __m128 a = _mm_cvtph_ps(_mm_setzero_si128()); __m256 a8 = _mm256_cvtph_ps(_mm_setzero_si128()); return (int)(_mm_cvtss_f32(a) + _mm_cvtss_f32(_mm256_castps256_ps128(a8))); } <|start_filename|>venv/Lib/site-packages/numpy/core/include/numpy/arrayobject.h<|end_filename|> #ifndef Py_ARRAYOBJECT_H #define Py_ARRAYOBJECT_H #include "ndarrayobject.h" #include "npy_interrupt.h" #ifdef NPY_NO_PREFIX #include "noprefix.h" #endif #endif <|start_filename|>venv/Lib/site-packages/numpy/distutils/checks/cpu_popcnt.c<|end_filename|> #ifdef _MSC_VER #include <nmmintrin.h> #else #include <popcntintrin.h> #endif int main(void) { long long a = 0; int b; #ifdef _MSC_VER #ifdef _M_X64 a = _mm_popcnt_u64(1); #endif b = _mm_popcnt_u32(1); #else #ifdef __x86_64__ a = __builtin_popcountll(1); #endif b = __builtin_popcount(1); #endif return (int)a + b; } <|start_filename|>venv/Lib/site-packages/numpy/distutils/checks/cpu_avx512_icl.c<|end_filename|> #include <immintrin.h> int main(void) { /* VBMI2 */ __m512i a = _mm512_shrdv_epi64(_mm512_setzero_si512(), _mm512_setzero_si512(), _mm512_setzero_si512()); /* BITLAG */ a = _mm512_popcnt_epi8(a); /* VPOPCNTDQ */ a = _mm512_popcnt_epi64(a); return _mm_cvtsi128_si32(_mm512_castsi512_si128(a)); }
EkremBayar/bayar
<|start_filename|>src/ultimap.c<|end_filename|> /* Ultimap implements the recording of all the branches in the target process Requires dbvm for process selection */ #pragma warning( disable: 4100 4101 4213) #include <ntifs.h> #include "ultimap.h" #include "vmxhelper.h" #include "DBKFunc.h" #include <windef.h> #include "ultimap2\apic.h" JUMPBACK perfmonJumpBackLocation; /* #ifdef AMD64 volatile PAPIC APIC_BASE=0; //(PAPIC)0xfffffffffffe0000; #else volatile PAPIC APIC_BASE=0; //(PAPIC)0xfffe0000; #endif */ BOOL SaveToFile; //If set it will save the results to a file instead of sending a message to the usermode app that is watching the data HANDLE FileHandle; int MaxDataBlocks=1; KSEMAPHORE DataBlockSemaphore; //governs how many events can be active at a time FAST_MUTEX DataBlockMutex; //when a thread passes the semaphore this is used to pick a DataBlock typedef struct { BOOL Available; PBTS Data; int DataSize; int CpuID; KEVENT DataReady; } _DataBlock; _DataBlock *DataBlock; PVOID *DataReadyPointerList; int perfmon_interrupt_centry(void); /* use apic.* now #define MSR_IA32_APICBASE 0x0000001b void setup_APIC_BASE(void) { PHYSICAL_ADDRESS Physical_APIC_BASE; DbgPrint("Fetching the APIC base\n"); Physical_APIC_BASE.QuadPart=readMSR(MSR_IA32_APICBASE) & 0xFFFFFFFFFFFFF000ULL; DbgPrint("Physical_APIC_BASE=%p\n", Physical_APIC_BASE.QuadPart); APIC_BASE = (PAPIC)MmMapIoSpace(Physical_APIC_BASE, sizeof(APIC), MmNonCached); DbgPrint("APIC_BASE at %p\n", APIC_BASE); } void clean_APIC_BASE(void) { if (APIC_BASE) MmUnmapIoSpace((PVOID)APIC_BASE, sizeof(APIC)); }*/ void ultimap_flushBuffers_all(UINT_PTR param) { DbgPrint("Calling perfmon_interrupt_centry() manually\n"); if (DS_AREA[cpunr()]) //don't call if ultimap has been disabled { perfmon_interrupt_centry(); enableInterrupts(); //the handler disables it on exit so re-enable it } } void ultimap_flushBuffers(void) { //call this when the buffer of the current cpu needs to be flushed and handled int i; int count; DbgPrint("ultimap_flushBuffers\n"); //what it does: //for each cpu emulate a "buffer filled" event. //the handler then copies all the current data to a temporary buffer and signals the worker thread to deal with it. If there is no available worker thread it waits forEachCpuPassive(ultimap_flushBuffers_all,0); DbgPrint("ultimap_flushBuffers_all has returned\n"); //it returned and all worker thread are currently working on this data (it only returns when it has send a worker to work) //now wait for all workers to finish //do this by aquiring all semaphore slots and waiting for them to return again //forEachCpuPassive(ultimap_flushBuffers_all,0); //DbgPrint("ultimap_flushBuffers_all has returned a second time\n"); //this means that the previous blocks have been dealt with //actually... no, this is no guarantee. Now that the buffers are empty handling is so fast that while block 2,3,4,5 and 6 are still being handled block 1 can become available multiple times } NTSTATUS ultimap_continue(PULTIMAPDATAEVENT data) /* Called from usermode to signal that the data has been handled */ { DbgPrint("ultimap_continue\n"); MmUnmapLockedPages((PVOID)(UINT_PTR)data->Address, (PMDL)(UINT_PTR)data->Mdl); IoFreeMdl((PMDL)(UINT_PTR)data->Mdl); ExFreePool((PVOID)(UINT_PTR)data->KernelAddress); //this memory is not needed anymore if (DataBlock) DataBlock[data->Block].Available=TRUE; KeReleaseSemaphore(&DataBlockSemaphore, 1, 1, FALSE); //Let the next block go through DbgPrint("Released semaphore\n"); return STATUS_SUCCESS; } NTSTATUS ultimap_waitForData(ULONG timeout, PULTIMAPDATAEVENT data) /* Called from usermode to wait for data */ { NTSTATUS r; LARGE_INTEGER wait; PKWAIT_BLOCK waitblock; if (DataBlock) { waitblock=ExAllocatePool(NonPagedPool, MaxDataBlocks*sizeof(KWAIT_BLOCK)); wait.QuadPart=-10000LL * timeout; //Wait for the events in the list //If an event is triggered find out which one is triggered, then map that block into the usermode space and return the address and block //That block will be needed to continue if (timeout==0xffffffff) //infinite wait r=KeWaitForMultipleObjects(MaxDataBlocks, DataReadyPointerList, WaitAny, UserRequest, UserMode, TRUE, NULL, waitblock); else r=KeWaitForMultipleObjects(MaxDataBlocks, DataReadyPointerList, WaitAny, UserRequest, UserMode, TRUE, &wait, waitblock); ExFreePool(waitblock); data->Block=r-STATUS_WAIT_0; if (data->Block <= MaxDataBlocks) { //Map this block to usermode ExAcquireFastMutex(&DataBlockMutex); if (DataBlock) { data->KernelAddress=(UINT64)DataBlock[data->Block].Data; data->Mdl=(UINT64)IoAllocateMdl(DataBlock[data->Block].Data, DataBlock[data->Block].DataSize, FALSE, FALSE, NULL); if (data->Mdl) { MmBuildMdlForNonPagedPool((PMDL)(UINT_PTR)data->Mdl); data->Address=(UINT_PTR)MmMapLockedPagesSpecifyCache((PMDL)(UINT_PTR)data->Mdl, UserMode, MmCached, NULL, FALSE, NormalPagePriority); if (data->Address) { data->Size=DataBlock[data->Block].DataSize; data->CpuID=DataBlock[data->Block].CpuID; r=STATUS_SUCCESS; } else r=STATUS_UNSUCCESSFUL; } else r=STATUS_UNSUCCESSFUL; } else r=STATUS_UNSUCCESSFUL; ExReleaseFastMutex(&DataBlockMutex); return r; } else return STATUS_UNSUCCESSFUL; } else return STATUS_UNSUCCESSFUL; } /* void apic_clearPerfmon() { APIC_BASE->LVT_Performance_Monitor.a = APIC_BASE->LVT_Performance_Monitor.a & 0xff; APIC_BASE->EOI.a = 0; } */ void ultimap_cleanstate() { apic_clearPerfmon(); } int perfmon_interrupt_centry(void) { KIRQL old = PASSIVE_LEVEL; int changedIRQL = 0; void *temp; int causedbyme=(DS_AREA[cpunr()]->BTS_IndexBaseAddress>=DS_AREA[cpunr()]->BTS_InterruptThresholdAddress); UINT_PTR blocksize; DbgPrint("perfmon_interrupt_centry\n", cpunr()); if (causedbyme) ultimap_cleanstate(); blocksize=(UINT_PTR)(DS_AREA[cpunr()]->BTS_IndexBaseAddress-DS_AREA[cpunr()]->BTS_BufferBaseAddress); { if (KeGetCurrentIrql() < DISPATCH_LEVEL) { //When called by the pre-emptive caller changedIRQL = 1; old = KeRaiseIrqlToDpcLevel(); } DbgPrint("Entry cpunr=%d\n", cpunr()); DbgPrint("Entry threadid=%d\n", PsGetCurrentThreadId()); temp=ExAllocatePool(NonPagedPool, blocksize); if (temp) { RtlCopyMemory(temp, (PVOID *)(UINT_PTR)DS_AREA[cpunr()]->BTS_BufferBaseAddress, blocksize); DbgPrint("temp=%p\n", temp); DS_AREA[cpunr()]->BTS_IndexBaseAddress=DS_AREA[cpunr()]->BTS_BufferBaseAddress; //don't reset on alloc error } else { DbgPrint("ExAllocatePool has failed\n"); KeLowerIrql(old); disableInterrupts(); return causedbyme; } if (changedIRQL) KeLowerIrql(old); //should be passive mode, taskswitches and cpu switches will happen now (When this returns, I may not be on the same interrupt as I was when I started) if (SaveToFile) { IO_STATUS_BLOCK iosb; NTSTATUS r; //Instead of sending the data to a usermode app it was chosen to store the data to a file for later usage DbgPrint("Writing buffer to disk\n"); r=ZwWriteFile(FileHandle, NULL, NULL, NULL, &iosb, temp, (ULONG)blocksize, NULL, NULL); DbgPrint("Done Writing. Result=%x\n", r); } else { DbgPrint("Waiting till there is a block free\n"); //When all workers are busy do not continue if ((DataBlock) && (KeWaitForSingleObject(&DataBlockSemaphore, Executive, KernelMode, FALSE, NULL) == STATUS_SUCCESS)) { int currentblock; int i; //Enter a critical section and choose a block DbgPrint("Acquired semaphore. Now picking a usable datablock\n"); ExAcquireFastMutex(&DataBlockMutex); DbgPrint("Acquired mutex. Looking for a Datablock that can be used\n"); if (DataBlock) { currentblock=-1; for (i=0; i< MaxDataBlocks; i++) { if (DataBlock[i].Available) //look for a block that is set as available { currentblock=i; DataBlock[currentblock].Available=FALSE; //not available anymore break; } } } else currentblock=-1; if (currentblock>=0) { DbgPrint("Using datablock %d\n", currentblock); DataBlock[currentblock].Data=temp; DataBlock[currentblock].DataSize=(int)blocksize; DataBlock[currentblock].CpuID=cpunr(); DbgPrint("Calling KeSetEvent/KeWaitForSingleObject\n"); KeSetEvent(&DataBlock[currentblock].DataReady, 1, FALSE); //Trigger a worker thread to start working } ExReleaseFastMutex(&DataBlockMutex); //DbgPrint("Released mutex\n"); } else { DbgPrint("if ((DataBlock) && (KeWaitForSingleObject(&DataBlockSemaphore, Executive, KernelMode, FALSE, NULL) == STATUS_SUCCESS)) failed\n"); } } //and return to the caller process disableInterrupts(); return causedbyme; } } #ifdef AMD64 extern void perfmon_interrupt(); #else _declspec( naked ) void perfmon_interrupt( void ) { __asm{ cld push ebp mov ebp,esp //store state pushad xor eax,eax mov ax,ds push eax mov ax,es push eax mov ax,fs push eax mov ax,gs push eax mov ax,0x23 //0x10 should work too, but even windows itself is using 0x23 mov ds,ax mov es,ax mov gs,ax mov ax,0x30 mov fs,ax call perfmon_interrupt_centry cmp eax,1 //set flag //restore state pop gs pop fs pop es pop ds popad pop ebp je skip_original_perfmon jmp far [perfmonJumpBackLocation] skip_original_perfmon: // commented out: I don't think a APIC interrupt has an errorcode.... add esp,4 //undo errorcode push iretd } } #endif VOID ultimap_pause_dpc(IN struct _KDPC *Dpc, IN PVOID DeferredContext, IN PVOID SystemArgumen1, IN PVOID SystemArgument2) { vmx_ultimap_pause(); } void ultimap_pause(void) { forEachCpu(ultimap_pause_dpc, NULL, NULL, NULL, NULL); } VOID ultimap_resume_dpc(IN struct _KDPC *Dpc, IN PVOID DeferredContext, IN PVOID SystemArgumen1, IN PVOID SystemArgument2) { vmx_ultimap_resume(); } void ultimap_resume(void) { forEachCpu(ultimap_resume_dpc, NULL, NULL, NULL, NULL); } VOID ultimap_disable_dpc(IN struct _KDPC *Dpc, IN PVOID DeferredContext, IN PVOID SystemArgumen1, IN PVOID SystemArgument2) { int i; //DbgPrint("ultimap_disable_dpc()\n"); if (vmxusable) { i=vmx_ultimap_disable(); if (DS_AREA[cpunr()]) { ExFreePool(DS_AREA[cpunr()]); DS_AREA[cpunr()]=NULL; } } } void ultimap_disable(void) { void *clear = NULL; if (DataBlock) { int i; forEachCpu(ultimap_disable_dpc, NULL, NULL, NULL, NULL); if (SaveToFile && FileHandle) { ZwClose(FileHandle); FileHandle=NULL; } //all logging should have stopped now //Trigger all events waking up each thread that was waiting for the events ExAcquireFastMutex(&DataBlockMutex); for (i=0; i<MaxDataBlocks; i++) KeSetEvent(&DataBlock[i].DataReady,0, FALSE); ExFreePool(DataBlock); DataBlock=NULL; if (DataReadyPointerList) { ExFreePool(DataReadyPointerList); DataReadyPointerList=NULL; } ExReleaseFastMutex(&DataBlockMutex); HalSetSystemInformation(HalProfileSourceInterruptHandler, sizeof(PVOID*), &clear); //unhook the perfmon interrupt } } VOID ultimap_setup_dpc(IN struct _KDPC *Dpc, IN PVOID DeferredContext, IN PVOID SystemArgument1, IN PVOID SystemArgument2) /* initializes ultimap. If the DS_AREA_SIZE is bigger than 0 it will allocate the required region (the usual option, but if not used it could be a LBR only thing) Call this for each processor */ { struct { UINT64 cr3; UINT64 dbgctl_msr; int DS_AREA_SIZE; } *params; params=DeferredContext; DS_AREA_SIZE=params->DS_AREA_SIZE; if (DS_AREA_SIZE == 0) { DbgPrint("DS_AREA_SIZE==0\n"); return; } DbgPrint("ultimap(%I64x, %I64x, %d)", (UINT64)params->cr3, (UINT64)params->dbgctl_msr, params->DS_AREA_SIZE); DS_AREA[cpunr()]=NULL; if (params->DS_AREA_SIZE) { DS_AREA[cpunr()]=ExAllocatePool(NonPagedPool, params->DS_AREA_SIZE); if (DS_AREA[cpunr()] == NULL) { DbgPrint("ExAllocatePool failed\n"); return; } RtlZeroMemory(DS_AREA[cpunr()], params->DS_AREA_SIZE); DbgPrint("DS_AREA[%d]=%p", cpunr(), DS_AREA[cpunr()]); //Initialize the DS_AREA DS_AREA[cpunr()]->BTS_BufferBaseAddress=(QWORD)(UINT_PTR)DS_AREA[cpunr()]+sizeof(DS_AREA_MANAGEMENT); DS_AREA[cpunr()]->BTS_BufferBaseAddress+=sizeof(BTS); DS_AREA[cpunr()]->BTS_BufferBaseAddress-=DS_AREA[cpunr()]->BTS_BufferBaseAddress % sizeof(BTS); DS_AREA[cpunr()]->BTS_IndexBaseAddress=DS_AREA[cpunr()]->BTS_BufferBaseAddress; DS_AREA[cpunr()]->BTS_AbsoluteMaxAddress=(QWORD)(UINT_PTR)DS_AREA[cpunr()]+params->DS_AREA_SIZE-sizeof(BTS); DS_AREA[cpunr()]->BTS_AbsoluteMaxAddress-=DS_AREA[cpunr()]->BTS_AbsoluteMaxAddress % sizeof(BTS); DS_AREA[cpunr()]->BTS_AbsoluteMaxAddress++; DS_AREA[cpunr()]->BTS_InterruptThresholdAddress=(DS_AREA[cpunr()]->BTS_AbsoluteMaxAddress-1) - 4*sizeof(BTS); } if (params->dbgctl_msr & (1 << 8)) { //hook the perfmon interrupt. First get the interrupt assigned (usually 0xfe, but let's be sure and read it from the apic) int perfmonIVT=(APIC_BASE->LVT_Performance_Monitor.a) & 0xff; DbgPrint("APIC_BASE->LVT_Performance_Monitor.a=%x\n", APIC_BASE->LVT_Performance_Monitor.a); if (perfmonIVT==0) //if not setup at all then set it up now perfmonIVT=0xfe; APIC_BASE->LVT_Performance_Monitor.a=perfmonIVT; //clear mask flag if it was set DbgPrint("APIC_BASE->LVT_Performance_Monitor.a=%x\n", APIC_BASE->LVT_Performance_Monitor.a); /* if (inthook_HookInterrupt((unsigned char)perfmonIVT, getCS(), (ULONG_PTR)perfmon_interrupt, &perfmonJumpBackLocation)) DbgPrint("Interrupt hooked\n"); else DbgPrint("Failed to hook interrupt\n"); */ } //and finally activate the mapping if (vmxusable) { vmx_ultimap((UINT_PTR)params->cr3, params->dbgctl_msr, DS_AREA[cpunr()]); } else { DbgPrint("vmxusable is false. So no ultimap for you!!!\n"); } } void ultimapapc(PKAPC Apc, PKNORMAL_ROUTINE NormalRoutine, PVOID NormalContext, PVOID SystemArgument1, PVOID SystemArgument2) { EFLAGS e = getEflags(); DbgPrint("ultimapapc call for cpu %d ( IF=%d IRQL=%d)\n", KeGetCurrentProcessorNumber(), e.IF, KeGetCurrentIrql()); DbgPrint("SystemArgument1=%x\n", *(PULONG)SystemArgument1); DbgPrint("tid=%x\n", PsGetCurrentThreadId()); DbgPrint("Apc=%p\n", Apc); } void ultimapapcnormal(PVOID arg1, PVOID arg2, PVOID arg3) { EFLAGS e = getEflags(); DbgPrint("ultimapapcnormal call for cpu %d ( IF=%d IRQL=%d)\n", KeGetCurrentProcessorNumber(), e.IF, KeGetCurrentIrql()); DbgPrint("tid=%x\n", PsGetCurrentThreadId()); ultimap_flushBuffers(); return; } KAPC kApc[128]; volatile LONG apcnr = 0; void perfmon_hook(__in struct _KINTERRUPT *Interrupt, __in PVOID ServiceContext) { int i = InterlockedIncrement(&apcnr) % 128; EFLAGS e = getEflags(); DbgPrint("permon_hook call for cpu %d ( IF=%d IRQL=%d)\n", KeGetCurrentProcessorNumber(), e.IF, KeGetCurrentIrql()); DbgPrint("kApc=%p\n", &kApc); //switch buffer pointers //call DPC for ultimap for this cpu //todo: if this is buggy use a dpc instead to create the apc. (slower) KeInitializeApc(&kApc[i], (PKTHREAD)PsGetCurrentThread(), 0, (PKKERNEL_ROUTINE)ultimapapc, NULL, (PKNORMAL_ROUTINE)ultimapapcnormal, KernelMode, 0 ); KeInsertQueueApc(&kApc[i], NULL, NULL, 0); DbgPrint("after KeInsertQueueApc"); //perfmon_interrupt_centry(); ultimap_cleanstate(); DbgPrint("permon_return"); } void *pperfmon_hook = (void*)perfmon_hook; NTSTATUS ultimap(UINT64 cr3, UINT64 dbgctl_msr, int _DS_AREA_SIZE, BOOL savetofile, WCHAR *filename, int handlerCount) { struct { UINT64 cr3; UINT64 dbgctl_msr; int DS_AREA_SIZE; } params; int i; if (handlerCount>64) return STATUS_UNSUCCESSFUL; //create file SaveToFile=savetofile; if (SaveToFile) { UNICODE_STRING usFile; OBJECT_ATTRIBUTES oaFile; IO_STATUS_BLOCK iosb; NTSTATUS r; RtlInitUnicodeString(&usFile, filename); InitializeObjectAttributes(&oaFile,&usFile, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL,NULL); DbgPrint("Creating file %S", usFile.Buffer); FileHandle=0; r=ZwCreateFile(&FileHandle,SYNCHRONIZE|FILE_READ_DATA|FILE_APPEND_DATA | GENERIC_ALL,&oaFile,&iosb,0,FILE_ATTRIBUTE_NORMAL,0,FILE_SUPERSEDE, FILE_SEQUENTIAL_ONLY | FILE_SYNCHRONOUS_IO_NONALERT,NULL,0); DbgPrint("ZwCreateFile=%x\n", r); } MaxDataBlocks=handlerCount; KeInitializeSemaphore(&DataBlockSemaphore, MaxDataBlocks, MaxDataBlocks); ExInitializeFastMutex(&DataBlockMutex); //Datablock inits DataBlock=ExAllocatePool(NonPagedPool, sizeof(_DataBlock) * MaxDataBlocks); DataReadyPointerList=ExAllocatePool(NonPagedPool, sizeof(PVOID) * MaxDataBlocks); RtlZeroMemory(DataBlock, sizeof(_DataBlock) * MaxDataBlocks); RtlZeroMemory(DataReadyPointerList, sizeof(PVOID) * MaxDataBlocks); if ((DataBlock) && (DataReadyPointerList)) { NTSTATUS r; for (i=0; i< MaxDataBlocks; i++) { //DataBlock[i]-> DataBlock[i].Data=NULL; KeInitializeEvent(&DataBlock[i].DataReady, SynchronizationEvent , FALSE); DataBlock[i].Available=TRUE; DataReadyPointerList[i]=&DataBlock[i].DataReady; } params.cr3=cr3; params.dbgctl_msr=dbgctl_msr; params.DS_AREA_SIZE=_DS_AREA_SIZE; r=HalSetSystemInformation(HalProfileSourceInterruptHandler, sizeof(PVOID*), &pperfmon_hook); //hook the perfmon interrupt DbgPrint("HalSetSystemInformation returned %x\n", r); forEachCpu(ultimap_setup_dpc, &params, NULL, NULL, NULL); return STATUS_SUCCESS; } else { DbgPrint("Failure allocating DataBlock and DataReadyPointerList\n"); return STATUS_MEMORY_NOT_ALLOCATED; } } <|start_filename|>src/amd64/dbkfunca.asm<|end_filename|> ;RCX: 1st integer argument ;RDX: 2nd integer argument ;R8: 3rd integer argument ;R9: 4th integer argument ;I should probably start converting to inrinsics _TEXT SEGMENT 'CODE' PUBLIC getCS getCS: mov ax,cs ret PUBLIC getSS getSS: mov ax,ss ret PUBLIC getDS getDS: mov ax,ds ret PUBLIC getES getES: mov ax,es ret PUBLIC getFS getFS: mov ax,fs ret PUBLIC getGS getGS: mov ax,gs ret PUBLIC GetTR GetTR: STR AX ret PUBLIC GetLDT GetLDT: SLDT ax ret PUBLIC GetGDT GetGDT: SGDT [rcx] ret PUBLIC _fxsave _fxsave: fxsave [rcx] ret PUBLIC getRSP getRSP: mov rax,rsp add rax,8 ;undo the call push ret PUBLIC getRBP getRBP: push rbp pop rax ret PUBLIC getRAX getRAX: ret PUBLIC getRBX getRBX: mov rax,rbx ret PUBLIC getRCX getRCX: mov rax,rcx ret PUBLIC getRDX getRDX: mov rax,rdx ret PUBLIC getRSI getRSI: mov rax,rsi ret PUBLIC getRDI getRDI: mov rax,rdi ret PUBLIC getR8 getR8: mov rax,r8 ret PUBLIC getR9 getR9: mov rax,r9 ret PUBLIC getR10 getR10: mov rax,r10 ret PUBLIC getR11 getR11: mov rax,r11 ret PUBLIC getR12 getR12: mov rax,r12 ret PUBLIC getR13 getR13: mov rax,r13 ret PUBLIC getR14 getR14: mov rax,r14 ret PUBLIC getR15 getR15: mov rax,r15 ret PUBLIC getAccessRights getAccessRights: xor rax,rax lar rax,rcx jnz getAccessRights_invalid shr rax,8 and rax,0f0ffh ret getAccessRights_invalid: mov rax,010000h ret PUBLIC getSegmentLimit getSegmentLimit: xor rax,rax lsl rax,rcx ret _TEXT ENDS END <|start_filename|>src/vmxoffload.c<|end_filename|> /* sets up all the needed data structures copies dbvm into physical memory jumps into dbvm's os entry point */ #pragma warning( disable: 4100 4103 4152 4189 4456) #ifndef AMD64 #pragma warning( disable: 4740) #endif #include <ntifs.h> #include <windef.h> #include "dbkfunc.h" #include "vmxoffload.h" #include "vmxhelper.h" #ifdef TOBESIGNED #include "sigcheck.h" #endif unsigned char *vmm; #pragma pack(2) struct { WORD limit; UINT_PTR base; } NewGDTDescriptor; #pragma pack() #pragma pack(1) typedef struct _INITVARS { UINT64 loadedOS; //physical address of the loadedOS section UINT64 vmmstart; //physical address of virtual address 00400000 (obsoletish...) UINT64 pagedirlvl4; //Virtual address of the pml4 table (the virtual memory after this until the next 4MB alignment is free to use) UINT64 nextstack; //The virtual address of the stack for the next CPU (vmloader only sets it up when 0) UINT64 extramemory; //Physical address of some extra initial memory (physically contiguous) UINT64 extramemorysize; //the number of pages that extramemory spans UINT64 contiguousmemory; //Physical address of some extra initial memory (physically contiguous) UINT64 contiguousmemorysize; //the number of pages that extramemory spans } INITVARS, *PINITVARS; typedef struct { //ok, everything uint64, I hate these incompatibilities with alignment between gcc and ms c UINT64 cpucount; UINT64 originalEFER; UINT64 originalLME; UINT64 idtbase; UINT64 idtlimit; UINT64 gdtbase; UINT64 gdtlimit; UINT64 cr0; UINT64 cr2; UINT64 cr3; UINT64 cr4; UINT64 dr7; UINT64 rip; UINT64 rax; UINT64 rbx; UINT64 rcx; UINT64 rdx; UINT64 rsi; UINT64 rdi; UINT64 rbp; UINT64 rsp; UINT64 r8; UINT64 r9; UINT64 r10; UINT64 r11; UINT64 r12; UINT64 r13; UINT64 r14; UINT64 r15; UINT64 rflags; UINT64 cs; UINT64 ss; UINT64 ds; UINT64 es; UINT64 fs; UINT64 gs; UINT64 tr; UINT64 ldt; UINT64 cs_AccessRights; UINT64 ss_AccessRights; UINT64 ds_AccessRights; UINT64 es_AccessRights; UINT64 fs_AccessRights; UINT64 gs_AccessRights; UINT64 cs_Limit; UINT64 ss_Limit; UINT64 ds_Limit; UINT64 es_Limit; UINT64 fs_Limit; UINT64 gs_Limit; UINT64 fsbase; UINT64 gsbase; } OriginalState, *POriginalState; #pragma pack() unsigned char *enterVMM2; PMDL enterVMM2MDL; POriginalState originalstate; //one of the reasons why multiple cpu's don't start at exactly the same time PMDL originalstateMDL; UINT_PTR enterVMM2PA; PVOID TemporaryPagingSetup; UINT_PTR TemporaryPagingSetupPA; PMDL TemporaryPagingSetupMDL; UINT_PTR DBVMPML4PA; UINT_PTR originalstatePA; UINT_PTR NewGDTDescriptorVA; UINT_PTR vmmPA; int initializedvmm=0; KSPIN_LOCK LoadedOSSpinLock; //spinlock to prevent LoadedOS from being overwritten (should not be needed, but just being safe) #ifdef AMD64 extern void enterVMM( void ); //declared in vmxoffloada.asm extern void enterVMMPrologue(void); extern void enterVMMEpilogue(void); extern void JTAGBP(void); #else _declspec( naked ) void enterVMM( void ) { __asm { begin: xchg bx,bx //trigger bochs breakpoint //setup the GDT lgdt [ebx] //ebx is the 'virtual address' so just do that before disabling paging ok... //switch to identify mapped pagetable mov cr3,edx jmp short weee weee: //now jump to the physical address (identity mapped to the same virtual address) mov eax,secondentry sub eax,begin add eax,esi jmp eax secondentry: //disable paging mov eax,cr0 and eax,0x7FFFFFFF mov cr0,eax //paging off jmp short weee2 weee2: //load paging for vmm (but don't apply yet, in nonpaged mode) mov cr3,ecx //enable PAE and PSE mov eax,0x30 __emit 0x0f //-| __emit 0x22 //-|-mov cr4,eax (still WTF's me that visual studio doesn't know about cr4) __emit 0xe0 //-| mov ecx,0xc0000080 //enable efer_lme rdmsr or eax,0x100 wrmsr //mov eax,cr0 //or eax,0x80000020 //re-enable pg (and ne to be sure) //edit, who cares, fuck the original state, it's my own state now mov eax,0x80000021 mov cr0,eax mov eax,edi //tell dbvm it's an OS entry and a that location the start info is mov ebx,ebp //tell vmmPA __emit 0xea //-| __emit 0x00 //-| __emit 0x00 //-| __emit 0x40 //-|JMP FAR 0x50:0x00400000 __emit 0x00 //-| __emit 0x50 //-| __emit 0x00 //-| __emit 0xce __emit 0xce __emit 0xce __emit 0xce __emit 0xce __emit 0xce __emit 0xce } } #endif PMDL DBVMMDL; PINITVARS initvars; void cleanupDBVM() { if (!initializedvmm) return; if (enterVMM2MDL) { MmUnlockPages(enterVMM2MDL); IoFreeMdl(enterVMM2MDL); enterVMM2MDL = 0; } if (enterVMM2) { RtlZeroMemory(enterVMM2, 4096); MmFreeContiguousMemory(enterVMM2); enterVMM2 = 0; } if (TemporaryPagingSetupMDL) { MmUnlockPages(TemporaryPagingSetupMDL); IoFreeMdl(TemporaryPagingSetupMDL); TemporaryPagingSetupMDL = 0; } if (TemporaryPagingSetup) { RtlZeroMemory(TemporaryPagingSetup, 4096 * 4); ExFreePool(TemporaryPagingSetup); TemporaryPagingSetup = 0; } if (originalstateMDL) { MmUnlockPages(originalstateMDL); IoFreeMdl(originalstateMDL); originalstateMDL = 0; } if (originalstate) { RtlZeroMemory(originalstate, 4096); ExFreePool(originalstate); originalstate = 0; } initializedvmm = 0; } void initializeDBVM(PCWSTR dbvmimgpath) /* Runs at passive mode */ { if (initializedvmm) return; //already initialized DbgPrint("First time run. Initializing vmm section"); PHYSICAL_ADDRESS LowAddress, HighAddress, SkipBytes; LowAddress.QuadPart = 0; HighAddress.QuadPart = -1; SkipBytes.QuadPart = 0; DBVMMDL = MmAllocatePagesForMdlEx(LowAddress, HighAddress, SkipBytes, 4 * 1024 * 1024, MmCached, MM_ALLOCATE_REQUIRE_CONTIGUOUS_CHUNKS | MM_ALLOCATE_FULLY_REQUIRED); if (!DBVMMDL) { DbgPrint("Failure allocating the required 4MB\n"); return; } vmm = MmMapLockedPagesSpecifyCache(DBVMMDL, KernelMode, MmCached, NULL, FALSE, 0); //default password when dbvm is just loaded (needed for adding extra ram) vmx_password1 = <PASSWORD>; vmx_password2 = <PASSWORD>; vmx_password3 = <PASSWORD>; if (vmm) { int i; PHYSICAL_ADDRESS maxPA; HANDLE dbvmimghandle; UNICODE_STRING filename; IO_STATUS_BLOCK statusblock; OBJECT_ATTRIBUTES oa; NTSTATUS OpenedFile; vmmPA = (UINT_PTR)MmGetPhysicalAddress(vmm).QuadPart; DbgPrint("Allocated memory at virtual address %p (physical address %I64x)\n", vmm, MmGetPhysicalAddress(vmm)); vmmPA = MmGetMdlPfnArray(DBVMMDL)[0] << 12; DbgPrint("(physical address %I64x)\n", vmmPA); RtlZeroMemory(vmm, 4 * 1024 * 1024); //initialize RtlInitUnicodeString(&filename, dbvmimgpath); //Load the .img file InitializeObjectAttributes(&oa, &filename, 0, NULL, NULL); OpenedFile = ZwCreateFile(&dbvmimghandle, SYNCHRONIZE | STANDARD_RIGHTS_READ, &oa, &statusblock, NULL, FILE_SYNCHRONOUS_IO_NONALERT | FILE_ATTRIBUTE_NORMAL, 0, FILE_OPEN, 0, NULL, 0); #ifdef TOBESIGNED if (OpenedFile==STATUS_SUCCESS) OpenedFile=CheckSignatureOfFile(&filename, FALSE); #endif if (OpenedFile == STATUS_SUCCESS) { WORD startsector; LARGE_INTEGER byteoffset; FILE_STANDARD_INFORMATION fsi; NTSTATUS ReadFile; //Getting filesize ZwQueryInformationFile(dbvmimghandle, &statusblock, &fsi, sizeof(fsi), FileStandardInformation); //fsi.EndOfFile contains the filesize if (fsi.EndOfFile.QuadPart>4 * 1024 * 1024) { DbgPrint("File bigger than 4MB. Big retard detected\n"); return; } byteoffset.QuadPart = 0x8; //offset containing sectornumber of the vmm location ReadFile = ZwReadFile(dbvmimghandle, NULL, NULL, NULL, &statusblock, &startsector, 2, &byteoffset, NULL); if (ReadFile == STATUS_PENDING) { if (ZwWaitForSingleObject(dbvmimghandle, FALSE, NULL) != STATUS_SUCCESS) { DbgPrint("Read failure\n"); return; } } if (statusblock.Status == STATUS_SUCCESS) { DWORD vmmsize = fsi.EndOfFile.LowPart;// -(startsector * 512); //now read the vmdisk into the allocated memory DbgPrint("The startsector=%d (that's offset %d)\n", startsector, startsector * 512); byteoffset.QuadPart = startsector * 512; ReadFile = ZwReadFile(dbvmimghandle, NULL, NULL, NULL, &statusblock, vmm, vmmsize, &byteoffset, NULL); if (ReadFile == STATUS_PENDING) ZwWaitForSingleObject(dbvmimghandle, FALSE, NULL); vmmsize = (vmmsize + 4096) & 0xfffffffffffff000ULL; //adjust the size internally to a page boundary (sure, there's some mem loss, but it's predicted, dbvm assumes first 10 pages are scratch pages) DbgPrint("vmmsize=%x\n", vmmsize); if (statusblock.Status == STATUS_SUCCESS) { //basic paging setup for the vmm, will get expanded by the vmm itself UINT64 *GDTBase; PPDPTE_PAE PageMapLevel4; PPDPTE_PAE PageDirPtr; PPDE_PAE PageDir; PPTE_PAE PageTable1, PageTable2; UINT_PTR FreeVA = (((UINT_PTR)vmm + vmmsize) & 0xfffffffffffff000ULL) + 4096; //next free virtual address UINT64 mainstack; initvars = (PINITVARS)&vmm[0x10]; mainstack = FreeVA; FreeVA += 16 * 4096; GDTBase = (UINT64*)FreeVA; FreeVA += 4096; PageDirPtr = (PPDPTE_PAE)FreeVA; FreeVA += 4096; PageDir = (PPDE_PAE)FreeVA; FreeVA += 4096; PageTable1 = (PPTE_PAE)FreeVA; FreeVA += 4096; PageTable2 = (PPTE_PAE)FreeVA; FreeVA += 4096; PageMapLevel4 = (PPDPTE_PAE)FreeVA; FreeVA += 4096; //has to be the last alloc DBVMPML4PA = (UINT_PTR)MmGetPhysicalAddress(PageMapLevel4).QuadPart; //blame MS for making this hard to read DbgPrint("Setting up initial paging table for vmm\n"); *(PUINT64)(&PageMapLevel4[0]) = MmGetPhysicalAddress(PageDirPtr).QuadPart; PageMapLevel4[0].P = 1; PageMapLevel4[0].RW = 1; *(PUINT64)(&PageDirPtr[0]) = MmGetPhysicalAddress(PageDir).QuadPart; PageDirPtr[0].P = 1; PageDirPtr[0].RW = 1; //DBVM 11 does no longer need the map at 0 to 00400000 *(PUINT64)(&PageDir[0]) = 0; //00000000-00200000 PageDir[0].P = 1; PageDir[0].RW = 0; //map as readonly (only for the jump to 0x00400000) PageDir[0].PS = 1; *(PUINT64)(&PageDir[1]) = 0x00200000; //00200000-00400000 PageDir[1].P = 1; PageDir[1].RW = 0; PageDir[1].PS = 1; { *(PUINT64)(&PageDir[2]) = MmGetPhysicalAddress(PageTable1).QuadPart; PageDir[2].P = 1; PageDir[2].RW = 1; PageDir[2].PS = 0; //points to a pagetable *(PUINT64)(&PageDir[3]) = MmGetPhysicalAddress(PageTable2).QuadPart; PageDir[3].P = 1; PageDir[3].RW = 1; PageDir[3].PS = 0; } //fill in the pagetables for (i = 0; i<1024; i++) //pagetable1 and 2 are allocated after eachother, so 1024 can be used here using pagetable1 { *(PUINT64)(&PageTable1[i]) = MmGetPhysicalAddress((PVOID)(((UINT_PTR)vmm) + (4096 * i))).QuadPart; PageTable1[i].P = 1; PageTable1[i].RW = 1; } i = (int)((UINT64)((mainstack - (UINT64)vmm)) >> 12); PageTable1[i].P = 0; //mark the first page of the stack as unreadable //setup GDT GDTBase[0] = 0; //0 : GDTBase[1] = 0x00cf92000000ffffULL; //8 : 32-bit data GDTBase[2] = 0x00cf96000000ffffULL; //16: test, stack, failed, unused GDTBase[3] = 0x00cf9b000000ffffULL; //24: 32-bit code GDTBase[4] = 0x00009a000000ffffULL; //32: 16-bit code GDTBase[5] = 0x000092000000ffffULL; //40: 16-bit data GDTBase[6] = 0x00009a030000ffffULL; //48: 16-bit code, starting at 0x30000 GDTBase[7] = 0; //56: 32-bit task GDTBase[8] = 0; //64: 64-bit task GDTBase[9] = 0; //72: ^ ^ ^ GDTBase[10] = 0x00af9b000000ffffULL; //80: 64-bit code GDTBase[11] = 0; //88: ^ ^ ^ GDTBase[12] = 0; //96: 64-bit tss descriptor (2) GDTBase[13] = 0; //104: ^ ^ ^ NewGDTDescriptor.limit = 0x6f; //111 NewGDTDescriptor.base = 0x00400000 + (UINT64)GDTBase - (UINT64)vmm; DbgPrint("&NewGDTDescriptor=%p, &NewGDTDescriptor.limit=%p, &NewGDTDescriptor.base=%p\n", &NewGDTDescriptor, &NewGDTDescriptor.limit, &NewGDTDescriptor.base); DbgPrint("NewGDTDescriptor.limit=%x\n", NewGDTDescriptor.limit); DbgPrint("NewGDTDescriptor.base=%p\n", NewGDTDescriptor.base); NewGDTDescriptorVA = (UINT_PTR)&NewGDTDescriptor; maxPA.QuadPart = 0x003fffffULL; //allocate 4k at the lower 4MB DbgPrint("Before enterVMM2 alloc: maxPA=%I64x\n", maxPA.QuadPart); enterVMM2 = MmAllocateContiguousMemory(4096, maxPA); if (enterVMM2) { unsigned char *original = (unsigned char *)enterVMM; RtlZeroMemory(enterVMM2, 4096); enterVMM2MDL = IoAllocateMdl(enterVMM2, 4096, FALSE, FALSE, NULL); MmProbeAndLockPages(enterVMM2MDL, KernelMode, IoReadAccess); DbgPrint("enterVMM is located at %p (%I64x)\n", enterVMM, MmGetPhysicalAddress(enterVMM).QuadPart); DbgPrint("enterVMM2 is located at %p (%I64x)\n", enterVMM2, MmGetPhysicalAddress(enterVMM2).QuadPart); DbgPrint("Copying function till end\n"); //copy memory i = 0; while ((i<4096) && ((original[i] != 0xce) || (original[i + 1] != 0xce) || (original[i + 2] != 0xce) || (original[i + 3] != 0xce) || (original[i + 4] != 0xce))) i++; DbgPrint("size is %d", i); RtlCopyMemory(enterVMM2, original, i); DbgPrint("Copy done\n"); } else { DbgPrint("Failure allocating enterVMM2\n"); return; } //now create a paging setup where enterVMM2 is identity mapped AND mapped at the current virtual address, needed to be able to go down to nonpaged mode //easiest way, make every page point to enterVMM2 //allocate 4 pages DbgPrint("Allocating memory for the temp pagedir\n"); TemporaryPagingSetup = ExAllocatePool(PagedPool, 4 * 4096); if (TemporaryPagingSetup == NULL) { DbgPrint("TemporaryPagingSetup==NULL!!!\n"); return; } TemporaryPagingSetupMDL = IoAllocateMdl(TemporaryPagingSetup, 4 * 4096, FALSE, FALSE, NULL); MmProbeAndLockPages(TemporaryPagingSetupMDL, KernelMode, IoReadAccess); RtlZeroMemory(TemporaryPagingSetup, 4096 * 4); DbgPrint("TemporaryPagingSetup is located at %p (%I64x)\n", TemporaryPagingSetup, MmGetPhysicalAddress(TemporaryPagingSetup).QuadPart); TemporaryPagingSetupPA = MmGetMdlPfnArray(TemporaryPagingSetupMDL)[0] << 12; // (UINT_PTR)MmGetPhysicalAddress(TemporaryPagingSetup).QuadPart; enterVMM2PA = MmGetMdlPfnArray(enterVMM2MDL)[0] << 12; DbgPrint("TemporaryPagingSetupPA = (%I64x) (Should be %I64x)\n", (UINT64)TemporaryPagingSetupPA, (UINT64)MmGetPhysicalAddress(TemporaryPagingSetup).QuadPart); #ifdef AMD64 DbgPrint("Setting up temporary paging setup for x64\n"); { PUINT64 PML4Table = (PUINT64)TemporaryPagingSetup; PUINT64 PageDirPtr = (PUINT64)((UINT_PTR)TemporaryPagingSetup + 4096); PUINT64 PageDir = (PUINT64)((UINT_PTR)TemporaryPagingSetup + 2 * 4096); PUINT64 PageTable = (PUINT64)((UINT_PTR)TemporaryPagingSetup + 3 * 4096); DbgPrint("PAE paging\n"); for (i = 0; i<512; i++) { PML4Table[i] = MmGetPhysicalAddress(PageDirPtr).QuadPart; ((PPDPTE_PAE)(&PML4Table[i]))->P = 1; PageDirPtr[i] = MmGetPhysicalAddress(PageDir).QuadPart; ((PPDPTE_PAE)(&PageDirPtr[i]))->P = 1; PageDir[i] = MmGetPhysicalAddress(PageTable).QuadPart; ((PPDE_PAE)(&PageDir[i]))->P = 1; ((PPDE_PAE)(&PageDir[i]))->PS = 0; //4KB PageTable[i] = enterVMM2PA; ((PPTE_PAE)(&PageTable[i]))->P = 1; } } #else DbgPrint("Setting up temporary paging setup\n"); if (PTESize==8) //PAE paging { PUINT64 PageDirPtr=(PUINT64)TemporaryPagingSetup; PUINT64 PageDir=(PUINT64)((UINT_PTR)TemporaryPagingSetup+4096); PUINT64 PageTable=(PUINT64)((UINT_PTR)TemporaryPagingSetup+2*4096); DbgPrint("PAE paging\n"); for (i=0; i<512; i++) { PageDirPtr[i]=MmGetPhysicalAddress(PageDir).QuadPart; ((PPDPTE_PAE)(&PageDirPtr[i]))->P=1; //((PPDPTE_PAE)(&PageDirPtr[i]))->RW=1; PageDir[i]=MmGetPhysicalAddress(PageTable).QuadPart; ((PPDE_PAE)(&PageDir[i]))->P=1; //((PPDE_PAE)(&PageDir[i]))->RW=1; ((PPDE_PAE)(&PageDir[i]))->PS=0; //4KB PageTable[i]=MmGetPhysicalAddress(enterVMM2).QuadPart; ((PPTE_PAE)(&PageTable[i]))->P=1; //((PPTE_PAE)(&PageTable[i]))->RW=1; } } else { //normal(old) 4 byte page entries PDWORD PageDir=(PDWORD)TemporaryPagingSetup; PDWORD PageTable=(PDWORD)((DWORD)TemporaryPagingSetup+4096); DbgPrint("Normal paging\n"); for (i=0; i<1024; i++) { PageDir[i]=MmGetPhysicalAddress(PageTable).LowPart; ((PPDE)(&PageDir[i]))->P=1; ((PPDE)(&PageDir[i]))->RW=1; ((PPDE)(&PageDir[i]))->PS=0; //4KB PageTable[i]=MmGetPhysicalAddress(enterVMM2).LowPart; ((PPTE)(&PageTable[i]))->P=1; ((PPTE)(&PageTable[i]))->RW=1; } } #endif DbgPrint("Temp paging has been setup\n"); //enterVMM2PA = (UINT_PTR)MmGetPhysicalAddress(enterVMM2).QuadPart; originalstate = ExAllocatePool(PagedPool, 4096); originalstateMDL = IoAllocateMdl(originalstate, 4096, FALSE, FALSE, NULL); MmProbeAndLockPages(originalstateMDL, KernelMode, IoReadAccess); RtlZeroMemory(originalstate, 4096); originalstatePA = MmGetMdlPfnArray(originalstateMDL)[0] << 12; //(UINT_PTR)MmGetPhysicalAddress(originalstate).QuadPart; DbgPrint("enterVMM2PA=%llx\n", enterVMM2PA); DbgPrint("originalstatePA=%llx\n", originalstatePA); DbgPrint("originalstatePA=%llx\n", (UINT_PTR)MmGetPhysicalAddress(originalstate).QuadPart); //setup init vars initvars->loadedOS = originalstatePA; initvars->vmmstart = vmmPA; initvars->pagedirlvl4 = 0x00400000 + ((UINT64)PageMapLevel4 - (UINT64)vmm); initvars->nextstack = 0x00400000 + ((UINT64)mainstack - (UINT64)vmm) + (16 * 4096) - 0x40; initvars->contiguousmemory = 0; PMDL contiguousMDL = MmAllocatePagesForMdlEx(LowAddress, HighAddress, SkipBytes, 8 * 4096, MmCached, MM_ALLOCATE_REQUIRE_CONTIGUOUS_CHUNKS | MM_ALLOCATE_FULLY_REQUIRED); if (contiguousMDL) { initvars->contiguousmemory = MmGetMdlPfnArray(contiguousMDL)[0] << 12; DbgPrint("contiguous PA =%llx\n", initvars->contiguousmemory); initvars->contiguousmemorysize = 8; ExFreePool(contiguousMDL); } else DbgPrint("Failed allocating 32KB of contiguous memory"); initializedvmm = TRUE; KeInitializeSpinLock(&LoadedOSSpinLock); } } ZwClose(dbvmimghandle); DbgPrint("Opened and processed: %S\n", filename.Buffer); } else { DbgPrint("Failure opening the file. Status=%x (filename=%S)\n", OpenedFile, filename.Buffer); } //fill in some specific memory regions MmUnmapLockedPages(vmm, DBVMMDL); } else { DbgPrint("Failure allocating the required 4MB\n"); } ExFreePool(DBVMMDL); } void vmxoffload(void) { //save entry state for easy exit in ReturnFromvmxoffload EFLAGS eflags; PHYSICAL_ADDRESS minPA, maxPA,boundary; GDT gdt; IDT idt; /* __try { DbgBreakPoint(); } __except (1) { DbgPrint("No debugger\n"); }*/ //allocate 8MB of contigues physical memory minPA.QuadPart=0; maxPA.QuadPart=0xffffffffff000000ULL; boundary.QuadPart=0x00800000ULL; //8 mb boundaries DbgPrint("vmxoffload\n"); DbgPrint("initializedvmm=%d\n", initializedvmm); if (initializedvmm) { DbgPrint("cpunr=%d\n",cpunr()); DbgPrint("Storing original state\n"); originalstate->cpucount=getCpuCount(); DbgPrint("originalstate->cpucount=%d",originalstate->cpucount); originalstate->originalEFER=readMSR(0xc0000080); //amd prefers this over an LME originalstate->originalLME=(int)(((DWORD)(readMSR(0xc0000080)) >> 8) & 1); DbgPrint("originalstate->originalLME=%d",originalstate->originalLME); originalstate->cr0=(UINT_PTR)getCR0(); DbgPrint("originalstate->cr0=%I64x",originalstate->cr0); /* { int xxx; unsigned char *x; x=&originalstate->cr0; for (xxx=0; xxx<8; xxx++) { DbgPrint("%x ",x[xxx]); } } */ originalstate->cr2=(UINT_PTR)getCR2(); DbgPrint("originalstate->cr2=%I64x",originalstate->cr2); /* { int xxx; unsigned char *x; x=&originalstate->cr2; for (xxx=0; xxx<8; xxx++) { DbgPrint("%x ",x[xxx]); } }*/ originalstate->cr3=(UINT_PTR)getCR3(); //DbgPrint("originalstate->cr3=%I64x",originalstate->cr3); originalstate->cr4=(UINT_PTR)getCR4(); //DbgPrint("originalstate->cr4=%I64x",originalstate->cr4); originalstate->ss=getSS(); originalstate->ss_AccessRights = getAccessRights(originalstate->ss); originalstate->ss_Limit = getSegmentLimit(originalstate->ss); //DbgPrint("originalstate->ss=%I64x",originalstate->ss); originalstate->cs=getCS(); originalstate->cs_AccessRights = getAccessRights(originalstate->cs); originalstate->cs_Limit = getSegmentLimit(originalstate->cs); //DbgPrint("originalstate->cs=%I64x",originalstate->cs); originalstate->ds=getDS(); originalstate->ds_AccessRights = getAccessRights(originalstate->ds); originalstate->ds_Limit = getSegmentLimit(originalstate->ds); //DbgPrint("originalstate->ds=%I64x",originalstate->ds); originalstate->es=getES(); originalstate->es_AccessRights = getAccessRights(originalstate->es); originalstate->es_Limit = getSegmentLimit(originalstate->es); //DbgPrint("originalstate->es=%I64x",originalstate->es); originalstate->fs=getFS(); originalstate->fs_AccessRights = getAccessRights(originalstate->fs); originalstate->fs_Limit = getSegmentLimit(originalstate->fs); //DbgPrint("originalstate->fs=%I64x",originalstate->fs); originalstate->gs=getGS(); originalstate->gs_AccessRights = getAccessRights(originalstate->gs); originalstate->gs_Limit = getSegmentLimit(originalstate->gs); //DbgPrint("originalstate->gs=%I64x",originalstate->gs); originalstate->ldt=GetLDT(); //DbgPrint("originalstate->ldt=%I64x",originalstate->ldt); originalstate->tr=GetTR(); //DbgPrint("originalstate->tr=%I64x",originalstate->tr); originalstate->fsbase=readMSR(0xc0000100); originalstate->gsbase=readMSR(0xc0000101); //DbgPrint("originalstate->fsbase=%I64x originalstate->gsbase=%I64x\n", originalstate->fsbase, originalstate->gsbase); originalstate->dr7=getDR7(); gdt.vector=0; gdt.wLimit=0; GetGDT(&gdt); originalstate->gdtbase=(ULONG_PTR)gdt.vector; originalstate->gdtlimit=gdt.wLimit; //DbgPrint("originalstate->gdtbase=%I64x",originalstate->gdtbase); //DbgPrint("originalstate->gdtlimit=%I64x",originalstate->gdtlimit); GetIDT(&idt); originalstate->idtbase=(ULONG_PTR)idt.vector; originalstate->idtlimit=idt.wLimit; //DbgPrint("originalstate->idtbase=%I64x",originalstate->idtbase); //DbgPrint("originalstate->idtlimit=%I64x",originalstate->idtlimit); eflags=getEflags(); eflags.IF = 0; originalstate->rflags=*(PUINT_PTR)&eflags; originalstate->rsp=getRSP(); //DbgPrint("originalstate->rsp=%I64x",originalstate->rsp); originalstate->rbp=getRBP(); //DbgPrint("originalstate->rbp=%I64x",originalstate->rbp); originalstate->rax=getRAX(); //DbgPrint("originalstate->rax=%I64x",originalstate->rax); originalstate->rbx=getRBX(); //DbgPrint("originalstate->rbx=%I64x",originalstate->rbx); originalstate->rcx=getRCX(); //DbgPrint("originalstate->rcx=%I64x",originalstate->rcx); originalstate->rdx=getRDX(); //DbgPrint("originalstate->rdx=%I64x",originalstate->rdx); originalstate->rsi=getRSI(); //DbgPrint("originalstate->rsi=%I64x",originalstate->rsi); originalstate->rdi=getRDI(); //DbgPrint("originalstate->rdi=%I64x",originalstate->rdi); #ifdef AMD64 originalstate->r8=getR8(); //DbgPrint("originalstate->r8=%I64x",originalstate->r8); originalstate->r9=getR9(); //DbgPrint("originalstate->r9=%I64x",originalstate->r9); originalstate->r10=getR10(); //DbgPrint("originalstate->r10=%I64x",originalstate->r10); originalstate->r11=getR11(); //DbgPrint("originalstate->r11=%I64x",originalstate->r11); originalstate->r12=getR12(); //DbgPrint("originalstate->r12=%I64x",originalstate->r12); originalstate->r13=getR13(); //DbgPrint("originalstate->r13=%I64x",originalstate->r13); originalstate->r14=getR14(); //DbgPrint("originalstate->r14=%I64x",originalstate->r14); originalstate->r15=getR15(); //DbgPrint("originalstate->r15=%I64x",originalstate->r15); #endif #ifdef AMD64 originalstate->rsp-=8; //adjust rsp for the "call entervmmprologue" originalstate->rip=(UINT_PTR)enterVMMEpilogue; //enterVMMEpilogue is an address inside the entervmmprologue function //DbgPrint("originalstate->rip=%llx",originalstate->rip); //DbgPrint("Calling entervmm2. (Originalstate=%p (%llx))\n",originalstate,originalstatePA); //call to entervmmprologue, pushes the return value on the stack enterVMMPrologue(); enableInterrupts(); //DbgPrint("Returned from enterVMMPrologue\n"); //DbgPrint("cpunr=%d\n",cpunr()); //KeLowerIrql(oldirql); //DbgPrint("cpunr=%d\n",cpunr()); #else { ULONG vmmentryeip; __asm { lea eax,[enterVMMEpilogue] mov vmmentryeip,eax } originalstate->rip=(UINT64)vmmentryeip; } __asm{ cli //goodbye interrupts xchg bx,bx mov ebx,vmmPA __emit 0x8b __emit 0xeb //mov ebp,ebx lea ebx,NewGDTDescriptor mov ecx,DBVMPML4PA; mov edx,TemporaryPagingSetupPA //for the mov cr3,ecx mov esi,enterVMM2PA mov edi,originalstatePA call [enterVMM2] //Will never get here. NEVER FUUUUU: xchg bx,bx jmp FUUUUU enterVMMEpilogue: //cli //test nop nop xchg bx,bx //bochs bp nop nop sti nop nop nop nop nop nop } //KeLowerIrql(oldirql); #endif //DbgPrint("Returning\n"); return; } } void vmxoffload_override(CCHAR cpunr, PKDEFERRED_ROUTINE Dpc, PVOID DeferredContext, PVOID *SystemArgument1, PVOID *SystemArgument2) { //runs at passive (in any unrelated cpu) //allocate 64KB of extra memory for this(and every other) cpu's DBVM PHYSICAL_ADDRESS LowAddress, HighAddress, SkipBytes; PMDL mdl; DbgPrint("vmxoffload_override\n"); LowAddress.QuadPart = 0; HighAddress.QuadPart = 0xffffffffffffffffI64; SkipBytes.QuadPart = 0; mdl = MmAllocatePagesForMdlEx(LowAddress, HighAddress, SkipBytes, 64 * 1024, MmCached, MM_ALLOCATE_REQUIRE_CONTIGUOUS_CHUNKS | MM_ALLOCATE_FULLY_REQUIRED); //do not free this, EVER if (mdl) { //convert the pfnlist to a list DBVM understands PDBVMOffloadMemInfo mi = ExAllocatePool(NonPagedPool, sizeof(DBVMOffloadMemInfo)); int i; PFN_NUMBER *pfnlist; DbgPrint("vmxoffload_override: mi=%p\n", mi); mi->List = ExAllocatePool(NonPagedPool, sizeof(UINT64) * 16); DbgPrint("vmxoffload_override: mi->list=%p\n", mi->List); pfnlist = MmGetMdlPfnArray(mdl); for (i = 0; i < 16; i++) mi->List[i] = pfnlist[i] << 12; mi->Count = 16; ExFreePool(mdl); *SystemArgument1 = mi; } } __drv_functionClass(KDEFERRED_ROUTINE) __drv_maxIRQL(DISPATCH_LEVEL) __drv_minIRQL(DISPATCH_LEVEL) __drv_requiresIRQL(DISPATCH_LEVEL) __drv_sameIRQL VOID vmxoffload_dpc( __in struct _KDPC *Dpc, __in_opt PVOID DeferredContext, __in_opt PVOID SystemArgument1, __in_opt PVOID SystemArgument2 ) { int c = cpunr(); DbgPrint("vmxoffload_dpc: CPU %d\n", c); KeAcquireSpinLockAtDpcLevel(&LoadedOSSpinLock); vmxoffload(); //still here so very likely DBVM is loaded if (SystemArgument1) { int x; PDBVMOffloadMemInfo mi = (PDBVMOffloadMemInfo)SystemArgument1; DbgPrint("mi->List=%p mi->Count=%d\n", mi->List, mi->Count); x=vmx_add_memory(mi->List, mi->Count); DbgPrint("vmx_add_memory returned %x\n", x); if (mi->List) ExFreePool(mi->List); ExFreePool(mi); } else DbgPrint("Error: SystemArgument1=NULL\n"); KeReleaseSpinLockFromDpcLevel(&LoadedOSSpinLock); } <|start_filename|>src/amd64/vmxhelpera.asm<|end_filename|> ;RCX: 1st integer argument ;RDX: 2nd integer argument ;R8: 3rd integer argument ;R9: 4th integer argument ;vmcall: rdx = password1 info(rax)->password(@offset 4)=password 2 ;vmcall(info) extern vmx_password1 : QWORD extern vmx_password3 : QWORD _TEXT SEGMENT 'CODE' PUBLIC dovmcall_intel dovmcall_intel: mov rax,rcx mov rdx,vmx_password1 mov rcx,vmx_password3 vmcall ret PUBLIC dovmcall_amd dovmcall_amd: mov rax,rcx mov rdx,vmx_password1 mov rcx,vmx_password3 vmmcall ret _TEXT ENDS END <|start_filename|>src/amd64/noexceptionsa.asm<|end_filename|> _TEXT SEGMENT 'CODE' PUBLIC NoException14 NoException14: ;Security cookies sucks, so getjmp/longjmp are not usable ;So, just falling back to an exceptionless Copy command instead ;or disassemble the instruction RIP points at ;rsp=errorcode ;rsp+8=rip ;rsp+10=cs ;20 ;rsp+18=eflags ;rsp+20=rsp ;rsp+28=ss add rsp,8 ;skip the errorcode push rax ;push rax -state as above again mov rax,ExceptionlessCopy_Exception mov [rsp+8],rax pop rax iretq ;go to the designated return address PUBLIC ExceptionlessCopy_Internal ;rcx=destination ;rdx=source ;r8=size in bytes ExceptionlessCopy_Internal: push rbp mov rbp,rsp ;[rbp] = old rbp value ;[rbp+8] = return address ;[rbp+10h] - [rbp+30h] = scratchspace mov [rbp+10h],rsi mov [rbp+18h],rdi mov rsi,rdx mov rdi,rcx mov rcx,r8 rep movsb ;todo: split this up into movsq, movsd, movsw, movsd, or some of those other string routines ;on exception just exit ExceptionlessCopy_Exception: mov rsi,[rbp+10h] mov rdi,[rbp+18h] sub r8,rcx ;decrease the number of bytes left from the total amount of bytes to get the total bytes written mov rax,r8 pop rbp ret _TEXT ENDS END <|start_filename|>package.json<|end_filename|> { "dependencies": { "dotenv": "^10.0.0", "handlebars": "^4.7.7", "rimraf": "^3.0.2" }, "scripts": { "all": "node ./scripts/cmd.js all", "purge": "node ./scripts/cmd.js purge", "compile": "node ./scripts/cmd.js compile", "geninf": "node ./scripts/cmd.js geninf", "selfsign": "node ./scripts/cmd.js selfsign" } } <|start_filename|>src/vmxhelper.h<|end_filename|> #ifndef VMXHELPER_H #define VMXHELPER_H #pragma warning( disable: 4200) #define VMCALL_GETVERSION 0 #define VMCALL_CHANGEPASSWORD 1 #define VMCALL_READ_PHYSICAL_MEMORY 3 #define VMCALL_WRITE_PHYSICAL_MEMORY 4 #define VMCALL_REDIRECTINT1 9 #define VMCALL_INT1REDIRECTED 10 #define VMCALL_CHANGESELECTORS 12 #define VMCALL_BLOCK_INTERRUPTS 13 #define VMCALL_RESTORE_INTERRUPTS 14 #define VMCALL_REGISTER_CR3_EDIT_CALLBACK 16 #define VMCALL_RETURN_FROM_CR3_EDIT_CALLBACK 17 #define VMCALL_GETCR0 18 #define VMCALL_GETCR3 19 #define VMCALL_GETCR4 20 #define VMCALL_RAISEPRIVILEGE 21 #define VMCALL_REDIRECTINT14 22 #define VMCALL_INT14REDIRECTED 23 #define VMCALL_REDIRECTINT3 24 #define VMCALL_INT3REDIRECTED 25 //dbvm v6+ #define VMCALL_READMSR 26 #define VMCALL_WRITEMSR 27 #define VMCALL_ULTIMAP 28 #define VMCALL_ULTIMAP_DISABLE 29 //dbvm v7+ #define VMCALL_SWITCH_TO_KERNELMODE 30 #define VMCALL_DISABLE_DATAPAGEFAULTS 31 #define VMCALL_ENABLE_DATAPAGEFAULTS 32 #define VMCALL_GETLASTSKIPPEDPAGEFAULT 33 #define VMCALL_ULTIMAP_PAUSE 34 #define VMCALL_ULTIMAP_RESUME 35 #define VMCALL_ULTIMAP_DEBUGINFO 36 //dbvm v10+ #define VMCALL_WATCH_WRITES 41 #define VMCALL_WATCH_READS 41 #define VMCALL_WATCH_RETRIEVELOG 43 #define VMCALL_WATCH_DELETE 44 #define VMCALL_CLOAK_ACTIVATE 45 #define VMCALL_CLOAK_DEACTIVATE 46 #define VMCALL_CLOAK_READORIGINAL 47 #define VMCALL_CLOAK_WRITEORIGINAL 48 #define VMCALL_CLOAK_CHANGEREGONBP 49 #define VMCALL_ADD_MEMORY 57 #define VMCALL_CAUSEDDEBUGBREAK 63 typedef UINT64 QWORD; typedef struct _CHANGEREGONBPINFO { struct { unsigned changeRAX : 1; unsigned changeRBX : 1; unsigned changeRCX : 1; unsigned changeRDX : 1; unsigned changeRSI : 1; unsigned changeRDI : 1; unsigned changeRBP : 1; unsigned changeRSP : 1; unsigned changeRIP : 1; unsigned changeR8 : 1; unsigned changeR9 : 1; unsigned changeR10 : 1; unsigned changeR11 : 1; unsigned changeR12 : 1; unsigned changeR13 : 1; unsigned changeR14 : 1; unsigned changeR15 : 1; //flags reg: unsigned changeCF : 1; unsigned changePF : 1; unsigned changeAF : 1; unsigned changeZF : 1; unsigned changeSF : 1; unsigned changeOF : 1; unsigned newCF : 1; unsigned newPF : 1; unsigned newAF : 1; unsigned newZF : 1; unsigned newSF : 1; unsigned newOF : 1; unsigned reserved : 3; } Flags; QWORD newRAX; QWORD newRBX; QWORD newRCX; QWORD newRDX; QWORD newRSI; QWORD newRDI; QWORD newRBP; QWORD newRSP; QWORD newRIP; QWORD newR8; QWORD newR9; QWORD newR10; QWORD newR11; QWORD newR12; QWORD newR13; QWORD newR14; QWORD newR15; } CHANGEREGONBPINFO, *PCHANGEREGONBPINFO; typedef struct _pageevent_basic { QWORD VirtualAddress; QWORD PhysicalAddress; QWORD CR3; //in case of kernel or other process QWORD FSBASE; QWORD GSBASE; QWORD FLAGS; QWORD RAX; QWORD RBX; QWORD RCX; QWORD RDX; QWORD RSI; QWORD RDI; QWORD R8; QWORD R9; QWORD R10; QWORD R11; QWORD R12; QWORD R13; QWORD R14; QWORD R15; QWORD RBP; QWORD RSP; QWORD RIP; WORD CS; WORD DS; WORD ES; WORD SS; WORD FS; WORD GS; DWORD Count; } PageEventBasic, *PPageEventBasic; typedef struct _fxsave64 { WORD FCW; WORD FSW; BYTE FTW; BYTE Reserved; WORD FOP; UINT64 FPU_IP; UINT64 FPU_DP; DWORD MXCSR; DWORD MXCSR_MASK; QWORD FP_MM0; QWORD FP_MM0_H; QWORD FP_MM1; QWORD FP_MM1_H; QWORD FP_MM2; QWORD FP_MM2_H; QWORD FP_MM3; QWORD FP_MM3_H; QWORD FP_MM4; QWORD FP_MM4_H; QWORD FP_MM5; QWORD FP_MM5_H; QWORD FP_MM6; QWORD FP_MM6_H; QWORD FP_MM7; QWORD FP_MM7_H; QWORD XMM0; QWORD XMM0_H; QWORD XMM1; QWORD XMM1_H; QWORD XMM2; QWORD XMM2_H; QWORD XMM3; QWORD XMM3_H; QWORD XMM4; QWORD XMM4_H; QWORD XMM5; QWORD XMM5_H; QWORD XMM6; QWORD XMM6_H; QWORD XMM7; QWORD XMM7_H; QWORD XMM8; QWORD XMM8_H; QWORD XMM9; QWORD XMM9_H; QWORD XMM10; QWORD XMM10_H; QWORD XMM11; QWORD XMM11_H; QWORD XMM12; QWORD XMM12_H; QWORD XMM13; QWORD XMM13_H; QWORD XMM14; QWORD XMM14_H; QWORD XMM15; QWORD XMM15_H; QWORD res1; QWORD res1_H; QWORD res2; QWORD res2_H; QWORD res3; QWORD res3_H; QWORD res4; QWORD res4_H; QWORD res5; QWORD res5_H; QWORD res6; QWORD res6_H; } FXSAVE64, *PFXSAVE64; typedef struct _pageevent_extended { PageEventBasic basic; FXSAVE64 fpudata; } PageEventExtended, *PPageEventExtended; typedef struct _pageevent_basic_withstack { PageEventBasic basic; unsigned char stack[4096]; } PageEventBasicWithStack, *PPageEventBasicWithStack; typedef struct _pageevent_extended_withstack { PageEventBasic basic; FXSAVE64 fpudata; unsigned char stack[4096]; } PageEventExtendedWithStack, *PPageEventExtendedWithStack; typedef struct _pageeventlistdescriptor { DWORD ID; DWORD maxSize; DWORD numberOfEntries; DWORD missedEntries; DWORD entryType; //0=PageEventBasic, 1=PageEventExtended, 2=PageEventBasicWithStack, 3=PageEventExtendedWithStack union { PageEventBasic basic[0]; PageEventExtended extended[0]; PageEventBasicWithStack basics[0]; PageEventExtendedWithStack extendeds[0]; } pe; } PageEventListDescriptor, *PPageEventListDescriptor; typedef enum {virt_differentInterrupt=0, virt_emulateInterrupt=1} VMXInterruptRedirectType; typedef struct { UINT64 Active; //set to 1 when active UINT64 CR3; //Holds the CR3 value to watch taskswitch to and from UINT64 DEBUGCTL; //Holds the DebugCTL value to set when inside the target process UINT64 DS_AREA; //Holds the DS_AREA to set when UINT64 OriginalDebugCTL; //When inside the target process this holds the debugctl that was set before entering. Return this on readMSR (and set with writeMSR when inside the process) UINT64 OriginalDS_AREA; //When inside the target process this holds the DS_AREA that was set before entering. Return this with readMSR ('''') UINT64 CR3_switchcount; UINT64 CR3_switchcount2; UINT64 LastOldCR3; UINT64 LastNewCR3; } ULTIMAPDEBUGINFO, *PULTIMAPDEBUGINFO; unsigned int vmcall(void *vmcallinfo, unsigned int level1pass); unsigned int vmx_getversion(); unsigned int vmx_getRealCR0(); UINT_PTR vmx_getRealCR3(); unsigned int vmx_getRealCR4(); unsigned int vmx_redirect_interrupt1(VMXInterruptRedirectType redirecttype, unsigned int newintvector, unsigned int int1cs, UINT_PTR int1eip); unsigned int vmx_redirect_interrupt3(VMXInterruptRedirectType redirecttype, unsigned int newintvector, unsigned int int3cs, UINT_PTR int3eip); unsigned int vmx_redirect_interrupt14(VMXInterruptRedirectType redirecttype, unsigned int newintvector, unsigned int int14cs, UINT_PTR int14eip); unsigned int vmx_register_cr3_callback(unsigned int cs, unsigned int eip, unsigned int ss, unsigned int esp); unsigned int vmx_exit_cr3_callback(unsigned int newcr3); unsigned int vmx_ultimap(UINT_PTR cr3towatch, UINT64 debugctl_value, void *storeaddress); unsigned int vmx_ultimap_disable(); unsigned int vmx_ultimap_pause(); unsigned int vmx_ultimap_resume(); unsigned int vmx_ultimap_getDebugInfo(PULTIMAPDEBUGINFO debuginfo); unsigned int vmxusable; UINT64 vmx_password1; unsigned int vmx_password2; UINT64 vmx_password3; unsigned int vmx_version; UINT_PTR vmx_getLastSkippedPageFault(); unsigned int vmx_enable_dataPageFaults(); unsigned int vmx_disable_dataPageFaults(); unsigned int vmx_add_memory(UINT64 *list, int count); int vmx_causedCurrentDebugBreak(); void vmx_init_dovmcall(int isIntel); #endif <|start_filename|>src/vmxhelper.c<|end_filename|> #pragma warning( disable: 4100 4103 4213) #include <ntifs.h> #include <ntddk.h> #include <windef.h> #include "vmxhelper.h" #include "DBKFunc.h" #ifdef AMD64 extern UINT_PTR dovmcall_intel(void *vmcallinfo, unsigned int level1pass); extern UINT_PTR dovmcall_amd(void *vmcallinfo, unsigned int level1pass); //dovmcall is defined in vmxhelpera.asm #else _declspec( naked ) UINT_PTR dovmcall_intel(void *vmcallinfo) { __asm { push edx mov eax,[esp+8] //+8 because of push mov edx, dword ptr vmx_password1 mov ecx, dword ptr vmx_password3 __emit 0x0f __emit 0x01 __emit 0xc1 //vmcall, eax will be edited, or a UD exception will be raised pop edx ret 8 } } _declspec( naked ) UINT_PTR dovmcall_amd(void *vmcallinfo) { __asm { push edx mov eax,[esp+8] mov edx, dword ptr vmx_password1 mov ecx, dword ptr vmx_password3 __emit 0x0f __emit 0x01 __emit 0xd9 //vmmcall, eax will be edited, or a UD exception will be raised pop edx ret 8 } } #endif typedef UINT_PTR (DOVMCALL) (void *vmcallinfo); DOVMCALL *dovmcall; int vmx_hasredirectedint1() { struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_INT1REDIRECTED; return (int)dovmcall(&vmcallinfo); } unsigned int vmx_getversion() /* This will either raise a unhandled opcode exception, or return the used dbvm version */ { struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; DbgPrint("vmx_getversion()\n"); vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_GETVERSION; return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_getRealCR0() { struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_GETCR0; return (unsigned int)dovmcall(&vmcallinfo);; } UINT_PTR vmx_getRealCR3() { struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_GETCR3; return dovmcall(&vmcallinfo);; } unsigned int vmx_getRealCR4() { struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_GETCR4; return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_redirect_interrupt1(VMXInterruptRedirectType redirecttype, unsigned int newintvector, unsigned int int1cs, UINT_PTR int1eip) { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; unsigned int redirecttype; unsigned int newintvector; UINT64 int1eip; unsigned int int1cs; } vmcallinfo; #pragma pack() DbgPrint("vmx_redirect_interrupt1: redirecttype=%d int1cs=%x int1eip=%llx sizeof(vmcallinfo)=%x\n", redirecttype, int1cs, int1eip, sizeof(vmcallinfo)); vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_REDIRECTINT1; vmcallinfo.redirecttype=redirecttype; vmcallinfo.newintvector=newintvector; vmcallinfo.int1eip=int1eip; vmcallinfo.int1cs=int1cs; return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_redirect_interrupt3(VMXInterruptRedirectType redirecttype, unsigned int newintvector, unsigned int int3cs, UINT_PTR int3eip) { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; unsigned int redirecttype; unsigned int newintvector; unsigned long long int3eip; unsigned int int3cs; } vmcallinfo; #pragma pack() DbgPrint("vmx_redirect_interrupt3: int3cs=%x int3eip=%x sizeof(vmcallinfo)=%x\n", int3cs, int3eip, sizeof(vmcallinfo)); vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_REDIRECTINT3; vmcallinfo.redirecttype=redirecttype; vmcallinfo.newintvector=newintvector; vmcallinfo.int3eip=int3eip; vmcallinfo.int3cs=int3cs; return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_redirect_interrupt14(VMXInterruptRedirectType redirecttype, unsigned int newintvector, unsigned int int14cs, UINT_PTR int14eip) { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; unsigned int redirecttype; unsigned int newintvector; unsigned long long int14eip; unsigned int int14cs; } vmcallinfo; #pragma pack() DbgPrint("vmx_redirect_interrupt14: int14cs=%x int14eip=%x sizeof(vmcallinfo)=%x\n", int14cs, int14eip, sizeof(vmcallinfo)); vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_REDIRECTINT14; vmcallinfo.redirecttype=redirecttype; vmcallinfo.newintvector=newintvector; vmcallinfo.int14eip=int14eip; vmcallinfo.int14cs=int14cs; return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_register_cr3_callback(unsigned int cs, unsigned int eip, unsigned int ss, unsigned int esp) { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; unsigned int callbacktype; //32-bit for this driver, so always 0 unsigned long long callback_eip; unsigned int callback_cs; unsigned long long callback_esp; unsigned int callback_ss; } vmcallinfo; #pragma pack() vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_REGISTER_CR3_EDIT_CALLBACK; vmcallinfo.callbacktype=0; vmcallinfo.callback_eip=eip; vmcallinfo.callback_cs=cs; vmcallinfo.callback_esp=esp; vmcallinfo.callback_ss=ss; return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_exit_cr3_callback(unsigned int newcr3) { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; unsigned long long newcr3; } vmcallinfo; #pragma pack() //DbgPrint("vmx_exit_cr3_callback(%x)\n",newcr3); vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_RETURN_FROM_CR3_EDIT_CALLBACK; vmcallinfo.newcr3=newcr3; return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_watch_pagewrites(UINT64 PhysicalAddress, int Size, int Options, int MaxEntryCount) { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; //VMCALL_FINDWHATWRITESPAGE UINT64 PhysicalAddress; int Size; int Options; //binary. // Bit 0: 0=Log RIP once. 1=Log RIP multiple times (when different registers) // Bit 1: 0=Only log given Physical Address. 1=Log everything in the page(s) that is/are affected // Bit 2: 0=Do not save FPU/XMM data, 1=Also save FPU/XMM data // Bit 3: 0=Do not save a stack snapshot, 1=Save stack snapshot // Bit 4: 0=No PMI when full, 1=PMI when full int MaxEntryCount; //how much memory should DBVM allocate for the buffer int UsePMI; //trigger a PMI interrupt when full (so you don't lose info) int ID; //ID describing this watcher for this CPU (keep track of this on a per cpu basis if you do more than 1) } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_WATCH_WRITES; vmcallinfo.PhysicalAddress = PhysicalAddress; if (((PhysicalAddress + Size) & 0xfffffffffffff000ULL) > PhysicalAddress) //passes a pageboundary, strip of the excess Size = 0x1000 - (PhysicalAddress & 0xfff); vmcallinfo.Size = Size; vmcallinfo.Options = Options; vmcallinfo.MaxEntryCount = MaxEntryCount; vmcallinfo.ID = 0xffffffff; dovmcall(&vmcallinfo);; return vmcallinfo.ID; } unsigned int vmx_watch_pageaccess(UINT64 PhysicalAddress, int Size, int Options, int MaxEntryCount) { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; //VMCALL_FINDWHATWRITESPAGE UINT64 PhysicalAddress; int Size; int Options; //binary. // Bit 0: 0=Log RIP once. 1=Log RIP multiple times (when different registers) // Bit 1: 0=Only log given Physical Address. 1=Log everything in the page(s) that is/are affected // Bit 2: 0=Do not save FPU/XMM data, 1=Also save FPU/XMM data // Bit 3: 0=Do not save a stack snapshot, 1=Save stack snapshot // Bit 4: 0=No PMI when full, 1=PMI when full int MaxEntryCount; //how much memory should DBVM allocate for the buffer int ID; //ID describing this watcher for this CPU (keep track of this on a per cpu basis if you do more than 1) } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_WATCH_READS; vmcallinfo.PhysicalAddress = PhysicalAddress; if (((PhysicalAddress + Size) & 0xfffffffffffff000ULL) > PhysicalAddress) //passes a pageboundary, strip of the excess Size = 0x1000 - (PhysicalAddress & 0xfff); vmcallinfo.Size = Size; vmcallinfo.Options = Options; vmcallinfo.MaxEntryCount = MaxEntryCount; vmcallinfo.ID = 0xffffffff; dovmcall(&vmcallinfo);; return vmcallinfo.ID; } unsigned int vmx_watch_retreivelog(int ID, PPageEventListDescriptor result, int *resultsize) /* Used to retrieve both read and write watches */ { unsigned int r; #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; //VMCALL_FINDWHATWRITESPAGE DWORD ID; UINT64 results; int resultsize; int copied; //the number of bytes copied so far (This is a repeating instruction) } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_WATCH_RETRIEVELOG; vmcallinfo.ID = ID; vmcallinfo.results = (UINT64)result; vmcallinfo.resultsize = *resultsize; r=(unsigned int)dovmcall(&vmcallinfo);; *resultsize = vmcallinfo.resultsize; return r; //returns 0 on success, 1 on too small buffer. buffersize contains the size in both cases } unsigned int vmx_watch_delete(int ID) { //disables the watch operation #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; //VMCALL_FINDWHATWRITESPAGE DWORD ID; } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_WATCH_DELETE; vmcallinfo.ID = ID; return (unsigned int)dovmcall(&vmcallinfo);; //0 on success, anything else fail } unsigned int vmx_cloak_activate(QWORD physicalPage) /* Copies a page to a shadow page and marks the original page as execute only (or no access at all if the cpu does not support it) On read/write the shadow page's contents are read/written, but execute will execute the original page To access the contents of the original(executing) page use vmx_cloak_readOriginal and vmx_cloak_writeOriginal possible issue: the read and execute operation can be in the same page at the same time, so when the page is swapped by the contents of the unmodified page to facilitate the read of unmodified memory the unmodified code will execute as well (integrity check checking itself) possible solutions: do not cloak pages with integrity checks and then edit the integrity check willy nilly use single byte edits (e.g int3 bps to facilitate changes) make edits so integrity check routines are jumped over Note: Affects ALL cpu's so only needs to be called once */ { //disables the watch operation #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; //VMCALL_CLOAK_ACTIVATE QWORD physicalAddress; } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_CLOAK_ACTIVATE; vmcallinfo.physicalAddress = physicalPage; return (unsigned int)dovmcall(&vmcallinfo);; //0 on success, anything else fail } //todo: vmx_cload_passthrougwrites() : lets you specify which write operation locations can be passed through to the execute page unsigned int vmx_cloak_deactivate(QWORD physicalPage) { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; //VMCALL_CLOAK_ACTIVATE QWORD physicalAddress; } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_CLOAK_DEACTIVATE; vmcallinfo.physicalAddress = physicalPage; return (unsigned int)dovmcall(&vmcallinfo);; //0 on success, anything else fail } unsigned int vmx_cloak_readOriginal(QWORD physicalPage, void *destination) /* reads 4096 bytes from the cloaked page and put it into original (original must be able to hold 4096 bytes, and preferably on a page boundary) */ { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; QWORD physicalAddress; QWORD destination; } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_CLOAK_READORIGINAL; vmcallinfo.physicalAddress = physicalPage; vmcallinfo.destination = (QWORD)destination; return (unsigned int)dovmcall(&vmcallinfo);; //0 on success, anything else fail } unsigned int vmx_cloak_writeOriginal(QWORD physicalPage, void *source) /* reads 4096 bytes from the cloaked page and put it into original (original must be able to hold 4096 bytes, and preferably on a page boundary) */ { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; //VMCALL_CLOAK_ACTIVATE QWORD physicalAddress; QWORD source; } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_CLOAK_WRITEORIGINAL; vmcallinfo.physicalAddress = physicalPage; vmcallinfo.source = (QWORD)source; return (unsigned int)dovmcall(&vmcallinfo);; //0 on success, anything else fail } unsigned int vmx_changeregonbp(QWORD physicalAddress, CHANGEREGONBPINFO *changereginfo) /* places an int3 bp at the given address, and on execution changes the state to the given state if a cloaked page is given, the BP will be set in the executing page if no cloaked page is given, cloak it (needed for the single step if no IP change is done) Note: effects ALL cpu's */ { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; //VMCALL_CLOAK_CHANGEREGONBP QWORD physicalAddress; CHANGEREGONBPINFO changereginfo; } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_CLOAK_CHANGEREGONBP; vmcallinfo.physicalAddress = physicalAddress; vmcallinfo.changereginfo = *changereginfo; return (unsigned int)dovmcall(&vmcallinfo);; //0 on success, anything else fail } unsigned int vmx_ultimap_getDebugInfo(PULTIMAPDEBUGINFO debuginfo) { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; ULTIMAPDEBUGINFO debuginfo; } vmcallinfo; #pragma pack() unsigned int i; vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_ULTIMAP_DEBUGINFO; i=(unsigned int)dovmcall(&vmcallinfo);; *debuginfo=vmcallinfo.debuginfo; return i; } unsigned int vmx_ultimap(UINT_PTR cr3towatch, UINT64 debugctl_value, void *storeaddress) { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; UINT64 cr3; UINT64 debugctl; UINT64 storeaddress; } vmcallinfo; #pragma pack() vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_ULTIMAP; vmcallinfo.cr3=(UINT64)cr3towatch; vmcallinfo.debugctl=(UINT64)debugctl_value; vmcallinfo.storeaddress=(UINT64)(UINT_PTR)storeaddress; DbgPrint("vmx_ultimap(%I64x, %I64x, %I64x)\n", (UINT64)vmcallinfo.cr3, (UINT64)vmcallinfo.debugctl, vmcallinfo.storeaddress); return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_ultimap_disable() { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; #pragma pack() vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_ULTIMAP_DISABLE; return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_ultimap_pause() { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_ULTIMAP_PAUSE; return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_ultimap_resume() { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_ULTIMAP_RESUME; return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_disable_dataPageFaults() { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; #pragma pack() vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_DISABLE_DATAPAGEFAULTS; return (unsigned int)dovmcall(&vmcallinfo);; } unsigned int vmx_enable_dataPageFaults() { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; #pragma pack() vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_ENABLE_DATAPAGEFAULTS; return (unsigned int)dovmcall(&vmcallinfo);; } UINT_PTR vmx_getLastSkippedPageFault() { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; #pragma pack() vmcallinfo.structsize=sizeof(vmcallinfo); vmcallinfo.level2pass=<PASSWORD>; vmcallinfo.command=VMCALL_GETLASTSKIPPEDPAGEFAULT; return (UINT_PTR)dovmcall(&vmcallinfo);; } unsigned int vmx_add_memory(UINT64 *list, int count) { int r=0; int j=0; #pragma pack(1) typedef struct _vmcall_add_memory { unsigned int structsize; unsigned int level2pass; unsigned int command; UINT64 PhysicalPages[0]; } AddMemoryInfoCall, *PAddMemoryInfoCall; #pragma pack() PAddMemoryInfoCall vmcallinfo=ExAllocatePool(NonPagedPool, sizeof(AddMemoryInfoCall) + count * sizeof(UINT64)); DbgPrint("vmx_add_memory(%p,%d)\n", list, count); DbgPrint("vmx_add_memory(vmx_password1=%x,vmx_password2=%x)\n", vmx_password1, vmx_password2); DbgPrint("structsize at offset %d\n", (UINT64)(&vmcallinfo->structsize) - (UINT64)vmcallinfo); DbgPrint("level2pass at offset %d\n", (UINT64)(&vmcallinfo->level2pass) - (UINT64)vmcallinfo); DbgPrint("command at offset %d\n", (UINT64)(&vmcallinfo->command) - (UINT64)vmcallinfo); DbgPrint("PhysicalPages[0] at offset %d\n", (UINT64)(&vmcallinfo->PhysicalPages[0]) - (UINT64)vmcallinfo); DbgPrint("PhysicalPages[1] at offset %d\n", (UINT64)(&vmcallinfo->PhysicalPages[1]) - (UINT64)vmcallinfo); __try { int i; vmcallinfo->structsize = sizeof(AddMemoryInfoCall) + count * sizeof(UINT64); DbgPrint("vmcallinfo->structsize=%d\n", vmcallinfo->structsize); vmcallinfo->level2pass = <PASSWORD>; vmcallinfo->command = VMCALL_ADD_MEMORY; j = 1; for (i = 0; i < count; i++) { vmcallinfo->PhysicalPages[i] = list[i]; } j = 2; r = (unsigned int)dovmcall(vmcallinfo); j = 3; //never } __except (1) { DbgPrint("vmx_add_memory(%p,%d) gave an exception at part %d with exception code %x\n", list, count, j, GetExceptionCode()); r = 0x100; } ExFreePool(vmcallinfo); return r; } int vmx_causedCurrentDebugBreak() { #pragma pack(1) struct { unsigned int structsize; unsigned int level2pass; unsigned int command; } vmcallinfo; #pragma pack() vmcallinfo.structsize = sizeof(vmcallinfo); vmcallinfo.level2pass = <PASSWORD>; vmcallinfo.command = VMCALL_CAUSEDDEBUGBREAK; return (int)dovmcall(&vmcallinfo);; } void vmx_init_dovmcall(int isIntel) { if (isIntel) (void *)dovmcall=(void *)dovmcall_intel; else (void *)dovmcall=(void *)dovmcall_amd; } //DBVMInterruptService <|start_filename|>src/ultimap2.c<|end_filename|> #pragma warning( disable: 4100 4706) #include <ntifs.h> #include <ntddk.h> #include <minwindef.h> #include <wdm.h> #include <windef.h> #include "Ntstrsafe.h" #include "DBKFunc.h" #include "ultimap2\apic.h" #include "ultimap2.h" PSSUSPENDPROCESS PsSuspendProcess; PSSUSPENDPROCESS PsResumeProcess; KDPC RTID_DPC; BOOL LogKernelMode; BOOL LogUserMode; PEPROCESS CurrentTarget; UINT64 CurrentCR3; HANDLE Ultimap2Handle; volatile BOOLEAN UltimapActive = FALSE; volatile BOOLEAN isSuspended = FALSE; volatile BOOLEAN flushallbuffers = FALSE; //set to TRUE if all the data should be flushed KEVENT FlushData; BOOL SaveToFile; WCHAR OutputPath[200]; int Ultimap2RangeCount; PURANGE Ultimap2Ranges = NULL; PVOID *Ultimap2_DataReady; #if (NTDDI_VERSION < NTDDI_VISTA) //implement this function for XP unsigned int KeQueryMaximumProcessorCount() { CCHAR cpunr; KAFFINITY cpus, original; ULONG cpucount; cpucount = 0; cpus = KeQueryActiveProcessors(); original = cpus; while (cpus) { if (cpus % 2) cpucount++; cpus = cpus / 2; } return cpucount; } #endif typedef struct { PToPA_ENTRY ToPAHeader; PToPA_ENTRY ToPAHeader2; PVOID ToPABuffer; PVOID ToPABuffer2; PMDL ToPABufferMDL; PMDL ToPABuffer2MDL; PRTL_GENERIC_TABLE ToPALookupTable; PRTL_GENERIC_TABLE ToPALookupTable2; KEVENT Buffer2ReadyForSwap; KEVENT InitiateSave; KEVENT DataReady; KEVENT DataProcessed; UINT64 CurrentOutputBase; UINT64 CurrentSaveOutputBase; UINT64 CurrentSaveOutputMask; UINT64 MappedAddress; //set by WaitForData , use with continue UINT64 Buffer2FlushSize; //used by WaitForData KDPC OwnDPC; HANDLE WriterThreadHandle; //for saveToFile mode HANDLE FileHandle; KEVENT FileAccess; UINT64 TraceFileSize; volatile BOOL Interrupted; } ProcessorInfo, *PProcessorInfo; volatile PProcessorInfo *PInfo; int Ultimap2CpuCount; KMUTEX SuspendMutex; KEVENT SuspendEvent; HANDLE SuspendThreadHandle; volatile int suspendCount; BOOL ultimapEnabled = FALSE; BOOL singleToPASystem = FALSE; BOOL NoPMIMode = FALSE; void suspendThread(PVOID StartContext) /* Thread responsible for suspending the target process when the buffer is getting full */ { NTSTATUS wr; __try { while (UltimapActive) { wr = KeWaitForSingleObject(&SuspendEvent, Executive, KernelMode, FALSE, NULL); if (!UltimapActive) return; DbgPrint("suspendThread event triggered"); KeWaitForSingleObject(&SuspendMutex, Executive, KernelMode, FALSE, NULL); if (!isSuspended) { if (CurrentTarget == 0) { if (PsSuspendProcess(CurrentTarget) == 0) isSuspended = TRUE; else DbgPrint("Failed to suspend target\n"); } } KeReleaseMutex(&SuspendMutex, FALSE); } } __except (1) { DbgPrint("Exception in suspendThread thread\n"); } } NTSTATUS ultimap2_continue(int cpunr) { NTSTATUS r = STATUS_UNSUCCESSFUL; if ((cpunr < 0) || (cpunr >= Ultimap2CpuCount)) { DbgPrint("ultimap2_continue(%d)", cpunr); return STATUS_UNSUCCESSFUL; } if (PInfo) { PProcessorInfo pi = PInfo[cpunr]; if (pi->MappedAddress) { MmUnmapLockedPages((PVOID)(UINT_PTR)pi->MappedAddress, pi->ToPABuffer2MDL); //unmap this memory pi->MappedAddress = 0; r = STATUS_SUCCESS; } else DbgPrint("MappedAddress was 0"); DbgPrint("%d DataProcessed", cpunr); KeSetEvent(&pi->DataProcessed, 0, FALSE); //let the next swap happen if needed } return r; } NTSTATUS ultimap2_waitForData(ULONG timeout, PULTIMAP2DATAEVENT data) { NTSTATUS r=STATUS_UNSUCCESSFUL; //Wait for the events in the list //If an event is triggered find out which one is triggered, then map that block into the usermode space and return the address and block //That block will be needed to continue if (UltimapActive) { NTSTATUS wr = STATUS_UNSUCCESSFUL; LARGE_INTEGER wait; PKWAIT_BLOCK waitblock; int cpunr; waitblock = ExAllocatePool(NonPagedPool, Ultimap2CpuCount*sizeof(KWAIT_BLOCK)); wait.QuadPart = -10000LL * timeout; if (timeout == 0xffffffff) //infinite wait wr = KeWaitForMultipleObjects(Ultimap2CpuCount, Ultimap2_DataReady, WaitAny, UserRequest, UserMode, TRUE, NULL, waitblock); else wr = KeWaitForMultipleObjects(Ultimap2CpuCount, Ultimap2_DataReady, WaitAny, UserRequest, UserMode, TRUE, &wait, waitblock); ExFreePool(waitblock); DbgPrint("ultimap2_waitForData wait returned %x", wr); cpunr = wr - STATUS_WAIT_0; if ((cpunr < Ultimap2CpuCount) && (cpunr>=0)) { PProcessorInfo pi = PInfo[cpunr]; if (pi->Buffer2FlushSize) { if (pi->ToPABuffer2MDL) { __try { data->Address = (UINT64)MmMapLockedPagesSpecifyCache(pi->ToPABuffer2MDL, UserMode, MmCached, NULL, FALSE, NormalPagePriority); DbgPrint("MmMapLockedPagesSpecifyCache returned address %p\n", data->Address); if (data->Address) { data->Size = pi->Buffer2FlushSize; data->CpuID = cpunr; pi->MappedAddress = data->Address; r = STATUS_SUCCESS; } } __except (1) { DbgPrint("ultimap2_waitForData: Failure mapping memory into waiter process. Count=%d", (int)MmGetMdlByteCount(pi->ToPABuffer2MDL)); } } else { DbgPrint("ToPABuffer2MDL is NULL. Not even gonna try"); } } else { DbgPrint("ultimap2_waitForData flushsize was 0"); } } } DbgPrint("ultimap2_waitForData returned %x\n", r); return r; } void createUltimap2OutputFile(int cpunr) { NTSTATUS r; PProcessorInfo pi = PInfo[cpunr]; UNICODE_STRING usFile; OBJECT_ATTRIBUTES oaFile; IO_STATUS_BLOCK iosb; WCHAR Buffer[200]; #ifdef AMD64 DbgPrint("OutputPath=%S", OutputPath); swprintf_s(Buffer, 200, L"%sCPU%d.trace", OutputPath, cpunr); #else RtlStringCbPrintfW(Buffer, 200, L"%sCPU%d.trace", OutputPath, cpunr); #endif DbgPrint("Buffer=%S", Buffer); RtlInitUnicodeString(&usFile, Buffer); InitializeObjectAttributes(&oaFile, &usFile, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); DbgPrint("Creating file %S", usFile.Buffer); pi->FileHandle = 0; ZwDeleteFile(&oaFile); r = ZwCreateFile(&pi->FileHandle, SYNCHRONIZE | FILE_READ_DATA | FILE_APPEND_DATA | GENERIC_ALL, &oaFile, &iosb, 0, FILE_ATTRIBUTE_NORMAL, 0, FILE_SUPERSEDE, FILE_SEQUENTIAL_ONLY | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); DbgPrint("%d: ZwCreateFile=%x\n", (int)cpunr, r); } void WriteThreadForSpecificCPU(PVOID StartContext) { int cpunr = (int)(UINT_PTR)StartContext; PProcessorInfo pi = PInfo[cpunr]; IO_STATUS_BLOCK iosb; NTSTATUS r = STATUS_UNSUCCESSFUL; //DbgPrint("WriteThreadForSpecificCPU %d alive", (int)StartContext); if (SaveToFile) { if (KeWaitForSingleObject(&pi->FileAccess, Executive, KernelMode, FALSE, NULL) == STATUS_SUCCESS) { createUltimap2OutputFile(cpunr); KeSetEvent(&pi->FileAccess, 0, FALSE); } else createUltimap2OutputFile(cpunr); } KeSetSystemAffinityThread((KAFFINITY)(1 << cpunr)); while (UltimapActive) { NTSTATUS wr = KeWaitForSingleObject(&pi->InitiateSave, Executive, KernelMode, FALSE, NULL); //DbgPrint("WriteThreadForSpecificCPU %d: wr=%x", (int)StartContext, wr); if (!UltimapActive) break; if (wr == STATUS_SUCCESS) { UINT64 Size; ToPA_LOOKUP tl; PToPA_LOOKUP result; //DbgPrint("%d: writing buffer", (int)StartContext); //figure out the size tl.PhysicalAddress = pi->CurrentSaveOutputBase; tl.index = 0; result = RtlLookupElementGenericTable(pi->ToPALookupTable2, &tl); if (result) { //write... //DbgPrint("%d: result->index=%d CurrentSaveOutputMask=%p", (int)StartContext, result->index, pi->CurrentSaveOutputMask); if (singleToPASystem) Size = pi->CurrentSaveOutputMask >> 32; else Size = ((result->index * 511) + ((pi->CurrentSaveOutputMask & 0xffffffff) >> 7)) * 4096 + (pi->CurrentSaveOutputMask >> 32); if (Size > 0) { if (SaveToFile) { wr = KeWaitForSingleObject(&pi->FileAccess, Executive, KernelMode, FALSE, NULL); if (wr==STATUS_SUCCESS) { if (pi->FileHandle==0) //a usermode flush has happened createUltimap2OutputFile(cpunr); r = ZwWriteFile(pi->FileHandle, NULL, NULL, NULL, &iosb, pi->ToPABuffer2, (ULONG)Size, NULL, NULL); pi->TraceFileSize += Size; //DbgPrint("%d: ZwCreateFile(%p, %d)=%x\n", (int)StartContext, pi->ToPABuffer2, (ULONG)Size, r); KeSetEvent(&pi->FileAccess, 0, FALSE); } } else { //map ToPABuffer2 into the CE process //wake up a worker thread pi->Buffer2FlushSize = Size; DbgPrint("%d: WorkerThread(%p, %d)=%x\n", (int)(UINT_PTR)StartContext, pi->ToPABuffer2, (ULONG)Size, r); KeSetEvent(&pi->DataReady, 0, TRUE); //a ce thread waiting in ultimap2_waitForData should now wake and process the data //and wait for it to finish r=KeWaitForSingleObject(&pi->DataProcessed, Executive, KernelMode, FALSE, NULL); DbgPrint("KeWaitForSingleObject(DataProcessed)=%x", r); } //DbgPrint("%d: Writing %x bytes\n", (int)StartContext, Size); } } else DbgPrint("Unexpected physical address while writing results for cpu %d (%p)", (int)(UINT_PTR)StartContext, pi->CurrentSaveOutputBase); KeSetEvent(&pi->Buffer2ReadyForSwap, 0, FALSE); } } KeSetSystemAffinityThread(KeQueryActiveProcessors()); if (pi->FileHandle) ZwClose(pi->FileHandle); KeSetEvent(&pi->Buffer2ReadyForSwap, 0, FALSE); } void ultimap2_LockFile(int cpunr) { if ((cpunr < 0) || (cpunr >= Ultimap2CpuCount)) return; if (PInfo) { NTSTATUS wr; PProcessorInfo pi = PInfo[cpunr]; //DbgPrint("AcquireUltimap2File()"); wr = KeWaitForSingleObject(&pi->FileAccess, Executive, KernelMode, FALSE, NULL); if (wr == STATUS_SUCCESS) { //DbgPrint("Acquired"); if (pi->FileHandle) { ZwClose(pi->FileHandle); pi->FileHandle = 0; } } } } void ultimap2_ReleaseFile(int cpunr) { if ((cpunr < 0) || (cpunr >= Ultimap2CpuCount)) return; if (PInfo) { PProcessorInfo pi = PInfo[cpunr]; KeSetEvent(&pi->FileAccess, 0, FALSE); //DbgPrint("Released"); } } UINT64 ultimap2_GetTraceFileSize() //Gets an aproximation of the filesize. Don't take this too exact { UINT64 size = 0; if (PInfo) { int i; for (i = 0; i < Ultimap2CpuCount; i++) size += PInfo[i]->TraceFileSize; } return size; } void ultimap2_ResetTraceFileSize() { if (PInfo) { int i; for (i = 0; i < Ultimap2CpuCount; i++) PInfo[i]->TraceFileSize = 0; } } void SwitchToPABuffer(struct _KDPC *Dpc, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2) /* DPC routine that switches the Buffer pointer and marks buffer2 that it's ready for data saving Only called when buffer2 is ready for flushing */ { //write the contents of the current cpu buffer PProcessorInfo pi = PInfo[KeGetCurrentProcessorNumber()]; //DbgPrint("SwitchToPABuffer for cpu %d\n", KeGetCurrentProcessorNumber()); if (pi) { UINT64 CTL = __readmsr(IA32_RTIT_CTL); UINT64 Status = __readmsr(IA32_RTIT_STATUS); PVOID temp; if ((Status >> 5) & 1) //Stopped DbgPrint("%d Not all data recorded\n", KeGetCurrentProcessorNumber()); if ((Status >> 4) & 1) DbgPrint("ALL LOST"); //only if the buffer is bigger than 2 pages. That you can check in IA32_RTIT_OUTPUT_MASK_PTRS and IA32_RTIT_OUTPUT_BASE //if (KeGetCurrentProcessorNumber() == 0) // DbgPrint("%d: pi->CurrentOutputBase=%p __readmsr(IA32_RTIT_OUTPUT_BASE)=%p __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)=%p", KeGetCurrentProcessorNumber(), pi->CurrentOutputBase, __readmsr(IA32_RTIT_OUTPUT_BASE), __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)); if (pi->Interrupted == FALSE) { //return; //debug test. remove me when released if (!singleToPASystem) { if ((!flushallbuffers) && (((__readmsr(IA32_RTIT_OUTPUT_MASK_PTRS) & 0xffffffff) >> 7) < 2)) return; //don't flush yet } else { INT64 offset = __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS); /*if (KeGetCurrentProcessorNumber() == 0) { DbgPrint("pi->CurrentOutputBase=%p", pi->CurrentOutputBase); DbgPrint("offset=%p", offset); }*/ offset = offset >> 32; //if (KeGetCurrentProcessorNumber() == 0) // DbgPrint("offset=%p", offset); if ((!flushallbuffers) && (((pi->CurrentOutputBase == 0) || (offset < 8192)))) return; //don't flush yet } } else { DbgPrint("%d:Flushing because of interrupt", KeGetCurrentProcessorNumber()); } DbgPrint("%d: Flush this data (%p)", KeGetCurrentProcessorNumber(), __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)); //DbgPrint("%d: pi->CurrentOutputBase=%p __readmsr(IA32_RTIT_OUTPUT_BASE)=%p __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)=%p", KeGetCurrentProcessorNumber(), pi->CurrentOutputBase, __readmsr(IA32_RTIT_OUTPUT_BASE), __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)); __writemsr(IA32_RTIT_CTL, 0); //disable packet generation __writemsr(IA32_RTIT_STATUS, 0); //DbgPrint("%d: pi->CurrentOutputBase=%p __readmsr(IA32_RTIT_OUTPUT_BASE)=%p __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)=%p", KeGetCurrentProcessorNumber(), pi->CurrentOutputBase, __readmsr(IA32_RTIT_OUTPUT_BASE), __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)); //switch the pointer to the secondary buffers KeClearEvent(&pi->Buffer2ReadyForSwap); //swap the buffer temp = pi->ToPABuffer; pi->ToPABuffer = pi->ToPABuffer2; pi->ToPABuffer2 = temp; //swap the MDL that describes it temp = pi->ToPABufferMDL; pi->ToPABufferMDL = pi->ToPABuffer2MDL; pi->ToPABuffer2MDL = temp; //swap the header temp = pi->ToPAHeader; pi->ToPAHeader = pi->ToPAHeader2; pi->ToPAHeader2 = temp; //swap the lookup table temp = pi->ToPALookupTable; pi->ToPALookupTable = pi->ToPALookupTable2; pi->ToPALookupTable2 = temp; //lookup which entry it's pointing at pi->CurrentSaveOutputBase = __readmsr(IA32_RTIT_OUTPUT_BASE); pi->CurrentSaveOutputMask = __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS); KeSetEvent(&pi->InitiateSave,0,FALSE); pi->Interrupted = FALSE; //reactivate packet generation pi->CurrentOutputBase = MmGetPhysicalAddress(pi->ToPAHeader).QuadPart; __writemsr(IA32_RTIT_OUTPUT_BASE, pi->CurrentOutputBase); __writemsr(IA32_RTIT_OUTPUT_MASK_PTRS, 0); __writemsr(IA32_RTIT_CTL, CTL); } } void WaitForWriteToFinishAndSwapWriteBuffers(BOOL interruptedOnly) { int i; for (i = 0; i < Ultimap2CpuCount; i++) { PProcessorInfo pi = PInfo[i]; if ((pi->ToPABuffer2) && ((pi->Interrupted) || (!interruptedOnly))) { KeWaitForSingleObject(&pi->Buffer2ReadyForSwap, Executive, KernelMode, FALSE, NULL); if (!UltimapActive) return; KeInsertQueueDpc(&pi->OwnDPC, NULL, NULL); } } KeFlushQueuedDpcs(); } void bufferWriterThread(PVOID StartContext) { //passive mode //wait for event LARGE_INTEGER Timeout; NTSTATUS wr; DbgPrint("bufferWriterThread active"); while (UltimapActive) { if (NoPMIMode) Timeout.QuadPart = -1000LL; //- 10000LL=1 millisecond //-100000000LL = 10 seconds -1000000LL= 0.1 second else Timeout.QuadPart = -10000LL; //- 10000LL=1 millisecond //-100000000LL = 10 seconds -1000000LL= 0.1 second //DbgPrint("%d : Wait for FlushData", cpunr()); wr = KeWaitForSingleObject(&FlushData, Executive, KernelMode, FALSE, &Timeout); //DbgPrint("%d : After wait for FlushData", cpunr()); //wr = KeWaitForSingleObject(&FlushData, Executive, KernelMode, FALSE, NULL); //DbgPrint("bufferWriterThread: Alive (wr==%x)", wr); if (!UltimapActive) { DbgPrint("bufferWriterThread: Terminating"); return; } //if (wr != STATUS_SUCCESS) continue; //DEBUG code so PMI's get triggered if ((wr == STATUS_SUCCESS) || (wr == STATUS_TIMEOUT)) { if ((wr == STATUS_SUCCESS) && (!isSuspended)) { //woken up by a dpc DbgPrint("FlushData event set and not suspended. Suspending target process\n"); KeWaitForSingleObject(&SuspendMutex, Executive, KernelMode, FALSE, NULL); if (!isSuspended) { DbgPrint("Still going to suspend target process"); if (PsSuspendProcess(CurrentTarget)==0) isSuspended = TRUE; } KeReleaseMutex(&SuspendMutex, FALSE); DbgPrint("After the target has been suspended (isSuspended=%d)\n", isSuspended); } if (wr == STATUS_SUCCESS) //the filled cpu's must take preference { unsigned int i; BOOL found = TRUE; //DbgPrint("bufferWriterThread: Suspended"); //first flush the CPU's that complained their buffers are full DbgPrint("Flushing full CPU\'s"); while (found) { WaitForWriteToFinishAndSwapWriteBuffers(TRUE); if (!UltimapActive) return; //check if no interrupt has been triggered while this was busy ('could' happen as useless info like core ratio is still recorded) found = FALSE; for (i = 0; i < KeQueryMaximumProcessorCount(); i++) { if (PInfo[i]->Interrupted) { DbgPrint("PInfo[%d]->Interrupted\n", PInfo[i]->Interrupted); found = TRUE; break; } } } } //wait till the previous buffers are done writing //DbgPrint("%d: Normal flush", cpunr()); WaitForWriteToFinishAndSwapWriteBuffers(FALSE); //DbgPrint("%d : after flush", cpunr()); if (isSuspended) { KeWaitForSingleObject(&SuspendMutex, Executive, KernelMode, FALSE, NULL); if (isSuspended) { DbgPrint("Resuming target process"); PsResumeProcess(CurrentTarget); isSuspended = FALSE; } KeReleaseMutex(&SuspendMutex, FALSE); } //an interrupt could have fired while WaitForWriteToFinishAndSwapWriteBuffers was busy, pausing the process. If that happened, then the next KeWaitForSingleObject will exit instantly due to it being signaled } else DbgPrint("Unexpected wait result"); } } NTSTATUS ultimap2_flushBuffers() { if (!UltimapActive) return STATUS_UNSUCCESSFUL; DbgPrint("ultimap2_flushBuffers"); KeWaitForSingleObject(&SuspendMutex, Executive, KernelMode, FALSE, NULL); if (CurrentTarget) { if (!isSuspended) { PsSuspendProcess(CurrentTarget); isSuspended = TRUE; } } KeReleaseMutex(&SuspendMutex, FALSE); flushallbuffers = TRUE; DbgPrint("wait1"); WaitForWriteToFinishAndSwapWriteBuffers(FALSE); //write the last saved buffer DbgPrint("wait2"); WaitForWriteToFinishAndSwapWriteBuffers(FALSE); //write the current buffer flushallbuffers = FALSE; DbgPrint("after wait"); KeWaitForSingleObject(&SuspendMutex, Executive, KernelMode, FALSE, NULL); if (CurrentTarget) { if (isSuspended) { PsResumeProcess(CurrentTarget); isSuspended = FALSE; } } KeReleaseMutex(&SuspendMutex, FALSE); DbgPrint("ultimap2_flushBuffers exit"); return STATUS_SUCCESS; } void RTIT_DPC_Handler(__in struct _KDPC *Dpc, __in_opt PVOID DeferredContext, __in_opt PVOID SystemArgument1,__in_opt PVOID SystemArgument2) { //Signal the bufferWriterThread KeSetEvent(&SuspendEvent, 0, FALSE); KeSetEvent(&FlushData, 0, FALSE); } void PMI(__in struct _KINTERRUPT *Interrupt, __in PVOID ServiceContext) { //check if caused by me, if so defer to dpc DbgPrint("PMI"); __try { if ((__readmsr(IA32_PERF_GLOBAL_STATUS) >> 55) & 1) { UINT64 Status = __readmsr(IA32_RTIT_STATUS); DbgPrint("PMI: caused by me"); __writemsr(IA32_PERF_GLOBAL_OVF_CTRL, (UINT64)1 << 55); //clear ToPA full status if ((__readmsr(IA32_PERF_GLOBAL_STATUS) >> 55) & 1) { DbgPrint("PMI: Failed to clear the status\n"); } DbgPrint("PMI: IA32_RTIT_OUTPUT_MASK_PTRS=%p\n", __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)); DbgPrint("PMI: IA32_RTIT_STATUS=%p\n", Status); if ((Status >> 5) & 1) //Stopped DbgPrint("PMI %d: Not all data recorded (AT THE PMI!)\n", KeGetCurrentProcessorNumber()); DbgPrint("PMI: IA32_RTIT_OUTPUT_MASK_PTRS %p\n", __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)); PInfo[KeGetCurrentProcessorNumber()]->Interrupted = TRUE; KeInsertQueueDpc(&RTID_DPC, NULL, NULL); //clear apic state apic_clearPerfmon(); } else { DbgPrint("Unexpected PMI"); } } __except (0) { DbgPrint("PMI exception"); } } void *pperfmon_hook2 = (void *)PMI; void ultimap2_disable_dpc(struct _KDPC *Dpc, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2) { DbgPrint("ultimap2_disable_dpc for cpu %d\n", KeGetCurrentProcessorNumber()); __try { if (DeferredContext) //only pause { RTIT_CTL ctl; DbgPrint("temp disable\n"); ctl.Value = __readmsr(IA32_RTIT_CTL); ctl.Bits.TraceEn = 0; __writemsr(IA32_RTIT_CTL, ctl.Value); } else { DbgPrint("%d: disable all\n", KeGetCurrentProcessorNumber()); __writemsr(IA32_RTIT_CTL, 0); __writemsr(IA32_RTIT_STATUS, 0); __writemsr(IA32_RTIT_CR3_MATCH, 0); __writemsr(IA32_RTIT_OUTPUT_BASE, 0); __writemsr(IA32_RTIT_OUTPUT_MASK_PTRS, 0); } } __except (1) { DbgPrint("ultimap2_disable_dpc exception"); } } void ultimap2_setup_dpc(struct _KDPC *Dpc, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2) { RTIT_CTL ctl; RTIT_STATUS s; int i = -1; __try { ctl.Value = __readmsr(IA32_RTIT_CTL); } __except (1) { DbgPrint("ultimap2_setup_dpc: IA32_RTIT_CTL in unreadable"); return; } ctl.Bits.TraceEn = 1; if (LogKernelMode) ctl.Bits.OS = 1; else ctl.Bits.OS = 0; if (LogUserMode) ctl.Bits.USER = 1; else ctl.Bits.USER = 0; if (CurrentCR3) ctl.Bits.CR3Filter = 1; else ctl.Bits.CR3Filter = 0; ctl.Bits.ToPA = 1; ctl.Bits.TSCEn = 0; ctl.Bits.DisRETC = 0; ctl.Bits.BranchEn = 1; if (PInfo == NULL) return; if (PInfo[KeGetCurrentProcessorNumber()]->ToPABuffer == NULL) { DbgPrint("ToPA for cpu %d not setup\n", KeGetCurrentProcessorNumber()); return; } __try { int cpunr = KeGetCurrentProcessorNumber(); i = 0; PInfo[cpunr]->CurrentOutputBase = MmGetPhysicalAddress(PInfo[cpunr]->ToPAHeader).QuadPart; __writemsr(IA32_RTIT_OUTPUT_BASE, PInfo[cpunr]->CurrentOutputBase); i = 1; __writemsr(IA32_RTIT_OUTPUT_MASK_PTRS, 0); i = 2; __try { __writemsr(IA32_RTIT_CR3_MATCH, CurrentCR3); } __except (1) { CurrentCR3 = CurrentCR3 & 0xfffffffffffff000ULL; DbgPrint("Failed to set the actual CR3. Using a sanitized CR3: %llx\n", CurrentCR3); } i = 3; //ranges if (Ultimap2Ranges && Ultimap2RangeCount) { for (i = 0; i < Ultimap2RangeCount; i++) { ULONG msr_start = IA32_RTIT_ADDR0_A + (2 * i); ULONG msr_stop = IA32_RTIT_ADDR0_B + (2 * i); UINT64 bit = 32 + (i * 4); DbgPrint("Range %d: (%p -> %p)", i, (PVOID)(UINT_PTR)(Ultimap2Ranges[i].StartAddress), (PVOID)(UINT_PTR)(Ultimap2Ranges[i].EndAddress)); DbgPrint("Writing range %d to msr %x and %x", i, msr_start, msr_stop); __writemsr(msr_start, Ultimap2Ranges[i].StartAddress); __writemsr(msr_stop, Ultimap2Ranges[i].EndAddress); DbgPrint("bit=%d", bit); DbgPrint("Value before=%llx", ctl.Value); if (Ultimap2Ranges[i].IsStopAddress) ctl.Value |= (UINT64)2ULL << bit; //TraceStop This stops all tracing on this cpu. Doesn't get reactivated else ctl.Value |= (UINT64)1ULL << bit; //FilterEn //not supported in the latest windows build DbgPrint("Value after=%llx", ctl.Value); } } i = 4; __writemsr(IA32_RTIT_STATUS, 0); i = 5; //if (KeGetCurrentProcessorNumber() == 0) __writemsr(IA32_RTIT_CTL, ctl.Value); i = 6; s.Value=__readmsr(IA32_RTIT_STATUS); if (s.Bits.Error) DbgPrint("Setup for cpu %d failed", KeGetCurrentProcessorNumber()); else DbgPrint("Setup for cpu %d succesful", KeGetCurrentProcessorNumber()); } __except (1) { DbgPrint("Error in ultimap2_setup_dpc. i=%d",i); DbgPrint("ctl.Value=%p\n", ctl.Value); DbgPrint("CR3=%p\n", CurrentCR3); //DbgPrint("OutputBase=%p", __readmsr(IA32_RTIT_OUTPUT_BASE)); } } int getToPAHeaderCount(ULONG _BufferSize) { return 1 + (_BufferSize / 4096) / 511; } int getToPAHeaderSize(ULONG _BufferSize) { //511 entries per ToPA header (4096*511=2093056 bytes per ToPA header) //BufferSize / 2093056 = Number of ToPA headers needed return getToPAHeaderCount(_BufferSize) * 4096; } RTL_GENERIC_COMPARE_RESULTS NTAPI ToPACompare(__in struct _RTL_GENERIC_TABLE *Table, __in PToPA_LOOKUP FirstStruct, __in PToPA_LOOKUP SecondStruct) { //DbgPrint("Comparing %p with %p", FirstStruct->PhysicalAddress, FirstStruct->PhysicalAddress); if (FirstStruct->PhysicalAddress == SecondStruct->PhysicalAddress) return GenericEqual; else { if (SecondStruct->PhysicalAddress < FirstStruct->PhysicalAddress) return GenericLessThan; else return GenericGreaterThan; } } PVOID NTAPI ToPAAlloc(__in struct _RTL_GENERIC_TABLE *Table, __in CLONG ByteSize) { return ExAllocatePool(NonPagedPool, ByteSize); } VOID NTAPI ToPADealloc(__in struct _RTL_GENERIC_TABLE *Table, __in __drv_freesMem(Mem) __post_invalid PVOID Buffer) { ExFreePool(Buffer); } void* setupToPA(PToPA_ENTRY *Header, PVOID *OutputBuffer, PMDL *BufferMDL, PRTL_GENERIC_TABLE *gt, ULONG _BufferSize, int NoPMI) { ToPA_LOOKUP tl; PToPA_ENTRY r; UINT_PTR Output, Stop; ULONG ToPAIndex = 0; int PABlockSize = 0; int BlockSize; PRTL_GENERIC_TABLE x; int i; if (singleToPASystem) { PHYSICAL_ADDRESS la,ha, boundary; ULONG newsize; BlockSize = _BufferSize; //yup, only 1 single entry //get the closest possible if (BlockSize > 64 * 1024 * 1024) { PABlockSize = 15; BlockSize = 128 * 1024 * 1024; } else if (BlockSize > 32 * 1024 * 1024) { PABlockSize = 14; BlockSize = 64 * 1024 * 1024; } else if (BlockSize > 16 * 1024 * 1024) { PABlockSize = 13; BlockSize = 32 * 1024 * 1024; } else if (BlockSize > 8 * 1024 * 1024) { PABlockSize = 12; BlockSize = 16 * 1024 * 1024; } else if (BlockSize > 4 * 1024 * 1024) { PABlockSize = 11; BlockSize = 8 * 1024 * 1024; } else if (BlockSize > 2 * 1024 * 1024) { PABlockSize = 10; BlockSize = 4 * 1024 * 1024; } else if (BlockSize > 1 * 1024 * 1024) { PABlockSize = 9; BlockSize = 2 * 1024 * 1024; } else if (BlockSize > 512 * 1024) { PABlockSize = 8; BlockSize = 1 * 1024 * 1024; } else if (BlockSize > 256 * 1024) { PABlockSize = 7; BlockSize = 512 * 1024; } else if (BlockSize > 128 * 1024) { PABlockSize = 6; BlockSize = 256 * 1024; } else if (BlockSize > 64 * 1024) { PABlockSize = 5; BlockSize = 128 * 1024; } else if (BlockSize > 32 * 1024) { PABlockSize = 4; BlockSize = 64 * 1024; } else if (BlockSize > 16*1024) { PABlockSize = 3; BlockSize = 32 * 1024; } else if (BlockSize > 8 * 1024) { PABlockSize = 2; BlockSize = 16 * 1024; } else if (BlockSize > 4 * 1024) { PABlockSize = 1; BlockSize = 8 * 1024; } else { PABlockSize = 0; BlockSize = 4096; } //adjust the buffersize so it is dividable by the blocksize newsize = BlockSize; DbgPrint("BufferSize=%x\n", _BufferSize); DbgPrint("BlockSize=%x (PABlockSize=%d)\n", BlockSize, PABlockSize); DbgPrint("newsize=%x\n", newsize); la.QuadPart = 0; ha.QuadPart = 0xFFFFFFFFFFFFFFFFULL; boundary.QuadPart = BlockSize; *OutputBuffer=MmAllocateContiguousMemorySpecifyCache(newsize, la, ha, boundary, MmCached); //*OutputBuffer=MmAllocateContiguousMemory(newsize, ha); DbgPrint("Allocated OutputBuffer at %p", MmGetPhysicalAddress(*OutputBuffer).QuadPart); _BufferSize = newsize; if (*OutputBuffer == NULL) { DbgPrint("setupToPA (Single ToPA System): Failure allocating output buffer"); return NULL; } r = ExAllocatePool(NonPagedPool, 4096); if (r == NULL) { MmFreeContiguousMemory(*OutputBuffer); *OutputBuffer = NULL; DbgPrint("setupToPA (Single ToPA System): Failure allocating header for buffer"); return NULL; } } else { //Not a single ToPA system BlockSize = 4096; *OutputBuffer = ExAllocatePool(NonPagedPool, _BufferSize); if (*OutputBuffer == NULL) { DbgPrint("setupToPA: Failure allocating output buffer"); return NULL; } r = ExAllocatePool(NonPagedPool, getToPAHeaderSize(_BufferSize)); if (r == NULL) { ExFreePool(*OutputBuffer); *OutputBuffer = NULL; DbgPrint("setupToPA: Failure allocating header for buffer"); return NULL; } } *Header = r; *gt=ExAllocatePool(NonPagedPool, sizeof(RTL_GENERIC_TABLE)); if (*gt == NULL) { DbgPrint("Failure allocating table"); if (singleToPASystem) MmFreeContiguousMemory(*OutputBuffer); else ExFreePool(*OutputBuffer); *OutputBuffer = NULL; ExFreePool(*Header); *Header = NULL; return NULL; } x = *gt; RtlInitializeGenericTable(x, ToPACompare, ToPAAlloc, ToPADealloc, NULL); tl.index = 0; tl.PhysicalAddress = MmGetPhysicalAddress(&r[0]).QuadPart; RtlInsertElementGenericTable(x, &tl, sizeof(tl), NULL); Output = (UINT_PTR)*OutputBuffer; Stop = Output+_BufferSize; *BufferMDL = IoAllocateMdl(*OutputBuffer, _BufferSize, FALSE, FALSE, NULL); MmBuildMdlForNonPagedPool(*BufferMDL); if (singleToPASystem) { r[0].Value = (UINT64)MmGetPhysicalAddress((PVOID)Output).QuadPart; r[0].Bits.Size = PABlockSize; if (NoPMI) r[0].Bits.INT = 0; else r[0].Bits.INT = 1; r[0].Bits.STOP = 1; r[1].Value = MmGetPhysicalAddress(&r[0]).QuadPart; r[1].Bits.END = 1; } else { while (Output < Stop) { //fill in the topa entries pointing to eachother if ((ToPAIndex + 1) % 512 == 0) { //point it to the next ToPA table r[ToPAIndex].Value = MmGetPhysicalAddress(&r[ToPAIndex + 1]).QuadPart; r[ToPAIndex].Bits.END = 1; tl.index = tl.index++; tl.PhysicalAddress = MmGetPhysicalAddress(&r[ToPAIndex + 1]).QuadPart; RtlInsertElementGenericTable(x, &tl, sizeof(tl), NULL); } else { r[ToPAIndex].Value = (UINT64)MmGetPhysicalAddress((PVOID)Output).QuadPart; r[ToPAIndex].Bits.Size = 0; Output += 4096; } ToPAIndex++; } ToPAIndex--; r[ToPAIndex].Bits.STOP = 1; i = (ToPAIndex * 90) / 100; //90% if ((i == (int)ToPAIndex) && (i > 0)) //don't interrupt on the very last entry (if possible) i--; if ((i > 0) && ((i + 1) % 512 == 0)) i--; DbgPrint("Interrupt at index %d", i); if (NoPMI) r[i].Bits.INT = 0; else r[i].Bits.INT = 1; //Interrupt after filling this entry //and every 2nd page after this. (in case of a rare situation where resume is called right after suspend) if (ToPAIndex > 0) { while (i < (int)(ToPAIndex - 1)) { if (((i + 1) % 512) && (NoPMI==0)) //anything but 0 r[i].Bits.INT = 1; i += 2; } } } return (void *)r; } NTSTATUS ultimap2_pause() { if (ultimapEnabled) { forEachCpu(ultimap2_disable_dpc, (PVOID)1, NULL, NULL, NULL); if (UltimapActive) { flushallbuffers = TRUE; WaitForWriteToFinishAndSwapWriteBuffers(FALSE); //write the last saved buffer WaitForWriteToFinishAndSwapWriteBuffers(FALSE); //write the current buffer flushallbuffers = FALSE; } } return STATUS_SUCCESS; } NTSTATUS ultimap2_resume() { if ((ultimapEnabled) && (PInfo)) forEachCpu(ultimap2_setup_dpc, NULL, NULL, NULL, NULL); return STATUS_SUCCESS; } void *clear = NULL; BOOL RegisteredProfilerInterruptHandler; void SetupUltimap2(UINT32 PID, UINT32 BufferSize, WCHAR *Path, int rangeCount, PURANGE Ranges, int NoPMI, int UserMode, int KernelMode) { //for each cpu setup tracing //add the PMI interupt int i; NTSTATUS r= STATUS_UNSUCCESSFUL; int cpuid_r[4]; if (Path) DbgPrint("SetupUltimap2(%x, %x, %S, %d, %p,%d,%d,%d\n", PID, BufferSize, Path, rangeCount, Ranges, NoPMI, UserMode, KernelMode); else DbgPrint("SetupUltimap2(%x, %x, %d, %p,%d,%d,%d\n", PID, BufferSize, rangeCount, Ranges, NoPMI, UserMode, KernelMode); __cpuidex(cpuid_r, 0x14, 0); if ((cpuid_r[2] & 2) == 0) { DbgPrint("Single ToPA System"); singleToPASystem = TRUE; } NoPMIMode = NoPMI; LogKernelMode = KernelMode; LogUserMode = UserMode; DbgPrint("Path[0]=%d\n", Path[0]); SaveToFile = (Path[0] != 0); if (SaveToFile) { wcsncpy(OutputPath, Path, 199); OutputPath[199] = 0; DbgPrint("Ultimap2: SaveToFile==TRUE: OutputPath=%S",OutputPath); } else { DbgPrint("Ultimap2: Runtime processing"); } if (rangeCount) { if (Ultimap2Ranges) { ExFreePool(Ultimap2Ranges); Ultimap2Ranges = NULL; } Ultimap2Ranges = ExAllocatePool(NonPagedPool, rangeCount*sizeof(URANGE)); for (i = 0; i < rangeCount; i++) Ultimap2Ranges[i] = Ranges[i]; Ultimap2RangeCount = rangeCount; } else Ultimap2RangeCount = 0; //get the EProcess and CR3 for this PID if (PID) { if (PsLookupProcessByProcessId((PVOID)PID, &CurrentTarget) == STATUS_SUCCESS) { //todo add specific windows version checks and hardcode offsets/ or use scans if (getCR3() & 0xfff) { DbgPrint("Split kernel/usermode pages\n"); //uses supervisor/usermode pagemaps CurrentCR3 = *(UINT64 *)((UINT_PTR)CurrentTarget + 0x278); if ((CurrentCR3 & 0xfffffffffffff000ULL) == 0) { DbgPrint("No usermode CR3\n"); CurrentCR3 = *(UINT64 *)((UINT_PTR)CurrentTarget + 0x28); } DbgPrint("CurrentCR3=%llx\n", CurrentCR3); } else { KAPC_STATE apc_state; RtlZeroMemory(&apc_state, sizeof(apc_state)); __try { KeStackAttachProcess((PVOID)CurrentTarget, &apc_state); CurrentCR3 = getCR3(); KeUnstackDetachProcess(&apc_state); } __except (1) { DbgPrint("Failure getting CR3 for this process"); return; } } } else { DbgPrint("Failure getting the EProcess for pid %d", PID); return; } } else { CurrentTarget = 0; CurrentCR3 = 0; } DbgPrint("CurrentCR3=%llx\n", CurrentCR3); if ((PsSuspendProcess == NULL) || (PsResumeProcess == NULL)) { DbgPrint("No Suspend/Resume support"); return; } KeInitializeDpc(&RTID_DPC, RTIT_DPC_Handler, NULL); KeInitializeEvent(&FlushData, SynchronizationEvent, FALSE); KeInitializeEvent(&SuspendEvent, SynchronizationEvent, FALSE); KeInitializeMutex(&SuspendMutex, 0); Ultimap2CpuCount = KeQueryMaximumProcessorCount(); PInfo = ExAllocatePool(NonPagedPool, Ultimap2CpuCount*sizeof(PProcessorInfo)); Ultimap2_DataReady = ExAllocatePool(NonPagedPool, Ultimap2CpuCount*sizeof(PVOID)); if (PInfo == NULL) { DbgPrint("PInfo alloc failed"); return; } if (Ultimap2_DataReady == NULL) { DbgPrint("Ultimap2_DataReady alloc failed"); return; } for (i = 0; i < Ultimap2CpuCount; i++) { PInfo[i] = ExAllocatePool(NonPagedPool, sizeof(ProcessorInfo)); RtlZeroMemory(PInfo[i], sizeof(ProcessorInfo)); KeInitializeEvent(&PInfo[i]->InitiateSave, SynchronizationEvent, FALSE); KeInitializeEvent(&PInfo[i]->Buffer2ReadyForSwap, NotificationEvent, TRUE); setupToPA(&PInfo[i]->ToPAHeader, &PInfo[i]->ToPABuffer, &PInfo[i]->ToPABufferMDL, &PInfo[i]->ToPALookupTable, BufferSize, NoPMI); setupToPA(&PInfo[i]->ToPAHeader2, &PInfo[i]->ToPABuffer2, &PInfo[i]->ToPABuffer2MDL, &PInfo[i]->ToPALookupTable2, BufferSize, NoPMI); DbgPrint("cpu %d:", i); DbgPrint("ToPAHeader=%p ToPABuffer=%p Size=%x", PInfo[i]->ToPAHeader, PInfo[i]->ToPABuffer, BufferSize); DbgPrint("ToPAHeader2=%p ToPABuffer2=%p Size=%x", PInfo[i]->ToPAHeader2, PInfo[i]->ToPABuffer2, BufferSize); KeInitializeEvent(&PInfo[i]->DataReady, SynchronizationEvent, FALSE); KeInitializeEvent(&PInfo[i]->DataProcessed, SynchronizationEvent, FALSE); KeInitializeEvent(&PInfo[i]->FileAccess, SynchronizationEvent, TRUE); Ultimap2_DataReady[i] = &PInfo[i]->DataReady; KeInitializeDpc(&PInfo[i]->OwnDPC, SwitchToPABuffer, NULL); KeSetTargetProcessorDpc(&PInfo[i]->OwnDPC, (CCHAR)i); } UltimapActive = TRUE; ultimapEnabled = TRUE; PsCreateSystemThread(&SuspendThreadHandle, 0, NULL, 0, NULL, suspendThread, NULL); PsCreateSystemThread(&Ultimap2Handle, 0, NULL, 0, NULL, bufferWriterThread, NULL); for (i = 0; i < Ultimap2CpuCount; i++) PsCreateSystemThread(&PInfo[i]->WriterThreadHandle, 0, NULL, 0, NULL, WriteThreadForSpecificCPU, (PVOID)i); if ((NoPMI == FALSE) && (RegisteredProfilerInterruptHandler == FALSE)) { DbgPrint("Registering PMI handler\n"); pperfmon_hook2 = (void *)PMI; r = HalSetSystemInformation(HalProfileSourceInterruptHandler, sizeof(PVOID*), &pperfmon_hook2); //hook the perfmon interrupt if (r == STATUS_SUCCESS) RegisteredProfilerInterruptHandler = TRUE; DbgPrint("HalSetSystemInformation returned %x\n", r); if (r != STATUS_SUCCESS) DbgPrint("Failure hooking the permon interrupt. Ultimap2 will not be able to use interrupts until you reboot (This can happen when the perfmon interrupt is hooked more than once. It has no restore/undo hook)\n"); } forEachCpu(ultimap2_setup_dpc, NULL, NULL, NULL, NULL); } void UnregisterUltimapPMI() { NTSTATUS r; DbgPrint("UnregisterUltimapPMI()\n"); if (RegisteredProfilerInterruptHandler) { pperfmon_hook2 = NULL; r = HalSetSystemInformation(HalProfileSourceInterruptHandler, sizeof(PVOID*), &pperfmon_hook2); DbgPrint("1: HalSetSystemInformation to disable returned %x\n", r); if (r == STATUS_SUCCESS) return; r = HalSetSystemInformation(HalProfileSourceInterruptHandler, sizeof(PVOID*), &clear); //unhook the perfmon interrupt DbgPrint("2: HalSetSystemInformation to disable returned %x\n", r); if (r == STATUS_SUCCESS) return; r = HalSetSystemInformation(HalProfileSourceInterruptHandler, sizeof(PVOID*), 0); DbgPrint("3: HalSetSystemInformation to disable returned %x\n", r); } else DbgPrint("UnregisterUltimapPMI() not needed\n"); } void DisableUltimap2(void) { int i; DbgPrint("-------------------->DisableUltimap2<------------------"); if (!ultimapEnabled) return; DbgPrint("-------------------->DisableUltimap2:Stage 1<------------------"); forEachCpuAsync(ultimap2_disable_dpc, NULL, NULL, NULL, NULL); UltimapActive = FALSE; if (SuspendThreadHandle) { DbgPrint("Waiting for SuspendThreadHandle"); KeSetEvent(&SuspendEvent, 0, FALSE); ZwWaitForSingleObject(SuspendThreadHandle, FALSE, NULL); ZwClose(SuspendThreadHandle); SuspendThreadHandle = NULL; } if (PInfo) { for (i = 0; i < Ultimap2CpuCount; i++) { KeSetEvent(&PInfo[i]->DataProcessed, 0, FALSE); KeSetEvent(&PInfo[i]->DataReady, 0, FALSE); } } if (Ultimap2Handle) { DbgPrint("Waiting for Ultimap2Handle"); KeSetEvent(&FlushData, 0, FALSE); ZwWaitForSingleObject(Ultimap2Handle, FALSE, NULL); ZwClose(Ultimap2Handle); Ultimap2Handle = NULL; } if (PInfo) { DbgPrint("going to deal with the PInfo data"); for (i = 0; i < Ultimap2CpuCount; i++) { if (PInfo[i]) { PToPA_LOOKUP li; KeSetEvent(&PInfo[i]->Buffer2ReadyForSwap, 0, FALSE); KeSetEvent(&PInfo[i]->InitiateSave, 0, FALSE); DbgPrint("Waiting for WriterThreadHandle[%d]",i); ZwWaitForSingleObject(PInfo[i]->WriterThreadHandle, FALSE, NULL); ZwClose(PInfo[i]->WriterThreadHandle); PInfo[i]->WriterThreadHandle = NULL; if (PInfo[i]->ToPABufferMDL) { IoFreeMdl(PInfo[i]->ToPABufferMDL); PInfo[i]->ToPABufferMDL = NULL; } if (PInfo[i]->ToPABuffer) { if (singleToPASystem) MmFreeContiguousMemory(PInfo[i]->ToPABuffer); else ExFreePool(PInfo[i]->ToPABuffer); PInfo[i]->ToPABuffer = NULL; } if (PInfo[i]->ToPABuffer2MDL) { IoFreeMdl(PInfo[i]->ToPABuffer2MDL); PInfo[i]->ToPABufferMDL = NULL; } if (PInfo[i]->ToPABuffer2) { if (singleToPASystem) MmFreeContiguousMemory(PInfo[i]->ToPABuffer2); else ExFreePool(PInfo[i]->ToPABuffer2); PInfo[i]->ToPABuffer2 = NULL; } if (PInfo[i]->ToPAHeader) { ExFreePool(PInfo[i]->ToPAHeader); PInfo[i]->ToPAHeader = NULL; } if (PInfo[i]->ToPAHeader2) { ExFreePool(PInfo[i]->ToPAHeader2); PInfo[i]->ToPAHeader2 = NULL; } while (li = RtlGetElementGenericTable(PInfo[i]->ToPALookupTable, 0)) RtlDeleteElementGenericTable(PInfo[i]->ToPALookupTable, li); ExFreePool(PInfo[i]->ToPALookupTable); PInfo[i]->ToPALookupTable = NULL; while (li = RtlGetElementGenericTable(PInfo[i]->ToPALookupTable2, 0)) RtlDeleteElementGenericTable(PInfo[i]->ToPALookupTable2, li); ExFreePool(PInfo[i]->ToPALookupTable2); PInfo[i]->ToPALookupTable2 = NULL; ExFreePool(PInfo[i]); PInfo[i] = NULL; } } ExFreePool(PInfo); ExFreePool(Ultimap2_DataReady); PInfo = NULL; DbgPrint("Finished terminating ultimap2"); } if (Ultimap2Ranges) { ExFreePool(Ultimap2Ranges); Ultimap2Ranges = NULL; Ultimap2RangeCount = 0; } DbgPrint("-------------------->DisableUltimap2:Finish<------------------"); } <|start_filename|>src/DBKFunc.h<|end_filename|> #ifndef DBKFUNC_H #define DBKFUNC_H #pragma warning( disable: 4214 ) #include <ntifs.h> #include <ntstrsafe.h> #include <windef.h> #include "interruptHook.h" #ifdef RELEASE #define DbgPrint(...) #endif int _fltused; typedef VOID F(UINT_PTR param); typedef F *PF; typedef VOID PREDPC_CALLBACK(CCHAR cpunr, PKDEFERRED_ROUTINE Dpc, PVOID DeferredContext, PVOID *SystemArgument1, PVOID *SystemArgument2); typedef PREDPC_CALLBACK *PPREDPC_CALLBACK; typedef struct _criticalSection { LONG locked; int cpunr; //unique id for a cpu int lockcount; int oldIFstate; } criticalSection, *PcriticalSection; //ntosp.h typedef _Function_class_(KNORMAL_ROUTINE) _IRQL_requires_max_(PASSIVE_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_(PASSIVE_LEVEL) _IRQL_requires_same_ VOID KNORMAL_ROUTINE( _In_opt_ PVOID NormalContext, _In_opt_ PVOID SystemArgument1, _In_opt_ PVOID SystemArgument2 ); typedef KNORMAL_ROUTINE *PKNORMAL_ROUTINE; typedef _Function_class_(KKERNEL_ROUTINE) _IRQL_requires_max_(APC_LEVEL) _IRQL_requires_min_(APC_LEVEL) _IRQL_requires_(APC_LEVEL) _IRQL_requires_same_ VOID KKERNEL_ROUTINE( _In_ struct _KAPC *Apc, _Inout_ PKNORMAL_ROUTINE *NormalRoutine, _Inout_ PVOID *NormalContext, _Inout_ PVOID *SystemArgument1, _Inout_ PVOID *SystemArgument2 ); typedef KKERNEL_ROUTINE *PKKERNEL_ROUTINE; typedef _Function_class_(KRUNDOWN_ROUTINE) _IRQL_requires_max_(PASSIVE_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_(PASSIVE_LEVEL) _IRQL_requires_same_ VOID KRUNDOWN_ROUTINE( _In_ struct _KAPC *Apc ); typedef KRUNDOWN_ROUTINE *PKRUNDOWN_ROUTINE; typedef _IRQL_requires_same_ _Function_class_(KENUM_ROUTINE) VOID KENUM_ROUTINE( _In_reads_(_Inexpressible_(Length)) PVOID Data, _In_ ULONG Length, _In_ PVOID Context ); typedef KENUM_ROUTINE *PKENUM_ROUTINE; typedef enum _KAPC_ENVIRONMENT { OriginalApcEnvironment, AttachedApcEnvironment, CurrentApcEnvironment, InsertApcEnvironment } KAPC_ENVIRONMENT; NTKERNELAPI _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_same_ VOID KeEnumerateQueueApc( _Inout_ PKTHREAD Thread, _In_ PKENUM_ROUTINE CallbackRoutine, _In_ PVOID Context, _In_opt_ KPROCESSOR_MODE *ApcMode ); NTKERNELAPI _IRQL_requires_same_ _When_(Environment != OriginalApcEnvironment, __drv_reportError("Caution: " "Using an APC environment other than the original environment can lead to " "a system bugcheck if the target thread is attached to a process with APCs " "disabled. APC environments should be used with care.")) VOID KeInitializeApc( _Out_ PRKAPC Apc, _In_ PRKTHREAD Thread, _In_ KAPC_ENVIRONMENT Environment, _In_ PKKERNEL_ROUTINE KernelRoutine, _In_opt_ PKRUNDOWN_ROUTINE RundownRoutine, _In_opt_ PKNORMAL_ROUTINE NormalRoutine, _In_opt_ KPROCESSOR_MODE ProcessorMode, _In_opt_ PVOID NormalContext ); NTKERNELAPI _Must_inspect_result_ _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_same_ BOOLEAN KeInsertQueueApc( _Inout_ PRKAPC Apc, _In_opt_ PVOID SystemArgument1, _In_opt_ PVOID SystemArgument2, _In_ KPRIORITY Increment ); NTSYSAPI NTSTATUS NTAPI ZwOpenThread( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId ); struct PTEStruct { unsigned P : 1; // present (1 = present) unsigned RW : 1; // read/write unsigned US : 1; // user/supervisor unsigned PWT : 1; // page-level write-through unsigned PCD : 1; // page-level cache disabled unsigned A : 1; // accessed unsigned Reserved : 1; // dirty unsigned PS : 1; // page size (0 = 4-KB page) unsigned G : 1; // global page unsigned A1 : 1; // available 1 aka copy-on-write unsigned A2 : 1; // available 2/ is 1 when paged to disk unsigned A3 : 1; // available 3 unsigned PFN : 20; // page-frame number }; //typedef struct PTEStruct *PPDPTE; //typedef struct PTEStruct *PPDE; //typedef struct PTEStruct *PPTE; struct PTEStruct64 { unsigned long long P : 1; // present (1 = present) unsigned long long RW : 1; // read/write unsigned long long US : 1; // user/supervisor unsigned long long PWT : 1; // page-level write-through unsigned long long PCD : 1; // page-level cache disabled unsigned long long A : 1; // accessed unsigned long long Reserved : 1; // dirty unsigned long long PS : 1; // page size (0 = 4-KB page) unsigned long long G : 1; // global page unsigned long long A1 : 1; // available 1 aka copy-on-write unsigned long long A2 : 1; // available 2/ is 1 when paged to disk unsigned long long A3 : 1; // available 3 unsigned long long PFN : 52; // page-frame number }; //typedef struct PTEStruct64 *PPDPTE_PAE; //typedef struct PTEStruct64 *PPDE_PAE; //typedef struct PTEStruct64 *PPTE_PAE; typedef struct tagDebugregs { ULONG DR0; ULONG DR1; ULONG DR2; ULONG DR3; ULONG DR5; ULONG DR6; ULONG DR7; } Debugregs; typedef struct { unsigned CF :1; // 0 unsigned reserved1 :1; // 1 unsigned PF :1; // 2 unsigned reserved2 :1; // 3 unsigned AF :1; // 4 unsigned reserved3 :1; // 5 unsigned ZF :1; // 6 unsigned SF :1; // 7 unsigned TF :1; // 8 unsigned IF :1; // 9 unsigned DF :1; // 10 unsigned OF :1; // 11 unsigned IOPL :2; // 12+13 unsigned NT :1; // 14 unsigned reserved4 :1; // 15 unsigned RF :1; // 16 unsigned VM :1; // 17 unsigned AC :1; // 18 unsigned VIF :1; // 19 unsigned VIP :1; // 20 unsigned ID :1; // 21 unsigned reserved5 :10; // 22-31 #ifdef AMD64 unsigned reserved6 :8; unsigned reserved7 :8; unsigned reserved8 :8; unsigned reserved9 :8; #endif } EFLAGS,*PEFLAGS; typedef struct tagDebugReg7 { unsigned L0 :1; // 0 unsigned G0 :1; // 1 unsigned L1 :1; // 2 unsigned G1 :1; // 3 unsigned L2 :1; // 4 unsigned G2 :1; // 5 unsigned L3 :1; // 6 unsigned G3 :1; // 7 unsigned GL :1; // 8 unsigned GE :1; // 9 unsigned undefined_1: 1; //1 10 unsigned RTM : 1; // 11 unsigned undefined_0: 1; //0 12 unsigned GD :1; // 13 unsigned undefined2 :2; // 00 unsigned RW0 :2; unsigned LEN0 :2; unsigned RW1 :2; unsigned LEN1 :2; unsigned RW2 :2; unsigned LEN2 :2; unsigned RW3 :2; unsigned LEN3 :2; #ifdef AMD64 unsigned undefined3 :8; unsigned undefined4 :8; unsigned undefined5 :8; unsigned undefined6 :8; #endif } DebugReg7; typedef struct DebugReg6 { unsigned B0 :1; unsigned B1 :1; unsigned B2 :1; unsigned B3 :1; unsigned undefined1 :9; // 011111111 unsigned BD :1; unsigned BS :1; unsigned BT :1; unsigned RTM : 1; //0=triggered unsigned undefined2 :15; // 111111111111111 #ifdef AMD64 unsigned undefined3 :8; unsigned undefined4 :8; unsigned undefined5 :8; unsigned undefined6 :8; #endif } DebugReg6; #pragma pack(2) //allignment of 2 bytes typedef struct tagGDT { WORD wLimit; PVOID vector; } GDT, *PGDT; #pragma pack() //UCHAR BufferSize; void GetIDT(PIDT pIdt); #ifdef AMD64 extern void _fxsave(volatile void *); extern void GetGDT(PGDT pGdt); extern WORD GetLDT(); extern WORD GetTR(void); #else void GetGDT(PGDT pGdt); WORD GetLDT(); WORD GetTR(void); #endif UINT64 readMSR(DWORD msr); UINT64 getDR7(void); void setCR0(UINT64 newCR0); UINT64 getCR0(void); UINT64 getCR2(void); void setCR3(UINT64 newCR3); UINT64 getCR3(void); UINT64 getCR4(void); void setCR4(UINT64 newcr4); UINT64 getTSC(void); #ifdef AMD64 extern WORD getCS(void); extern WORD getSS(void); extern WORD getDS(void); extern WORD getES(void); extern WORD getFS(void); extern WORD getGS(void); extern UINT64 getRSP(void); extern UINT64 getRBP(void); extern UINT64 getRAX(void); extern UINT64 getRBX(void); extern UINT64 getRCX(void); extern UINT64 getRDX(void); extern UINT64 getRSI(void); extern UINT64 getRDI(void); #else WORD getCS(void); WORD getSS(void); WORD getDS(void); WORD getES(void); WORD getFS(void); WORD getGS(void); ULONG getRSP(void); ULONG getRBP(void); ULONG getRAX(void); ULONG getRBX(void); ULONG getRCX(void); ULONG getRDX(void); ULONG getRSI(void); ULONG getRDI(void); #endif extern UINT64 getR8(void); extern UINT64 getR9(void); extern UINT64 getR10(void); extern UINT64 getR11(void); extern UINT64 getR12(void); extern UINT64 getR13(void); extern UINT64 getR14(void); extern UINT64 getR15(void); extern UINT64 getAccessRights(UINT64 segment); extern UINT64 getSegmentLimit(UINT64 segment); int getCpuCount(void); BOOL loadedbydbvm; int PTESize; UINT_PTR PAGE_SIZE_LARGE; UINT_PTR MAX_PDE_POS; UINT_PTR MAX_PTE_POS; int cpu_stepping; int cpu_model; int cpu_familyID; int cpu_type; int cpu_ext_modelID; int cpu_ext_familyID; int KernelCodeStepping; int KernelWritesIgnoreWP; int isPrefix(unsigned char b); EFLAGS getEflags(void); int cpunr(void); void disableInterrupts(void); void enableInterrupts(void); void csEnter(PcriticalSection CS); void csLeave(PcriticalSection CS); void forOneCpu(CCHAR cpunr, PKDEFERRED_ROUTINE dpcfunction, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2, OPTIONAL PPREDPC_CALLBACK preDPCCallback); void forEachCpu(PKDEFERRED_ROUTINE dpcfunction, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2, OPTIONAL PPREDPC_CALLBACK preDPCCallback); void forEachCpuAsync(PKDEFERRED_ROUTINE dpcfunction, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2, OPTIONAL PPREDPC_CALLBACK preDPCCallback); void forEachCpuPassive(PF f, UINT_PTR param); #endif; <|start_filename|>src/ultimap2/apic.h<|end_filename|> #ifndef apic_h #define apic_h #include <ntddk.h> #include <windef.h> typedef struct { DWORD a; DWORD b; DWORD c; DWORD d; } UINT128; typedef volatile struct { UINT128 Reserved1; UINT128 Reserved2; UINT128 LocalAPIC_ID; UINT128 LocalAPIC_Version; UINT128 Reserved3; UINT128 Reserved4; UINT128 Reserved5; UINT128 Reserved6; UINT128 Task_Priority; UINT128 Arbritation_Priority; UINT128 Processor_Priority; UINT128 EOI; UINT128 Reserved7; UINT128 Logical_Destination; UINT128 Destination_Format; UINT128 Spurious_Interrupt_Vector; UINT128 In_Service[8]; UINT128 Trigger_Mode[8]; UINT128 Interrupt_Request[8]; UINT128 Error_Status; UINT128 Reserved8[7]; UINT128 Interrupt_Command_Low32Bit; UINT128 Interrupt_Command_High32Bit; UINT128 LVT_Timer; UINT128 LVT_Thermal_Sensor; UINT128 LVT_Performance_Monitor; UINT128 LVT_LINT0; UINT128 LVT_LINT1; UINT128 LVT_Error; UINT128 Initial_Count; UINT128 Current_Count; UINT128 Reserved9[4]; UINT128 Divide_Configuration; UINT128 Reserved10; } APIC, *PAPIC; extern volatile PAPIC APIC_BASE; void apic_clearPerfmon(); void setup_APIC_BASE(void); void clean_APIC_BASE(void); #endif <|start_filename|>src/amd64/debuggera.asm<|end_filename|> ;RCX: 1st integer argument ;RDX: 2nd integer argument ;R8: 3rd integer argument ;R9: 4th integer argument CALLBACK struct A qword ? S qword ? CALLBACK ends ASMENTRY_STACK struct ;keep this 16 byte aligned Scratchspace qword ? Scratchspace2 qword ? Scratchspace3 qword ? Scratchspace4 qword ? Originalmxcsr qword ? OriginalRAX qword ? ;0 OriginalRBX qword ? ;1 OriginalRCX qword ? ;2 OriginalRDX qword ? ;3 OriginalRSI qword ? ;4 OriginalRDI qword ? ;5 OriginalRBP qword ? ;6 OriginalRSP qword ? ;7 not really 'original' OriginalR8 qword ? ;8 OriginalR9 qword ? ;9 OriginalR10 qword ? ;10 OriginalR11 qword ? ;11 OriginalR12 qword ? ;12 OriginalR13 qword ? ;13 OriginalR14 qword ? ;14 OriginalR15 qword ? ;15 OriginalES qword ? ;16 OriginalDS qword ? ;17 OriginalSS qword ? ;18 fxsavespace db 512 dup(?) ;fpu state ;errorcode/returnaddress ;19 ;4096 bytes ;eip ;20 ;cs ;21 ;eflags ;esp ;ss ASMENTRY_STACK ends _TEXT SEGMENT 'CODE' EXTERN interrupt1_centry : proc EXTERN Int1JumpBackLocation : CALLBACK PUBLIC interrupt1_asmentry interrupt1_asmentry: ;save stack position push [Int1JumpBackLocation.A] ;push an errorcode on the stack so the stackindex enum type can stay the same relative to interrupts that do have an errorcode (int 14). Also helps with variable interrupt handlers sub rsp,4096 ;functions like setThreadContext adjust the stackframe entry directly. I can't have that messing up my own stack cld ;stack is aligned at this point sub rsp,SIZEOF ASMENTRY_STACK mov (ASMENTRY_STACK PTR [rsp]).OriginalRBP,rbp lea rbp,(ASMENTRY_STACK PTR [rsp]).OriginalRAX mov (ASMENTRY_STACK PTR [rsp]).OriginalRAX,rax mov (ASMENTRY_STACK PTR [rsp]).OriginalRBX,rbx mov (ASMENTRY_STACK PTR [rsp]).OriginalRCX,rcx mov (ASMENTRY_STACK PTR [rsp]).OriginalRDX,rdx mov (ASMENTRY_STACK PTR [rsp]).OriginalRSI,rsi mov (ASMENTRY_STACK PTR [rsp]).OriginalRDI,rdi mov (ASMENTRY_STACK PTR [rsp]).OriginalRSP,rsp mov (ASMENTRY_STACK PTR [rsp]).OriginalR8,r8 mov (ASMENTRY_STACK PTR [rsp]).OriginalR9,r9 mov (ASMENTRY_STACK PTR [rsp]).OriginalR10,r10 mov (ASMENTRY_STACK PTR [rsp]).OriginalR11,r11 mov (ASMENTRY_STACK PTR [rsp]).OriginalR12,r12 mov (ASMENTRY_STACK PTR [rsp]).OriginalR13,r13 mov (ASMENTRY_STACK PTR [rsp]).OriginalR14,r14 mov (ASMENTRY_STACK PTR [rsp]).OriginalR15,r15 fxsave (ASMENTRY_STACK PTR [rsp]).fxsavespace mov ax,ds mov word ptr (ASMENTRY_STACK PTR [rsp]).OriginalDS,ax mov ax,es mov word ptr (ASMENTRY_STACK PTR [rsp]).OriginalES,ax mov ax,ss mov word ptr (ASMENTRY_STACK PTR [rsp]).OriginalSS,ax mov ax,2bh mov ds,ax mov es,ax mov ax,18h mov ss,ax ; rbp= pointer to OriginalRAX cmp qword ptr [rbp+8*21+512+4096],010h ;check if origin is in kernelmode (check ss) je skipswap1 ;if so, skip the swapgs swapgs ;swap gs with the kernel version skipswap1: stmxcsr dword ptr (ASMENTRY_STACK PTR [rsp]).Originalmxcsr mov (ASMENTRY_STACK PTR [rsp]).scratchspace2,1f80h ldmxcsr dword ptr (ASMENTRY_STACK PTR [rsp]).scratchspace2 mov rcx,rbp call interrupt1_centry ldmxcsr dword ptr (ASMENTRY_STACK PTR [rsp]).Originalmxcsr cmp qword ptr [rbp+8*21+512+4096],10h ;was it a kernelmode interrupt ? je skipswap2 ;if so, skip the swapgs part swapgs ;swap back skipswap2: cmp al,1 ;restore state fxrstor (ASMENTRY_STACK PTR [rsp]).fxsavespace mov ax,word ptr (ASMENTRY_STACK PTR [rsp]).OriginalDS mov ds,ax mov ax,word ptr (ASMENTRY_STACK PTR [rsp]).OriginalES mov es,ax mov ax,word ptr (ASMENTRY_STACK PTR [rsp]).OriginalSS mov ss,ax mov rax,(ASMENTRY_STACK PTR [rsp]).OriginalRAX mov rbx,(ASMENTRY_STACK PTR [rsp]).OriginalRBX mov rcx,(ASMENTRY_STACK PTR [rsp]).OriginalRCX mov rdx,(ASMENTRY_STACK PTR [rsp]).OriginalRDX mov rsi,(ASMENTRY_STACK PTR [rsp]).OriginalRSI mov rdi,(ASMENTRY_STACK PTR [rsp]).OriginalRDI mov r8, (ASMENTRY_STACK PTR [rsp]).OriginalR8 mov r9, (ASMENTRY_STACK PTR [rsp]).OriginalR9 mov r10,(ASMENTRY_STACK PTR [rsp]).OriginalR10 mov r11,(ASMENTRY_STACK PTR [rsp]).OriginalR11 mov r12,(ASMENTRY_STACK PTR [rsp]).OriginalR12 mov r13,(ASMENTRY_STACK PTR [rsp]).OriginalR13 mov r14,(ASMENTRY_STACK PTR [rsp]).OriginalR14 mov r15,(ASMENTRY_STACK PTR [rsp]).OriginalR15 je skip_original_int1 ;stack unwind mov rbp,(ASMENTRY_STACK PTR [rsp]).OriginalRBP add rsp,SIZEOF ASMENTRY_STACK add rsp,4096 ;at this point [rsp] holds the original int1 handler ret ; used to be add rsp,8 ;+8 for the push 0 ;todo: do a jmp [Int1JumpBackLocationCPUNR] and have 256 Int1JumpBackLocationCPUNR's and each cpu goes to it's own interrupt1_asmentry[cpunr] ;jmp [Int1JumpBackLocation.A] ;<-works fine skip_original_int1: ;stack unwind mov rbp,(ASMENTRY_STACK PTR [rsp]).OriginalRBP add rsp,SIZEOF ASMENTRY_STACK add rsp,4096 add rsp,8 ;+8 for the push iretq _TEXT ENDS END <|start_filename|>src/extradefines.h<|end_filename|> /*#define HDESK ULONG #define HWND ULONG #define DWORD ULONG #define WORD USHORT #define BYTE UCHAR #define UINT ULONG #define FILE_DEVICE_UNKNOWN 0x00000022 #define IOCTL_UNKNOWN_BASE FILE_DEVICE_UNKNOWN*/ NTKERNELAPI NTSTATUS ObOpenObjectByName( IN POBJECT_ATTRIBUTES ObjectAttributes, IN POBJECT_TYPE ObjectType, IN KPROCESSOR_MODE AccessMode, IN OUT PACCESS_STATE PassedAccessState OPTIONAL, IN ACCESS_MASK DesiredAccess OPTIONAL, IN OUT PVOID ParseContext OPTIONAL, OUT PHANDLE Handle ); <|start_filename|>src/amd64/ultimapa.asm<|end_filename|> ;RCX: 1st integer argument ;RDX: 2nd integer argument ;R8: 3rd integer argument ;R9: 4th integer argument CALLBACK struct A qword ? S qword ? CALLBACK ends ASMENTRY_STACK struct ;keep this 16 byte aligned Scratchspace qword ? ;0 Scratchspace2 qword ? ;8 Scratchspace3 qword ? ;0 Scratchspace4 qword ? ;8 Originalmxcsr qword ? OriginalRAX qword ? OriginalRBX qword ? OriginalRCX qword ? OriginalRDX qword ? OriginalRSI qword ? OriginalRDI qword ? OriginalRBP qword ? OriginalRSP qword ? ;not really 'original' OriginalR8 qword ? OriginalR9 qword ? OriginalR10 qword ? OriginalR11 qword ? OriginalR12 qword ? OriginalR13 qword ? OriginalR14 qword ? OriginalR15 qword ? OriginalES qword ? OriginalDS qword ? OriginalSS qword ? ASMENTRY_STACK ends _TEXT SEGMENT 'CODE' EXTERN perfmon_interrupt_centry : proc EXTERN perfmonJumpBackLocation : CALLBACK PUBLIC perfmon_interrupt perfmon_interrupt: ;save stack position cld push 0 ;push an errorcode on the stack so the stackindex enum type can stay the same relative to interrupts that do have an errorcode (int 14) ;stack is aligned at this point sub rsp, 4096 sub rsp,SIZEOF ASMENTRY_STACK mov (ASMENTRY_STACK PTR [rsp]).OriginalRBP,rbp lea rbp,(ASMENTRY_STACK PTR [rsp]).OriginalRAX ;make rbp point to the start of the structure mov (ASMENTRY_STACK PTR [rsp]).OriginalRAX,rax mov (ASMENTRY_STACK PTR [rsp]).OriginalRBX,rbx mov (ASMENTRY_STACK PTR [rsp]).OriginalRCX,rcx mov (ASMENTRY_STACK PTR [rsp]).OriginalRDX,rdx mov (ASMENTRY_STACK PTR [rsp]).OriginalRSI,rsi mov (ASMENTRY_STACK PTR [rsp]).OriginalRDI,rdi mov (ASMENTRY_STACK PTR [rsp]).OriginalRSP,rsp mov (ASMENTRY_STACK PTR [rsp]).OriginalR8,r8 mov (ASMENTRY_STACK PTR [rsp]).OriginalR9,r9 mov (ASMENTRY_STACK PTR [rsp]).OriginalR10,r10 mov (ASMENTRY_STACK PTR [rsp]).OriginalR11,r11 mov (ASMENTRY_STACK PTR [rsp]).OriginalR12,r12 mov (ASMENTRY_STACK PTR [rsp]).OriginalR13,r13 mov (ASMENTRY_STACK PTR [rsp]).OriginalR14,r14 mov (ASMENTRY_STACK PTR [rsp]).OriginalR15,r15 mov ax,ds mov word ptr (ASMENTRY_STACK PTR [rsp]).OriginalDS,ax mov ax,es mov word ptr (ASMENTRY_STACK PTR [rsp]).OriginalES,ax mov ax,ss mov word ptr (ASMENTRY_STACK PTR [rsp]).OriginalSS,ax mov ax,2bh mov ds,ax mov es,ax mov ax,18h mov ss,ax cmp qword ptr [rbp+8*21+4096],010h ;check if origin is in kernelmode (check ss) je skipswap1 ;if so, skip the swapgs swapgs ;swap gs with the kernel version (not to self fix when called from inside kernel) skipswap1: stmxcsr dword ptr (ASMENTRY_STACK PTR [rsp]).Originalmxcsr mov (ASMENTRY_STACK PTR [rsp]).scratchspace,1f80h ldmxcsr dword ptr (ASMENTRY_STACK PTR [rsp]).scratchspace ;mov rcx,rbp call perfmon_interrupt_centry ldmxcsr dword ptr (ASMENTRY_STACK PTR [rsp]).Originalmxcsr cmp qword ptr [rbp+8*21+4096],10h ;was it a kernelmode interrupt ? je skipswap2 ;if so, skip the swapgs part swapgs ;swap back skipswap2: cmp al,1 ;restore state mov ax,word ptr (ASMENTRY_STACK PTR [rsp]).OriginalDS mov ds,ax mov ax,word ptr (ASMENTRY_STACK PTR [rsp]).OriginalES mov es,ax mov ax,word ptr (ASMENTRY_STACK PTR [rsp]).OriginalSS mov ss,ax mov rax,(ASMENTRY_STACK PTR [rsp]).OriginalRAX mov rbx,(ASMENTRY_STACK PTR [rsp]).OriginalRBX mov rcx,(ASMENTRY_STACK PTR [rsp]).OriginalRCX mov rdx,(ASMENTRY_STACK PTR [rsp]).OriginalRDX mov rsi,(ASMENTRY_STACK PTR [rsp]).OriginalRSI mov rdi,(ASMENTRY_STACK PTR [rsp]).OriginalRDI mov r8,(ASMENTRY_STACK PTR [rsp]).OriginalR8 mov r9,(ASMENTRY_STACK PTR [rsp]).OriginalR9 mov r10,(ASMENTRY_STACK PTR [rsp]).OriginalR10 mov r11,(ASMENTRY_STACK PTR [rsp]).OriginalR11 mov r12,(ASMENTRY_STACK PTR [rsp]).OriginalR12 mov r13,(ASMENTRY_STACK PTR [rsp]).OriginalR13 mov r14,(ASMENTRY_STACK PTR [rsp]).OriginalR14 mov r15,(ASMENTRY_STACK PTR [rsp]).OriginalR15 je skip_original_perfmon jmp skip_original_perfmon ;stack unwind mov rbp,(ASMENTRY_STACK PTR [rsp]).OriginalRBP add rsp,SIZEOF ASMENTRY_STACK ;+8 for the push 0 add rsp,8 add rsp,4096 jmp [perfmonJumpBackLocation.A] ;<-works fine skip_original_perfmon: ;stack unwind mov rbp,(ASMENTRY_STACK PTR [rsp]).OriginalRBP add rsp,SIZEOF ASMENTRY_STACK ;+8 for the push 0 add rsp,4096 add rsp,8 ;jump to when the stack has been completly restored to what it was at interrupt time ;push rax ;push rbx ;unmask the perfmon interrupt ;mov rax,0fffffffffffe0330h ;mov rbx,[rax] ;and rbx,0ffh ;mov [rax],rbx ;End of interrupt ;mov rax,0fffffffffffe00b0h ;xor rbx,rbx ;mov [rax],rbx ;set EOI to 0 ;pop rbx ;pop rax iretq _TEXT ENDS END <|start_filename|>src/noexceptions.h<|end_filename|> #ifndef NOEXCEPTIONS_H #define NOEXCEPTIONS_H /* Will be responsible for temporarily switching out the IDT of the curent CPU with one that doesn't call windows functions on errors */ #include <ntifs.h> #include <wdm.h> #include <windef.h> #include "interruptHook.h" #include "dbkfunc.h" typedef struct { KIRQL entryIRQL; PINT_VECTOR NoExceptionVectorList; //list pointing to an idt table with hooked ints IDT OriginalIDT; IDT ModdedIDT; } CPUSTATE, *PCPUSTATE; BOOL NoExceptions_Enter(); int NoExceptions_CopyMemory(PVOID Destination, PVOID Source, int size); void NoExceptions_Leave(); void NoExceptions_Cleanup(); void NoException14_ErrorHandler(); #endif <|start_filename|>src/interruptHook.c<|end_filename|> #pragma warning( disable: 4103) #include "ntifs.h" #include <windef.h> #include "DBKFunc.h" #include "vmxhelper.h" #include "interruptHook.h" //this sourcefile only so no need to worry about it being modified by out of context code struct { int hooked; int dbvmInterruptEmulation; //if used, originalCS and originalEIP are ignored and the current IDT data is used to resume the interrupt, currently only for interrupt 1 and 14 WORD originalCS; ULONG_PTR originalEIP; } InterruptHook[256]; WORD inthook_getOriginalCS(unsigned char intnr) { return InterruptHook[intnr].originalCS; } ULONG_PTR inthook_getOriginalEIP(unsigned char intnr) { return InterruptHook[intnr].originalEIP; } int inthook_isHooked(unsigned char intnr) { if (InterruptHook[intnr].hooked) { //todo: add a check to see if the hook is still present. if not, return false and update the hooked value return TRUE; } else return FALSE; } int inthook_isDBVMHook(unsigned char intnr) { return InterruptHook[intnr].dbvmInterruptEmulation; } int inthook_UnhookInterrupt(unsigned char intnr) { if (InterruptHook[intnr].hooked) { //it's hooked, try to unhook DbgPrint("cpu %d : interrupt %d is hooked\n",cpunr(),intnr); if (InterruptHook[intnr].dbvmInterruptEmulation) { if (intnr==1) vmx_redirect_interrupt1(virt_differentInterrupt, 1, 0, 0); else if (intnr==3) vmx_redirect_interrupt3(virt_differentInterrupt, 3, 0, 0); else vmx_redirect_interrupt14(virt_differentInterrupt, 14, 0, 0); return TRUE; //that's all we need } //still here so not a dbvm hook, unhook the old way and hope nothing has interfered { INT_VECTOR newVector; //newVector.bUnused=0; /* newVector.gatetype=6; //interrupt gate newVector.gatesize=1; //32-bit newVector.zero=0; newVector.DPL=0; newVector.P=1; */ newVector.wHighOffset=(WORD)((DWORD)(InterruptHook[intnr].originalEIP >> 16)); newVector.wLowOffset=(WORD)InterruptHook[intnr].originalEIP; newVector.wSelector=(WORD)InterruptHook[intnr].originalCS; #ifdef AMD64 newVector.TopOffset=(InterruptHook[intnr].originalEIP >> 32); newVector.Reserved=0; #endif { IDT idt; GetIDT(&idt); newVector.bAccessFlags=idt.vector[intnr].bAccessFlags; disableInterrupts(); idt.vector[intnr]=newVector; enableInterrupts(); } DbgPrint("Restored\n"); } } return TRUE; } int inthook_HookInterrupt(unsigned char intnr, int newCS, ULONG_PTR newEIP, PJUMPBACK jumpback) { IDT idt; GetIDT(&idt); DbgPrint("inthook_HookInterrupt for cpu %d (vmxusable=%d)\n",cpunr(), vmxusable); #ifdef AMD64 DbgPrint("interrupt %d newCS=%x newEIP=%llx jumpbacklocation=%p\n",intnr, newCS, newEIP, jumpback); #else DbgPrint("interrupt %d newCS=%x newEIP=%x jumpbacklocation=%p\n",intnr, newCS, newEIP, jumpback); #endif DbgPrint("InterruptHook[%d].hooked=%d\n", intnr, InterruptHook[intnr].hooked); if (!InterruptHook[intnr].hooked) { //new hook, so save the originals InterruptHook[intnr].originalCS=idt.vector[intnr].wSelector; InterruptHook[intnr].originalEIP=idt.vector[intnr].wLowOffset+(idt.vector[intnr].wHighOffset << 16); #ifdef AMD64 InterruptHook[intnr].originalEIP|=(UINT64)((UINT64)idt.vector[intnr].TopOffset << 32); #endif } if (jumpback) { jumpback->cs=InterruptHook[intnr].originalCS; jumpback->eip=InterruptHook[intnr].originalEIP; } DbgPrint("vmxusable=%d\n", vmxusable); if (vmxusable && ((intnr==1) || (intnr==3) || (intnr==14)) ) { DbgPrint("VMX Hook path\n"); switch (intnr) { case 1: vmx_redirect_interrupt1(virt_emulateInterrupt, 0, newCS, newEIP); break; case 3: vmx_redirect_interrupt3(virt_emulateInterrupt, 0, newCS, newEIP); break; case 14: vmx_redirect_interrupt14(virt_emulateInterrupt, 0, newCS, newEIP); break; } InterruptHook[intnr].dbvmInterruptEmulation=1; } else { //old fashioned hook INT_VECTOR newVector; #ifdef AMD64 if (intnr<32) { DbgPrint("64-bit: DBVM is not loaded and a non dbvm hookable interrupt is being hooked that falls below 32\n"); return FALSE; } #endif DbgPrint("sizeof newVector=%d\n",sizeof(INT_VECTOR)); newVector.wHighOffset=(WORD)((DWORD)(newEIP >> 16)); newVector.wLowOffset=(WORD)newEIP; newVector.wSelector=(WORD)newCS; newVector.bUnused=0; newVector.bAccessFlags=idt.vector[intnr].bAccessFlags; //don't touch accessflag, the default settings are good (e.g: int3,4 and 8 have dpl=3) #ifdef AMD64 newVector.TopOffset=(newEIP >> 32); newVector.Reserved=0; #endif disableInterrupts(); //no kernelmode taskswitches please idt.vector[intnr]=newVector; enableInterrupts(); InterruptHook[intnr].dbvmInterruptEmulation=0; DbgPrint("int %d will now go to %x:%p\n",intnr, newCS, newEIP); } InterruptHook[intnr].hooked=1; return TRUE; } <|start_filename|>src/IOPLDispatcher.c<|end_filename|> #pragma warning( disable: 4100 4101 4103 4189) #include "IOPLDispatcher.h" #include "DBKFunc.h" #include "DBKDrvr.h" #include "memscan.h" #include "deepkernel.h" #include "processlist.h" #include "threads.h" #include "interruptHook.h" #include "debugger.h" #include "vmxhelper.h" #include "vmxoffload.h" #include "ultimap.h" #include "ultimap2.h" UINT64 PhysicalMemoryRanges=0; //initialized once, and used thereafter. If the user adds/removes ram at runtime, screw him and make him the reload the driver UINT64 PhysicalMemoryRangesListSize=0; #if (NTDDI_VERSION >= NTDDI_VISTA) PVOID DRMHandle = NULL; PEPROCESS DRMProcess = NULL; PEPROCESS DRMProcess2 = NULL; #endif typedef PCHAR (*GET_PROCESS_IMAGE_NAME) (PEPROCESS Process); GET_PROCESS_IMAGE_NAME PsGetProcessImageFileName; /* typedef struct { int listcount; char cpunrs[255]; } CPULISTFILLSTRUCT, *PCPULISTFILLSTRUCT; VOID GetCPUIDS_all(PCPULISTFILLSTRUCT p) { DbgPrint("GetCPUIDS_all(for cpu %d)\n", cpunr()); if (p->listcount<255) { p->cpunrs[p->listcount]=cpunr(); p->listcount++; } } */ NTSYSAPI NTSTATUS NTAPI ZwQueryInformationProcess(IN HANDLE ProcessHandle, IN PROCESSINFOCLASS ProcessInformationClass, OUT PVOID ProcessInformation, IN ULONG ProcessInformationLength, OUT PULONG ReturnLength OPTIONAL); void mykapc2(PKAPC Apc, PKNORMAL_ROUTINE NormalRoutine, PVOID NormalContext, PVOID SystemArgument1, PVOID SystemArgument2) { ULONG_PTR iswow64; ExFreePool(Apc); DbgPrint("My second kernelmode apc!!!!\n"); DbgPrint("SystemArgument1=%x\n",*(PULONG)SystemArgument1); DbgPrint("SystemArgument2=%x\n", *(PULONG)SystemArgument2); if (ZwQueryInformationProcess(ZwCurrentProcess(), ProcessWow64Information, &iswow64, sizeof(iswow64), NULL) == STATUS_SUCCESS) { #if (NTDDI_VERSION >= NTDDI_VISTA) if (iswow64) { DbgPrint("WOW64 apc"); PsWrapApcWow64Thread(NormalContext, (PVOID*)NormalRoutine); } #endif } } void nothing2(PVOID arg1, PVOID arg2, PVOID arg3) { return; } void mykapc(PKAPC Apc, PKNORMAL_ROUTINE NormalRoutine, PVOID NormalContext, PVOID SystemArgument1, PVOID SystemArgument2) { //kernelmode apc, always gets executed PKAPC kApc; LARGE_INTEGER Timeout; kApc = ExAllocatePool(NonPagedPool, sizeof(KAPC)); ExFreePool(Apc); DbgPrint("My kernelmode apc!!!!(irql=%d)\n", KeGetCurrentIrql()); DbgPrint("NormalRoutine=%p\n",*(PUINT_PTR)NormalRoutine); DbgPrint("NormalContext=%p\n",*(PUINT_PTR)NormalContext); DbgPrint("SystemArgument1=%p\n",*(PUINT_PTR)SystemArgument1); DbgPrint("SystemArgument2=%p\n",*(PUINT_PTR)SystemArgument2); KeInitializeApc(kApc, (PKTHREAD)PsGetCurrentThread(), 0, (PKKERNEL_ROUTINE)mykapc2, NULL, (PKNORMAL_ROUTINE)*(PUINT_PTR)SystemArgument1, UserMode, (PVOID)*(PUINT_PTR)NormalContext ); KeInsertQueueApc (kApc, (PVOID)*(PUINT_PTR)SystemArgument1, (PVOID)*(PUINT_PTR)SystemArgument2, 0); //wait in usermode (so interruptable by a usermode apc) Timeout.QuadPart = 0; KeDelayExecutionThread(UserMode, TRUE, &Timeout); return; } void nothing(PVOID arg1, PVOID arg2, PVOID arg3) { return; } void CreateRemoteAPC(ULONG threadid,PVOID addresstoexecute) { PKTHREAD kThread; PKAPC kApc; kApc = ExAllocatePool(NonPagedPool, sizeof(KAPC)); kThread=(PKTHREAD)getPEThread(threadid); DbgPrint("(PVOID)KThread=%p\n",kThread); DbgPrint("addresstoexecute=%p\n", addresstoexecute); KeInitializeApc(kApc, kThread, 0, (PKKERNEL_ROUTINE)mykapc, NULL, (PKNORMAL_ROUTINE)nothing, KernelMode, 0 ); KeInsertQueueApc (kApc, addresstoexecute, addresstoexecute, 0); } #define PROCESS_TERMINATE (0x0001) #define PROCESS_CREATE_THREAD (0x0002) #define PROCESS_SET_SESSIONID (0x0004) #define PROCESS_VM_OPERATION (0x0008) #define PROCESS_VM_READ (0x0010) #define PROCESS_VM_WRITE (0x0020) #define PROCESS_DUP_HANDLE (0x0040) #define PROCESS_CREATE_PROCESS (0x0080) #define PROCESS_SET_QUOTA (0x0100) #define PROCESS_SET_INFORMATION (0x0200) #define PROCESS_QUERY_INFORMATION (0x0400) #define PROCESS_SUSPEND_RESUME (0x0800) #define PROCESS_QUERY_LIMITED_INFORMATION (0x1000) #if (NTDDI_VERSION >= NTDDI_VISTA) OB_PREOP_CALLBACK_STATUS ThreadPreCallback(PVOID RegistrationContext, POB_PRE_OPERATION_INFORMATION OperationInformation) { if (DRMProcess == NULL) return OB_PREOP_SUCCESS; if (PsGetCurrentProcess() == DRMProcess) return OB_PREOP_SUCCESS; if (OperationInformation->ObjectType == *PsThreadType) { if ((PsGetProcessId(DRMProcess) == PsGetThreadProcessId(OperationInformation->Object)) || ((DRMProcess2) && (PsGetProcessId(DRMProcess2) == PsGetThreadProcessId(OperationInformation->Object)))) { //probably block it if (OperationInformation->Operation == OB_OPERATION_HANDLE_CREATE) { //create handle ACCESS_MASK da = OperationInformation->Parameters->CreateHandleInformation.DesiredAccess; DbgPrint("PID %d opened a handle to the a CE thread with access mask %x", PsGetCurrentProcessId(), da); da = da & (THREAD_SET_LIMITED_INFORMATION | THREAD_QUERY_LIMITED_INFORMATION); OperationInformation->Parameters->CreateHandleInformation.DesiredAccess = 0;// da; } else if (OperationInformation->Operation == OB_OPERATION_HANDLE_DUPLICATE) { //duplicate handle ACCESS_MASK da = OperationInformation->Parameters->DuplicateHandleInformation.DesiredAccess; DbgPrint("PID %d duplicated a handle to a CE thread with access mask %x", PsGetCurrentProcessId(), da); da = da & (THREAD_SET_LIMITED_INFORMATION | THREAD_QUERY_LIMITED_INFORMATION); OperationInformation->Parameters->DuplicateHandleInformation.DesiredAccess = 0;// da; } } } return OB_PREOP_SUCCESS; } VOID ThreadPostCallback(PVOID RegistrationContext, POB_POST_OPERATION_INFORMATION OperationInformation) { //DbgPrint("ProcessPostCallback"); } OB_PREOP_CALLBACK_STATUS ProcessPreCallback(PVOID RegistrationContext, POB_PRE_OPERATION_INFORMATION OperationInformation) { if (DRMProcess == NULL) return OB_PREOP_SUCCESS; //if (PsGetCurrentProcess() == DRMProcess) // return OB_PREOP_SUCCESS; if (OperationInformation->ObjectType == *PsProcessType) { if ((OperationInformation->Object == DRMProcess) || (OperationInformation->Object == DRMProcess2)) { //probably block it if (OperationInformation->Operation == OB_OPERATION_HANDLE_CREATE) { //create handle ACCESS_MASK da = OperationInformation->Parameters->CreateHandleInformation.DesiredAccess; DbgPrint("PID %d(%p) opened a handle to the CE process(%p) with access mask %x", PsGetCurrentProcessId(), PsGetCurrentProcess(), DRMProcess, da); da = da & (PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SUSPEND_RESUME); //da = da & PROCESS_SUSPEND_RESUME; OperationInformation->Parameters->CreateHandleInformation.DesiredAccess = 0;// da; } else if (OperationInformation->Operation == OB_OPERATION_HANDLE_DUPLICATE) { //duplicate handle ACCESS_MASK da = OperationInformation->Parameters->DuplicateHandleInformation.DesiredAccess; DbgPrint("PID %d(%p) opened a handle to the CE process(%p) with access mask %x", PsGetCurrentProcessId(), PsGetCurrentProcess(), DRMProcess, da); da = da & (PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SUSPEND_RESUME); //da = da & PROCESS_SUSPEND_RESUME; OperationInformation->Parameters->DuplicateHandleInformation.DesiredAccess = 0;// da; } } } return OB_PREOP_SUCCESS; } VOID ProcessPostCallback(PVOID RegistrationContext, POB_POST_OPERATION_INFORMATION OperationInformation) { //DbgPrint("ProcessPostCallback"); } #endif BOOL DispatchIoctlDBVM(IN PDEVICE_OBJECT DeviceObject, ULONG IoControlCode, PVOID lpInBuffer, DWORD nInBufferSize, PVOID lpOutBuffer, DWORD nOutBufferSize, PDWORD lpBytesReturned) /* Called if dbvm has loaded the driver. Use this to setup a fake irp */ { //allocate a in and out buffer //setup a fake IRP IRP FakeIRP; BOOL r; PVOID buffer; buffer=ExAllocatePool(PagedPool, max(nInBufferSize, nOutBufferSize)); RtlCopyMemory(buffer, lpInBuffer, nInBufferSize); DbgPrint("DispatchIoctlDBVM\n"); FakeIRP.AssociatedIrp.SystemBuffer=buffer; FakeIRP.Flags=IoControlCode; //(ab)using an unused element r=DispatchIoctl(DeviceObject, &FakeIRP)==STATUS_SUCCESS; RtlCopyMemory(lpOutBuffer, buffer, nOutBufferSize); ExFreePool(buffer); return r; } NTSTATUS DispatchIoctl(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { NTSTATUS ntStatus=STATUS_UNSUCCESSFUL; PIO_STACK_LOCATION irpStack=NULL; LUID sedebugprivUID; ULONG IoControlCode; if (!loadedbydbvm) { irpStack=IoGetCurrentIrpStackLocation(Irp); IoControlCode=irpStack->Parameters.DeviceIoControl.IoControlCode; } else IoControlCode=Irp->Flags; //DbgPrint("DispatchIoctl. IoControlCode=%x\n", IoControlCode); #ifdef TOBESIGNED sedebugprivUID.LowPart=SE_DEBUG_PRIVILEGE; sedebugprivUID.HighPart=0; if (SeSinglePrivilegeCheck(sedebugprivUID, UserMode)==FALSE) { DbgPrint("DispatchIoctl called by a process without SeDebugPrivilege"); return STATUS_UNSUCCESSFUL; } #endif switch(IoControlCode) { case IOCTL_CE_READMEMORY: __try { struct input { UINT64 processid; UINT64 startaddress; WORD bytestoread; } *pinp; pinp=Irp->AssociatedIrp.SystemBuffer; ntStatus=ReadProcessMemory((DWORD)pinp->processid,NULL,(PVOID)(UINT_PTR)pinp->startaddress,pinp->bytestoread,pinp) ? STATUS_SUCCESS : STATUS_UNSUCCESSFUL; } __except(1) { ntStatus = STATUS_UNSUCCESSFUL; }; break; case IOCTL_CE_WRITEMEMORY: __try { struct input { UINT64 processid; UINT64 startaddress; WORD bytestowrite; } *pinp,inp; DbgPrint("sizeof(inp)=%d\n",sizeof(inp)); pinp=Irp->AssociatedIrp.SystemBuffer; ntStatus=WriteProcessMemory((DWORD)pinp->processid,NULL,(PVOID)(UINT_PTR)pinp->startaddress,pinp->bytestowrite,(PVOID)((UINT_PTR)pinp+sizeof(inp))) ? STATUS_SUCCESS : STATUS_UNSUCCESSFUL; } __except(1) { //something went wrong and I don't know what ntStatus = STATUS_UNSUCCESSFUL; }; break; case IOCTL_CE_OPENPROCESS: { PEPROCESS selectedprocess = NULL; ULONG processid=*(PULONG)Irp->AssociatedIrp.SystemBuffer; HANDLE ProcessHandle = GetHandleForProcessID((HANDLE)processid); struct out { UINT64 h; BYTE Special; } *POutput = Irp->AssociatedIrp.SystemBuffer; ntStatus = STATUS_SUCCESS; if (ProcessHandle == 0) { POutput->Special = 0; __try { ProcessHandle = 0; if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(processid), &selectedprocess) == STATUS_SUCCESS) { //DbgPrint("Calling ObOpenObjectByPointer\n"); ntStatus = ObOpenObjectByPointer( selectedprocess, 0, NULL, PROCESS_ALL_ACCESS, *PsProcessType, KernelMode, //UserMode, &ProcessHandle); //DbgPrint("ntStatus=%x",ntStatus); } } __except (1) { ntStatus = STATUS_UNSUCCESSFUL; } } else { //DbgPrint("ProcessHandle=%x", (int)ProcessHandle); POutput->Special = 1; } if (selectedprocess) { ObDereferenceObject(selectedprocess); } POutput->h=(UINT64)ProcessHandle; break; } case IOCTL_CE_OPENTHREAD: { HANDLE ThreadHandle; CLIENT_ID ClientID; OBJECT_ATTRIBUTES ObjectAttributes; RtlZeroMemory(&ObjectAttributes,sizeof(OBJECT_ATTRIBUTES)); ntStatus=STATUS_SUCCESS; ClientID.UniqueProcess=0; ClientID.UniqueThread=(HANDLE)(UINT_PTR)*(PULONG)Irp->AssociatedIrp.SystemBuffer; ThreadHandle=0; __try { ThreadHandle=0; ntStatus=ZwOpenThread(&ThreadHandle,PROCESS_ALL_ACCESS,&ObjectAttributes,&ClientID); } __except(1) { ntStatus=STATUS_UNSUCCESSFUL; } *(PUINT64)Irp->AssociatedIrp.SystemBuffer=(UINT64)ThreadHandle; break; } case IOCTL_CE_MAKEWRITABLE: { #ifdef AMD64 //untill I know how win64 handles paging, not implemented #else struct InputBuf { UINT64 StartAddress; ULONG Size; BYTE CopyOnWrite; } *PInputBuf; PInputBuf=Irp->AssociatedIrp.SystemBuffer; ntStatus=MakeWritable((PVOID)(UINT_PTR)PInputBuf->StartAddress,PInputBuf->Size,(PInputBuf->CopyOnWrite==1)) ? STATUS_SUCCESS : STATUS_UNSUCCESSFUL; #endif break; } case IOCTL_CE_QUERY_VIRTUAL_MEMORY: { struct InputBuf { UINT64 ProcessID; UINT64 StartAddress; } *PInputBuf; struct OutputBuf { UINT64 length; DWORD protection; } *POutputBuf; UINT_PTR BaseAddress; UINT_PTR length; BOOL ShowResult=0; ntStatus=STATUS_SUCCESS; PInputBuf=Irp->AssociatedIrp.SystemBuffer; POutputBuf=Irp->AssociatedIrp.SystemBuffer; if (PInputBuf->StartAddress==(UINT64)0x12000) ShowResult=1; __try { ntStatus = GetMemoryRegionData((DWORD)PInputBuf->ProcessID, NULL, (PVOID)(UINT_PTR)(PInputBuf->StartAddress), &(POutputBuf->protection), &length, &BaseAddress); } __except(1) { DbgPrint("GetMemoryRegionData error"); ntStatus = STATUS_UNSUCCESSFUL; break; } POutputBuf->length=(UINT64)length; if (ShowResult) { DbgPrint("GetMemoryRegionData returned %x\n",ntStatus); DbgPrint("protection=%x\n",POutputBuf->protection); DbgPrint("length=%p\n",POutputBuf->length); DbgPrint("BaseAddress=%p\n", BaseAddress); } break; } case IOCTL_CE_TEST: //just a test to see it's working { UNICODE_STRING test; PVOID x; QWORD a, b; _disable(); a = __rdtsc(); b = __rdtsc(); _enable(); DbgPrint("%d\n", (int)(b - a)); break; } case IOCTL_CE_GETPETHREAD: { *(PUINT64)Irp->AssociatedIrp.SystemBuffer=(UINT64)getPEThread((UINT_PTR)*(PULONG)Irp->AssociatedIrp.SystemBuffer); ntStatus= STATUS_SUCCESS; break; } case IOCTL_CE_GETPEPROCESS: { DWORD processid=*(PDWORD)Irp->AssociatedIrp.SystemBuffer; PEPROCESS selectedprocess; if (processid==0) { ntStatus=STATUS_UNSUCCESSFUL; } else { if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(processid),&selectedprocess)==STATUS_SUCCESS) { #ifdef AMD64 *(PUINT64)Irp->AssociatedIrp.SystemBuffer=(UINT64)selectedprocess; #else *(PUINT64)Irp->AssociatedIrp.SystemBuffer=(DWORD)selectedprocess; #endif //DbgPrint("PEProcess=%llx\n", *(PUINT64)Irp->AssociatedIrp.SystemBuffer); ObDereferenceObject(selectedprocess); } else *(PUINT64)Irp->AssociatedIrp.SystemBuffer=0; } ntStatus= STATUS_SUCCESS; break; } case IOCTL_CE_READPHYSICALMEMORY: { struct input { UINT64 startaddress; UINT64 bytestoread; } *pinp; pinp=Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_READPHYSICALMEMORY:pinp->startaddress=%x, pinp->bytestoread=%d", pinp->startaddress, pinp->bytestoread); ntStatus = ReadPhysicalMemory((PVOID)(UINT_PTR)pinp->startaddress, (UINT_PTR)pinp->bytestoread, pinp); break; } case IOCTL_CE_WRITEPHYSICALMEMORY: { HANDLE physmem; UNICODE_STRING physmemString; OBJECT_ATTRIBUTES attributes; WCHAR physmemName[] = L"\\device\\physicalmemory"; UCHAR* memoryview; RtlInitUnicodeString( &physmemString, physmemName ); InitializeObjectAttributes( &attributes, &physmemString, OBJ_CASE_INSENSITIVE, NULL, NULL ); ntStatus=ZwOpenSection( &physmem, SECTION_ALL_ACCESS, &attributes ); if (ntStatus==STATUS_SUCCESS) { //hey look, it didn't kill it struct input { UINT64 startaddress; UINT64 bytestoread; } *pinp; UCHAR* pinp2; SIZE_T length; PHYSICAL_ADDRESS viewBase; UINT_PTR offset; UINT_PTR toread; pinp=Irp->AssociatedIrp.SystemBuffer; pinp2=(UCHAR *)pinp; viewBase.QuadPart = (ULONGLONG)(pinp->startaddress); length=0x2000;//pinp->bytestoread; toread=(UINT_PTR)pinp->bytestoread; memoryview=NULL; ntStatus=ZwMapViewOfSection( physmem, //sectionhandle NtCurrentProcess(), //processhandle &memoryview, //BaseAddress 0L, //ZeroBits length, //CommitSize &viewBase, //SectionOffset &length, //ViewSize ViewShare, 0, PAGE_READWRITE); if (ntStatus==STATUS_SUCCESS) { offset=(UINT_PTR)(pinp->startaddress)-(UINT_PTR)viewBase.QuadPart; RtlCopyMemory(&memoryview[offset],&pinp2[16],toread); ZwUnmapViewOfSection( NtCurrentProcess(), //processhandle memoryview); } ZwClose(physmem); } break; } case IOCTL_CE_GETPHYSICALADDRESS: { struct input { UINT64 ProcessID; UINT64 BaseAddress; } *pinp; PEPROCESS selectedprocess; PHYSICAL_ADDRESS physical; physical.QuadPart = 0; ntStatus=STATUS_SUCCESS; pinp=Irp->AssociatedIrp.SystemBuffer; //DbgPrint("IOCTL_CE_GETPHYSICALADDRESS. ProcessID(%p)=%x BaseAddress(%p)=%x\n",&pinp->ProcessID, pinp->ProcessID, &pinp->BaseAddress, pinp->BaseAddress); __try { //switch to the selected process if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(pinp->ProcessID),&selectedprocess)==STATUS_SUCCESS) { KAPC_STATE apc_state; RtlZeroMemory(&apc_state,sizeof(apc_state)); KeStackAttachProcess((PVOID)selectedprocess,&apc_state); __try { physical=MmGetPhysicalAddress((PVOID)(UINT_PTR)pinp->BaseAddress); } __finally { KeUnstackDetachProcess(&apc_state); } ObDereferenceObject(selectedprocess); } } __except(1) { ntStatus=STATUS_UNSUCCESSFUL; } if (ntStatus==STATUS_SUCCESS) { //DbgPrint("physical.LowPart=%x",physical.LowPart); RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer,&physical.QuadPart,8); } break; } case IOCTL_CE_GETMEMORYRANGES: { struct output { UINT64 address; UINT64 size; } *poutp=Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_GETMEMORYRANGES\n"); if (PhysicalMemoryRanges==0) { __try { PPHYSICAL_MEMORY_RANGE mr=MmGetPhysicalMemoryRanges(); if (mr) { //find the end int i; PhysicalMemoryRanges=(UINT64)mr; for (i=0; mr[i].NumberOfBytes.QuadPart || mr[i].BaseAddress.QuadPart; i++); PhysicalMemoryRangesListSize=(UINT64)(&mr[i])-(UINT64)(&mr[0]); } } __except(1) { //just in case this function decides to bug out in the future } } poutp->address=PhysicalMemoryRanges; poutp->size=PhysicalMemoryRangesListSize; ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_GETSDTADDRESS: { DbgPrint("Obsolete\n"); ntStatus=STATUS_UNSUCCESSFUL; break; } case IOCTL_CE_GETCR0: { *(UINT64*)Irp->AssociatedIrp.SystemBuffer=getCR0(); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_GETCR4: { //seems CR4 isn't seen as a register... *(UINT64*)Irp->AssociatedIrp.SystemBuffer=(UINT64)getCR4(); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_SETCR4: { //seems CR4 isn't seen as a register... ULONG cr4reg=*(ULONG*)Irp->AssociatedIrp.SystemBuffer; setCR4((UINT64)cr4reg); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_GETCR3: { UINT_PTR cr3reg=0; PEPROCESS selectedprocess; ntStatus=STATUS_SUCCESS; //switch context to the selected process. (processid is stored in the systembuffer) if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(*(ULONG*)Irp->AssociatedIrp.SystemBuffer),&selectedprocess)==STATUS_SUCCESS) { __try { KAPC_STATE apc_state; RtlZeroMemory(&apc_state,sizeof(apc_state)); KeStackAttachProcess((PVOID)selectedprocess,&apc_state); __try { cr3reg=(UINT_PTR)getCR3(); } __finally { KeUnstackDetachProcess(&apc_state); } } __except(1) { ntStatus=STATUS_UNSUCCESSFUL; break; } ObDereferenceObject(selectedprocess); } DbgPrint("cr3reg=%p\n",cr3reg); *(UINT64*)Irp->AssociatedIrp.SystemBuffer=cr3reg; break; } case IOCTL_CE_GETSDT: { //returns the address of KeServiceDescriptorTable ntStatus = STATUS_UNSUCCESSFUL; break; } case IOCTL_CE_GETIDT: { //returns the address of the IDT of the current CPU IDT idt; RtlZeroMemory(&idt,sizeof(IDT)); GetIDT(&idt); RtlZeroMemory(Irp->AssociatedIrp.SystemBuffer,2+8); //so that the 32-bit version doesn't have to deal with garbage at the end RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer,&idt,sizeof(IDT)); //copy idt ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_GETGDT: { //returns the address of the IDT of the current CPU GDT gdt; RtlZeroMemory(&gdt,sizeof(GDT)); GetGDT(&gdt); RtlZeroMemory(Irp->AssociatedIrp.SystemBuffer,2+8); RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer,&gdt,sizeof(GDT)); //copy gdt ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_LAUNCHDBVM: { struct intput { UINT64 dbvmimgpath; DWORD32 cpuid; } *pinp; pinp=Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_LAUNCHDBVM\n"); initializeDBVM((PCWSTR)(UINT_PTR)pinp->dbvmimgpath); if (pinp->cpuid == 0xffffffff) { forEachCpu(vmxoffload_dpc, NULL, NULL, NULL, vmxoffload_override); cleanupDBVM(); } else forOneCpu((CCHAR)pinp->cpuid, vmxoffload_dpc, NULL, NULL, NULL, vmxoffload_override); DbgPrint("Returned from vmxoffload()\n"); break; } case IOCTL_CE_HOOKINTS: //hooks the DEBUG interrupts { DbgPrint("IOCTL_CE_HOOKINTS\n"); forEachCpu(debugger_initHookForCurrentCPU_DPC, NULL, NULL, NULL, NULL); ntStatus=STATUS_SUCCESS; /* DbgPrint("IOCTL_CE_HOOKINTS for cpu %d\n", cpunr()); if (debugger_initHookForCurrentCPU()) ntStatus=STATUS_SUCCESS; else ntStatus=STATUS_UNSUCCESSFUL;*/ break; } case IOCTL_CE_USERDEFINEDINTERRUPTHOOK: { struct intput { UINT64 interruptnumber; UINT64 newCS; UINT64 newRIP; UINT64 addressofjumpback; } *pinp; DbgPrint("IOCTL_CE_USERDEFINEDINTERRUPTHOOK\n"); pinp=Irp->AssociatedIrp.SystemBuffer; inthook_HookInterrupt((unsigned char)(pinp->interruptnumber), (int)pinp->newCS, (ULONG_PTR)pinp->newRIP, (PJUMPBACK)(UINT_PTR)(pinp->addressofjumpback)); DbgPrint("After the hook\n"); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_UNHOOKALLINTERRUPTS: { int i; DbgPrint("IOCTL_CE_UNHOOKALLINTERRUPTS for cpu %d\n",cpunr()); for (i=0; i<256; i++) inthook_UnhookInterrupt((unsigned char)i); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_SETGLOBALDEBUGSTATE: { struct intput { BOOL newstate; } *pinp; pinp=Irp->AssociatedIrp.SystemBuffer; debugger_setGlobalDebugState(pinp->newstate); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_DEBUGPROCESS: { struct input { DWORD ProcessID; } *pinp; DbgPrint("IOCTL_CE_DEBUGPROCESS\n"); pinp=Irp->AssociatedIrp.SystemBuffer; debugger_startDebugging(pinp->ProcessID); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_STOPDEBUGGING: { debugger_stopDebugging(); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_STARTPROCESSWATCH: { NTSTATUS r = STATUS_SUCCESS; DbgPrint("IOCTL_CE_STARTPROCESSWATCH\n"); ProcessWatcherOpensHandles = *(char *)Irp->AssociatedIrp.SystemBuffer != 0; if (CreateProcessNotifyRoutineEnabled && WatcherProcess) { ntStatus = STATUS_UNSUCCESSFUL; break; } //still here ExAcquireResourceExclusiveLite(&ProcesslistR, TRUE); ProcessEventCount=0; ExReleaseResourceLite(&ProcesslistR); //DbgPrint("IOCTL_CE_STARTPROCESSWATCH\n"); CleanProcessList(); if ((r == STATUS_SUCCESS) && (CreateProcessNotifyRoutineEnabled == FALSE)) { DbgPrint("calling PsSetCreateProcessNotifyRoutine\n"); #if (NTDDI_VERSION >= NTDDI_VISTASP1) r=PsSetCreateProcessNotifyRoutineEx(CreateProcessNotifyRoutineEx, FALSE); CreateProcessNotifyRoutineEnabled = r== STATUS_SUCCESS; #else CreateProcessNotifyRoutineEnabled = (PsSetCreateProcessNotifyRoutine(CreateProcessNotifyRoutine,FALSE)==STATUS_SUCCESS); #endif if (CreateProcessNotifyRoutineEnabled) CreateThreadNotifyRoutineEnabled = (PsSetCreateThreadNotifyRoutine(CreateThreadNotifyRoutine) == STATUS_SUCCESS); } ntStatus=(CreateProcessNotifyRoutineEnabled) ? STATUS_SUCCESS : STATUS_UNSUCCESSFUL; if (ntStatus==STATUS_SUCCESS) DbgPrint("CreateProcessNotifyRoutineEnabled worked\n"); else DbgPrint("CreateProcessNotifyRoutineEnabled failed (r=%x)\n",r); break; } case IOCTL_CE_GETPROCESSEVENTS: { ExAcquireResourceExclusiveLite(&ProcesslistR, TRUE); *(PUCHAR)Irp->AssociatedIrp.SystemBuffer=ProcessEventCount; RtlCopyMemory((PVOID)((UINT_PTR)Irp->AssociatedIrp.SystemBuffer+1),&ProcessEventdata[0],ProcessEventCount*sizeof(ProcessEventdta)); ProcessEventCount=0; //there's room for new events ExReleaseResourceLite(&ProcesslistR); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_GETTHREADEVENTS: { ExAcquireResourceExclusiveLite(&ProcesslistR, TRUE); *(PUCHAR)Irp->AssociatedIrp.SystemBuffer=ThreadEventCount; RtlCopyMemory((PVOID)((UINT_PTR)Irp->AssociatedIrp.SystemBuffer+1),&ThreadEventData[0],ThreadEventCount*sizeof(ThreadEventDta)); ThreadEventCount=0; //there's room for new events ExReleaseResourceLite(&ProcesslistR); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_CREATEAPC: { struct input { UINT64 threadid; UINT64 addresstoexecute; } *inp; inp=Irp->AssociatedIrp.SystemBuffer; CreateRemoteAPC((ULONG)inp->threadid,(PVOID)(UINT_PTR)inp->addresstoexecute); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_SUSPENDTHREAD: { struct input { ULONG threadid; } *inp; inp=Irp->AssociatedIrp.SystemBuffer; DbgPrint("CE_SUSPENDTHREAD\n"); DBKSuspendThread(inp->threadid); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_RESUMETHREAD: { struct input { ULONG threadid; } *inp; inp=Irp->AssociatedIrp.SystemBuffer; DbgPrint("CE_RESUMETHREAD\n"); DBKResumeThread(inp->threadid); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_SUSPENDPROCESS: { struct input { ULONG processid; } *inp; inp=Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_SUSPENDPROCESS\n"); if (PsSuspendProcess) { PEPROCESS selectedprocess; if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(inp->processid), &selectedprocess) == STATUS_SUCCESS) { ntStatus = PsSuspendProcess(selectedprocess); ObDereferenceObject(selectedprocess); } else ntStatus = STATUS_NOT_FOUND; } else ntStatus = STATUS_NOT_IMPLEMENTED; break; } case IOCTL_CE_RESUMEPROCESS: { struct input { ULONG processid; } *inp; inp = Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_RESUMEPROCESS\n"); if (PsResumeProcess) { PEPROCESS selectedprocess; if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(inp->processid), &selectedprocess) == STATUS_SUCCESS) { ntStatus = PsResumeProcess(selectedprocess); ObDereferenceObject(selectedprocess); } else ntStatus = STATUS_NOT_FOUND; } else ntStatus = STATUS_NOT_IMPLEMENTED; break; } case IOCTL_CE_ALLOCATEMEM: { struct input { UINT64 ProcessID; UINT64 BaseAddress; UINT64 Size; UINT64 AllocationType; UINT64 Protect; } *inp; PEPROCESS selectedprocess; PVOID BaseAddress; SIZE_T RegionSize; inp=Irp->AssociatedIrp.SystemBuffer; BaseAddress=(PVOID)(UINT_PTR)inp->BaseAddress; RegionSize=(SIZE_T)(inp->Size); if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(inp->ProcessID),&selectedprocess)==STATUS_SUCCESS) { __try { KAPC_STATE apc_state; RtlZeroMemory(&apc_state,sizeof(apc_state)); KeAttachProcess((PVOID)selectedprocess); //local process is much more fun!!!! DbgPrint("Switched Process\n"); __try { DbgPrint("Calling ZwAllocateVirtualMemory\n"); DbgPrint("Before call: BaseAddress=%p\n", BaseAddress); DbgPrint("Before call: RegionSize=%x\n", RegionSize); ntStatus=ZwAllocateVirtualMemory((HANDLE)-1, &BaseAddress, 0, &RegionSize, (ULONG)inp->AllocationType, (ULONG)inp->Protect); if ((ntStatus==STATUS_SUCCESS) && (HiddenDriver)) { //initialize the memory with crap so it becomes paged int i; char *x; x=BaseAddress; for (i=0; i < (int)RegionSize;i++) x[i]=(unsigned char)i; } DbgPrint("ntStatus=%x\n", ntStatus); DbgPrint("BaseAddress=%p\n",BaseAddress); DbgPrint("RegionSize=%x\n",RegionSize); *(PUINT64)Irp->AssociatedIrp.SystemBuffer=0; *(PUINT_PTR)Irp->AssociatedIrp.SystemBuffer=(UINT_PTR)BaseAddress; } __finally { KeDetachProcess(); } } __except(1) { ntStatus=STATUS_UNSUCCESSFUL; break; } ObDereferenceObject(selectedprocess); } break; } case IOCTL_CE_ALLOCATEMEM_NONPAGED: { struct input { ULONG Size; } *inp; PVOID address; int size; inp=Irp->AssociatedIrp.SystemBuffer; size=inp->Size; address=ExAllocatePool(NonPagedPool,size); *(PUINT64)Irp->AssociatedIrp.SystemBuffer=0; *(PUINT_PTR)Irp->AssociatedIrp.SystemBuffer=(UINT_PTR)address; if (address==0) ntStatus=STATUS_UNSUCCESSFUL; else { DbgPrint("Alloc success. Cleaning memory... (size=%d)\n",size); DbgPrint("address=%p\n", address); RtlZeroMemory(address, size); ntStatus=STATUS_SUCCESS; } break; } case IOCTL_CE_FREE_NONPAGED: { struct input { UINT64 Address; } *inp; inp = Irp->AssociatedIrp.SystemBuffer; ExFreePool((PVOID)(UINT_PTR)inp->Address); ntStatus = STATUS_SUCCESS; break; } case IOCTL_CE_MAP_MEMORY: { struct input { UINT64 FromPID; UINT64 ToPID; UINT64 address; DWORD size; } *inp; struct output { UINT64 FromMDL; UINT64 Address; } *outp; KAPC_STATE apc_state; PEPROCESS selectedprocess; PMDL FromMDL=NULL; inp = Irp->AssociatedIrp.SystemBuffer; outp = Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_MAP_MEMORY\n"); DbgPrint("address %x size %d\n", inp->address, inp->size); ntStatus = STATUS_UNSUCCESSFUL; if (inp->FromPID) { //switch DbgPrint("From PID %d\n", inp->FromPID); if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(inp->FromPID), &selectedprocess) == STATUS_SUCCESS) { __try { RtlZeroMemory(&apc_state, sizeof(apc_state)); KeStackAttachProcess((PVOID)selectedprocess, &apc_state); __try { FromMDL=IoAllocateMdl((PVOID)(UINT_PTR)inp->address, inp->size, FALSE, FALSE, NULL); if (FromMDL) MmProbeAndLockPages(FromMDL, KernelMode, IoReadAccess); } __finally { KeUnstackDetachProcess(&apc_state); } } __except (1) { DbgPrint("Exception\n"); ntStatus = STATUS_UNSUCCESSFUL; break; } ObDereferenceObject(selectedprocess); } } else { DbgPrint("From kernel or self\n", inp->FromPID); __try { FromMDL = IoAllocateMdl((PVOID)(UINT_PTR)inp->address, inp->size, FALSE, FALSE, NULL); if (FromMDL) { DbgPrint("IoAllocateMdl success\n"); MmProbeAndLockPages(FromMDL, KernelMode, IoReadAccess); } } __except (1) { DbgPrint("Exception\n"); if (FromMDL) { IoFreeMdl(FromMDL); FromMDL = NULL; } } } if (FromMDL) { DbgPrint("FromMDL is valid\n"); if (inp->ToPID) { //switch DbgPrint("To PID %d\n", inp->ToPID); if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(inp->ToPID), &selectedprocess) == STATUS_SUCCESS) { __try { RtlZeroMemory(&apc_state, sizeof(apc_state)); KeStackAttachProcess((PVOID)selectedprocess, &apc_state); __try { outp->Address = (UINT64)MmMapLockedPagesSpecifyCache(FromMDL, UserMode, MmWriteCombined, NULL, FALSE, NormalPagePriority); outp->FromMDL = (UINT64)FromMDL; ntStatus = STATUS_SUCCESS; } __finally { KeUnstackDetachProcess(&apc_state); } } __except (1) { DbgPrint("Exception part 2\n"); ntStatus = STATUS_UNSUCCESSFUL; break; } ObDereferenceObject(selectedprocess); } } else { DbgPrint("To kernel or self\n", inp->FromPID); __try { outp->Address = (UINT64)MmMapLockedPagesSpecifyCache(FromMDL, UserMode, MmWriteCombined, NULL, FALSE, NormalPagePriority); outp->FromMDL = (UINT64)FromMDL; ntStatus = STATUS_SUCCESS; } __except (1) { DbgPrint("Exception part 2\n"); } } } else DbgPrint("FromMDL==NULL\n"); break; } case IOCTL_CE_UNMAP_MEMORY: { struct output { UINT64 FromMDL; UINT64 Address; } *inp; PMDL mdl; inp = Irp->AssociatedIrp.SystemBuffer; mdl = (PMDL)(UINT_PTR)inp->FromMDL; MmUnmapLockedPages((PMDL)(UINT_PTR)inp->Address, mdl); MmUnlockPages(mdl); IoFreeMdl(mdl); ntStatus = STATUS_SUCCESS; //no BSOD means success ;) break; } case IOCTL_CE_LOCK_MEMORY: { struct { UINT64 ProcessID; UINT64 address; UINT64 size; } *inp; struct { UINT64 mdl; } *outp; KAPC_STATE apc_state; PEPROCESS selectedprocess; DbgPrint("IOCTL_CE_LOCK_MEMORY"); inp = Irp->AssociatedIrp.SystemBuffer; outp = Irp->AssociatedIrp.SystemBuffer; if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(inp->ProcessID), &selectedprocess) == STATUS_SUCCESS) { PMDL mdl = NULL; KeStackAttachProcess(selectedprocess, &apc_state); __try { mdl = IoAllocateMdl((PVOID)(UINT_PTR)inp->address, (ULONG)inp->size, FALSE, FALSE, NULL); if (mdl) { __try { MmProbeAndLockPages(mdl, UserMode, IoReadAccess); DbgPrint("MmProbeAndLockPages succeeded"); } __except (1) { DbgPrint("MmProbeAndLockPages failed"); IoFreeMdl(mdl); ntStatus = STATUS_UNSUCCESSFUL; break; } } } __finally { KeUnstackDetachProcess(&apc_state); } outp->mdl = (UINT_PTR)mdl; DbgPrint("Locked the page\n"); ntStatus = STATUS_SUCCESS; } break; } case IOCTL_CE_UNLOCK_MEMORY: { struct { UINT64 mdl; } *inp; DbgPrint("IOCTL_CE_UNLOCK_MEMORY"); inp = Irp->AssociatedIrp.SystemBuffer; MmUnlockPages((PMDL)(UINT_PTR)inp->mdl); IoFreeMdl((PMDL)(UINT_PTR)inp->mdl); break; } case IOCTL_CE_GETPROCADDRESS: { struct input { UINT64 s; } *inp; UNICODE_STRING y; UINT64 result; PVOID x; inp=Irp->AssociatedIrp.SystemBuffer; RtlInitUnicodeString(&y, (PCWSTR)(UINT_PTR)(inp->s)); x=MmGetSystemRoutineAddress(&y); result=(UINT64)x; RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer,&result,8); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_GETPROCESSNAMEADDRESS: { struct input { UINT64 PEPROCESS; } *inp; struct output { UINT64 Address; } *outp; UNICODE_STRING temp; inp=Irp->AssociatedIrp.SystemBuffer; outp=Irp->AssociatedIrp.SystemBuffer; RtlInitUnicodeString(&temp, L"PsGetProcessImageFileName"); PsGetProcessImageFileName=(GET_PROCESS_IMAGE_NAME)MmGetSystemRoutineAddress(&temp); if (PsGetProcessImageFileName!=NULL) { outp->Address=(UINT_PTR)PsGetProcessImageFileName((PEPROCESS)((UINT_PTR)(inp->PEPROCESS))); ntStatus=STATUS_SUCCESS; } else { DbgPrint("PsGetProcessImageFileName==NULL"); ntStatus=STATUS_UNSUCCESSFUL; } break; } /*x case IOCTL_CE_MAKEKERNELCOPY: { struct input { ULONG Base; ULONG KernelSize; } *inp; DbgPrint("IOCTL_CE_MAKEKERNELCOPY"); inp=Irp->AssociatedIrp.SystemBuffer; ntStatus=makeKernelCopy(inp->Base, inp->KernelSize); break; } */ case IOCTL_CE_CONTINUEDEBUGEVENT: { struct input { BOOL handled; } *inp=Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_CONTINUEDEBUGEVENT\n"); ntStatus=debugger_continueDebugEvent(inp->handled); break; } case IOCTL_CE_WAITFORDEBUGEVENT: { struct input { ULONG timeout; } *inp=Irp->AssociatedIrp.SystemBuffer; ntStatus=debugger_waitForDebugEvent(inp->timeout); break; } case IOCTL_CE_GETDEBUGGERSTATE: { DbgPrint("IOCTL_CE_GETDEBUGGERSTATE\n"); __try { ntStatus=debugger_getDebuggerState((PDebugStackState)(Irp->AssociatedIrp.SystemBuffer)); } __except(1) { DbgPrint("Exception happened\n"); ntStatus=STATUS_UNSUCCESSFUL; } DbgPrint("ntStatus=%x rax=%x\n",ntStatus, ((PDebugStackState)(Irp->AssociatedIrp.SystemBuffer))->rax); break; } case IOCTL_CE_SETDEBUGGERSTATE: { DbgPrint("IOCTL_CE_SETDEBUGGERSTATE: state->rax=%x\n", ((PDebugStackState)(Irp->AssociatedIrp.SystemBuffer))->rax); __try { ntStatus=debugger_setDebuggerState((PDebugStackState)Irp->AssociatedIrp.SystemBuffer); } __except(1) { DbgPrint("Exception happened\n"); ntStatus=STATUS_UNSUCCESSFUL; } break; } case IOCTL_CE_SETKERNELSTEPABILITY: { struct input { int state; } *inp=Irp->AssociatedIrp.SystemBuffer; KernelCodeStepping=inp->state; ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_WRITESIGNOREWP: { KernelWritesIgnoreWP = *(BYTE*)Irp->AssociatedIrp.SystemBuffer; ntStatus = STATUS_SUCCESS; break; } case IOCTL_CE_GD_SETBREAKPOINT: { struct input { BOOL active; int debugregspot; UINT64 address; DWORD breakType; DWORD breakLength; } *inp=Irp->AssociatedIrp.SystemBuffer; DbgPrint("sizeof(struct input)=%d\n",sizeof(struct input)); //DbgPrint("address=%llx breakType=%d breakLength=%d\n",inp->address, inp->breakType,inp->breakLength); if (inp->active) { DbgPrint("activating breapoint %d\n", inp->debugregspot); ntStatus=debugger_setGDBreakpoint(inp->debugregspot, (UINT_PTR)inp->address, (BreakType)inp->breakType, (BreakLength)inp->breakLength); } else { DbgPrint("Deactivating breakpoint :%d\n", inp->debugregspot); ntStatus=debugger_unsetGDBreakpoint(inp->debugregspot); } break; } case IOCTL_CE_TOUCHDEBUGREGISTER: //used after setting a global debug breakpoint { debugger_touchDebugRegister(0); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_SETSTORELBR: { BOOL newstate=*(PBOOL)Irp->AssociatedIrp.SystemBuffer; DbgPrint("Calling debugger_setStoreLBR(%d)\n", newstate); debugger_setStoreLBR(newstate); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_EXECUTE_CODE: { typedef NTSTATUS (*PARAMETERLESSFUNCTION)(UINT64 parameters); PARAMETERLESSFUNCTION functiontocall; struct input { UINT64 functionaddress; //function address to call UINT64 parameters; } *inp=Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_EXECUTE_CODE\n"); functiontocall=(PARAMETERLESSFUNCTION)(UINT_PTR)(inp->functionaddress); __try { ntStatus=functiontocall(inp->parameters); DbgPrint("Still alive\n"); ntStatus=STATUS_SUCCESS; } __except(1) { DbgPrint("Exception occured\n"); ntStatus=STATUS_UNSUCCESSFUL; } break; } case IOCTL_CE_GETVERSION: { DbgPrint("IOCTL_CE_GETVERSION. Version=%d\n",dbkversion); *(PULONG)Irp->AssociatedIrp.SystemBuffer=dbkversion; ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_READMSR: { DWORD msr=*(PDWORD)Irp->AssociatedIrp.SystemBuffer; //DbgPrint("IOCTL_CE_READMSR: msr=%x\n", msr); __try { *(PUINT64)Irp->AssociatedIrp.SystemBuffer=__readmsr(msr); //DbgPrint("Output: %llx\n",*(PUINT64)Irp->AssociatedIrp.SystemBuffer); ntStatus=STATUS_SUCCESS; } __except(1) { ntStatus=STATUS_UNSUCCESSFUL; } break; } case IOCTL_CE_WRITEMSR: { struct input { UINT64 msr; UINT64 value; } *inp=Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_WRITEMSR:\n"); DbgPrint("msr=%llx\n", inp->msr); DbgPrint("value=%llx\n", inp->value); __try { __writemsr(inp->msr, inp->value ); ntStatus=STATUS_SUCCESS; } __except(1) { DbgPrint("Error while writing value\n"); ntStatus=STATUS_UNSUCCESSFUL; } break; } case IOCTL_CE_ULTIMAP2: { struct input { UINT32 PID; UINT32 Size; UINT32 RangeCount; UINT32 NoPMI; UINT32 UserMode; UINT32 KernelMode; URANGE Ranges[8]; WCHAR OutputPath[200]; } *inp = Irp->AssociatedIrp.SystemBuffer; int i; DbgPrint("IOCTL_CE_ULTIMAP2"); for (i = 0; i < (int)(inp->RangeCount); i++) DbgPrint("%d=%p -> %p", i, (PVOID)(UINT_PTR)inp->Ranges[i].StartAddress, (PVOID)(UINT_PTR)inp->Ranges[i].EndAddress); SetupUltimap2(inp->PID, inp->Size, inp->OutputPath, inp->RangeCount, inp->Ranges, inp->NoPMI, inp->UserMode, inp->KernelMode); ntStatus = STATUS_SUCCESS; break; } case IOCTL_CE_ULTIMAP2_WAITFORDATA: { ULONG timeout = *(ULONG *)Irp->AssociatedIrp.SystemBuffer; PULTIMAP2DATAEVENT output = Irp->AssociatedIrp.SystemBuffer; output->Address = 0; ntStatus = ultimap2_waitForData(timeout, output); break; } case IOCTL_CE_ULTIMAP2_LOCKFILE: { int cpunr = *(int *)Irp->AssociatedIrp.SystemBuffer; ultimap2_LockFile(cpunr); ntStatus = STATUS_SUCCESS; break; } case IOCTL_CE_ULTIMAP2_RELEASEFILE: { int cpunr = *(int *)Irp->AssociatedIrp.SystemBuffer; ultimap2_ReleaseFile(cpunr); ntStatus = STATUS_SUCCESS; break; } case IOCTL_CE_ULTIMAP2_GETTRACESIZE: { *(UINT64*)Irp->AssociatedIrp.SystemBuffer = ultimap2_GetTraceFileSize(); ntStatus = STATUS_SUCCESS; break; } case IOCTL_CE_ULTIMAP2_RESETTRACESIZE: { ultimap2_ResetTraceFileSize(); ntStatus = STATUS_SUCCESS; break; } case IOCTL_CE_ULTIMAP2_CONTINUE: { int cpunr=*(int*)Irp->AssociatedIrp.SystemBuffer; ntStatus = ultimap2_continue(cpunr); break; } case IOCTL_CE_ULTIMAP2_FLUSH: { ntStatus = ultimap2_flushBuffers(); break; } case IOCTL_CE_ULTIMAP2_PAUSE: { ntStatus = ultimap2_pause(); break; } case IOCTL_CE_ULTIMAP2_RESUME: { ntStatus = ultimap2_resume(); break; } case IOCTL_CE_DISABLEULTIMAP2: { DisableUltimap2(); break; } case IOCTL_CE_ULTIMAP: { #pragma pack(1) struct input { UINT64 targetCR3; UINT64 dbgctl; UINT64 dsareasize; BOOL savetofile; int HandlerCount; WCHAR filename[200]; } *inp=Irp->AssociatedIrp.SystemBuffer; #pragma pack() DbgPrint("IOCTL_CE_ULTIMAP:\n"); DbgPrint("ultimap(%I64x, %I64x, %d):\n", (UINT64)inp->targetCR3, (UINT64)inp->dbgctl, inp->dsareasize); if (inp->savetofile) DbgPrint("filename=%S\n", &inp->filename[0]); ntStatus=ultimap(inp->targetCR3, inp->dbgctl, (int)inp->dsareasize, inp->savetofile, &inp->filename[0], inp->HandlerCount); break; } case IOCTL_CE_ULTIMAP_DISABLE: { ultimap_disable(); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_ULTIMAP_WAITFORDATA: { ULONG timeout=*(ULONG *)Irp->AssociatedIrp.SystemBuffer; PULTIMAPDATAEVENT output=Irp->AssociatedIrp.SystemBuffer; ntStatus=ultimap_waitForData(timeout, output); break; } case IOCTL_CE_ULTIMAP_CONTINUE: { PULTIMAPDATAEVENT input=Irp->AssociatedIrp.SystemBuffer; ntStatus=ultimap_continue(input); break; } case IOCTL_CE_ULTIMAP_FLUSH: { ultimap_flushBuffers(); ntStatus=STATUS_SUCCESS; break; } case IOCTL_CE_ULTIMAP_PAUSE: { ultimap_pause(); ntStatus = STATUS_SUCCESS; break; } case IOCTL_CE_ULTIMAP_RESUME: { ultimap_resume(); ntStatus = STATUS_SUCCESS; break; } /* case IOCTL_CE_GETCPUIDS: { CPULISTFILLSTRUCT x; forEachCpuPassive(GetCPUIDS_all,&x); }*/ case IOCTL_CE_STARTACCESMONITOR: { //this is used instead of writeProcessMemory for speed reasons (the reading out is still done with readProcessMemory because of easier memory management) struct input { UINT64 ProcessID; } *inp; PEPROCESS selectedprocess; PVOID BaseAddress; SIZE_T RegionSize; inp=Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_STARTACCESMONITOR(%d)\n", inp->ProcessID); ntStatus = STATUS_UNSUCCESSFUL; if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(inp->ProcessID), &selectedprocess) == STATUS_SUCCESS) { ntStatus = markAllPagesAsNeverAccessed(selectedprocess); ObDereferenceObject(selectedprocess); } break; } case IOCTL_CE_ENUMACCESSEDMEMORY: { struct input { UINT64 ProcessID; } *inp; PEPROCESS selectedprocess; PVOID BaseAddress; SIZE_T RegionSize; inp = Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_ENUMACCESSEDMEMORY(%d)\n", inp->ProcessID); ntStatus = STATUS_UNSUCCESSFUL; if (PsLookupProcessByProcessId((PVOID)(UINT_PTR)(inp->ProcessID), &selectedprocess) == STATUS_SUCCESS) { *(int *)Irp->AssociatedIrp.SystemBuffer = enumAllAccessedPages(selectedprocess); ObDereferenceObject(selectedprocess); } ntStatus = STATUS_SUCCESS; break; } case IOCTL_CE_GETACCESSEDMEMORYLIST: { int ListSizeInBytes = *(int *)Irp->AssociatedIrp.SystemBuffer; PPRANGE List = (PPRANGE)Irp->AssociatedIrp.SystemBuffer; DbgPrint("IOCTL_CE_GETACCESSEDMEMORYLIST\n"); getAccessedPageList(List, ListSizeInBytes); DbgPrint("return from IOCTL_CE_GETACCESSEDMEMORYLIST\n"); ntStatus = STATUS_SUCCESS; break; } case IOCTL_CE_INITIALIZE: { //find the KeServiceDescriptorTableShadow struct input { UINT64 AddressOfWin32K; UINT64 SizeOfWin32K; UINT64 NtUserBuildHwndList_callnumber; UINT64 NtUserQueryWindow_callnumber; UINT64 NtUserFindWindowEx_callnumber; UINT64 NtUserGetForegroundWindow_callnumber; UINT64 ActiveLinkOffset; UINT64 ProcessNameOffset; UINT64 DebugportOffset; UINT64 ProcessEvent; UINT64 ThreadEvent; } *pinp; DbgPrint("IOCTL_CE_INITIALIZE\n"); pinp=Irp->AssociatedIrp.SystemBuffer; ntStatus=STATUS_SUCCESS; //referencing event handles to objects ObReferenceObjectByHandle((HANDLE)(UINT_PTR)pinp->ProcessEvent, EVENT_ALL_ACCESS, NULL,KernelMode, &ProcessEvent, NULL); ObReferenceObjectByHandle((HANDLE)(UINT_PTR)pinp->ThreadEvent, EVENT_ALL_ACCESS, NULL,KernelMode, &ThreadEvent, NULL); *(UINT_PTR*)Irp->AssociatedIrp.SystemBuffer=(UINT_PTR)0; break; } case IOCTL_CE_VMXCONFIG: { #pragma pack(1) struct input { ULONG Virtualization_Enabled; QWORD Password1; ULONG Password2; QWORD Password3; } *pinp; #pragma pack() DbgPrint("IOCTL_CE_VMXCONFIG called\n"); ntStatus=STATUS_SUCCESS; pinp=Irp->AssociatedIrp.SystemBuffer; if (pinp->Virtualization_Enabled) { vmx_password1=pinp->Password1; vmx_password2=pinp->Password2; vmx_password3=<PASSWORD>-><PASSWORD>; DbgPrint("new passwords are: %p-%x-%p\n", (void*)vmx_password1, vmx_password2, (void*)vmx_password3); __try { vmx_version=vmx_getversion(); DbgPrint("Still here, so vmx is loaded. vmx_version=%x\n",vmx_version); vmxusable = 1; } __except(1) { DbgPrint("Exception happened. This means no vmx installed, or one of the passwords is wrong\n"); ntStatus = STATUS_UNSUCCESSFUL; vmxusable = 0; }; } else { DbgPrint("Virtualization_Enabled=0\n"); vmxusable=0; } break; } case IOCTL_CE_ENABLE_DRM: { #if (NTDDI_VERSION >= NTDDI_VISTA) struct { QWORD PreferedAltitude; QWORD ProtectedProcess; } *inp = Irp->AssociatedIrp.SystemBuffer; DbgPrint("inp->PreferedAltitude=%p", inp->PreferedAltitude); DbgPrint("inp->PreferedAltitude=%p", inp->ProtectedProcess); if (DRMProcess) { //check if this process has been terminated LARGE_INTEGER timeout; timeout.QuadPart = -500000; ntStatus=KeWaitForSingleObject(DRMProcess, UserRequest, UserMode, FALSE, &timeout); if (ntStatus != STATUS_SUCCESS) break; } DRMProcess = PsGetCurrentProcess(); if (inp->ProtectedProcess) { if (DRMProcess != (PEPROCESS)((UINT_PTR)inp->ProtectedProcess)) DRMProcess2 = (PEPROCESS)((UINT_PTR)inp->ProtectedProcess); } DbgPrint("DRMProcess=%p", DRMProcess); DbgPrint("DRMProcess2=%p", DRMProcess2); if (DRMHandle == NULL) { WCHAR wcAltitude[10]; UNICODE_STRING usAltitude; OB_CALLBACK_REGISTRATION r; LARGE_INTEGER tc; OB_OPERATION_REGISTRATION obr[2]; int RandomVal = (int)(inp->PreferedAltitude); int trycount = 0; if (RandomVal == 0) { tc.QuadPart = 0; KeQueryTickCount(&tc); RandomVal = 1000 + (tc.QuadPart % 50000); } DbgPrint("Activating CE's super advanced DRM"); //yeah right.... DbgPrint("RandomVal=%d", RandomVal); RtlStringCbPrintfW(wcAltitude, sizeof(wcAltitude) - 2, L"%d", RandomVal); DbgPrint("wcAltitude=%S", wcAltitude); RtlInitUnicodeString(&usAltitude, wcAltitude); r.Version = OB_FLT_REGISTRATION_VERSION; r.Altitude = usAltitude; r.RegistrationContext = NULL; obr[0].ObjectType = PsProcessType; obr[0].Operations = OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE; obr[0].PreOperation = ProcessPreCallback; obr[0].PostOperation = ProcessPostCallback; obr[1].ObjectType = PsThreadType; obr[1].Operations = OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE; obr[1].PreOperation = ThreadPreCallback; obr[1].PostOperation = ThreadPostCallback; r.OperationRegistration = obr; r.OperationRegistrationCount = 2; ntStatus = ObRegisterCallbacks(&r, &DRMHandle); while ((ntStatus == STATUS_FLT_INSTANCE_ALTITUDE_COLLISION) && (trycount<10)) { RandomVal++; RtlStringCbPrintfW(wcAltitude, sizeof(wcAltitude) - 2, L"%d", RandomVal); RtlInitUnicodeString(&usAltitude, wcAltitude); r.Altitude = usAltitude; trycount++; ntStatus = ObRegisterCallbacks(&r, &DRMHandle); } DbgPrint("ntStatus=%X", ntStatus); } else ntStatus = STATUS_SUCCESS; #else ntStatus = STATUS_NOT_IMPLEMENTED; #endif break; } case IOCTL_CE_GET_PEB: { KAPC_STATE oldstate; PEPROCESS ep = *(PEPROCESS *)Irp->AssociatedIrp.SystemBuffer; //DbgPrint("IOCTL_CE_GET_PEB"); KeStackAttachProcess((PKPROCESS)ep, &oldstate); __try { ULONG r; PROCESS_BASIC_INFORMATION pbi; //DbgPrint("Calling ZwQueryInformationProcess"); ntStatus = ZwQueryInformationProcess(ZwCurrentProcess(), ProcessBasicInformation, &pbi, sizeof(pbi), &r); if (ntStatus==STATUS_SUCCESS) { //DbgPrint("pbi.UniqueProcessId=%x\n", (int)pbi.UniqueProcessId); //DbgPrint("pbi.PebBaseAddress=%p\n", (PVOID)pbi.PebBaseAddress); *(QWORD *)Irp->AssociatedIrp.SystemBuffer = (QWORD)(pbi.PebBaseAddress); } else DbgPrint("ZwQueryInformationProcess failed"); } __finally { KeUnstackDetachProcess(&oldstate); } break; } case IOCTL_CE_QUERYINFORMATIONPROCESS: { struct { QWORD processid; QWORD ProcessInformationAddress; QWORD ProcessInformationClass; QWORD ProcessInformationLength; } *inp = Irp->AssociatedIrp.SystemBuffer; struct { QWORD result; QWORD returnLength; char data; } *outp = Irp->AssociatedIrp.SystemBuffer; PEPROCESS selectedprocess; DbgPrint("IOCTL_CE_QUERYINFORMATIONPROCESS"); if (inp->processid == 0) { DbgPrint("Still works\n"); ntStatus = STATUS_SUCCESS; break; } __try { if (PsLookupProcessByProcessId((HANDLE)(UINT_PTR)inp->processid, &selectedprocess) == STATUS_SUCCESS) { KAPC_STATE oldstate; KeStackAttachProcess((PKPROCESS)selectedprocess, &oldstate); __try { ULONG returnLength; if (inp->ProcessInformationAddress == 0) { DbgPrint("NULL ProcessInformationAddress"); outp->result = ZwQueryInformationProcess(NtCurrentProcess(), inp->ProcessInformationClass, NULL, (ULONG)inp->ProcessInformationLength, &returnLength); } else outp->result = ZwQueryInformationProcess(NtCurrentProcess(), inp->ProcessInformationClass, &(outp->data), (ULONG)inp->ProcessInformationLength, &returnLength); DbgPrint("outp->result=%x", outp->result); outp->returnLength = returnLength; DbgPrint("outp->returnLength=%x", outp->returnLength); ntStatus = STATUS_SUCCESS; } __finally { KeUnstackDetachProcess(&oldstate); } ObDereferenceObject(selectedprocess); } else { DbgPrint("Failed to find pid %x", inp->processid); ntStatus = STATUS_EXPIRED_HANDLE; } } __except (1) { DbgPrint("Exception"); ntStatus = STATUS_EXPIRED_HANDLE; } break; } case IOCTL_CE_NTPROTECTVIRTUALMEMORY: { break; } case IOCTL_CE_ALLOCATE_MEMORY_FOR_DBVM: { PHYSICAL_ADDRESS LowAddress, HighAddress, SkipBytes; PMDL mdl; QWORD pagecount = *(QWORD*)Irp->AssociatedIrp.SystemBuffer; PFN_NUMBER *pfnlist; DbgPrint("IOCTL_CE_ALLOCATE_MEMORY_FOR_DBVM(%d)\n", pagecount); if (!vmxusable) { DbgPrint("This only works when DBVM is present\n"); ntStatus = STATUS_INVALID_DEVICE_STATE; break; } LowAddress.QuadPart = 0; HighAddress.QuadPart = 0xffffffffffffffffI64; SkipBytes.QuadPart = 0; mdl = MmAllocatePagesForMdlEx(LowAddress, HighAddress, SkipBytes, (SIZE_T)pagecount * 4096, MmCached, MM_ALLOCATE_REQUIRE_CONTIGUOUS_CHUNKS | MM_ALLOCATE_FULLY_REQUIRED); //do not free this, EVER if (mdl) { int i; PDBVMOffloadMemInfo mi; pagecount = MmGetMdlByteCount(mdl) / 4096; DbgPrint("Allocated %d pages\n", pagecount); pfnlist = MmGetMdlPfnArray(mdl); if (pfnlist) { //convert the pfnlist to a list dbvm understands, and go in blocks of 32 mi = ExAllocatePool(PagedPool, sizeof(DBVMOffloadMemInfo)); if (mi) { mi->List = ExAllocatePool(PagedPool, sizeof(UINT64) * 32); if (mi->List) { mi->Count = 0; for (i = 0; i < pagecount; i++) { mi->List[mi->Count] = pfnlist[i] << 12; mi->Count++; if (mi->Count == 32) { int j; int r = vmx_add_memory(mi->List, mi->Count); DbgPrint("vmx_add_memory for %d pages returned %d\n", mi->Count, r); for (j = 0; j < mi->Count; j++) { DbgPrint("%d : %p\n", j, (void*)((UINT_PTR)mi->List[j])); } mi->Count = 0; } } if (mi->Count) { int r = vmx_add_memory(mi->List, mi->Count); DbgPrint("vmx_add_memory for %d pages returned %d\n", mi->Count, r); } ExFreePool(mi->List); } else DbgPrint("Failure allocating mi->List"); ExFreePool(mi); } else DbgPrint("Failure allocting mi"); } else DbgPrint("Failure getting pfn list"); ExFreePool(mdl); //only free the mdl, the rest belongs to dbvm now ntStatus = STATUS_SUCCESS; } else { DbgPrint("Failure allocating MDL"); ntStatus = STATUS_MEMORY_NOT_ALLOCATED; } break; } default: DbgPrint("Unhandled IO request: %x\n", IoControlCode); break; } Irp->IoStatus.Status = ntStatus; // Set # of bytes to copy back to user-mode... if (irpStack) //only NULL when loaded by dbvm { if (ntStatus == STATUS_SUCCESS) Irp->IoStatus.Information = irpStack->Parameters.DeviceIoControl.OutputBufferLength; else Irp->IoStatus.Information = 0; IoCompleteRequest(Irp, IO_NO_INCREMENT); } return ntStatus; } <|start_filename|>src/ultimap2/apic.c<|end_filename|> #include <ntifs.h> #include "apic.h" #include <ntddk.h> #include "..\DBKFunc.h" #define MSR_IA32_APICBASE 0x0000001b #define MSR_IA32_X2APIC_EOI 0x80b #define MSR_IA32_X2APIC_LVT_PMI 0x834 volatile PAPIC APIC_BASE; BOOL x2APICMode = FALSE; void apic_clearPerfmon() { if (x2APICMode) { __writemsr(MSR_IA32_X2APIC_LVT_PMI, (__readmsr(MSR_IA32_X2APIC_LVT_PMI) & (UINT64)0xff)); __writemsr(MSR_IA32_X2APIC_EOI, 0); } else { //DbgPrint("Clear perfmon (APIC_BASE at %llx)\n", APIC_BASE); //DbgPrint("APIC_BASE->LVT_Performance_Monitor.a at %p\n", &APIC_BASE->LVT_Performance_Monitor.a); //DbgPrint("APIC_BASE->EOI.a at %p\n", &APIC_BASE->EOI.a); //DbgPrint("APIC_BASE->LVT_Performance_Monitor.a had value %x\n", APIC_BASE->LVT_Performance_Monitor.a); //DbgPrint("APIC_BASE->LVT_Performance_Monitor.b had value %x\n", APIC_BASE->LVT_Performance_Monitor.b); // DbgPrint("APIC_BASE->LVT_Performance_Monitor.c had value %x\n", APIC_BASE->LVT_Performance_Monitor.c); // DbgPrint("APIC_BASE->LVT_Performance_Monitor.d had value %x\n", APIC_BASE->LVT_Performance_Monitor.d); APIC_BASE->LVT_Performance_Monitor.a = APIC_BASE->LVT_Performance_Monitor.a & 0xff; APIC_BASE->EOI.a = 0; } } void setup_APIC_BASE(void) { PHYSICAL_ADDRESS Physical_APIC_BASE; UINT64 APIC_BASE_VALUE = readMSR(MSR_IA32_APICBASE); DbgPrint("Fetching the APIC base\n"); Physical_APIC_BASE.QuadPart = APIC_BASE_VALUE & 0xFFFFFFFFFFFFF000ULL; DbgPrint("Physical_APIC_BASE=%p\n", Physical_APIC_BASE.QuadPart); APIC_BASE = (PAPIC)MmMapIoSpace(Physical_APIC_BASE, sizeof(APIC), MmNonCached); DbgPrint("APIC_BASE at %p\n", APIC_BASE); x2APICMode = (APIC_BASE_VALUE & (1 << 10))!=0; DbgPrint("x2APICMode=%d\n", x2APICMode); } void clean_APIC_BASE(void) { if (APIC_BASE) MmUnmapIoSpace((PVOID)APIC_BASE, sizeof(APIC)); } <|start_filename|>src/vmxoffload.h<|end_filename|> #ifndef VMXOFFLOAD_H #define VMXOFFLOAD_H void cleanupDBVM(); void initializeDBVM(PCWSTR dbvmimgpath); void vmxoffload(void); void vmxoffload_override(CCHAR cpunr, PKDEFERRED_ROUTINE Dpc, PVOID DeferredContext, PVOID *SystemArgument1, PVOID *SystemArgument2); VOID vmxoffload_dpc( __in struct _KDPC *Dpc, __in_opt PVOID DeferredContext, __in_opt PVOID SystemArgument1, __in_opt PVOID SystemArgument2 ); typedef struct _DBVMOffloadMemInfo { UINT64 *List; int Count; } DBVMOffloadMemInfo, *PDBVMOffloadMemInfo; #pragma pack (1) typedef struct _PTE { unsigned P : 1; // present (1 = present) unsigned RW : 1; // read/write unsigned US : 1; // user/supervisor unsigned PWT : 1; // page-level write-through unsigned PCD : 1; // page-level cache disabled unsigned A : 1; // accessed unsigned D : 1; // dirty unsigned PAT : 1; // PAT unsigned G : 1; // global page unsigned A1 : 1; // available 1 aka copy-on-write unsigned A2 : 1; // available 2/ is 1 when paged to disk unsigned A3 : 1; // available 3 unsigned PFN : 20; // page-frame number } *PPTE; typedef struct _PDE { unsigned P : 1; // present (1 = present) unsigned RW : 1; // read/write unsigned US : 1; // user/supervisor unsigned PWT : 1; // page-level write-through unsigned PCD : 1; // page-level cache disabled unsigned A : 1; // accessed unsigned D : 1; // dirty unsigned PS : 1; // reserved (0) unsigned G : 1; // reserved (0) unsigned A1 : 1; // available 1 aka copy-on-write unsigned A2 : 1; // available 2/ is 1 when paged to disk unsigned A3 : 1; // available 3 unsigned PFN : 20; // page-frame number } *PPDE; typedef struct _PDE2MB { unsigned P : 1; // present (1 = present) unsigned RW : 1; // read/write unsigned US : 1; // user/supervisor unsigned PWT : 1; // page-level write-through unsigned PCD : 1; // page-level cache disabled unsigned A : 1; // accessed unsigned reserved1 : 1; // reserved (0) unsigned PS : 1; // reserved (0) unsigned reserved3 : 1; // reserved (0) unsigned A1 : 1; // available 1 aka copy-on-write unsigned A2 : 1; // available 2/ is 1 when paged to disk unsigned A3 : 1; // available 3 unsigned PFN : 20; // page-frame number (>> 13 instead of >>12); } *PPDE2MB; typedef struct _PTE_PAE { unsigned P : 1; // present (1 = present) unsigned RW : 1; // read/write unsigned US : 1; // user/supervisor unsigned PWT : 1; // page-level write-through unsigned PCD : 1; // page-level cache disabled unsigned A : 1; // accessed unsigned D : 1; // dirty unsigned PAT : 1; // unsigned G : 1; // global page unsigned A1 : 1; // available 1 aka copy-on-write unsigned A2 : 1; // available 2/ is 1 when paged to disk unsigned A3 : 1; // available 3 unsigned PFN_LOW : 20; unsigned PFN_HIGH : 32; } PTE_PAE, *PPTE_PAE; typedef struct _PDE_PAE { unsigned P : 1; // present (1 = present) unsigned RW : 1; // read/write unsigned US : 1; // user/supervisor unsigned PWT : 1; // page-level write-through unsigned PCD : 1; // page-level cache disabled unsigned A : 1; // accessed unsigned D : 1; // dirty unsigned PS : 1; // pagesize unsigned G : 1; // reserved (0) unsigned A1 : 1; // available 1 aka copy-on-write unsigned A2 : 1; // available 2/ is 1 when paged to disk unsigned A3 : 1; // available 3 unsigned PFN_LOW : 20; unsigned PFN_HIGH : 32; } PDE_PAE, *PPDE_PAE; typedef struct _PDE2MB_PAE { unsigned P : 1; // present (1 = present) unsigned RW : 1; // read/write unsigned US : 1; // user/supervisor unsigned PWT : 1; // page-level write-through unsigned PCD : 1; // page-level cache disabled unsigned A : 1; // accessed unsigned reserved1 : 1; // reserved (0) unsigned PS : 1; // reserved (0) unsigned reserved3 : 1; // reserved (0) unsigned A1 : 1; // available 1 aka copy-on-write unsigned A2 : 1; // available 2/ is 1 when paged to disk unsigned A3 : 1; // available 3 unsigned PAT : 1; // unsigned PFN_LOW : 19; unsigned PFN_HIGH : 32; } *PPDE2MB_PAE; typedef struct _PDPTE_PAE { unsigned P : 1; // present (1 = present) unsigned RW : 1; // Read Write unsigned US : 1; // User supervisor unsigned PWT : 1; // page-level write-through unsigned PCD : 1; // page-level cache disabled unsigned reserved0 : 1; // reserved unsigned reserved1 : 1; // reserved unsigned reserved2 : 1; // reserved unsigned reserved3 : 1; // reserved unsigned A1 : 1; // available 1 aka copy-on-write unsigned A2 : 1; // available 2/ is 1 when paged to disk unsigned A3 : 1; // available 3 unsigned PFN_LOW : 20; unsigned PFN_HIGH : 32; } *PPDPTE_PAE; #endif <|start_filename|>src/deepkernel.c<|end_filename|> #pragma warning( disable: 4100 4103) #include "deepkernel.h" #include "DBKFunc.h" #include <windef.h> #include "vmxhelper.h" BOOLEAN MakeWritableKM(PVOID StartAddress,UINT_PTR size) { #ifndef AMD64 UINT_PTR PTE,PDE; struct PTEStruct *x; UINT_PTR CurrentAddress=(UINT_PTR)StartAddress; while (CurrentAddress<((UINT_PTR)StartAddress+size)) { //find the PTE or PDE of the selected address PTE=(UINT_PTR)CurrentAddress; PTE=PTE/0x1000*PTESize+0xc0000000; PTE=(UINT_PTR)StartAddress; PTE=PTE/0x1000*PTESize+0xc0000000; //now check if the address in PTE is valid by checking the page table directory at 0xc0300000 (same location as CR3 btw) PDE=PTE/0x1000*PTESize+0xc0000000; //same formula x=(PVOID)PDE; if ((x->P==0) && (x->A2==0)) { CurrentAddress+=PAGE_SIZE_LARGE; continue; } if (x->PS==1) { //big page, no pte x->RW=1; CurrentAddress+=PAGE_SIZE_LARGE; continue; } CurrentAddress+=0x1000; x=(PVOID)PTE; if ((x->P==0) && (x->A2==0)) continue; //see for explenation the part of the PDE x->RW=1; } return TRUE; #else return FALSE; #endif } BOOLEAN MakeWritable(PVOID StartAddress,UINT_PTR size,BOOLEAN usecopyonwrite) { #ifndef AMD64 struct PTEStruct *x; unsigned char y; UINT_PTR CurrentAddress=(UINT_PTR)StartAddress; //Makes usermode <0x80000000 writable if (((UINT_PTR)StartAddress>=0x80000000) || ((UINT_PTR)StartAddress+size>=0x80000000)) return MakeWritableKM(StartAddress,size); //safety check: don't do kernelmemory with this routine //4kb pages (assumption, I know, but thats the system i'm working with) //PTE/0x1000*4+0xc0000000; while (CurrentAddress<((UINT_PTR)StartAddress+size)) { __try { y=*(PCHAR)CurrentAddress; //page it in if it wasn't loaded already (BSOD if kernelmode address) x=(PVOID)(CurrentAddress/0x1000*PTESize+0xc0000000); if (x->RW==0) //if it's read only then { if (usecopyonwrite) x->A1=1; //set the copy-on-write bit to 1 else x->RW=1; //just writable } } __except(1) { //ignore and continue } CurrentAddress+=0x1000; } return TRUE; #else return FALSE; #endif } //this unit will contain the functions and other crap used by the hider function BOOLEAN CheckImageName(IN PUNICODE_STRING FullImageName, IN char* List,int listsize) { #ifndef AMD64 /* pre:List has been initialized and all entries are UPPERCASE. Each entry is seperated by a 0-marker so just setting the pointer ro the start and doing a compare will work */ ANSI_STRING tempstring; int i; DbgPrint("Checking this image name...\n"); RtlZeroMemory(&tempstring,sizeof(ANSI_STRING)); if (RtlUnicodeStringToAnsiString(&tempstring,FullImageName,TRUE)== STATUS_SUCCESS) { char *p; INT_PTR modulesize; __try { RtlUpperString(&tempstring,&tempstring); p=List; for (i=0;i<listsize;i++) { if (List[i]=='\0') { modulesize=i-(INT_PTR)(p-List); if (modulesize>=0) { DbgPrint("Checking %s with %s\n",&tempstring.Buffer[tempstring.Length-modulesize],p); if ((tempstring.Length>=modulesize) && (strcmp(p,&tempstring.Buffer[tempstring.Length-modulesize])==0)) { //we have a match!!! DbgPrint("It's a match with %s\n",p); return TRUE; } } p=&List[i+1]; } } } __finally { RtlFreeAnsiString(&tempstring); } } DbgPrint("No match\n"); #endif return FALSE; } VOID LoadImageNotifyRoutine(IN PUNICODE_STRING FullImageName, IN HANDLE ProcessId, IN PIMAGE_INFO ImageInfo) { } <|start_filename|>src/threads.c<|end_filename|> #pragma warning( disable: 4100 4103) #include "threads.h" #include "processlist.h" #include "memscan.h" /* NTSTATUS NTAPI PsGetContextThread(IN PETHREAD Thread, IN OUT PCONTEXT ThreadContext, IN KPROCESSOR_MODE PreviousMode); NTSTATUS NTAPI PsSetContextThread(IN PETHREAD Thread, IN OUT PCONTEXT ThreadContext, IN KPROCESSOR_MODE PreviousMode); NTSTATUS NTAPI DBKGetContextThread(IN PETHREAD Thread, IN OUT PCONTEXT ThreadContext) { return PsGetContextThread(Thread, ThreadContext, KernelMode); }*/ struct ThreadData* GetThreaddata(ULONG threadid) { struct ProcessData *tempProcessData; struct ThreadData *tempThreadData; //PRE: Lock the list before calling this routine tempProcessData=processlist; while (tempProcessData) { tempThreadData=tempProcessData->Threads; while (tempThreadData) { if (tempThreadData->ThreadID==(HANDLE)(UINT_PTR)threadid) return tempThreadData; tempThreadData=tempThreadData->next; } tempProcessData=tempProcessData->next; } return NULL; } void Ignore(PKAPC Apc, PKNORMAL_ROUTINE NormalRoutine, PVOID NormalContext, PVOID SystemArgument1, PVOID SystemArgument2) { //ignore return; } void SuspendThreadAPCRoutine(PVOID arg1, PVOID arg2, PVOID arg3) { LARGE_INTEGER Timeout; struct ThreadData *x; //DbgPrint("Inside SuspendThreadAPCRoutine\n"); x=arg1; //DbgPrint("x=%p",x); DbgPrint("Waiting...\n"); Timeout.QuadPart = -999999999999999; KeWaitForSingleObject(&(x->SuspendSemaphore), Suspended, KernelMode, FALSE, NULL); //KeDelayExecutionThread(KernelMode, FALSE, &Timeout); DbgPrint("Resuming...\n"); } void DBKSuspendThread(ULONG ThreadID) { struct ThreadData *t_data; if (ExAcquireResourceSharedLite(&ProcesslistR, TRUE)) { DbgPrint("Going to suspend this thread\n"); //find the thread in the threadlist //find the threadid in the processlist t_data = GetThreaddata(ThreadID); if (t_data) { DbgPrint("Suspending thread....\n"); if (!t_data->PEThread) { //not yet initialized t_data->PEThread = (PETHREAD)getPEThread(ThreadID); KeInitializeApc(&t_data->SuspendApc, (PKTHREAD)t_data->PEThread, 0, (PKKERNEL_ROUTINE)Ignore, (PKRUNDOWN_ROUTINE)NULL, (PKNORMAL_ROUTINE)SuspendThreadAPCRoutine, KernelMode, t_data); } DbgPrint("x should be %p", t_data); t_data->suspendcount++; if (t_data->suspendcount == 1) //not yet suspended so suspend it KeInsertQueueApc(&t_data->SuspendApc, t_data, t_data, 0); } else DbgPrint("Thread not found in the list\n"); } ExReleaseResourceLite(&ProcesslistR); } void DBKResumeThread(ULONG ThreadID) { struct ThreadData *t_data; if (ExAcquireResourceSharedLite(&ProcesslistR, TRUE)) { DbgPrint("Going to resume this thread\n"); //find the thread in the threadlist //find the threadid in the processlist t_data = GetThreaddata(ThreadID); if (t_data) { if (t_data->suspendcount) { t_data->suspendcount--; if (!t_data->suspendcount) //suspendcount=0 so resume KeReleaseSemaphore(&t_data->SuspendSemaphore, 0, 1, FALSE); } } else DbgPrint("Thread not found in the list\n"); } ExReleaseResourceLite(&ProcesslistR); } void DBKSuspendProcess(ULONG ProcessID) { struct ThreadData *t_data=NULL; struct ProcessData *tempProcessData=NULL; if (ExAcquireResourceSharedLite(&ProcesslistR, TRUE)) { DbgPrint("Going to suspend this process\n"); //find the process in the threadlist tempProcessData = processlist; while (tempProcessData) { if (tempProcessData->ProcessID == (HANDLE)(UINT_PTR)ProcessID) { t_data = tempProcessData->Threads; break; } tempProcessData = tempProcessData->next; } if (!t_data) { DbgPrint("This process was not found\n"); ExReleaseResourceLite(&ProcesslistR); return; //no process found } while (t_data) { DbgPrint("Suspending thread....\n"); if (!t_data->PEThread) { //not yet initialized t_data->PEThread = (PETHREAD)getPEThread((UINT_PTR)t_data->ThreadID); KeInitializeApc(&t_data->SuspendApc, (PKTHREAD)t_data->PEThread, 0, (PKKERNEL_ROUTINE)Ignore, (PKRUNDOWN_ROUTINE)NULL, (PKNORMAL_ROUTINE)SuspendThreadAPCRoutine, KernelMode, t_data); } DbgPrint("x should be %p", t_data); t_data->suspendcount++; if (t_data->suspendcount == 1) //not yet suspended so suspend it KeInsertQueueApc(&t_data->SuspendApc, t_data, t_data, 0); t_data = t_data->next; //next thread } } ExReleaseResourceLite(&ProcesslistR); } void DBKResumeProcess(ULONG ProcessID) { struct ThreadData *t_data=NULL; struct ProcessData *tempProcessData=NULL; if (ExAcquireResourceSharedLite(&ProcesslistR, TRUE)) { DbgPrint("Going to suspend this process\n"); //find the process in the threadlist tempProcessData = processlist; while (tempProcessData) { if (tempProcessData->ProcessID == (HANDLE)(UINT_PTR)ProcessID) { t_data = tempProcessData->Threads; break; } tempProcessData = tempProcessData->next; } if (!t_data) { DbgPrint("This process was not found\n"); ExReleaseResourceLite(&ProcesslistR); return; //no process found } while (t_data) { DbgPrint("Resuming thread....\n"); if (t_data->suspendcount) { t_data->suspendcount--; if (!t_data->suspendcount) //suspendcount=0 so resume KeReleaseSemaphore(&t_data->SuspendSemaphore, 0, 1, FALSE); } t_data = t_data->next; //next thread } } ExReleaseResourceLite(&ProcesslistR); } <|start_filename|>src/DBKDrvr.h<|end_filename|> #ifndef DBKDRVR_H #define DBKDRVR_H #define dbkversion 2000027 #endif <|start_filename|>src/noexceptions.c<|end_filename|> #include "noexceptions.h" int MaxCPUCount; PCPUSTATE cpustate = NULL; #ifdef AMD64 extern void NoException14(void); //declared in debuggera.asm extern int ExceptionlessCopy_Internal(PVOID destination, PVOID source, int size); #else extern void __cdecl NoException14(void); //declared in debuggera.asm extern int __cdecl ExceptionlessCopy_Internal(PVOID destination, PVOID source, int size); #endif #if (NTDDI_VERSION < NTDDI_VISTA) int KeQueryActiveProcessorCount(PVOID x) { int cpucount=0; KAFFINITY cpus = KeQueryActiveProcessors(); while (cpus) { if (cpus % 2) cpucount++; cpus = cpus / 2; } return cpucount; } #endif BOOL NoExceptions_Enter() { KIRQL old; int i; int cpunr; //DbgPrint("NoExceptions_Enter"); __try { if (cpustate == NULL) { //initialize the list MaxCPUCount = (int)KeQueryActiveProcessorCount(NULL); cpustate = ExAllocatePool(NonPagedPool, MaxCPUCount*sizeof(CPUSTATE)); if (cpustate) { RtlZeroMemory(cpustate, MaxCPUCount*sizeof(CPUSTATE)); for (i = 0; i < MaxCPUCount; i++) { cpustate[i].NoExceptionVectorList = ExAllocatePool(NonPagedPool, 256 * sizeof(INT_VECTOR)); if (cpustate[i].NoExceptionVectorList) { RtlZeroMemory(cpustate[i].NoExceptionVectorList, 256 * sizeof(INT_VECTOR)); } else { //alloc failed, cleanup and quit int j; for (j = i - 1; i >= 0; i--) ExFreePool(cpustate[i].NoExceptionVectorList); cpustate = NULL; return FALSE; } } } else return FALSE; } //DbgPrint("cpustate setup here"); KeRaiseIrql(HIGH_LEVEL, &old); cpunr = KeGetCurrentProcessorNumber(); cpustate[cpunr].entryIRQL = old; if (cpustate[cpunr].OriginalIDT.wLimit == 0) { //initialize this UINT_PTR newAddress; __sidt(&cpustate[cpunr].OriginalIDT); RtlCopyMemory(cpustate[cpunr].NoExceptionVectorList, cpustate[cpunr].OriginalIDT.vector, cpustate[cpunr].OriginalIDT.wLimit + 1); //DbgPrint("idt. Limit=%d Vector=%p", (int)cpustate[cpunr].OriginalIDT.wLimit, cpustate[cpunr].OriginalIDT.vector); //hook cpustate[cpunr].NoExceptionVectorList[0-15] //DbgPrint("") newAddress = (UINT_PTR)NoException14; cpustate[cpunr].NoExceptionVectorList[14].wHighOffset = (WORD)((DWORD)(newAddress >> 16)); cpustate[cpunr].NoExceptionVectorList[14].wLowOffset = (WORD)newAddress; #ifdef AMD64 cpustate[cpunr].NoExceptionVectorList[14].TopOffset = (newAddress >> 32); cpustate[cpunr].NoExceptionVectorList[14].Reserved = 0; #endif /* newVector.wHighOffset=(WORD)((DWORD)(newEIP >> 16)); newVector.wLowOffset=(WORD)newEIP; newVector.wSelector=(WORD)newCS; newVector.bUnused=0; newVector.bAccessFlags=idt.vector[intnr].bAccessFlags; //don't touch accessflag, the default settings are good (e.g: int3,4 and 8 have dpl=3) #ifdef AMD64 newVector.TopOffset=(newEIP >> 32); newVector.Reserved=0; #endif */ cpustate[cpunr].ModdedIDT = cpustate[cpunr].OriginalIDT; cpustate[cpunr].ModdedIDT.vector = cpustate[cpunr].NoExceptionVectorList; }; #ifdef AMD64 _disable(); #else __asm{ cli } #endif __lidt(&cpustate[cpunr].ModdedIDT); return TRUE; } __except (1) { DbgPrint("Exception during NoExceptions_Enter. Figures"); } //KeGetCurrentProcessorNumber() //hadError = FALSE; return FALSE; } int NoExceptions_CopyMemory(PVOID Destination, PVOID Source, int size) { BOOL EnteredNoExceptions = FALSE; int r; if (KeGetCurrentIrql() <= DISPATCH_LEVEL) { //DbgPrint("calling NoExceptions_Enter"); EnteredNoExceptions = NoExceptions_Enter(); if (EnteredNoExceptions == FALSE) return 0; } r = ExceptionlessCopy_Internal(Destination, Source, size); if (EnteredNoExceptions) { //DbgPrint("calling NoExceptions_Leave"); NoExceptions_Leave(); } return r; } void NoExceptions_Leave() { int cpunr = KeGetCurrentProcessorNumber(); //restore the IDT __lidt(&cpustate[cpunr].OriginalIDT); #ifdef AMD64 _enable(); #else __asm{ sti } #endif KeLowerIrql(cpustate[cpunr].entryIRQL); } void NoExceptions_Cleanup() { if (cpustate) { int i; for (i = 0; i < MaxCPUCount; i++) { if (cpustate[i].NoExceptionVectorList) { ExFreePool(cpustate[i].NoExceptionVectorList); cpustate[i].NoExceptionVectorList = NULL; } } ExFreePool(cpustate); } } <|start_filename|>src/processlist.h<|end_filename|> #include <ntifs.h> #include "extradefines.h" #include "extraimports.h" VOID CreateProcessNotifyRoutine(IN HANDLE ParentId, IN HANDLE ProcessId, IN BOOLEAN Create); VOID CreateProcessNotifyRoutineEx(IN HANDLE ParentId, IN HANDLE ProcessId, __in_opt PPS_CREATE_NOTIFY_INFO CreateInfo); struct ThreadData { HANDLE ThreadID; PETHREAD PEThread; KAPC SuspendApc; KSEMAPHORE SuspendSemaphore; //why not mutex? int suspendcount; struct ThreadData *previous; struct ThreadData *next; }; typedef struct { HANDLE ProcessID; PEPROCESS PEProcess; HANDLE ProcessHandle; BOOLEAN Deleted; } ProcessListData, *PProcessListData; struct ProcessData { HANDLE ProcessID; PEPROCESS PEProcess; struct ThreadData *Threads; struct ProcessData *previous; struct ProcessData *next; } *processlist; typedef struct tagProcessEventData { UINT64 Created; UINT64 ProcessID; UINT64 PEProcess; } ProcessEventdta; ProcessEventdta ProcessEventdata[50]; UCHAR ProcessEventCount; PKEVENT ProcessEvent; //HANDLE ProcessEventHandle; BOOLEAN CreateProcessNotifyRoutineEnabled; ERESOURCE ProcesslistR; VOID CreateThreadNotifyRoutine(IN HANDLE ProcessId, IN HANDLE ThreadId, IN BOOLEAN Create); typedef struct tagThreadEventData { BOOLEAN Created; UINT64 ProcessID; UINT64 ThreadID; } ThreadEventDta; ThreadEventDta ThreadEventData[50]; UCHAR ThreadEventCount; PKEVENT ThreadEvent; //HANDLE ThreadEventHandle; extern HANDLE WatcherHandle; extern PEPROCESS WatcherProcess; extern BOOLEAN ProcessWatcherOpensHandles; BOOLEAN CreateThreadNotifyRoutineEnabled; VOID CleanProcessList(); HANDLE GetHandleForProcessID(IN HANDLE ProcessID); <|start_filename|>src/deepkernel.h<|end_filename|> #include <ntifs.h> #include <windef.h> VOID LoadImageNotifyRoutine(IN PUNICODE_STRING FullImageName, IN HANDLE ProcessId, IN PIMAGE_INFO ImageInfo); BOOLEAN MakeWritable(PVOID StartAddress,UINT_PTR size,BOOLEAN usecopyonwrite); BOOLEAN ImageNotifyRoutineLoaded; char* ModuleList; int ModuleListSize; ULONG Size; UINT_PTR ActiveLinkOffset; UINT_PTR ProcessNameOffset; UINT_PTR DebugportOffset; UINT_PTR PIDOffset; <|start_filename|>src/IOPLDispatcher.h<|end_filename|> #ifndef IOPLDISPACTCHER_H #define IOPLDISPACTCHER_H #include "DBKfunc.h" #define IOCTL_UNKNOWN_BASE FILE_DEVICE_UNKNOWN #define IOCTL_CE_READMEMORY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0800, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_WRITEMEMORY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0801, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_OPENPROCESS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0802, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_QUERY_VIRTUAL_MEMORY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0803, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_TEST CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0804, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETPEPROCESS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0805, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_READPHYSICALMEMORY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0806, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_WRITEPHYSICALMEMORY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0807, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETPHYSICALADDRESS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0808, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) //#define IOCTL_CE_PROTECTME CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0809, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETCR3 CTL_CODE(IOCTL_UNKNOWN_BASE, 0x080a, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_SETCR3 CTL_CODE(IOCTL_UNKNOWN_BASE, 0x080b, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETSDT CTL_CODE(IOCTL_UNKNOWN_BASE, 0x080c, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_INITIALIZE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x080d, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_DONTPROTECTME CTL_CODE(IOCTL_UNKNOWN_BASE, 0x080e, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETIDT CTL_CODE(IOCTL_UNKNOWN_BASE, 0x080f, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_HOOKINTS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0810, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_DEBUGPROCESS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0811, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) //#define IOCTL_CE_RETRIEVEDEBUGDATA CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0812, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_STARTPROCESSWATCH CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0813, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETPROCESSEVENTS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0814, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETTHREADEVENTS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0815, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETVERSION CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0816, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETCR4 CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0817, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_OPENTHREAD CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0818, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_MAKEWRITABLE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0819, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) //obsolete: #define IOCTL_CE_DEBUGPROCESS_CHANGEREG CTL_CODE(IOCTL_UNKNOWN_BASE, 0x081a, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_STOPDEBUGGING CTL_CODE(IOCTL_UNKNOWN_BASE, 0x081b, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) //obsolete: #define IOCTL_CE_STOP_DEBUGPROCESS_CHANGEREG CTL_CODE(IOCTL_UNKNOWN_BASE, 0x081c, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) //#define IOCTL_CE_USEALTERNATEMETHOD CTL_CODE(IOCTL_UNKNOWN_BASE, 0x081d, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) //#define IOCTL_CE_ISUSINGALTERNATEMETHOD CTL_CODE(IOCTL_UNKNOWN_BASE, 0x081e, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ALLOCATEMEM CTL_CODE(IOCTL_UNKNOWN_BASE, 0x081f, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_CREATEAPC CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0820, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETPETHREAD CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0821, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_SUSPENDTHREAD CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0822, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_RESUMETHREAD CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0823, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_SUSPENDPROCESS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0824, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_RESUMEPROCESS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0825, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ALLOCATEMEM_NONPAGED CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0826, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETPROCADDRESS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0827, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) //#define IOCTL_CE_SETSDTADDRESS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0828, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETSDTADDRESS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0829, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETGDT CTL_CODE(IOCTL_UNKNOWN_BASE, 0x082a, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_SETCR4 CTL_CODE(IOCTL_UNKNOWN_BASE, 0x082b, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETTR CTL_CODE(IOCTL_UNKNOWN_BASE, 0x082c, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_VMXCONFIG CTL_CODE(IOCTL_UNKNOWN_BASE, 0x082d, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETCR0 CTL_CODE(IOCTL_UNKNOWN_BASE, 0x082e, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_USERDEFINEDINTERRUPTHOOK CTL_CODE(IOCTL_UNKNOWN_BASE, 0x082f, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_SETGLOBALDEBUGSTATE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0830, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_CONTINUEDEBUGEVENT CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0831, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_WAITFORDEBUGEVENT CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0832, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETDEBUGGERSTATE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0833, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_SETDEBUGGERSTATE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0834, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GD_SETBREAKPOINT CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0835, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_TOUCHDEBUGREGISTER CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0836, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_LAUNCHDBVM CTL_CODE(IOCTL_UNKNOWN_BASE, 0x083a, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_UNHOOKALLINTERRUPTS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x083b, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_EXECUTE_CODE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x083c, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETPROCESSNAMEADDRESS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x083d, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_SETKERNELSTEPABILITY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x083e, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_READMSR CTL_CODE(IOCTL_UNKNOWN_BASE, 0x083f, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_WRITEMSR CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0840, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_SETSTORELBR CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0841, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0842, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP_DISABLE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0843, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP_WAITFORDATA CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0844, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP_CONTINUE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0845, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP_FLUSH CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0846, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETMEMORYRANGES CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0847, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_STARTACCESMONITOR CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0848, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ENUMACCESSEDMEMORY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0849, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GETACCESSEDMEMORYLIST CTL_CODE(IOCTL_UNKNOWN_BASE, 0x084a, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_WRITESIGNOREWP CTL_CODE(IOCTL_UNKNOWN_BASE, 0x084b, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_FREE_NONPAGED CTL_CODE(IOCTL_UNKNOWN_BASE, 0x084c, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_MAP_MEMORY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x084d, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_UNMAP_MEMORY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x084e, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP2 CTL_CODE(IOCTL_UNKNOWN_BASE, 0x084f, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_DISABLEULTIMAP2 CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0850, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP2_WAITFORDATA CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0851, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP2_CONTINUE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0852, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP2_FLUSH CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0853, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP2_PAUSE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0854, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP2_RESUME CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0855, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP2_LOCKFILE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0856, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP2_RELEASEFILE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0857, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP_PAUSE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0858, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP_RESUME CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0859, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP2_GETTRACESIZE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x085a, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ULTIMAP2_RESETTRACESIZE CTL_CODE(IOCTL_UNKNOWN_BASE, 0x085b, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ENABLE_DRM CTL_CODE(IOCTL_UNKNOWN_BASE, 0x085c, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_GET_PEB CTL_CODE(IOCTL_UNKNOWN_BASE, 0x085d, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_QUERYINFORMATIONPROCESS CTL_CODE(IOCTL_UNKNOWN_BASE, 0x085e, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_NTPROTECTVIRTUALMEMORY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x085f, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_LOCK_MEMORY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0860, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_UNLOCK_MEMORY CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0861, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_CE_ALLOCATE_MEMORY_FOR_DBVM CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0862, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) extern PVOID DRMHandle; #define SYSTEMSERVICE(_function) KeServiceDescriptorTable->ServiceTable[ *(PULONG)((PUCHAR)_function+1)] #define SYSTEMSERVICELINK(_function) KeServiceDescriptorTable->ServiceTable[*((PUCHAR)(*(PULONG)*((PULONG)((PUCHAR)_function+2)))+1)] NTSTATUS DispatchIoctl(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp); BOOL DispatchIoctlDBVM(IN PDEVICE_OBJECT DeviceObject, ULONG IoControlCode, PVOID lpInBuffer, DWORD nInBufferSize, PVOID lpOutBuffer, DWORD nOutBufferSize, PDWORD lpBytesReturned); #endif <|start_filename|>src/DBKFunc.c<|end_filename|> #pragma warning( disable: 4103) #include <ntifs.h> #include <ntddk.h> #include "DBKFunc.h" /* #include "vmxhelper.h" #include "interruptHook.h" */ #ifdef TESTCOMPILE //small bypass to make test compiles function (this compiler doesn't have CLI/STI ) void _enable() {} void _disable() {} #endif void forEachCpuPassive(PF f, UINT_PTR param) /* calls a specific function for each cpu that runs in passive mode */ { CCHAR cpunr; KAFFINITY cpus, original; ULONG cpucount; //KeIpiGenericCall is not present in xp //count cpus first KeQueryActiveProcessorCount is not present in xp) cpucount=0; cpus=KeQueryActiveProcessors(); original=cpus; while (cpus) { if (cpus % 2) cpucount++; cpus=cpus / 2; } cpus=KeQueryActiveProcessors(); cpunr=0; while (cpus) { if (cpus % 2) { //bit is set #if (NTDDI_VERSION >= NTDDI_VISTA) KAFFINITY oldaffinity; #endif KAFFINITY newaffinity; //DbgPrint("Calling passive function for cpunr %d\n", cpunr); //set affinity newaffinity=(KAFFINITY)(1 << cpunr); #if (NTDDI_VERSION >= NTDDI_VISTA) oldaffinity=KeSetSystemAffinityThreadEx(newaffinity); #else //XP and earlier (this routine is not called often, only when the user asks explicitly { LARGE_INTEGER delay; delay.QuadPart=-50; //short wait just to be sure... (the docs do not say that a switch happens imeadiatly for the no Ex version) KeSetSystemAffinityThread(newaffinity); KeDelayExecutionThread(UserMode, FALSE, &delay); } #endif //call function f(param); #if (NTDDI_VERSION >= NTDDI_VISTA) KeRevertToUserAffinityThreadEx(oldaffinity); #endif } cpus=cpus / 2; cpunr++; } #if (NTDDI_VERSION < NTDDI_VISTA) KeSetSystemAffinityThread(original); #endif } void forOneCpu(CCHAR cpunr, PKDEFERRED_ROUTINE dpcfunction, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2, OPTIONAL PPREDPC_CALLBACK preDPCCallback) { PKDPC dpc; if (preDPCCallback) //if preDPCCallback is set call it which may change the system arguments preDPCCallback(cpunr, dpcfunction, DeferredContext, &SystemArgument1, &SystemArgument2); dpc = ExAllocatePool(NonPagedPool, sizeof(KDPC)); KeInitializeDpc(dpc, dpcfunction, DeferredContext); KeSetTargetProcessorDpc(dpc, cpunr); KeInsertQueueDpc(dpc, SystemArgument1, SystemArgument2); KeFlushQueuedDpcs(); ExFreePool(dpc); } void forEachCpu(PKDEFERRED_ROUTINE dpcfunction, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2, OPTIONAL PPREDPC_CALLBACK preDPCCallback) /* calls a specified dpcfunction for each cpu on the system */ { CCHAR cpunr; KAFFINITY cpus; ULONG cpucount; PKDPC dpc; int dpcnr; //KeIpiGenericCall is not present in xp //count cpus first KeQueryActiveProcessorCount is not present in xp) cpucount=0; cpus=KeQueryActiveProcessors(); while (cpus) { if (cpus % 2) cpucount++; cpus=cpus / 2; } dpc=ExAllocatePool(NonPagedPool, sizeof(KDPC)*cpucount); cpus=KeQueryActiveProcessors(); cpunr=0; dpcnr=0; while (cpus) { if (cpus % 2) { //bit is set //DbgPrint("Calling dpc routine for cpunr %d (dpc=%p)\n", cpunr, &dpc[dpcnr]); if (preDPCCallback) preDPCCallback(cpunr, dpcfunction, DeferredContext, &SystemArgument1, &SystemArgument2); KeInitializeDpc(&dpc[dpcnr], dpcfunction, DeferredContext); KeSetTargetProcessorDpc (&dpc[dpcnr], cpunr); KeInsertQueueDpc(&dpc[dpcnr], SystemArgument1, SystemArgument2); KeFlushQueuedDpcs(); dpcnr++; } cpus=cpus / 2; cpunr++; } ExFreePool(dpc); } void forEachCpuAsync(PKDEFERRED_ROUTINE dpcfunction, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2, OPTIONAL PPREDPC_CALLBACK preDPCCallback) /* calls a specified dpcfunction for each cpu on the system */ { CCHAR cpunr; KAFFINITY cpus; ULONG cpucount; PKDPC dpc; int dpcnr; //KeIpiGenericCall is not present in xp //count cpus first KeQueryActiveProcessorCount is not present in xp) cpucount = 0; cpus = KeQueryActiveProcessors(); while (cpus) { if (cpus % 2) cpucount++; cpus = cpus / 2; } dpc = ExAllocatePool(NonPagedPool, sizeof(KDPC)*cpucount); cpus = KeQueryActiveProcessors(); cpunr = 0; dpcnr = 0; while (cpus) { if (cpus % 2) { //bit is set //DbgPrint("Calling dpc routine for cpunr %d\n", cpunr); if (preDPCCallback) //if preDPCCallback is set call it which may change the system arguments preDPCCallback(cpunr, dpcfunction, DeferredContext, &SystemArgument1, &SystemArgument2); KeInitializeDpc(&dpc[dpcnr], dpcfunction, DeferredContext); KeSetTargetProcessorDpc(&dpc[dpcnr], cpunr); KeInsertQueueDpc(&dpc[dpcnr], SystemArgument1, SystemArgument2); dpcnr++; } cpus = cpus / 2; cpunr++; } KeFlushQueuedDpcs(); ExFreePool(dpc); } //own critical section implementation for use when the os is pretty much useless (dbvm tech) void spinlock(volatile LONG *lockvar) { while (1) { //it was 0, let's see if we can set it to 1 //race who can set it to 1: if (_InterlockedExchange((volatile LONG *)lockvar, 1)==0) return; //lock aquired, else continue loop _mm_pause(); } } void csEnter(PcriticalSection CS) { EFLAGS oldstate=getEflags(); if ((CS->locked) && (CS->cpunr==cpunr())) { //already locked but the locker is this cpu, so allow, just increase lockcount CS->lockcount++; return; } disableInterrupts(); //disable interrupts to prevent taskswitch in same cpu spinlock(&(CS->locked)); //sets CS->locked to 1 //here so the lock is aquired and locked is 1 CS->lockcount=1; CS->cpunr=cpunr(); CS->oldIFstate=oldstate.IF; } void csLeave(PcriticalSection CS) { if ((CS->locked) && (CS->cpunr==cpunr())) { CS->lockcount--; if (CS->lockcount==0) { //unlock if (CS->oldIFstate) enableInterrupts(); CS->cpunr=-1; //set to an cpunr CS->locked=0; } } } int getCpuCount(void) { KAFFINITY ap=KeQueryActiveProcessors(); int count=0; while (ap>0) { if (ap % 2) count++; ap=ap / 2; } return count; } int isPrefix(unsigned char b) { switch (b) { case 0x26: case 0x2e: case 0x36: case 0x3e: case 0x64: case 0x65: case 0x66: case 0x67: case 0xf0: //lock case 0xf2: //repne case 0xf3: //rep return 1; default: return 0; } } UINT64 getDR7(void) { return __readdr(7); } int cpunr(void) { DWORD x[4]; __cpuid(&x[0],1); return (x[1] >> 24)+1; } EFLAGS getEflags(void) { UINT64 x=__getcallerseflags(); PEFLAGS y = (PEFLAGS)&x; return *y; } UINT64 readMSR(DWORD msr) { return __readmsr(msr); } void setCR0(UINT64 newcr0) { __writecr0(newcr0); } UINT64 getCR0(void) { return __readcr0(); } UINT64 getCR2(void) { return __readcr2(); } void setCR3(UINT64 newCR3) { __writecr3((UINT_PTR)newCR3); } UINT64 getCR3(void) { return __readcr3(); } void setCR4(UINT64 newcr4) { __writecr4(newcr4); } UINT64 getCR4(void) { return __readcr4(); } void GetIDT(PIDT pIdt) { __sidt(pIdt); } void enableInterrupts(void) { #ifdef AMD64 _enable(); #else __asm{sti}; #endif } void disableInterrupts(void) { #ifdef AMD64 _disable(); #else __asm{cli}; #endif } UINT64 getTSC(void) { return __rdtsc(); } #ifndef AMD64 //function declarations that can be done inline without needing an .asm file _declspec( naked ) WORD getSS(void) { __asm { mov ax,ss ret } } _declspec( naked ) WORD getCS(void) { __asm { mov ax,cs ret } } _declspec( naked ) WORD getDS(void) { __asm { mov ax,ds ret } } _declspec( naked ) WORD getES(void) { __asm { mov ax,es ret } } _declspec( naked ) WORD getFS(void) { __asm { mov ax,fs ret } } _declspec( naked ) WORD getGS(void) { __asm { mov ax,gs ret } } _declspec( naked ) ULONG getRSP(void) //... { __asm { mov eax,esp add eax,4 //don't add this call ret } } _declspec( naked ) ULONG getRBP(void) { __asm { mov eax,ebp ret } } _declspec( naked ) ULONG getRAX(void) { __asm { mov eax,eax ret } } _declspec( naked ) ULONG getRBX(void) { __asm { mov eax,ebx ret } } _declspec( naked ) ULONG getRCX(void) { __asm { mov eax,ecx ret } } _declspec( naked ) ULONG getRDX(void) { __asm { mov eax,edx ret } } _declspec( naked ) ULONG getRSI(void) { __asm { mov eax,esi ret } } _declspec( naked ) ULONG getRDI(void) { __asm { mov eax,edi ret } } _declspec( naked ) unsigned short GetTR(void) { __asm{ STR AX ret } } void GetGDT(PGDT pGdt) { __asm { MOV EAX, [pGdt] SGDT [EAX] } } _declspec( naked )WORD GetLDT() { __asm { SLDT ax ret } } #endif <|start_filename|>src/memscan.h<|end_filename|> #include <windef.h> #ifdef AMD64 #define PAGETABLEBASE 0xfffff68000000000ULL //win10 1607 it's random #else #define PAGETABLEBASE 0xc0000000 #endif typedef struct _ADDRESSENTRY { DWORD Address; BYTE size; BOOLEAN frozen; PVOID frozendata; } ADDRESSENTRY; typedef struct _MEMREGION //only holds regions that are allowed { DWORD BaseAddress; DWORD Size; } MEMREGION; typedef struct _MEMSCANOPTIONS { BYTE ShowAsSigned; //obsolete (clientside now) BYTE BinariesAsDecimal; //obsolete (clientside now) WORD max; DWORD buffersize; BYTE skip_page_no_cache; //hmmmm BYTE UseDebugRegs; BYTE UseDBKQueryMemoryRegion; //always true BYTE UseDBKReadWriteMemory; //always true BYTE UseDBKOpenProcess; //always true } MEMSCANOPTIONS; MEMSCANOPTIONS MemscanOptions; typedef struct _SCANDATA { PEPROCESS process; DWORD Start; DWORD Stop; BYTE Vartype; BYTE Scantype; BYTE ScanOptions; BYTE scanvaluelength; char *scanvalue; BOOLEAN scanning; BOOLEAN ThreadActive; } SCANDATA; SCANDATA CurrentScan; typedef struct { UINT64 StartAddress; UINT64 EndAddress; } PRANGE, *PPRANGE; typedef struct { PRANGE Range; void *Next; } PENTRY, *PPENTRY; #ifdef CETC BOOLEAN FirstScan(PEPROCESS ActivePEPROCESS, DWORD start,DWORD stop,BYTE vartype,BYTE scantype,BYTE scanvaluesize,char *scanvalue,BYTE ScanOptions); #endif NTSTATUS ReadPhysicalMemory(char *startaddress, UINT_PTR bytestoread, void *output); BOOLEAN ReadProcessMemory(DWORD PID,PEPROCESS PEProcess,PVOID Address,DWORD Size, PVOID Buffer); BOOLEAN WriteProcessMemory(DWORD PID,PEPROCESS PEProcess,PVOID Address,DWORD Size, PVOID Buffer); BOOLEAN IsAddressSafe(UINT_PTR StartAddress); BOOLEAN GetMemoryRegionData(DWORD PID,PEPROCESS PEProcess, PVOID mempointer,ULONG *regiontype, UINT_PTR *memorysize,UINT_PTR *baseaddress); NTSTATUS markAllPagesAsNeverAccessed(PEPROCESS PEProcess); int enumAllAccessedPages(PEPROCESS PEProcess); int getAccessedPageList(PPRANGE List, int ListSizeInBytes); UINT_PTR getPageTableBase(); UINT_PTR getPEThread(UINT_PTR threadid); ADDRESSENTRY *AddressList; unsigned int AddressListSize; unsigned int AddressListEntries; KSPIN_LOCK AddressListSpinlock; PVOID FrozenData; //holds the buffer of all frozen data records int FrozenDataSize; LARGE_INTEGER FreezeInterval; HANDLE addressfile; HANDLE valuefile; BOOLEAN HiddenDriver; //scanoptions #define SO_FASTSCAN (0x1) #define SO_HEXADECIMAL (0x2) #define SO_READONLY (0x4) #define SO_FINDONLYONE (0x8) #define SO_ISBINARY (0x10) #define SO_UNICODE (0x20) //scantype #define ST_Exact_value 0 #define ST_Increased_value 1 #define ST_Increased_value_by 2 #define ST_Decreased_value 3 #define ST_Decreased_value_by 4 #define ST_Changed_value 5 #define ST_Unchanged_value 6 #define ST_Advanced_Scan 7 #define ST_String_Scan 8 #define ST_SmallerThan 9 #define ST_BiggerThan 10 #define ST_Userdefined 11 //scanerrors #define SE_IncorrectType -1 #define SE_NotSupported -2 #define SE_NoMemoryFound -3 <|start_filename|>src/threads.h<|end_filename|> #ifndef THREADS_H #define THREADS_H #include <ntifs.h> #include <windef.h> #include "DBKFunc.h" void Ignore(PKAPC Apc, PKNORMAL_ROUTINE NormalRoutine, PVOID NormalContext, PVOID SystemArgument1, PVOID SystemArgument2); void SuspendThreadAPCRoutine(PVOID arg1, PVOID arg2, PVOID arg3); void DBKSuspendThread(ULONG ThreadID); void DBKResumeThread(ULONG ThreadID); void DBKResumeProcess(ULONG ProcessID); void DBKSuspendProcess(ULONG ProcessID); //NTSTATUS NTAPI DBKGetContextThread(IN PETHREAD Thread, IN OUT PCONTEXT ThreadContext); #endif <|start_filename|>src/segmentinfo.asm<|end_filename|> _TEXT SEGMENT 'CODE' PUBLIC _getAccessRights@8 _getAccessRights@8: push ebp mov ebp,esp push ecx mov ecx,[ebp+8] ;0=old ebp, 4=return address, 8=param1 lar eax,ecx jnz getAccessRights_invalid shr eax,8 and eax,0f0ffh jmp getAccessRights_exit getAccessRights_invalid: mov eax,010000h getAccessRights_exit: pop ecx pop ebp ret PUBLIC _getSegmentLimit@8 _getSegmentLimit@8: push ebp mov ebp,esp push ecx mov ecx,[ebp+8] xor eax,eax lsl eax,ecx pop ecx pop ebp ret _TEXT ENDS END <|start_filename|>src/processlist.c<|end_filename|> #pragma warning( disable: 4100 4103 4706) #include "ntifs.h" #include "processlist.h" #include "threads.h" #include "memscan.h" #include "ultimap2.h" PRTL_GENERIC_TABLE InternalProcessList = NULL; PEPROCESS WatcherProcess = NULL; BOOLEAN ProcessWatcherOpensHandles = TRUE; RTL_GENERIC_COMPARE_RESULTS NTAPI ProcessListCompare(__in struct _RTL_GENERIC_TABLE *Table, __in PProcessListData FirstStruct, __in PProcessListData SecondStruct) { //DbgPrint("ProcessListCompate"); if (FirstStruct->ProcessID == SecondStruct->ProcessID) return GenericEqual; else { if (SecondStruct->ProcessID < FirstStruct->ProcessID) return GenericLessThan; else return GenericGreaterThan; } } PVOID NTAPI ProcessListAlloc(__in struct _RTL_GENERIC_TABLE *Table, __in CLONG ByteSize) { PVOID r=ExAllocatePool(PagedPool, ByteSize); RtlZeroMemory(r, ByteSize); //DbgPrint("ProcessListAlloc %d",(int)ByteSize); return r; } VOID NTAPI ProcessListDealloc(__in struct _RTL_GENERIC_TABLE *Table, __in __drv_freesMem(Mem) __post_invalid PVOID Buffer) { //DbgPrint("ProcessListDealloc"); ExFreePool(Buffer); } VOID GetThreadData(IN PDEVICE_OBJECT DeviceObject, IN PVOID Context) { struct ThreadData *tempThreadEntry; PETHREAD selectedthread; HANDLE tid; LARGE_INTEGER Timeout; PKAPC AP; tempThreadEntry=Context; DbgPrint("Gathering PEThread thread\n"); Timeout.QuadPart = -1; KeDelayExecutionThread(KernelMode, TRUE, &Timeout); selectedthread=NULL; if (ExAcquireResourceSharedLite(&ProcesslistR, TRUE)) { tid = tempThreadEntry->ThreadID; AP = &tempThreadEntry->SuspendApc; PsLookupThreadByThreadId((PVOID)tid, &selectedthread); if (selectedthread) { DbgPrint("PEThread=%p\n", selectedthread); KeInitializeApc(AP, (PKTHREAD)selectedthread, 0, (PKKERNEL_ROUTINE)Ignore, (PKRUNDOWN_ROUTINE)NULL, (PKNORMAL_ROUTINE)SuspendThreadAPCRoutine, KernelMode, NULL); ObDereferenceObject(selectedthread); } else { DbgPrint("Failed getting the pethread.\n"); } } ExReleaseResourceLite(&ProcesslistR); } VOID CreateThreadNotifyRoutine(IN HANDLE ProcessId,IN HANDLE ThreadId,IN BOOLEAN Create) { if (KeGetCurrentIrql()==PASSIVE_LEVEL) { /*if (DebuggedProcessID==(ULONG)ProcessId) { // PsSetContextThread (bah, xp only) }*/ if (ExAcquireResourceExclusiveLite(&ProcesslistR, TRUE)) { if (ThreadEventCount < 50) { ThreadEventData[ThreadEventCount].Created = Create; ThreadEventData[ThreadEventCount].ProcessID = (UINT_PTR)ProcessId; ThreadEventData[ThreadEventCount].ThreadID = (UINT_PTR)ThreadId; /* if (Create) DbgPrint("Create ProcessID=%x\nThreadID=%x\n",(UINT_PTR)ProcessId,(UINT_PTR)ThreadId); else DbgPrint("Destroy ProcessID=%x\nThreadID=%x\n",(UINT_PTR)ProcessId,(UINT_PTR)ThreadId); */ ThreadEventCount++; } } ExReleaseResourceLite(&ProcesslistR); KeSetEvent(ThreadEvent, 0, FALSE); KeClearEvent(ThreadEvent); } } VOID CreateProcessNotifyRoutine(IN HANDLE ParentId, IN HANDLE ProcessId, IN BOOLEAN Create) { PEPROCESS CurrentProcess = NULL; HANDLE ProcessHandle = 0; /* if (PsSuspendProcess) { DbgPrint("Suspending process %d", PsGetCurrentThreadId()); PsSuspendProcess(PsGetCurrentProcess()); DbgPrint("After PsGetCurrentProcess()"); } */ if (KeGetCurrentIrql()==PASSIVE_LEVEL) { struct ProcessData *tempProcessEntry; //aquire a spinlock if (ExAcquireResourceExclusiveLite(&ProcesslistR, TRUE)) { if (PsLookupProcessByProcessId((PVOID)ProcessId, &CurrentProcess) != STATUS_SUCCESS) { ExReleaseResourceLite(&ProcesslistR); return; } if ((ProcessWatcherOpensHandles) && (WatcherProcess)) { if (Create) { //Open a handle to this process /* HANDLE ph = 0; NTSTATUS r = ObOpenObjectByPointer(CurrentProcess, 0, NULL, PROCESS_ALL_ACCESS, *PsProcessType, KernelMode, &ph); DbgPrint("CreateProcessNotifyRoutine: ObOpenObjectByPointer=%x ph=%x", r, ph); r = ZwDuplicateObject(ZwCurrentProcess(), ph, WatcherHandle, &ProcessHandle, PROCESS_ALL_ACCESS, 0, DUPLICATE_CLOSE_SOURCE); DbgPrint("CreateProcessNotifyRoutine: ZwDuplicateObject=%x (handle=%x)", r, ProcessHandle); */ KAPC_STATE oldstate; KeStackAttachProcess((PKPROCESS)WatcherProcess, &oldstate); __try { __try { ObOpenObjectByPointer(CurrentProcess, 0, NULL, PROCESS_ALL_ACCESS, *PsProcessType, KernelMode, &ProcessHandle); } __except (1) { DbgPrint("Exception during ObOpenObjectByPointer"); } } __finally { KeUnstackDetachProcess(&oldstate); } } if (InternalProcessList == NULL) { InternalProcessList = ExAllocatePool(PagedPool, sizeof(RTL_GENERIC_TABLE)); if (InternalProcessList) RtlInitializeGenericTable(InternalProcessList, ProcessListCompare, ProcessListAlloc, ProcessListDealloc, NULL); } if (InternalProcessList) { ProcessListData d, *r; d.ProcessID = ProcessId; d.PEProcess = CurrentProcess; d.ProcessHandle = ProcessHandle; r = RtlLookupElementGenericTable(InternalProcessList, &d); if (Create) { //add it to the list BOOLEAN newElement = FALSE; if (r) //weird { DbgPrint("Duplicate PID detected..."); RtlDeleteElementGenericTable(InternalProcessList, r); } r = RtlInsertElementGenericTable(InternalProcessList, &d, sizeof(d), &newElement); DbgPrint("Added handle %x for pid %d to the list (newElement=%d r=%p)", (int)(UINT_PTR)d.ProcessHandle, (int)(UINT_PTR)d.ProcessID, newElement, r); } else { //remove it from the list (if it's there) DbgPrint("Process %d destruction. r=%p", (int)(UINT_PTR)d.ProcessID, r); if (r) { DbgPrint("Process that was in the list has been closed"); //if (r->ProcessHandle) // ZwClose(r->ProcessHandle); //RtlDeleteElementGenericTable(InternalProcessList, r); r->Deleted = 1; } if (CurrentProcess == WatcherProcess) { DbgPrint("CE Closed"); //ZwClose(WatcherHandle); CleanProcessList(); //CE closed WatcherProcess = 0; } } } } //fill in a processcreateblock with data if (ProcessEventCount < 50) { ProcessEventdata[ProcessEventCount].Created = Create; ProcessEventdata[ProcessEventCount].ProcessID = (UINT_PTR)ProcessId; ProcessEventdata[ProcessEventCount].PEProcess = (UINT_PTR)CurrentProcess; ProcessEventCount++; } //if (!HiddenDriver) if (FALSE) //moved till next version { if (Create) { //allocate a block of memory for the processlist tempProcessEntry = ExAllocatePool(PagedPool, sizeof(struct ProcessData)); tempProcessEntry->ProcessID = ProcessId; tempProcessEntry->PEProcess = CurrentProcess; tempProcessEntry->Threads = NULL; DbgPrint("Allocated a process at:%p\n", tempProcessEntry); if (!processlist) { processlist = tempProcessEntry; processlist->next = NULL; processlist->previous = NULL; } else { tempProcessEntry->next = processlist; tempProcessEntry->previous = NULL; processlist->previous = tempProcessEntry; processlist = tempProcessEntry; } } else { //find this process and delete it tempProcessEntry = processlist; while (tempProcessEntry) { if (tempProcessEntry->ProcessID == ProcessId) { int i; if (tempProcessEntry->next) tempProcessEntry->next->previous = tempProcessEntry->previous; if (tempProcessEntry->previous) tempProcessEntry->previous->next = tempProcessEntry->next; else processlist = tempProcessEntry->next; //it had no previous entry, so it's the root /* if (tempProcessEntry->Threads) { struct ThreadData *tempthread,*tempthread2; KIRQL OldIrql2; tempthread=tempProcessEntry->Threads; tempthread2=tempthread; DbgPrint("Process ended. Freeing threads\n"); while (tempthread) { tempthread=tempthread->next; DbgPrint("Free thread %p (next thread=%p)\n",tempthread2,tempthread); ExFreePool(tempthread2); tempthread2=tempthread; } } ExFreePool(tempProcessEntry);*/ i = 0; tempProcessEntry = processlist; while (tempProcessEntry) { i++; tempProcessEntry = tempProcessEntry->next; } DbgPrint("There are %d processes in the list\n", i); break; } tempProcessEntry = tempProcessEntry->next; } } } } ExReleaseResourceLite(&ProcesslistR); if (CurrentProcess!=NULL) ObDereferenceObject(CurrentProcess); //signal process event (if there's one waiting for a signal) if (ProcessEvent) { KeSetEvent(ProcessEvent, 0, FALSE); KeClearEvent(ProcessEvent); } } } VOID CreateProcessNotifyRoutineEx(IN HANDLE ParentId, IN HANDLE ProcessId, __in_opt PPS_CREATE_NOTIFY_INFO CreateInfo) { DbgPrint("CreateProcessNotifyRoutineEx"); CreateProcessNotifyRoutine(ParentId, ProcessId, CreateInfo!=NULL); } HANDLE GetHandleForProcessID(IN HANDLE ProcessID) { if (InternalProcessList) { ProcessListData d, *r; d.ProcessID = ProcessID; r = RtlLookupElementGenericTable(InternalProcessList, &d); if (r) { DbgPrint("Found a handle for PID %d (%x)", (int)(UINT_PTR)ProcessID, (int)(UINT_PTR)r->ProcessHandle); return r->ProcessHandle; // r->ProcessHandle; } } return 0; } VOID CleanProcessList() { if (InternalProcessList) { PProcessListData li; if (ExAcquireResourceExclusiveLite(&ProcesslistR, TRUE)) { KAPC_STATE oldstate; BOOLEAN ChangedContext; if ((WatcherProcess) && (WatcherProcess != PsGetCurrentProcess())) { KeStackAttachProcess((PKPROCESS)WatcherProcess, &oldstate); ChangedContext = TRUE; } while (li = RtlGetElementGenericTable(InternalProcessList, 0)) { if ((li->ProcessHandle) && (WatcherProcess)) ZwClose(li->ProcessHandle); RtlDeleteElementGenericTable(InternalProcessList, li); } ExFreePool(InternalProcessList); InternalProcessList = NULL; } ExReleaseResourceLite(&ProcesslistR); } } <|start_filename|>src/extraimports.h<|end_filename|> NTSYSAPI BOOLEAN KeAddSystemServiceTable( IN PULONG_PTR Base, IN PULONG Count OPTIONAL, IN ULONG Limit, IN PUCHAR Number, IN ULONG Index ); <|start_filename|>src/debugger.h<|end_filename|> #ifndef DEBUGGER_H #define DEBUGGER_H #include <ntifs.h> #include <windef.h> #pragma pack(4) typedef struct { UINT64 threadid; // UINT64 causedbydbvm; UINT64 rflags; UINT64 rax;// UINT64 rbx; UINT64 rcx;// UINT64 rdx; UINT64 rsi;// UINT64 rdi; UINT64 rbp;// UINT64 rsp; UINT64 rip;// UINT64 r8; UINT64 r9;// UINT64 r10; UINT64 r11;// UINT64 r12; UINT64 r13;// UINT64 r14; UINT64 r15;// UINT64 cs; UINT64 ds;// UINT64 es; UINT64 fs;// UINT64 gs; UINT64 ss;// UINT64 dr0; UINT64 dr1;// UINT64 dr2; UINT64 dr3;// UINT64 dr6; UINT64 dr7;// BYTE fxstate[512]; UINT64 LBR_Count; UINT64 LBR[16]; } DebugStackState, *PDebugStackState; #pragma pack() //stack index typedef enum {bt_OnInstruction=0,bt_OnWrites=1, bt_OnIOAccess=2, bt_OnReadsAndWrites=3} BreakType; typedef enum {bl_1byte=0, bl_2byte=1, bl_8byte=2/*Only when in 64-bit*/, bl_4byte=3} BreakLength; void debugger_initialize(void); void debugger_shutdown(void); int debugger_initHookForCurrentCPU(void); int debugger_setGlobalDebugState(BOOL state); void debugger_setStoreLBR(BOOL state); int debugger_startDebugging(DWORD debuggedProcessID); int debugger_setGDBreakpoint(int breakpointnr, ULONG_PTR Address, BreakType bt, BreakLength bl); int debugger_unsetGDBreakpoint(int breakpointnr); void debugger_touchDebugRegister(UINT_PTR param); int debugger_stopDebugging(void); NTSTATUS debugger_waitForDebugEvent(ULONG timeout); NTSTATUS debugger_continueDebugEvent(BOOL handled); UINT_PTR *debugger_getLastStackPointer(void); NTSTATUS debugger_getDebuggerState(PDebugStackState state); NTSTATUS debugger_setDebuggerState(PDebugStackState state); void GetDebuggerInfo(void); VOID debugger_initHookForCurrentCPU_DPC(IN struct _KDPC *Dpc, IN PVOID DeferredContext, IN PVOID SystemArgument1, IN PVOID SystemArgument2); #endif <|start_filename|>src/debugger.c<|end_filename|> /* debugger.c: This unit will handle all debugging related code, from hooking, to handling interrupts todo: this whole thing can be moved to a few simple lines in dbvm... */ #pragma warning( disable: 4100 4103 4189) #include <ntifs.h> #include <windef.h> #include "DBKFunc.h" #include "interruptHook.h" #include "debugger.h" #include "vmxhelper.h" #ifdef AMD64 extern void interrupt1_asmentry( void ); //declared in debuggera.asm #else void interrupt1_asmentry( void ); #endif volatile struct { BOOL isDebugging; //TRUE if a process is currently being debugged BOOL stoppingTheDebugger; DWORD debuggedProcessID; //The processID that is currently debugger struct { BOOL active; UINT_PTR address; //Up to 4 addresses to break on BreakType breakType; //What type of breakpoint for each seperate address BreakLength breakLength; //How many bytes does this breakpoint look at } breakpoint[4]; //... BOOL globalDebug; //If set all threads of every process will raise an interrupt on taskswitch //while debugging: UINT_PTR *LastStackPointer; UINT_PTR *LastRealDebugRegisters; HANDLE LastThreadID; BOOL CausedByDBVM; BOOL handledlastevent; //BOOL storeLBR; //int storeLBR_max; //UINT_PTR *LastLBRStack; volatile struct { UINT_PTR DR0; UINT_PTR DR1; UINT_PTR DR2; UINT_PTR DR3; UINT_PTR DR6; UINT_PTR DR7; UINT_PTR reserved; volatile int inEpilogue; //if set the global debug bit does no faking } FakedDebugRegisterState[256]; char b[1]; //volatile BYTE DECLSPEC_ALIGN(16) fxstate[512]; BOOL isSteppingTillClear; //when set the user has entered single stepping mode. This is a one thread only thing, so when it's active and another single step happens, discard it } DebuggerState; KEVENT debugger_event_WaitForContinue; //event for kernelmode. Waits till it's set by usermode (usermode function: DBK_Continue_Debug_Event sets it) KEVENT debugger_event_CanBreak; //event for kernelmode. Waits till a break has been handled so a new one can enter KEVENT debugger_event_WaitForDebugEvent; //event for usermode. Waits till it's set by a debugged event DebugReg7 debugger_dr7_getValue(void); void debugger_dr7_setValue(DebugReg7 value); DebugReg6 debugger_dr6_getValue(void); JUMPBACK Int1JumpBackLocation; typedef struct _SavedStack { BOOL inuse; QWORD stacksnapshot[600]; } SavedStack, *PSavedStack; criticalSection StacksCS; int StackCount; PSavedStack *Stacks; void debugger_dr7_setGD(int state) { DebugReg7 _dr7=debugger_dr7_getValue(); _dr7.GD=state; //usually 1 debugger_dr7_setValue(_dr7); } void debugger_dr0_setValue(UINT_PTR value) { __writedr(0,value); } UINT_PTR debugger_dr0_getValue(void) { return __readdr(0); } void debugger_dr1_setValue(UINT_PTR value) { __writedr(1,value); } UINT_PTR debugger_dr1_getValue(void) { return __readdr(1); } void debugger_dr2_setValue(UINT_PTR value) { __writedr(2,value); } UINT_PTR debugger_dr2_getValue(void) { return __readdr(2); } void debugger_dr3_setValue(UINT_PTR value) { __writedr(3,value); } UINT_PTR debugger_dr3_getValue(void) { return __readdr(3); } void debugger_dr6_setValue(UINT_PTR value) { __writedr(6,value); } void debugger_dr7_setValue(DebugReg7 value) { UINT_PTR temp=*(UINT_PTR *)&value; __writedr(7,temp); } void debugger_dr7_setValueDword(UINT_PTR value) { __writedr(7,value); } UINT_PTR debugger_dr7_getValueDword(void) //I wonder why I couldn't just typecast the DebugReg7 to a dword... { return __readdr(7); } DebugReg7 debugger_dr7_getValue(void) { UINT_PTR temp=debugger_dr7_getValueDword(); return *(DebugReg7 *)&temp; } UINT_PTR debugger_dr6_getValueDword(void) { return __readdr(6); } DebugReg6 debugger_dr6_getValue(void) { UINT_PTR temp=debugger_dr6_getValueDword(); return *(DebugReg6 *)&temp; } void debugger_touchDebugRegister(UINT_PTR param) { //DbgPrint("Touching debug register. inepilogue=\n", DebuggerState.FakedDebugRegisterState[cpunr()].inEpilogue); debugger_dr0_setValue(debugger_dr0_getValue()); } void debugger_initialize(void) { //DbgPrint("Initializing debugger events\n"); KeInitializeEvent(&debugger_event_WaitForContinue, SynchronizationEvent, FALSE); KeInitializeEvent(&debugger_event_CanBreak, SynchronizationEvent, TRUE); //true so the first can enter KeInitializeEvent(&debugger_event_WaitForDebugEvent, SynchronizationEvent, FALSE); //DbgPrint("DebuggerState.fxstate=%p\n",DebuggerState.fxstate); StackCount = getCpuCount() * 4; Stacks = (PSavedStack*)ExAllocatePool(NonPagedPool, StackCount*sizeof(PSavedStack)); int i; for (i = 0; i < StackCount; i++) { Stacks[i] = (PSavedStack)ExAllocatePool(NonPagedPool, sizeof(SavedStack)); RtlZeroMemory(Stacks[i], sizeof(SavedStack)); } } void debugger_shutdown(void) { if (Stacks) { int i; for (i = 0; i < StackCount; i++) { if (Stacks[i]) { ExFreePool(Stacks[i]); Stacks[i] = NULL; } } ExFreePool(Stacks); Stacks = NULL; } } void debugger_growstack() //called in passive mode { if (Stacks) { KIRQL oldIRQL=KeRaiseIrqlToDpcLevel(); csEnter(&StacksCS); enableInterrupts(); //csEnter disables it, but we need it int newStackCount = StackCount * 2; int i; PSavedStack *newStacks; newStacks = (PSavedStack*)ExAllocatePool(NonPagedPool, newStackCount * sizeof(PSavedStack)); if (newStacks) { for (i = 0; i < StackCount; i++) newStacks[i] = Stacks[i]; for (i = StackCount; i < newStackCount; i++) { newStacks[i] = (PSavedStack)ExAllocatePool(NonPagedPool, sizeof(SavedStack)); if (newStacks[i]) RtlZeroMemory(newStacks[i], sizeof(SavedStack)); else { ExFreePool(newStacks); csLeave(&StacksCS); KeLowerIrql(oldIRQL); return; } } ExFreePool(Stacks); Stacks = newStacks; } csLeave(&StacksCS); KeLowerIrql(oldIRQL); } } void debugger_setInitialFakeState(void) { //DbgPrint("setInitialFakeState for cpu %d\n",cpunr()); DebuggerState.FakedDebugRegisterState[cpunr()].DR0=debugger_dr0_getValue(); DebuggerState.FakedDebugRegisterState[cpunr()].DR1=debugger_dr1_getValue(); DebuggerState.FakedDebugRegisterState[cpunr()].DR2=debugger_dr2_getValue(); DebuggerState.FakedDebugRegisterState[cpunr()].DR3=debugger_dr3_getValue(); DebuggerState.FakedDebugRegisterState[cpunr()].DR6=debugger_dr6_getValueDword(); DebuggerState.FakedDebugRegisterState[cpunr()].DR7=debugger_dr7_getValueDword(); } VOID debugger_initHookForCurrentCPU_DPC(IN struct _KDPC *Dpc, IN PVOID DeferredContext, IN PVOID SystemArgument1, IN PVOID SystemArgument2) { debugger_initHookForCurrentCPU(); } int debugger_removeHookForCurrentCPU(UINT_PTR params) { //DbgPrint("Unhooking int1 for this cpu\n"); return inthook_UnhookInterrupt(1); } int debugger_initHookForCurrentCPU(void) /* Must be called for each cpu */ { int result=TRUE; //DbgPrint("Hooking int1 for cpu %d\n", cpunr()); result=inthook_HookInterrupt(1,getCS() & 0xfff8, (ULONG_PTR)interrupt1_asmentry, &Int1JumpBackLocation); #ifdef AMD64 if (result) { ;//DbgPrint("hooked int1. Int1JumpBackLocation=%x:%llx\n", Int1JumpBackLocation.cs, Int1JumpBackLocation.eip); } else { //DbgPrint("Failed hooking interrupt 1\n"); return result; } #endif if (DebuggerState.globalDebug) { //set the fake state //debugger_setInitialFakeState(); //DbgPrint("Setting GD bit for cpu %d\n",cpunr()); debugger_dr7_setGD(1); //enable the GD flag } /*if (DebuggerState.storeLBR) { //DbgPrint("Enabling LBR logging. IA32_DEBUGCTL was %x\n", __readmsr(0x1d9)); __writemsr(0x1d9, __readmsr(0x1d9) | 1); //DbgPrint("Enabling LBR logging. IA32_DEBUGCTL is %x\n", __readmsr(0x1d9)); }*/ return result; } void debugger_setStoreLBR(BOOL state) { return; //disabled for now /* //if (state) // DbgPrint("Setting storeLBR to true\n"); //else // DbgPrint("Setting storeLBR to false\n"); DebuggerState.storeLBR=state; //it's not THAT crucial to disable/enable it DebuggerState.storeLBR_max=0; switch (cpu_model) { case 0x2a: case 0x1a: case 0x1e: case 0x1f: case 0x2e: case 0x25: case 0x2c: DebuggerState.storeLBR_max=16; break; case 0x17: case 0x1d: case 0x0f: DebuggerState.storeLBR_max=4; break; case 0x1c: DebuggerState.storeLBR_max=8; break; } //DbgPrint("Because your cpu_model=%d I think that your storeLBR_max=%d\n", cpu_model, DebuggerState.storeLBR_max); */ } int debugger_setGlobalDebugState(BOOL state) //call this BEFORE debugging, if already debugging, the user must call this for each cpu { //DbgPrint("debugger_setGlobalDebugState(%d)\n",state); if (state) DebuggerState.globalDebug=state; //on enable set this first if (inthook_isHooked(1)) { int oldEpilogueState=DebuggerState.FakedDebugRegisterState[cpunr()].inEpilogue; //DbgPrint("Int 1 is hooked,%ssetting GD\n",(state ? "":"un")); //DbgPrint("oldEpilogueState=%d\n",oldEpilogueState); //debugger_setInitialFakeState(); DebuggerState.FakedDebugRegisterState[cpunr()].inEpilogue=TRUE; DebuggerState.globalDebug=state; debugger_dr7_setGD(state); DebuggerState.FakedDebugRegisterState[cpunr()].inEpilogue=oldEpilogueState; DebuggerState.FakedDebugRegisterState[cpunr()].DR7=0x400; debugger_dr7_setValueDword(0x400); } return TRUE; } int debugger_startDebugging(DWORD debuggedProcessID) /* Call this AFTER the interrupts are hooked */ { //DbgPrint("debugger_startDebugging. Processid=%x\n",debuggedProcessID); Int1JumpBackLocation.eip=inthook_getOriginalEIP(1); Int1JumpBackLocation.cs=inthook_getOriginalCS(1); #ifdef AMD64 //DbgPrint("Int1 jump back = %x:%llx\n", Int1JumpBackLocation.cs, Int1JumpBackLocation.eip); #endif DebuggerState.isDebugging=TRUE; DebuggerState.debuggedProcessID=debuggedProcessID; return TRUE; } int debugger_stopDebugging(void) { int i; //DbgPrint("Stopping the debugger if it is running\n"); DebuggerState.stoppingTheDebugger=TRUE; if (DebuggerState.globalDebug) { //touch the global debug for each debug processor //DbgPrint("Touching the debug registers\n"); forEachCpuPassive(debugger_touchDebugRegister, 0); } DebuggerState.globalDebug=FALSE; //stop when possible, saves speed DebuggerState.isDebugging=FALSE; for (i=0; i<4; i++) DebuggerState.breakpoint[i].active=FALSE; //unhook all processors forEachCpuPassive(debugger_removeHookForCurrentCPU, 0); return TRUE; } int debugger_unsetGDBreakpoint(int breakpointnr) { int result=DebuggerState.breakpoint[breakpointnr].active; DebuggerState.breakpoint[breakpointnr].active=FALSE; return result; //returns true if it was active } int debugger_setGDBreakpoint(int breakpointnr, ULONG_PTR Address, BreakType bt, BreakLength bl) /* Will register a specific breakpoint. If global debug is used it'll set this debug register accordingly */ { //DbgPrint("debugger_setGDBreakpoint(%d, %x, %d, %d)\n", breakpointnr, Address, bt, bl); DebuggerState.breakpoint[breakpointnr].active=TRUE; DebuggerState.breakpoint[breakpointnr].address=Address; DebuggerState.breakpoint[breakpointnr].breakType=bt; DebuggerState.breakpoint[breakpointnr].breakLength=bl; return TRUE; } NTSTATUS debugger_waitForDebugEvent(ULONG timeout) { NTSTATUS r; LARGE_INTEGER wait; //DbgPrint("debugger_waitForDebugEvent with timeout of %d\n",timeout); //-10000000LL=1 second //-10000LL should be 1 millisecond //-10000LL wait.QuadPart=-10000LL * timeout; if (timeout==0xffffffff) //infinite wait r=KeWaitForSingleObject(&debugger_event_WaitForDebugEvent, UserRequest, KernelMode, TRUE, NULL); else r=KeWaitForSingleObject(&debugger_event_WaitForDebugEvent, UserRequest, KernelMode, TRUE, &wait); if (r==STATUS_SUCCESS) return r; else return STATUS_UNSUCCESSFUL; } NTSTATUS debugger_continueDebugEvent(BOOL handled) /* Only call this by one thread only, and only when there's actually a debug eevnt in progress */ { //DbgPrint("debugger_continueDebugEvent\n"); DebuggerState.handledlastevent=handled; KeSetEvent(&debugger_event_WaitForContinue, 0,FALSE); return STATUS_SUCCESS; } UINT_PTR *debugger_getLastStackPointer(void) { return DebuggerState.LastStackPointer; } NTSTATUS debugger_getDebuggerState(PDebugStackState state) { //DbgPrint("debugger_getDebuggerState\n"); state->threadid=(UINT64)DebuggerState.LastThreadID; state->causedbydbvm = (UINT64)DebuggerState.CausedByDBVM; if (DebuggerState.LastStackPointer) { state->rflags=(UINT_PTR)DebuggerState.LastStackPointer[si_eflags]; state->rax=DebuggerState.LastStackPointer[si_eax]; state->rbx=DebuggerState.LastStackPointer[si_ebx]; state->rcx=DebuggerState.LastStackPointer[si_ecx]; state->rdx=DebuggerState.LastStackPointer[si_edx]; state->rsi=DebuggerState.LastStackPointer[si_esi]; state->rdi=DebuggerState.LastStackPointer[si_edi]; state->rbp=DebuggerState.LastStackPointer[si_ebp]; #ifdef AMD64 //fill in the extra registers state->r8=DebuggerState.LastStackPointer[si_r8]; state->r9=DebuggerState.LastStackPointer[si_r9]; state->r10=DebuggerState.LastStackPointer[si_r10]; state->r11=DebuggerState.LastStackPointer[si_r11]; state->r12=DebuggerState.LastStackPointer[si_r12]; state->r13=DebuggerState.LastStackPointer[si_r13]; state->r14=DebuggerState.LastStackPointer[si_r14]; state->r15=DebuggerState.LastStackPointer[si_r15]; memcpy(state->fxstate, (void *)&DebuggerState.LastStackPointer[si_xmm], 512); #endif //generally speaking, NOTHING should touch the esp register, but i'll provide it anyhow if ((DebuggerState.LastStackPointer[si_cs] & 3) == 3) //if usermode code segment { //priv level change, so the stack info was pushed as well state->rsp=DebuggerState.LastStackPointer[si_esp]; state->ss=DebuggerState.LastStackPointer[si_ss]; } else { //kernelmode stack, yeah, it's really useless here since changing it here only means certain doom, but hey... state->rsp=(UINT_PTR)(DebuggerState.LastStackPointer)-4; state->ss=getSS();; //unchangeble by the user } state->rip=DebuggerState.LastStackPointer[si_eip]; state->cs=DebuggerState.LastStackPointer[si_cs]; state->ds=DebuggerState.LastStackPointer[si_ds]; state->es=DebuggerState.LastStackPointer[si_es]; #ifdef AMD64 state->fs=0; state->gs=0; #else state->fs=DebuggerState.LastStackPointer[si_fs]; state->gs=DebuggerState.LastStackPointer[si_gs]; #endif state->dr0=DebuggerState.LastRealDebugRegisters[0]; state->dr1=DebuggerState.LastRealDebugRegisters[1]; state->dr2=DebuggerState.LastRealDebugRegisters[2]; state->dr3=DebuggerState.LastRealDebugRegisters[3]; state->dr6=DebuggerState.LastRealDebugRegisters[4]; state->dr7=DebuggerState.LastRealDebugRegisters[5]; /*if (DebuggerState.storeLBR) { //DbgPrint("Copying the LBR stack to usermode\n"); //DbgPrint("storeLBR_max=%d\n", DebuggerState.storeLBR_max); for (state->LBR_Count=0; state->LBR_Count<DebuggerState.storeLBR_max; state->LBR_Count++ ) { //DbgPrint("DebuggerState.LastLBRStack[%d]=%x\n", state->LBR_Count, DebuggerState.LastLBRStack[state->LBR_Count]); state->LBR[state->LBR_Count]=DebuggerState.LastLBRStack[state->LBR_Count]; if (state->LBR[state->LBR_Count]==0) //no need to copy once a 0 has been reached break; } } else*/ state->LBR_Count=0; return STATUS_SUCCESS; } else { //DbgPrint("debugger_getDebuggerState was called while DebuggerState.LastStackPointer was still NULL"); return STATUS_UNSUCCESSFUL; } } NTSTATUS debugger_setDebuggerState(PDebugStackState state) { if (DebuggerState.LastStackPointer) { DebuggerState.LastStackPointer[si_eflags]=(UINT_PTR)state->rflags; //DbgPrint("have set eflags to %x\n",DebuggerState.LastStackPointer[si_eflags]); DebuggerState.LastStackPointer[si_eax]=(UINT_PTR)state->rax; DebuggerState.LastStackPointer[si_ebx]=(UINT_PTR)state->rbx; DebuggerState.LastStackPointer[si_ecx]=(UINT_PTR)state->rcx; DebuggerState.LastStackPointer[si_edx]=(UINT_PTR)state->rdx; DebuggerState.LastStackPointer[si_esi]=(UINT_PTR)state->rsi; DebuggerState.LastStackPointer[si_edi]=(UINT_PTR)state->rdi; DebuggerState.LastStackPointer[si_ebp]=(UINT_PTR)state->rbp; //generally speaking, NOTHING should touch the esp register, but i'll provide it anyhow if ((DebuggerState.LastStackPointer[si_cs] & 3) == 3) //if usermode code segment { //priv level change, so the stack info was pushed as well DebuggerState.LastStackPointer[si_esp]=(UINT_PTR)state->rsp; //don't mess with ss } else { //no change in kernelmode allowed } DebuggerState.LastStackPointer[si_eip]=(UINT_PTR)state->rip; DebuggerState.LastStackPointer[si_cs]=(UINT_PTR)state->cs; DebuggerState.LastStackPointer[si_ds]=(UINT_PTR)state->ds; DebuggerState.LastStackPointer[si_es]=(UINT_PTR)state->es; #ifndef AMD64 DebuggerState.LastStackPointer[si_fs]=(UINT_PTR)state->fs; DebuggerState.LastStackPointer[si_gs]=(UINT_PTR)state->gs; #else //don't touch fs or gs in 64-bit DebuggerState.LastStackPointer[si_r8]=(UINT_PTR)state->r8; DebuggerState.LastStackPointer[si_r9]=(UINT_PTR)state->r9; DebuggerState.LastStackPointer[si_r10]=(UINT_PTR)state->r10; DebuggerState.LastStackPointer[si_r11]=(UINT_PTR)state->r11; DebuggerState.LastStackPointer[si_r12]=(UINT_PTR)state->r12; DebuggerState.LastStackPointer[si_r13]=(UINT_PTR)state->r13; DebuggerState.LastStackPointer[si_r14]=(UINT_PTR)state->r14; DebuggerState.LastStackPointer[si_r15]=(UINT_PTR)state->r15; memcpy((void *)&DebuggerState.LastStackPointer[si_xmm], state->fxstate, 512); #endif if (!DebuggerState.globalDebug) { //no idea why someone would want to use this method, but it's in (for NON globaldebug only) //updating this array too just so the user can see it got executed. (it eases their state of mind...) DebuggerState.LastRealDebugRegisters[0]=(UINT_PTR)state->dr0; DebuggerState.LastRealDebugRegisters[1]=(UINT_PTR)state->dr1; DebuggerState.LastRealDebugRegisters[2]=(UINT_PTR)state->dr2; DebuggerState.LastRealDebugRegisters[3]=(UINT_PTR)state->dr3; DebuggerState.LastRealDebugRegisters[4]=(UINT_PTR)state->dr6; DebuggerState.LastRealDebugRegisters[5]=(UINT_PTR)state->dr7; //no setting of the DebugRegs here } } else { //DbgPrint("debugger_setDebuggerState was called while DebuggerState.LastStackPointer was still NULL"); return STATUS_UNSUCCESSFUL; } return STATUS_SUCCESS; } int breakpointHandler_kernel(UINT_PTR *stackpointer, UINT_PTR *currentdebugregs, UINT_PTR *LBR_Stack, int causedbyDBVM) //Notice: This routine is called when interrupts are enabled and the GD bit has been set if globaL DEBUGGING HAS BEEN USED //Interrupts are enabled and should be at passive level, so taskswitching is possible { NTSTATUS r=STATUS_UNSUCCESSFUL; int handled=0; //0 means let the OS handle it LARGE_INTEGER timeout; timeout.QuadPart=-100000; //DbgPrint("breakpointHandler for kernel breakpoints\n"); #ifdef AMD64 //DbgPrint("cs=%x ss=%x ds=%x es=%x fs=%x gs=%x\n",getCS(), getSS(), getDS(), getES(), getFS(), getGS()); //DbgPrint("fsbase=%llx gsbase=%llx gskernel=%llx\n", readMSR(0xc0000100), readMSR(0xc0000101), readMSR(0xc0000102)); //DbgPrint("rbp=%llx\n", getRBP()); //DbgPrint("gs:188=%llx\n", __readgsqword(0x188)); //DbgPrint("causedbyDBVM=%d\n", causedbyDBVM); #endif if (KeGetCurrentIrql()==0) { //crititical section here if ((stackpointer[si_cs] & 3)==0) { //DbgPrint("Going to wait in a kernelmode routine\n"); } //block other threads from breaking until this one has been handled while (r != STATUS_SUCCESS) { r=KeWaitForSingleObject(&debugger_event_CanBreak,Executive, KernelMode, FALSE, NULL); //check r and handle specific events //DbgPrint("Woke up. r=%x\n",r); } if ((stackpointer[si_cs] & 3)==0) { //DbgPrint("Woke up in a kernelmode routine\n"); } //We're here, let's notify the usermode debugger of our situation //first store the stackpointer so it can be manipulated externally DebuggerState.LastStackPointer=stackpointer; DebuggerState.LastRealDebugRegisters=currentdebugregs; /*DebuggerState.LastLBRStack=LBR_Stack;*/ DebuggerState.LastThreadID=PsGetCurrentThreadId(); DebuggerState.CausedByDBVM = causedbyDBVM; //notify usermode app that this thread has halted due to a debug event KeSetEvent(&debugger_event_WaitForDebugEvent,0,FALSE); //wait for event from usermode that debgu event has been handled //KeWaitForSingleObject(); //continue with state while (1) { //LARGE_INTEGER wt; NTSTATUS s=STATUS_UNSUCCESSFUL; //wt.QuadPart=-10000000LL; //s=KeDelayExecutionThread(KernelMode, FALSE, &wt); //DbgPrint("Waiting...\n"); while (s != STATUS_SUCCESS) { s=KeWaitForSingleObject(&debugger_event_WaitForContinue, Executive, KernelMode, FALSE, NULL); //DbgPrint("KeWaitForSingleObject=%x\n",s); } if (s==STATUS_SUCCESS) { if (DebuggerState.handledlastevent) { //DbgPrint("handledlastevent=TRUE"); handled=1; } else handled=0; break; } } DebuggerState.LastStackPointer=NULL; //NULL the stackpointer so routines know it should not be called //i'm done, let other threads catch it KeSetEvent(&debugger_event_CanBreak, 0, FALSE); //DbgPrint("Returning after a wait. handled=%d and eflags=%x\n",handled, stackpointer[si_eflags]); if ((stackpointer[si_cs] & 3)==0) //check rpl of cs { //DbgPrint("and in kernelmode\n"); } return handled; } else { //DbgPrint("Breakpoint wasn't at passive level. Screw this, i'm not going to break here\n"); return 1; } } int interrupt1_handler(UINT_PTR *stackpointer, UINT_PTR *currentdebugregs) { HANDLE CurrentProcessID=PsGetCurrentProcessId(); UINT_PTR originaldr6=currentdebugregs[4]; DebugReg6 _dr6=*(DebugReg6 *)&currentdebugregs[4]; UINT_PTR LBR_Stack[16]; //max 16 // DebugReg7 _dr7=*(DebugReg7 *)&currentdebugregs[5]; int causedbyDBVM = vmxusable && vmx_causedCurrentDebugBreak(); /* if (cpu_familyID==0x6) { if (DebuggerState.storeLBR) { //fetch the lbr stack int MSR_LASTBRANCH_TOS=0x1c9; int MSR_LASTBRANCH_0=0x40; int i; int count; i=(int)__readmsr(MSR_LASTBRANCH_TOS); count=0; while (count<DebuggerState.storeLBR_max) { UINT64 x; x=__readmsr(MSR_LASTBRANCH_0+i); LBR_Stack[count]=(UINT_PTR)x; __writemsr(MSR_LASTBRANCH_0+i,0); //it has been read out, so can be erased now count++; i++; i=i % DebuggerState.storeLBR_max; } } } */ //DbgPrint("interrupt1_handler(%p). DR6=%x (%x) DR7=%x %x:%p\n", interrupt1_handler, originaldr6, debugger_dr6_getValueDword(), debugger_dr7_getValueDword(), stackpointer[si_cs], (void*)(stackpointer[si_eip])); //check if this break should be handled or not if (DebuggerState.globalDebug) { //DbgPrint("DebuggerState.globalDebug=TRUE\n"); //global debugging is being used if (_dr6.BD) { _dr6.BD = 0; debugger_dr6_setValue(*(UINT_PTR *)&_dr6); //The debug registers are being accessed, emulate it with DebuggerState.FakedDebugRegisterState[cpunr()].DRx if ((stackpointer[si_cs] & 3)==0) { int instructionPointer; #ifdef AMD64 int prefixpointer; #endif int currentcpunr = cpunr(); int debugregister; int generalpurposeregister; unsigned char *instruction = (unsigned char *)stackpointer[si_eip]; //unset this flag in DR6 _dr6.BD = 0; debugger_dr6_setValue(*(UINT_PTR *)&_dr6); if (DebuggerState.FakedDebugRegisterState[cpunr()].inEpilogue) { ((EFLAGS *)&stackpointer[si_eflags])->RF = 1; //repeat this instruction and don't break return 2; } //DbgPrint("handler: Setting fake dr6 to %x\n",*(UINT_PTR *)&_dr6); DebuggerState.FakedDebugRegisterState[cpunr()].DR6 = *(UINT_PTR *)&_dr6; for (instructionPointer = 0; instruction[instructionPointer] != 0x0f; instructionPointer++); //find the start of the instruction, skipping prefixes etc... //we now have the start of the instruction. //Find out which instruction it is, and which register is used debugregister = (instruction[instructionPointer + 2] >> 3) & 7; generalpurposeregister = instruction[instructionPointer + 2] & 7; #ifdef AMD64 for (prefixpointer = 0; prefixpointer < instructionPointer; prefixpointer++) { //check for a REX.B prefix (0x40 + 0x1 : 0x41) if ((instruction[prefixpointer] & 0x41) == 0x41) { //rex.b prefix is used, r8 to r15 are being accessed generalpurposeregister += 8; } } #endif //DbgPrint("debugregister=%d, generalpurposeregister=%d\n",debugregister,generalpurposeregister); if (instruction[instructionPointer + 1] == 0x21) { UINT_PTR drvalue = 0; //DbgPrint("read opperation\n"); //21=read switch (debugregister) { case 0: drvalue = DebuggerState.FakedDebugRegisterState[cpunr()].DR0; //DbgPrint("Reading DR0 (returning %x real %x)\n", drvalue, currentdebugregs[0]); break; case 1: drvalue = DebuggerState.FakedDebugRegisterState[cpunr()].DR1; break; case 2: drvalue = DebuggerState.FakedDebugRegisterState[cpunr()].DR2; break; case 3: drvalue = DebuggerState.FakedDebugRegisterState[cpunr()].DR3; break; case 4: case 6: drvalue = DebuggerState.FakedDebugRegisterState[cpunr()].DR6; //DbgPrint("reading dr6 value:%x\n",drvalue); break; case 5: case 7: drvalue = DebuggerState.FakedDebugRegisterState[cpunr()].DR7; break; default: //DbgPrint("Invalid debugregister\n"); drvalue = 0; break; } switch (generalpurposeregister) { case 0: stackpointer[si_eax] = drvalue; break; case 1: stackpointer[si_ecx] = drvalue; break; case 2: stackpointer[si_edx] = drvalue; break; case 3: stackpointer[si_ebx] = drvalue; break; case 4: if ((stackpointer[si_cs] & 3) == 3) //usermode dr access ? stackpointer[si_esp] = drvalue; else stackpointer[si_stack_esp] = drvalue; break; case 5: stackpointer[si_ebp] = drvalue; break; case 6: stackpointer[si_esi] = drvalue; break; case 7: stackpointer[si_edi] = drvalue; break; #ifdef AMD64 case 8: stackpointer[si_r8] = drvalue; break; case 9: stackpointer[si_r9] = drvalue; break; case 10: stackpointer[si_r10] = drvalue; break; case 11: stackpointer[si_r11] = drvalue; break; case 12: stackpointer[si_r12] = drvalue; break; case 13: stackpointer[si_r13] = drvalue; break; case 14: stackpointer[si_r14] = drvalue; break; case 15: stackpointer[si_r15] = drvalue; break; #endif } } else if (instruction[instructionPointer + 1] == 0x23) { //23=write UINT_PTR gpvalue = 0; //DbgPrint("Write operation\n"); switch (generalpurposeregister) { case 0: gpvalue = stackpointer[si_eax]; break; case 1: gpvalue = stackpointer[si_ecx]; break; case 2: gpvalue = stackpointer[si_edx]; break; case 3: gpvalue = stackpointer[si_ebx]; break; case 4: if ((stackpointer[si_cs] & 3) == 3) gpvalue = stackpointer[si_esp]; break; case 5: gpvalue = stackpointer[si_ebp]; break; case 6: gpvalue = stackpointer[si_esi]; break; case 7: gpvalue = stackpointer[si_edi]; break; #ifdef AMD64 case 8: gpvalue = stackpointer[si_r8]; break; case 9: gpvalue = stackpointer[si_r9]; break; case 10: gpvalue = stackpointer[si_r10]; break; case 11: gpvalue = stackpointer[si_r11]; break; case 12: gpvalue = stackpointer[si_r12]; break; case 13: gpvalue = stackpointer[si_r13]; break; case 14: gpvalue = stackpointer[si_r14]; break; case 15: gpvalue = stackpointer[si_r15]; break; default: //DbgPrint("Invalid register value\n"); break; #endif } //gpvalue now contains the value to set the debug register switch (debugregister) { case 0: //DbgPrint("Writing DR0. Original value=%x new value=%x\n", currentdebugregs[0], gpvalue); debugger_dr0_setValue(gpvalue); DebuggerState.FakedDebugRegisterState[cpunr()].DR0 = debugger_dr0_getValue(); break; case 1: debugger_dr1_setValue(gpvalue); DebuggerState.FakedDebugRegisterState[cpunr()].DR1 = debugger_dr1_getValue(); break; case 2: debugger_dr2_setValue(gpvalue); DebuggerState.FakedDebugRegisterState[cpunr()].DR2 = debugger_dr2_getValue(); break; case 3: debugger_dr3_setValue(gpvalue); DebuggerState.FakedDebugRegisterState[cpunr()].DR3 = debugger_dr3_getValue(); break; case 4: case 6: //DbgPrint("Setting dr6 to %x (was %x)\n", gpvalue, DebuggerState.FakedDebugRegisterState[cpunr()].DR6); _dr6 = *(DebugReg6 *)&gpvalue; //if (_dr6.BD) DbgPrint("Some code wants to set the BD flag to 1\n"); debugger_dr6_setValue(gpvalue); DebuggerState.FakedDebugRegisterState[cpunr()].DR6 = debugger_dr6_getValueDword(); if (_dr6.BD) { _dr6.BD = 0; debugger_dr6_setValue(gpvalue); } break; case 5: case 7: //make sure it doesn't set the GD flag here //DbgPrint("DR7 write\n"); //if (generalpurposeregister == 15) //{ // while (1); //patchguard //} //if (DebuggerState.FakedDebugRegisterState[cpunr()].inEpilogue) //{ // DbgPrint("Was in epilogue\n"); //} //check for invalid bits and raise a GPF if invalid gpvalue = (gpvalue | 0x400) & (~(1 << 13)); //unset the GD value //gpvalue=0xf0401; debugger_dr7_setValueDword(gpvalue); DebuggerState.FakedDebugRegisterState[cpunr()].DR7 = debugger_dr7_getValueDword(); break; } } else { //DbgPrint("Some unknown instruction accessed the debug registers?\n"); //if (CurrentProcessID==(HANDLE)(UINT_PTR)DebuggerState.debuggedProcessID) // DbgPrint("Happened inside the target process\n"); //DbgPrint("interrupt1_handler dr6=%x (original=%x) dr7=%d\n",_dr6, originaldr6, _dr7); //DbgPrint("eip=%x\n",stackpointer[si_eip]); } //adjust eip to after this instruction stackpointer[si_eip] += instructionPointer + 3; //0f xx /r return 1; //don't tell windows about it } else { //DbgPrint("DR6.BD == 1 in USERMODE! WTF\n"); _dr6.BD = 0; debugger_dr6_setValue(*(UINT_PTR *)&_dr6); DebuggerState.FakedDebugRegisterState[cpunr()].DR6 = debugger_dr6_getValueDword(); } } } if (DebuggerState.isSteppingTillClear) //this doesn't really work because when the state comes back to interruptable the system has a critical section lock on the GUI, so yeah... I really need a DBVM display driver for this { if ((((PEFLAGS)&stackpointer[si_eflags])->IF == 0) || (KeGetCurrentIrql() != PASSIVE_LEVEL)) { ((PEFLAGS)&stackpointer[si_eflags])->TF = 1; ((PEFLAGS)&stackpointer[si_eflags])->RF = 1; debugger_dr6_setValue(0xffff0ff0); return 1; } DebuggerState.isSteppingTillClear = FALSE; } if (DebuggerState.isDebugging) { //DbgPrint("DebuggerState.isDebugging\n"); //check if this should break if (CurrentProcessID == (HANDLE)(UINT_PTR)DebuggerState.debuggedProcessID) { UINT_PTR originaldebugregs[6]; UINT64 oldDR7 = getDR7(); if ((((PEFLAGS)&stackpointer[si_eflags])->IF == 0) || (KeGetCurrentIrql() != PASSIVE_LEVEL)) { //There's no way to display the state to the usermode part of CE //DbgPrint("int1 at unstoppable location"); if (!KernelCodeStepping) { ((PEFLAGS)&stackpointer[si_eflags])->TF = 0; //just give up stepping // DbgPrint("Quitting this"); } else { // DbgPrint("Stepping until valid\n"); ((PEFLAGS)&stackpointer[si_eflags])->TF = 1; //keep going until a valid state DebuggerState.isSteppingTillClear = TRUE; //Just in case a taskswitch happens right after enabling passive level with interrupts } ((PEFLAGS)&stackpointer[si_eflags])->RF = 1; debugger_dr6_setValue(0xffff0ff0); return 1; } DebuggerState.isSteppingTillClear = FALSE; //DbgPrint("CurrentProcessID==(HANDLE)(UINT_PTR)DebuggerState.debuggedProcessID\n"); if (DebuggerState.globalDebug) { originaldebugregs[0] = DebuggerState.FakedDebugRegisterState[cpunr()].DR0; originaldebugregs[1] = DebuggerState.FakedDebugRegisterState[cpunr()].DR1; originaldebugregs[2] = DebuggerState.FakedDebugRegisterState[cpunr()].DR2; originaldebugregs[3] = DebuggerState.FakedDebugRegisterState[cpunr()].DR3; originaldebugregs[4] = DebuggerState.FakedDebugRegisterState[cpunr()].DR6; originaldebugregs[5] = DebuggerState.FakedDebugRegisterState[cpunr()].DR7; } //DbgPrint("BP in target process\n"); //no extra checks if it's caused by the debugger or not. That is now done in the usermode part //if (*(PEFLAGS)(&stackpointer[si_eflags]).IF) /* if (((PEFLAGS)&stackpointer[si_eflags])->IF==0) { //DbgPrint("Breakpoint while interrupts are disabled: %x\n",stackpointer[si_eip]); //An breakpoint happened while IF was 0. Step through the code untill IF is 1 ((PEFLAGS)&stackpointer[si_eflags])->RF=1; ((PEFLAGS)&stackpointer[si_eflags])->TF=1; //keep going until IF=1 DbgPrint("IF==0\n"); return 1; //don't handle it but also don't tell windows }*/ //set the real debug registers to what it is according to the guest (so taskswitches take over these values) .... shouldn't be needed as global debug is on which fakes that read... if (DebuggerState.globalDebug) { //enable the GD flag for taskswitches that will occur as soon as interrupts are enabled //this also means: DO NOT EDIT THE DEBUG REGISTERS IN GLOBAL DEBUG MODE at this point. Only in the epilogue if (!DebuggerState.stoppingTheDebugger) //This is set when the driver is unloading. So do NOT set it back then debugger_dr7_setGD(DebuggerState.globalDebug); } else { //unset ALL debug registers before enabling taskswitching. Just re-enable it when back when interrupts are disabled again debugger_dr7_setValueDword(0x400); debugger_dr0_setValue(0); debugger_dr1_setValue(0); debugger_dr2_setValue(0); debugger_dr3_setValue(0); debugger_dr6_setValue(0xffff0ff0); } //start the windows taskswitching mode //if (1) return 1; //save the state of the thread to a place that won't get overwritten //todo: breaks 32-bit //int i; BOOL NeedsToGrowStackList = FALSE; PSavedStack SelectedStackEntry = NULL; /* csEnter(&StacksCS); for (i = 0; i < StackCount; i++) { if (Stacks[i]->inuse == FALSE) { SelectedStackEntry = Stacks[i]; SelectedStackEntry->inuse = TRUE; RtlCopyMemory(SelectedStackEntry->stacksnapshot, stackpointer, 600 * 8); if (i > StackCount / 2) NeedsToGrowStackList = TRUE; break; } } csLeave(&StacksCS); enableInterrupts(); //grow stack if needed if (NeedsToGrowStackList) debugger_growstack(); */ { int rs=1; //DbgPrint("calling breakpointHandler_kernel\n"); if (SelectedStackEntry == NULL) //fuck rs = breakpointHandler_kernel(stackpointer, currentdebugregs, LBR_Stack, causedbyDBVM); else rs = breakpointHandler_kernel((UINT_PTR *)(SelectedStackEntry->stacksnapshot), currentdebugregs, LBR_Stack, causedbyDBVM); //DbgPrint("After handler\n"); /* if (SelectedStackEntry) //restore the stack { RtlCopyMemory(stackpointer, SelectedStackEntry->stacksnapshot, 600 * 8); SelectedStackEntry->inuse = FALSE; } */ //DbgPrint("rs=%d\n",rs); disableInterrupts(); //restore the //we might be on a different CPU now if (DebuggerState.globalDebug) { DebuggerState.FakedDebugRegisterState[cpunr()].DR0=originaldebugregs[0]; DebuggerState.FakedDebugRegisterState[cpunr()].DR1=originaldebugregs[1]; DebuggerState.FakedDebugRegisterState[cpunr()].DR2=originaldebugregs[2]; DebuggerState.FakedDebugRegisterState[cpunr()].DR3=originaldebugregs[3]; DebuggerState.FakedDebugRegisterState[cpunr()].DR6=originaldebugregs[4]; DebuggerState.FakedDebugRegisterState[cpunr()].DR7=originaldebugregs[5]; } else { /*if (getDR7() != oldDR7) { DbgPrint("Something changed DR7. old=%llx new=%llx\n",oldDR7, getDR7()); }*/ //set the debugregisters to what they where set to before taskswitching was enable //with global debug this is done elsewhere debugger_dr0_setValue(currentdebugregs[0]); debugger_dr1_setValue(currentdebugregs[1]); debugger_dr2_setValue(currentdebugregs[2]); debugger_dr3_setValue(currentdebugregs[3]); debugger_dr6_setValue(currentdebugregs[4]); if ((currentdebugregs[5] >> 13) & 1) { // DbgPrint("WTF? GD is 1 in currentdebugregs[5]: %llx\n", currentdebugregs[5]); } else debugger_dr7_setValue(*(DebugReg7 *)&currentdebugregs[5]); } return rs; } } else { //DbgPrint("Not the debugged process (%x != %x)\n",CurrentProcessID,DebuggerState.debuggedProcessID ); //check if this break is due to a breakpoint ce has set. (during global debug threadsurfing)) //do that by checking if the breakpoint condition exists in the FAKE dr7 registers //if so, let windows handle it, if not, it is caused by ce, which then means, skip (so execute normally) if (DebuggerState.globalDebug) { DebugReg6 dr6=debugger_dr6_getValue(); DebugReg7 dr7=*(DebugReg7 *)&DebuggerState.FakedDebugRegisterState[cpunr()].DR7; //real dr6 //fake dr7 if ((dr6.B0) && (!(dr7.L0 || dr7.G0))) { /*DbgPrint("setting RF because of B0\n");*/ ((PEFLAGS)&stackpointer[si_eflags])->RF=1; return 1; } //break caused by DR0 and not expected by the current process, ignore this bp and continue if ((dr6.B1) && (!(dr7.L1 || dr7.G1))) { /*DbgPrint("setting RF because of B1\n");*/ ((PEFLAGS)&stackpointer[si_eflags])->RF=1; return 1; } // ... DR1 ... if ((dr6.B2) && (!(dr7.L2 || dr7.G2))) { /*DbgPrint("setting RF because of B2\n");*/ ((PEFLAGS)&stackpointer[si_eflags])->RF=1; return 1; } // ... DR2 ... if ((dr6.B3) && (!(dr7.L3 || dr7.G3))) { /*DbgPrint("setting RF because of B3\n");*/ ((PEFLAGS)&stackpointer[si_eflags])->RF=1; return 1; } // ... DR3 ... } if (causedbyDBVM) return 1; //correct PA, bad PID, ignore BP if (DebuggerState.isSteppingTillClear) //shouldn't happen often { //DbgPrint("That thing that shouldn\'t happen often happened\n"); ((PEFLAGS)&stackpointer[si_eflags])->TF = 0; DebuggerState.isSteppingTillClear = 0; return 1; //ignore } //DbgPrint("Returning unhandled. DR6=%x", debugger_dr6_getValueDword()); return 0; //still here, so let windows handle it } } else return 0; //Let windows handle it //get the current processid //is it being debugged //if yes, check if the breakpoint is something done by me //if no, exit } int interrupt1_centry(UINT_PTR *stackpointer) //code segment 8 has a 32-bit stackpointer { UINT_PTR before;//,after; UINT_PTR currentdebugregs[6]; //used for determining if the current bp is caused by the debugger or not int handled=0; //if 0 at return, the interupt will be passed down to the operating system QWORD naddress; //DbgPrint("interrupt1_centry cpunr=%d esp=%x\n",cpunr(), getRSP()); //bsod crashfix, but also disables kernelmode stepping IDT idt; GetIDT(&idt); naddress = idt.vector[1].wLowOffset + (idt.vector[1].wHighOffset << 16); #ifdef AMD64 naddress += ((UINT64)idt.vector[1].TopOffset << 32); #endif stackpointer[si_errorcode] = (UINT_PTR)naddress; //the errorcode is used as address to call the original function if needed /* if (Int1JumpBackLocation.eip != naddress) //no, just fucking no (patchguard will replace all inthandlers with invalid ones and then touch dr7) { //todo: the usual, but make sure not to use dbgprint or anything that could trigger a software int if (DebuggerState.globalDebug) { debugger_dr7_setGD(DebuggerState.globalDebug); stackpointer[si_eip] += 4; return 1; } } */ before=getRSP(); //Fetch current debug registers currentdebugregs[0]=debugger_dr0_getValue(); currentdebugregs[1]=debugger_dr1_getValue(); currentdebugregs[2]=debugger_dr2_getValue(); currentdebugregs[3]=debugger_dr3_getValue(); currentdebugregs[4]=debugger_dr6_getValueDword(); currentdebugregs[5]=debugger_dr7_getValueDword(); handled=interrupt1_handler(stackpointer, currentdebugregs); //epilogue: //At the end when returning: // //-------------------------------------------------------------------------- //--------------EPILOGUE (AFTER HAVING HANDLED THE BREAKPOINT)-------------- //-------------------------------------------------------------------------- // disableInterrupts(); //just making sure.. DebuggerState.FakedDebugRegisterState[cpunr()].inEpilogue=1; debugger_dr7_setGD(0); //make sure the GD bit is disabled (int1 within int1, oooh the fun..., and yes, THIS itself will cause one too) DebuggerState.FakedDebugRegisterState[cpunr()].inEpilogue=1; //just be sure... //if (inthook_isDBVMHook(1)) //{ //update the int1 return address, could have been changed //DbgPrint("This was a dbvm hook. Changing if the interrupt return address is still valid\n"); // Int1JumpBackLocation.cs=idt.vector[1].wSelector; // naddress=idt.vector[1].wLowOffset+(idt.vector[1].wHighOffset << 16); #ifdef AMD64 // naddress+=((UINT64)idt.vector[1].TopOffset << 32); #endif //} if (DebuggerState.globalDebug) //DR's are only accesses when there are DR's(no idea how it handles breakpoints in a different process...), so set them in each thread even those that don't belong original: && (PsGetCurrentProcessId()==(HANDLE)DebuggerState.debuggedProcessID)) { //set the breakpoint in this thread. DebugReg6 dr6=debugger_dr6_getValue(); //DebugReg7 dr7=debugger_dr7_getValue(); DebugReg6 _dr6=*(DebugReg6 *)&DebuggerState.FakedDebugRegisterState[cpunr()].DR6; DebugReg7 _dr7=*(DebugReg7 *)&DebuggerState.FakedDebugRegisterState[cpunr()].DR7; int debugregister=0, breakpoint=0; //first clear the DR6 bits caused by the debugger if (!handled) { //it's going to get sent to windows if (dr6.BD && _dr7.GD) _dr6.BD=1; //should already have been done, but what the heck... if (dr6.B0 && (_dr7.L0 || _dr7.G0)) _dr6.B0=1; if (dr6.B1 && (_dr7.L1 || _dr7.G1)) _dr6.B1=1; if (dr6.B2 && (_dr7.L2 || _dr7.G2)) _dr6.B2=1; if (dr6.B3 && (_dr7.L3 || _dr7.G3)) _dr6.B3=1; _dr6.BS=dr6.BS; _dr6.BT=dr6.BT; //DbgPrint("epilogue: Setting fake dr6 to %x (fake=%x)\n",*(DWORD *)&dr6, *(DWORD *)&_dr6); } debugger_dr6_setValue(0xffff0ff0); //set the debug registers of active breakpoints. Doesn't have to be in the specified order. Just find an unused debug registers //check DebuggerState.FakedDebugRegisterState[cpunumber].DR7 for unused breakpoints //set state to what the guest thinks it is debugger_dr0_setValue(DebuggerState.FakedDebugRegisterState[cpunr()].DR0); debugger_dr1_setValue(DebuggerState.FakedDebugRegisterState[cpunr()].DR1); debugger_dr2_setValue(DebuggerState.FakedDebugRegisterState[cpunr()].DR2); debugger_dr3_setValue(DebuggerState.FakedDebugRegisterState[cpunr()].DR3); debugger_dr6_setValue(DebuggerState.FakedDebugRegisterState[cpunr()].DR6); for (breakpoint=0; breakpoint<4; breakpoint++) { if (DebuggerState.breakpoint[breakpoint].active) { int foundone=0; // DbgPrint("Want to set breakpoint %d\n",breakpoint); //find a usable debugregister while ((debugregister<4) && (foundone==0)) { if (DebuggerState.FakedDebugRegisterState[cpunr()].inEpilogue==0) { DebuggerState.FakedDebugRegisterState[cpunr()].inEpilogue=1; } //check if this debugregister is usable if (((DebuggerState.FakedDebugRegisterState[cpunr()].DR7 >> (debugregister*2)) & 3)==0) //DR7.Gx and DR7.Lx are 0 { // DbgPrint("debugregister %d is free to be used\n",debugregister); foundone=1; //set address switch (debugregister) { case 0: debugger_dr0_setValue(DebuggerState.breakpoint[breakpoint].address); _dr7.L0=1; _dr7.LEN0=DebuggerState.breakpoint[breakpoint].breakLength; _dr7.RW0=DebuggerState.breakpoint[breakpoint].breakType; break; case 1: debugger_dr1_setValue(DebuggerState.breakpoint[breakpoint].address); _dr7.L1=1; _dr7.LEN1=DebuggerState.breakpoint[breakpoint].breakLength; _dr7.RW1=DebuggerState.breakpoint[breakpoint].breakType; break; case 2: debugger_dr2_setValue(DebuggerState.breakpoint[breakpoint].address); _dr7.L2=1; _dr7.LEN2=DebuggerState.breakpoint[breakpoint].breakLength; _dr7.RW2=DebuggerState.breakpoint[breakpoint].breakType; break; case 3: debugger_dr3_setValue(DebuggerState.breakpoint[breakpoint].address); _dr7.L3=1; _dr7.LEN3=DebuggerState.breakpoint[breakpoint].breakLength; _dr7.RW3=DebuggerState.breakpoint[breakpoint].breakType; break; } } debugregister++; } } } debugger_dr7_setValue(_dr7); //DbgPrint("after:\n"); //DbgPrint("after fake DR0=%x real DR0=%x\n",DebuggerState.FakedDebugRegisterState[currentcpunr].DR0, debugger_dr0_getValue()); //DbgPrint("after fake DR1=%x real DR1=%x\n",DebuggerState.FakedDebugRegisterState[currentcpunr].DR1, debugger_dr1_getValue()); //DbgPrint("after fake DR2=%x real DR2=%x\n",DebuggerState.FakedDebugRegisterState[currentcpunr].DR2, debugger_dr2_getValue()); //DbgPrint("after fake DR3=%x real DR3=%x\n",DebuggerState.FakedDebugRegisterState[currentcpunr].DR3, debugger_dr3_getValue()); //DbgPrint("after fake DR6=%x real DR6=%x\n",DebuggerState.FakedDebugRegisterState[currentcpunr].DR6, debugger_dr6_getValueDword()); //DbgPrint("after fake DR7=%x real DR7=%x\n",DebuggerState.FakedDebugRegisterState[currentcpunr].DR7, debugger_dr7_getValueDword()); } else { //not global debug, just clear all flags and be done with it if (handled) debugger_dr6_setValue(0xffff0ff0); } disableInterrupts(); if (handled == 2) { //DbgPrint("handled==2\n"); handled = 1; //epilogue = 1 Dr handler } else { //not handled by the epilogue set DR0, so the actual epilogue //DbgPrint("handled==1\n"); if (DebuggerState.globalDebug) { DebuggerState.FakedDebugRegisterState[cpunr()].inEpilogue=0; if (!DebuggerState.stoppingTheDebugger) debugger_dr7_setGD(DebuggerState.globalDebug); //set it back to 1, if not unloading } } //after=getRSP(); //DbgPrint("before=%llx after=%llx\n",before,after); //DbgPrint("end of interrupt1_centry. eflags=%x", stackpointer[si_eflags]); //if branch tracing set lbr back on (get's disabled on debug interrupts) /* if (DebuggerState.storeLBR) __writemsr(0x1d9, __readmsr(0x1d9) | 1); */ return handled; } #ifndef AMD64 _declspec( naked ) void interrupt1_asmentry( void ) //This routine is called upon an interrupt 1, even before windows gets it { __asm{ //change the start of the stack so that instructions like setthreadcontext do not affect the stack it when it's frozen and waiting for input //meaning the setting of debug registers will have to be done with the changestate call //sub esp,4096 //push [esp+4096+0+16] //optional ss //push [esp+4096+4+12] //optional esp //push [esp+4096+8+8] //eflags //push [esp+4096+12+4] //cs //push [esp+4096+16+0] //eip cld //reset the direction flag //save stack position push 0 //push an errorcode on the stack so the stackindex can stay the same push ebp mov ebp,esp //save state pushad xor eax,eax mov ax,ds push eax mov ax,es push eax mov ax,fs push eax mov ax,gs push eax //save fpu state //save sse state mov ax,0x23 //0x10 should work too, but even windows itself is using 0x23 mov ds,ax mov es,ax mov gs,ax mov ax,0x30 mov fs,ax push ebp call interrupt1_centry cmp eax,1 //set flag //restore state pop gs pop fs pop es pop ds popad pop ebp je skip_original_int1 add esp,4 //undo errorcode push (add effects eflags, so set it at both locations) jmp far [Int1JumpBackLocation] skip_original_int1: add esp,4 //undo errorcode push iretd } } #endif <|start_filename|>src/ultimap.h<|end_filename|> #ifndef ULTIMAP_H #define ULTIMAP_H #include <ntifs.h> #include <windef.h> typedef UINT64 QWORD; #pragma pack(push) #pragma pack(1) /* typedef struct { DWORD BTS_BufferBaseAddress; DWORD BTS_IndexBaseAddress; DWORD BTS_AbsoluteMaxAddress; DWORD BTS_InterruptThresholdAddress; DWORD PEBS_BufferBaseAddress; DWORD PEBS_IndexBaseAddress; DWORD PEBS_AbsoluteMaxAddress; DWORD PEBS_InterruptThresholdAddress; QWORD PEBS_CounterReset; QWORD Reserved; DWORD Reserved2; } DS_AREA_MANAGEMENT32,*PDS_AREA_MANAGEMENT32; */ typedef struct { QWORD BTS_BufferBaseAddress; QWORD BTS_IndexBaseAddress; QWORD BTS_AbsoluteMaxAddress; QWORD BTS_InterruptThresholdAddress; QWORD PEBS_BufferBaseAddress; QWORD PEBS_IndexBaseAddress; QWORD PEBS_AbsoluteMaxAddress; QWORD PEBS_InterruptThresholdAddress; QWORD PEBS_CounterReset; QWORD Reserved; QWORD Reserved2; } DS_AREA_MANAGEMENT64,*PDS_AREA_MANAGEMENT64; typedef struct { QWORD LastBranchFrom; QWORD LastBranchTo; QWORD Extra; } BTS,*PBTS; //#ifdef AMD64 typedef DS_AREA_MANAGEMENT64 DS_AREA_MANAGEMENT; typedef PDS_AREA_MANAGEMENT64 PDS_AREA_MANAGEMENT; //#else //typedef DS_AREA_MANAGEMENT32 DS_AREA_MANAGEMENT; //typedef PDS_AREA_MANAGEMENT32 PDS_AREA_MANAGEMENT; //#endif typedef struct { UINT64 DataReadyEvent; UINT64 DataHandledEvent; } ULTIMAPEVENT, *PULTIMAPEVENT; typedef struct { UINT64 Address; UINT64 Size; UINT64 Block; UINT64 CpuID; UINT64 KernelAddress; UINT64 Mdl; //go ahead, scream } ULTIMAPDATAEVENT, *PULTIMAPDATAEVENT; NTSTATUS ultimap_continue(PULTIMAPDATAEVENT data); NTSTATUS ultimap_waitForData(ULONG timeout, PULTIMAPDATAEVENT data); NTSTATUS ultimap(UINT64 cr3, UINT64 dbgctl_msr, int _DS_AREA_SIZE, BOOL savetofile, WCHAR *filename, int handlerCount); void ultimap_pause(); void ultimap_resume(); void ultimap_disable(void); void ultimap_flushBuffers(void); PDS_AREA_MANAGEMENT DS_AREA[256]; //used to store the addresses. (reading the msr that holds the DS_AREA is impossible with dbvm active) int DS_AREA_SIZE; #pragma pack(pop) #endif <|start_filename|>src/memscan.c<|end_filename|> #pragma warning( disable: 4100 4103 4146 4213) #include "ntifs.h" #include <windef.h> #ifdef CETC #include "tdiwrapper.h" #include "kfiles.h" #endif #include "memscan.h" #include "DBKFunc.h" #include "vmxhelper.h" #include "vmxoffload.h" //PTE structs #include "noexceptions.h" /*#include "deepkernel.h" */ UINT_PTR KnownPageTableBase = 0; void VirtualAddressToIndexes(QWORD address, int *pml4index, int *pagedirptrindex, int *pagedirindex, int *pagetableindex) /* * Returns the indexes for the given address (ia32e) */ { if (PTESize == 8) { *pml4index = (address >> 39) & 0x1ff; *pagedirptrindex = (address >> 30) & 0x1ff; *pagedirindex = (address >> 21) & 0x1ff; *pagetableindex = (address >> 12) & 0x1ff; } else { *pml4index = 0; *pagedirptrindex = 0; *pagedirindex = (address >> 22) & 0x3ff; *pagetableindex = (address >> 12) & 0x3ff; } } QWORD IndexesToVirtualAddress(int pml4index, int pagedirptrindex, int pagedirindex, int pagetableindex, int offset) { QWORD r; #ifndef AMD64 if (PTESize == 8) { #endif r = ((QWORD)pml4index & 0x1ff) << 39; if (pml4index >= 256) r = r | 0xFFFF000000000000ULL; r |= ((QWORD)pagedirptrindex & 0x1ff) << 30; r |= ((QWORD)pagedirindex & 0x1ff) << 21; r |= ((QWORD)pagetableindex & 0x1ff) << 12; r |= offset & 0xfff; #ifndef AMD64 } else { r |= (pagedirindex & 0x3ff) << 22; r |= (pagetableindex & 0x3ff) << 12; r |= offset & 0xfff; } #endif return r; } #ifndef AMD64 void VirtualAddressToPageEntries32(DWORD address, PPDE *pagedirentry, PPTE *pagetableentry) { DWORD PTE = address; UINT_PTR PTB = (DWORD)getPageTableBase(); PTE = PTE >> 12; PTE = PTE * 4; PTE = PTE + PTB; *pagetableentry = (PPTE)PTE; UINT_PTR PDE = PTE; PDE = PDE & 0x0000ffffffffffffULL; PDE = PDE >> 12; PDE = PDE * 4; PDE = PDE + PTB; *pagedirentry = (PPDE)PDE; } #endif void VirtualAddressToPageEntries64(QWORD address, PPDPTE_PAE *pml4entry, PPDPTE_PAE *pagedirpointerentry, PPDE_PAE *pagedirentry, PPTE_PAE *pagetableentry) { QWORD PTE = address; QWORD PTB=getPageTableBase(); PTE = PTE & 0x0000ffffffffffffULL; PTE = PTE >> 12; PTE = PTE * 8; PTE = PTE + PTB; *pagetableentry = (PPTE_PAE)(UINT_PTR)PTE; //*pagetableentry = (PPTE_PAE)((((QWORD)address & 0x0000ffffffffffffull) >> 12)*8) + 0xfffff80000000000ULL; QWORD PDE = PTE; PDE = PDE & 0x0000ffffffffffffULL; PDE = PDE >> 12; PDE = PDE * 8; PDE = PDE + PTB; *pagedirentry = (PPDE_PAE)(UINT_PTR)PDE; //*pagedirentry = (PPDE_PAE)((((QWORD)*pagetableentry & 0x0000ffffffffffffull )>> 12)*8) + 0xfffff80000000000ULL; QWORD PDPTR = PDE; PDPTR = PDPTR & 0x0000ffffffffffffULL; PDPTR = PDPTR >> 12; PDPTR = PDPTR * 8; PDPTR = PDPTR + PTB; *pagedirpointerentry = (PPDPTE_PAE)(UINT_PTR)PDPTR; //*pagedirpointerentry = (PPDPTE_PAE)((((QWORD)*pagedirentry & 0x0000ffffffffffffull )>> 12)*8) + 0xfffff80000000000ULL; #ifdef AMD64 QWORD PML4 = PDPTR; PML4 = PML4 & 0x0000ffffffffffffULL; PML4 = PML4 >> 12; PML4 = PML4 * 8; PML4 = PML4 + PTB; *pml4entry = (PPDPTE_PAE)PML4; #else *pml4entry = NULL; #endif } BOOLEAN IsAddressSafe(UINT_PTR StartAddress) { #ifdef AMD64 //cannonical check. Bits 48 to 63 must match bit 47 UINT_PTR toppart=(StartAddress >> 47); if (toppart & 1) { //toppart must be 0x1ffff if (toppart != 0x1ffff) return FALSE; } else { //toppart must be 0 if (toppart != 0) return FALSE; } #endif //return TRUE; if (loadedbydbvm) { BYTE x=0; UINT_PTR lasterror; disableInterrupts(); vmx_disable_dataPageFaults(); x=*(volatile BYTE *)StartAddress; vmx_enable_dataPageFaults(); lasterror=vmx_getLastSkippedPageFault(); enableInterrupts(); DbgPrint("IsAddressSafe dbvm-mode: lastError=%p\n", lasterror); if (lasterror) return FALSE; } { #ifdef AMD64 UINT_PTR kernelbase=0x7fffffffffffffffULL; if (StartAddress<kernelbase) return TRUE; else { PHYSICAL_ADDRESS physical; physical.QuadPart=0; physical=MmGetPhysicalAddress((PVOID)StartAddress); return (physical.QuadPart!=0); } #else /* MDL x; MmProbeAndLockPages(&x,KernelMode,IoModifyAccess); MmUnlockPages(&x); */ ULONG kernelbase=0x7ffe0000; if ((!HiddenDriver) && (StartAddress<kernelbase)) return TRUE; { UINT_PTR PTE,PDE; struct PTEStruct *x; /* PHYSICAL_ADDRESS physical; physical=MmGetPhysicalAddress((PVOID)StartAddress); return (physical.QuadPart!=0);*/ PTE=(UINT_PTR)StartAddress; PTE=PTE/0x1000*PTESize+0xc0000000; //now check if the address in PTE is valid by checking the page table directory at 0xc0300000 (same location as CR3 btw) PDE=PTE/0x1000*PTESize+0xc0000000; //same formula x=(PVOID)PDE; if ((x->P==0) && (x->A2==0)) { //Not present or paged, and since paging in this area isn't such a smart thing to do just skip it //perhaps this is only for the 4 mb pages, but those should never be paged out, so it should be 1 //bah, I've got no idea what this is used for return FALSE; } if (x->PS==1) { //This is a 4 MB page (no pte list) //so, (startaddress/0x400000*0x400000) till ((startaddress/0x400000*0x400000)+(0x400000-1) ) ) is specified by this page } else //if it's not a 4 MB page then check the PTE { //still here so the page table directory agreed that it is a usable page table entry x=(PVOID)PTE; if ((x->P==0) && (x->A2==0)) return FALSE; //see for explenation the part of the PDE } return TRUE; } #endif } } UINT_PTR getPEThread(UINT_PTR threadid) { //UINT_PTR *threadid; PETHREAD selectedthread; UINT_PTR result=0; if (PsLookupThreadByThreadId((PVOID)(UINT_PTR)threadid,&selectedthread)==STATUS_SUCCESS) { result=(UINT_PTR)selectedthread; ObDereferenceObject(selectedthread); } return result; } BOOLEAN WriteProcessMemory(DWORD PID,PEPROCESS PEProcess,PVOID Address,DWORD Size, PVOID Buffer) { PEPROCESS selectedprocess=PEProcess; KAPC_STATE apc_state; NTSTATUS ntStatus=STATUS_UNSUCCESSFUL; if (selectedprocess==NULL) { //DbgPrint("WriteProcessMemory:Getting PEPROCESS\n"); if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)(UINT_PTR)PID,&selectedprocess))) return FALSE; //couldn't get the PID //DbgPrint("Retrieved peprocess"); } //selectedprocess now holds a valid peprocess value __try { RtlZeroMemory(&apc_state,sizeof(apc_state)); KeAttachProcess((PEPROCESS)selectedprocess); __try { char* target; char* source; unsigned int i; //DbgPrint("Checking safety of memory\n"); if ((IsAddressSafe((UINT_PTR)Address)) && (IsAddressSafe((UINT_PTR)Address+Size-1))) { //still here, then I gues it's safe to read. (But I can't be 100% sure though, it's still the users problem if he accesses memory that doesn't exist) BOOL disabledWP = FALSE; target=Address; source=Buffer; if ((loadedbydbvm) || (KernelWritesIgnoreWP)) //add a extra security around it as the PF will not be handled { disableInterrupts(); if (loadedbydbvm) vmx_disable_dataPageFaults(); if (KernelWritesIgnoreWP) { DbgPrint("Disabling CR0.WP"); setCR0(getCR0() & (~(1 << 16))); //disable the WP bit disabledWP = TRUE; } } if ((loadedbydbvm) || ((UINT_PTR)target < 0x8000000000000000ULL)) { RtlCopyMemory(target, source, Size); ntStatus = STATUS_SUCCESS; } else { i = NoExceptions_CopyMemory(target, source, Size); if (i != (int)Size) ntStatus = STATUS_UNSUCCESSFUL; else ntStatus = STATUS_SUCCESS; } if ((loadedbydbvm) || (disabledWP)) { UINT_PTR lastError=0; if (disabledWP) { setCR0(getCR0() | (1 << 16)); DbgPrint("Enabled CR0.WP"); } if (loadedbydbvm) { lastError = vmx_getLastSkippedPageFault(); vmx_enable_dataPageFaults(); } enableInterrupts(); DbgPrint("lastError=%p\n", lastError); if (lastError) ntStatus=STATUS_UNSUCCESSFUL; } } } __finally { KeDetachProcess(); } } __except(1) { //DbgPrint("Error while writing\n"); ntStatus = STATUS_UNSUCCESSFUL; } if (PEProcess==NULL) //no valid peprocess was given so I made a reference, so lets also dereference ObDereferenceObject(selectedprocess); return NT_SUCCESS(ntStatus); } BOOLEAN ReadProcessMemory(DWORD PID,PEPROCESS PEProcess,PVOID Address,DWORD Size, PVOID Buffer) { PEPROCESS selectedprocess=PEProcess; //KAPC_STATE apc_state; NTSTATUS ntStatus=STATUS_UNSUCCESSFUL; if (PEProcess==NULL) { if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)(UINT_PTR)PID,&selectedprocess))) return FALSE; //couldn't get the PID } //selectedprocess now holds a valid peprocess value __try { KeAttachProcess((PEPROCESS)selectedprocess); __try { char* target; char* source; int i; if ((IsAddressSafe((UINT_PTR)Address)) && (IsAddressSafe((UINT_PTR)Address+Size-1))) { target=Buffer; source=Address; if (loadedbydbvm) //add a extra security around it { disableInterrupts(); vmx_disable_dataPageFaults(); } if ((loadedbydbvm) || ((UINT_PTR)source < 0x8000000000000000ULL)) { RtlCopyMemory(target, source, Size); ntStatus = STATUS_SUCCESS; } else { i=NoExceptions_CopyMemory(target, source, Size); if (i != (int)Size) ntStatus = STATUS_UNSUCCESSFUL; else ntStatus = STATUS_SUCCESS; } if (loadedbydbvm) { UINT_PTR lastError; lastError=vmx_getLastSkippedPageFault(); vmx_enable_dataPageFaults(); enableInterrupts(); DbgPrint("lastError=%p\n", lastError); if (lastError) ntStatus=STATUS_UNSUCCESSFUL; } } } __finally { KeDetachProcess(); } } __except(1) { //DbgPrint("Error while reading: ReadProcessMemory(%x,%p, %p, %d, %p\n", PID, PEProcess, Address, Size, Buffer); ntStatus = STATUS_UNSUCCESSFUL; } if (PEProcess==NULL) //no valid peprocess was given so I made a reference, so lets also dereference ObDereferenceObject(selectedprocess); return NT_SUCCESS(ntStatus); } UINT64 maxPhysAddress = 0; UINT64 getMaxPhysAddress(void) { if (maxPhysAddress==0) { int physicalbits; DWORD r[4]; __cpuid(r, 0x80000008); //get max physical address physicalbits = r[0] & 0xff; maxPhysAddress = 0xFFFFFFFFFFFFFFFFULL; maxPhysAddress = maxPhysAddress >> physicalbits; //if physicalbits==36 then maxPhysAddress=0x000000000fffffff maxPhysAddress = ~(maxPhysAddress << physicalbits); //<< 36 = 0xfffffff000000000 . after inverse : 0x0000000fffffffff } return maxPhysAddress; } NTSTATUS ReadPhysicalMemory(char *startaddress, UINT_PTR bytestoread, void *output) { HANDLE physmem; UNICODE_STRING physmemString; OBJECT_ATTRIBUTES attributes; WCHAR physmemName[] = L"\\device\\physicalmemory"; UCHAR* memoryview; NTSTATUS ntStatus = STATUS_UNSUCCESSFUL; PMDL outputMDL; DbgPrint("ReadPhysicalMemory(%p, %d, %p)", startaddress, bytestoread, output); if (((UINT64)startaddress > getMaxPhysAddress()) || ((UINT64)startaddress + bytestoread > getMaxPhysAddress())) { DbgPrint("Invalid physical address\n"); return ntStatus; } outputMDL = IoAllocateMdl(output, (ULONG)bytestoread, FALSE, FALSE, NULL); __try { MmProbeAndLockPages(outputMDL, KernelMode, IoWriteAccess); } __except (1) { IoFreeMdl(outputMDL); return STATUS_UNSUCCESSFUL; } __try { RtlInitUnicodeString( &physmemString, physmemName ); InitializeObjectAttributes( &attributes, &physmemString, OBJ_CASE_INSENSITIVE, NULL, NULL ); ntStatus=ZwOpenSection( &physmem, SECTION_ALL_ACCESS, &attributes ); if (ntStatus==STATUS_SUCCESS) { //hey look, it didn't kill it SIZE_T length; PHYSICAL_ADDRESS viewBase; UINT_PTR offset; UINT_PTR toread; viewBase.QuadPart = (ULONGLONG)(startaddress); length=0x2000;//pinp->bytestoread; //in case of a overlapping region toread=bytestoread; memoryview=NULL; DbgPrint("ReadPhysicalMemory:viewBase.QuadPart=%x", viewBase.QuadPart); ntStatus=ZwMapViewOfSection( physmem, //sectionhandle NtCurrentProcess(), //processhandle (should be -1) &memoryview, //BaseAddress 0L, //ZeroBits length, //CommitSize &viewBase, //SectionOffset &length, //ViewSize ViewShare, 0, PAGE_READWRITE); if ((ntStatus == STATUS_SUCCESS) && (memoryview!=NULL)) { if (toread > length) toread = length; if (toread) { __try { offset = (UINT_PTR)(startaddress)-(UINT_PTR)viewBase.QuadPart; if (offset + toread > length) { DbgPrint("Too small map"); } else { RtlCopyMemory(output, &memoryview[offset], toread); } ZwUnmapViewOfSection(NtCurrentProcess(), memoryview); } __except (1) { DbgPrint("Failure mapping physical memory"); } } } else { DbgPrint("ReadPhysicalMemory error:ntStatus=%x", ntStatus); } ZwClose(physmem); }; } __except(1) { DbgPrint("Error while reading physical memory\n"); } MmUnlockPages(outputMDL); IoFreeMdl(outputMDL); return ntStatus; } UINT_PTR SignExtend(UINT_PTR a) { #ifdef AMD64 if ((a >> 47)==1) return a | 0xFFFF000000000000ULL; //add sign extended bits else return a; #else return a; #endif } UINT_PTR getPageTableBase() { #if (NTDDI_VERSION >= NTDDI_VISTA) if (KnownPageTableBase==0) { RTL_OSVERSIONINFOW v; v.dwOSVersionInfoSize = sizeof(v); if (RtlGetVersion(&v)) { DbgPrint("RtlGetVersion failed"); return 0; } if ((v.dwMajorVersion >= 10) && (v.dwBuildNumber >= 14393)) { PHYSICAL_ADDRESS a; PVOID r; a.QuadPart = getCR3() & 0xFFFFFFFFFFFFF000ULL; r = MmGetVirtualForPhysical(a); //if this stops working, look for CR3 in the pml4 table KnownPageTableBase = ((UINT_PTR)r) & 0xFFFFFF8000000000ULL; MAX_PTE_POS = (UINT_PTR)((QWORD)KnownPageTableBase + 0x7FFFFFFFF8ULL); MAX_PDE_POS = (UINT_PTR)((QWORD)KnownPageTableBase + 0x7B7FFFFFF8ULL); } else KnownPageTableBase=PAGETABLEBASE; DbgPrint("PageTableBase at %p\n", KnownPageTableBase); } return KnownPageTableBase; #else return PAGETABLEBASE; #endif } typedef void PRESENTPAGECALLBACK(UINT_PTR StartAddress, UINT_PTR EndAddress, struct PTEStruct *pageEntry); BOOL walkPagingLayout(PEPROCESS PEProcess, UINT_PTR MaxAddress, PRESENTPAGECALLBACK OnPresentPage) { #ifdef AMD64 UINT_PTR pagebase = getPageTableBase(); #else UINT_PTR pagebase = PAGETABLEBASE; #endif if (pagebase == 0) return FALSE; if (OnPresentPage == NULL) return FALSE; __try { KeAttachProcess((PEPROCESS)PEProcess); __try { UINT_PTR currentAddress = 0; //start from address 0 UINT_PTR lastAddress = 0; struct PTEStruct *PPTE, *PPDE, *PPDPE, *PPML4E; while ((currentAddress < MaxAddress) && (lastAddress<=currentAddress) ) { //DbgPrint("currentAddress=%p\n", currentAddress); lastAddress = currentAddress; (UINT_PTR)PPTE = (UINT_PTR)(((currentAddress & 0xFFFFFFFFFFFFULL) >> 12) *PTESize + pagebase); (UINT_PTR)PPDE = (UINT_PTR)((((UINT_PTR)PPTE) & 0xFFFFFFFFFFFFULL) >> 12) *PTESize + pagebase; (UINT_PTR)PPDPE = (UINT_PTR)((((UINT_PTR)PPDE) & 0xFFFFFFFFFFFFULL) >> 12) *PTESize + pagebase; (UINT_PTR)PPML4E = (UINT_PTR)((((UINT_PTR)PPDPE) & 0xFFFFFFFFFFFFULL) >> 12) *PTESize + pagebase; if (PTESize == 8) (UINT_PTR)PPDPE = ((((UINT_PTR)PPDE) & 0xFFFFFFFFFFFFULL) >> 12) *PTESize + pagebase; else (UINT_PTR)PPDPE = 0; #ifdef AMD64 (UINT_PTR)PPML4E = ((((UINT_PTR)PPDPE) & 0xFFFFFFFFFFFFULL) >> 12) *PTESize + pagebase; #else (UINT_PTR)PPML4E = 0; #endif #ifdef AMD64 if ((PPML4E) && (PPML4E->P == 0)) { currentAddress &= 0xffffff8000000000ULL; currentAddress += 0x8000000000ULL; continue; } #endif if ((PPDPE) && (PPDPE->P == 0)) { currentAddress &= 0xffffffffc0000000ULL; currentAddress += 0x40000000; continue; } if (PPDPE->PS) //some systems have 1GB page support. But not sure windows uses these { DbgPrint("----->%llx is a 1GB range", currentAddress); OnPresentPage(currentAddress, currentAddress + 0x40000000 - 1, PPDPE); currentAddress += 0x40000000; continue; } if (PPDE->P == 0) { if (PAGE_SIZE_LARGE == 0x200000) currentAddress &= 0xffffffffffe00000ULL; else currentAddress &= 0xffffffffffc00000ULL; currentAddress += PAGE_SIZE_LARGE; continue; } if (PPDE->PS) { OnPresentPage(currentAddress, currentAddress + PAGE_SIZE_LARGE-1, PPDE); currentAddress += PAGE_SIZE_LARGE; continue; } if (PPTE->P == 0) { currentAddress &= 0xfffffffffffff000ULL; currentAddress += 0x1000; continue; } OnPresentPage(currentAddress, currentAddress + 0xfff, PPTE); currentAddress += 0x1000; } } __finally { KeDetachProcess(); } } __except (1) { DbgPrint("Excepion while walking the paging layout\n"); return FALSE; } return TRUE; } PPENTRY AccessedList = NULL; int AccessedListSize; void CleanAccessedList() { PPENTRY e = AccessedList; PPENTRY previous; //DbgPrint("Cleaning list"); while (e) { previous = e; e = e->Next; ExFreePool(previous); } AccessedList = NULL; AccessedListSize = 0; } void StoreAccessedRanges(UINT_PTR StartAddress, UINT_PTR EndAddress, struct PTEStruct *pageEntry) { if (pageEntry->A) { if ((AccessedList) && (AccessedList->Range.EndAddress == StartAddress - 1)) //group AccessedList->Range.EndAddress = EndAddress; else { //insert PPENTRY e; e = ExAllocatePool(PagedPool, sizeof(PENTRY)); e->Range.StartAddress = StartAddress; e->Range.EndAddress = EndAddress; e->Next = AccessedList; AccessedList = e; AccessedListSize++; } } } int enumAllAccessedPages(PEPROCESS PEProcess) { #ifdef AMD64 UINT_PTR MaxAddress = 0x80000000000ULL; #else UINT_PTR MaxAddress = 0x80000000; #endif CleanAccessedList(); if (walkPagingLayout(PEProcess, MaxAddress, StoreAccessedRanges)) { //DbgPrint("AccessedListSize=%d\n", AccessedListSize); return AccessedListSize*sizeof(PRANGE); } else return 0; } int getAccessedPageList(PPRANGE List, int ListSizeInBytes) { PPENTRY e = AccessedList; int maxcount = ListSizeInBytes / sizeof(PRANGE); int i = 0; // DbgPrint("getAccessedPageList\n"); while (e) { if (i >= maxcount) { //DbgPrint("%d>=%d", i, maxcount); break; } //DbgPrint("i=%d (%p -> %p)\n", i, e->Range.StartAddress, e->Range.EndAddress); List[i] = e->Range; e = e->Next; i++; } CleanAccessedList(); return i*sizeof(PRANGE); } void MarkPageAsNotAccessed(UINT_PTR StartAddress, UINT_PTR EndAddress, struct PTEStruct *pageEntry) { pageEntry->A = 0; } NTSTATUS markAllPagesAsNeverAccessed(PEPROCESS PEProcess) { #ifdef AMD64 UINT_PTR MaxAddress = 0x80000000000ULL; #else UINT_PTR MaxAddress = 0x80000000; #endif if (walkPagingLayout(PEProcess, MaxAddress, MarkPageAsNotAccessed)) return STATUS_SUCCESS; else return STATUS_UNSUCCESSFUL; } UINT_PTR FindFirstDifferentAddress(QWORD address, DWORD *protection) //scans the pagetable system for the first fully present entry //returns 0 when there is no other present address { int i,ri; int pml4index, pagedirpointerindex, pagedirindex, pagetableindex; VirtualAddressToIndexes(address, &pml4index, &pagedirpointerindex, &pagedirindex, &pagetableindex); #ifndef AMD64 if (PTESize == 8) #endif { PPDPTE_PAE pml4entry, pagedirpointerentry; PPDE_PAE pagedirentry; PPTE_PAE pagetableentry; *protection = 0; //scan till present or end of memory while (1) { VirtualAddressToPageEntries64(address, &pml4entry, &pagedirpointerentry, &pagedirentry, &pagetableentry); VirtualAddressToIndexes(address, &pml4index, &pagedirpointerindex, &pagedirindex, &pagetableindex); if (*protection == 0) { //get the initial protection if ((((pml4entry) && (pml4entry->P)) || (pml4entry == NULL)) && (pagedirpointerentry->P) && (pagedirentry->P) && ((pagedirentry->PS) || (pagetableentry->P))) { if (pagedirentry->PS) { if (pagedirentry->RW) *protection = PAGE_EXECUTE_READWRITE; else *protection = PAGE_EXECUTE_READ; } else { if (pagetableentry->RW) *protection = PAGE_EXECUTE_READWRITE; else *protection = PAGE_EXECUTE_READ; } } else *protection = PAGE_NOACCESS; } #ifdef AMD64 if (pml4entry->P == 0) { //unreadable at PML4 level if (*protection != PAGE_NOACCESS) return address; pagedirpointerindex = 0; pagedirindex = 0; pagetableindex = 0; for (ri=1, i = pml4index + 1; i < 512; i++, ri++) { if ((ri >= 512) || (ri < 0)) DbgBreakPointWithStatus(ri); if (pml4entry[ri].P) { //found a valid PML4 entry //scan for a valid pagedirpointerentry pml4index = i; address = IndexesToVirtualAddress(pml4index, pagedirpointerindex, pagedirindex, pagetableindex, 0); VirtualAddressToPageEntries64(address, &pml4entry, &pagedirpointerentry, &pagedirentry, &pagetableentry); break; } } } if (pml4entry->P == 0) { //nothing readable found return 0; } #endif if (pagedirpointerentry->P == 0) { if (*protection != PAGE_NOACCESS) return (UINT_PTR)address; pagedirindex = 0; pagetableindex = 0; for (ri=1, i = pagedirpointerindex + 1; i < 512; i++, ri++) { if ((ri >= 512) || (ri < 0)) DbgBreakPointWithStatus(ri); if (pagedirpointerentry[ri].P) { //found a valid pagedirpointerentry pagedirpointerindex = i; address = IndexesToVirtualAddress(pml4index, pagedirpointerindex, pagedirindex, pagetableindex, 0); VirtualAddressToPageEntries64(address, &pml4entry, &pagedirpointerentry, &pagedirentry, &pagetableentry); break; } } if (pagedirpointerentry->P == 0) { #ifdef AMD64 pagedirpointerindex = 0; pml4index++; if (pml4index >= 512) return 0; //end of the list address = IndexesToVirtualAddress(pml4index, pagedirpointerindex, pagedirindex, pagetableindex, 0); continue; //try the next PML4 entry #else //nothing readable found return 0; #endif } } if (pagedirentry->P == 0) { if (*protection != PAGE_NOACCESS) return (UINT_PTR)address; pagetableindex = 0; for (ri=1, i = pagedirindex + 1; i < 512; i++, ri++) { if ((ri >= 512) || (ri < 0)) DbgBreakPointWithStatus(ri); if (pagedirentry[ri].P) { //found a valid pagedirentry pagedirindex = i; address = IndexesToVirtualAddress(pml4index, pagedirpointerindex, pagedirindex, pagetableindex, 0); VirtualAddressToPageEntries64(address, &pml4entry, &pagedirpointerentry, &pagedirentry, &pagetableentry); break; } } if (pagedirentry->P == 0) { pagedirindex = 0; pagedirpointerindex++; if (pagedirpointerindex >= 512) { pagedirpointerindex = 0; pml4index++; if (pml4index >= 512) return 0; //end of the list } address = IndexesToVirtualAddress(pml4index, pagedirpointerindex, pagedirindex, pagetableindex, 0); continue; //try the next pagedirpointer entry } } if (pagedirentry->PS) { if (*protection == PAGE_NOACCESS) return (UINT_PTR)address; if ((pagedirentry->RW) && (*protection != PAGE_EXECUTE_READWRITE)) return (UINT_PTR)address; //go to the next one pagedirindex++; if (pagedirindex >= 512) { pagedirindex = 0; pagedirpointerindex++; if (pagedirpointerindex >= 512) { pagedirpointerindex = 0; pml4index++; if (pml4index >= 512) return 0; //end of the list } } address = IndexesToVirtualAddress(pml4index, pagedirpointerindex, pagedirindex, pagetableindex, 0); continue; } if (pagetableentry->P == 0) { if (*protection != PAGE_NOACCESS) return (UINT_PTR)address; for (ri=1, i = pagetableindex + 1; i < 512; i++, ri++) { if ((ri >= 512) || (ri < 0)) DbgBreakPointWithStatus(ri); if (pagetableentry[ri].P) { //found a valid pagetable entry pagetableindex = i; address = IndexesToVirtualAddress(pml4index, pagedirpointerindex, pagedirindex, pagetableindex, 0); VirtualAddressToPageEntries64(address, &pml4entry, &pagedirpointerentry, &pagedirentry, &pagetableentry); break; } } if (pagetableentry->P == 0) { pagetableindex = 0; pagedirindex++; if (pagedirindex >= 512) { pagedirindex = 0; pagedirpointerindex++; if (pagedirpointerindex >= 512) { pagedirpointerindex = 0; pml4index++; if (pml4index >= 512) return 0; //end of the list } } address = IndexesToVirtualAddress(pml4index, pagedirpointerindex, pagedirindex, pagetableindex, 0); continue; //try the next pagedir entry } } //still here so a present page if (*protection == PAGE_NOACCESS) return (UINT_PTR)address; if ((pagetableentry->RW) && (*protection != PAGE_EXECUTE_READWRITE)) return (UINT_PTR)address; //next entry pagetableindex++; if (pagetableindex >= 512) { pagetableindex = 0; pagedirindex++; if (pagedirindex >= 512) { pagedirindex = 0; pagedirpointerindex++; if (pagedirpointerindex >= 512) { pagedirpointerindex = 0; pml4index++; if (pml4index >= 512) return 0; } } } address = IndexesToVirtualAddress(pml4index, pagedirpointerindex, pagedirindex, pagetableindex, 0); } } #ifndef AMD64 else { PPDE pagedirentry; PPTE pagetableentry; while (1) { VirtualAddressToPageEntries32((UINT_PTR)address, &pagedirentry, &pagetableentry); VirtualAddressToIndexes((UINT_PTR)address, &pml4index, &pagedirpointerindex, &pagedirindex, &pagetableindex); if (*protection == 0) { //get the initial protection if ((pagedirentry->P) && ((pagedirentry->PS) || (pagetableentry->P))) { if (pagedirentry->PS) { if (pagedirentry->RW) *protection = PAGE_EXECUTE_READWRITE; else *protection = PAGE_EXECUTE_READ; } else { if (pagetableentry->RW) *protection = PAGE_EXECUTE_READWRITE; else *protection = PAGE_EXECUTE_READ; } } else *protection = PAGE_NOACCESS; } if (pagedirentry->P == 0) { if (*protection != PAGE_NOACCESS) return (UINT_PTR)address; pagetableindex = 0; for (ri=1, i = pagedirindex + 1; i < 1024; i++, ri++) { if (pagedirentry[ri].P) { //found a valid pagedirentry pagedirindex = i; address = IndexesToVirtualAddress(0, 0, pagedirindex, pagetableindex, 0); VirtualAddressToPageEntries32((UINT_PTR)address, &pagedirentry, &pagetableentry); break; } } if (pagedirentry->P == 0) return 0; //end of the list } if (pagedirentry->PS) { if (*protection == PAGE_NOACCESS) return (UINT_PTR)address; if ((pagedirentry->RW) && (*protection != PAGE_EXECUTE_READWRITE)) return (UINT_PTR)address; //go to the next one pagedirindex++; if (pagedirindex >= 1024) return 0; address = IndexesToVirtualAddress(0, 0, pagedirindex, pagetableindex, 0); } if (pagetableentry->P == 0) { if (*protection != PAGE_NOACCESS) return (UINT_PTR)address; for (ri=1, i = pagetableindex + 1; i < 1024; i++, ri++) { if (pagetableentry[ri].P) { //found a valid pagetable entry pagetableindex = i; address = IndexesToVirtualAddress(0, 0, pagedirindex, pagetableindex, 0); break; } } if (pagetableentry->P == 0) { pagetableindex = 0; pagedirindex++; if (pagedirindex >= 1024) return 0; address = IndexesToVirtualAddress(0, 0, pagedirindex, pagetableindex, 0); continue; //try the next pagedir entry } } //still here so a present page if (*protection == PAGE_NOACCESS) return (UINT_PTR)address; if ((pagetableentry->RW) && (*protection != PAGE_EXECUTE_READWRITE)) return (UINT_PTR)address; //next entry pagetableindex++; if (pagetableindex >= 1024) { pagetableindex = 0; pagedirindex++; if (pagedirindex >= 1024) return 0; } address = IndexesToVirtualAddress(pml4index, pagedirpointerindex, pagedirindex, pagetableindex, 0); } } #endif } BOOLEAN GetMemoryRegionData(DWORD PID,PEPROCESS PEProcess, PVOID mempointer,ULONG *regiontype, UINT_PTR *memorysize,UINT_PTR *baseaddress) { UINT_PTR CurrentAddress; KAPC_STATE apc_state; PEPROCESS selectedprocess=PEProcess; if (getPageTableBase() == 0) { DbgPrint("GetMemoryRegionData failed because pagebase == 0"); return FALSE; } if (PEProcess==NULL) { if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)(UINT_PTR)PID,&selectedprocess))) return FALSE; //couldn't get the PID } *baseaddress=(UINT_PTR)mempointer & (UINT_PTR)(~0xfff); *memorysize=0; *regiontype=0; //switch context to the target process RtlZeroMemory(&apc_state,sizeof(apc_state)); __try { KeAttachProcess((PEPROCESS)selectedprocess); __try { CurrentAddress=FindFirstDifferentAddress(*baseaddress, regiontype); *memorysize = CurrentAddress-*baseaddress; } __finally { KeDetachProcess(); if (PEProcess==NULL) //no valid peprocess was given so I made a reference, so lets also dereference ObDereferenceObject(selectedprocess); } } __except(1) { DbgPrint("Exception in GetMemoryRegionData\n"); DbgPrint("mempointer=%p",mempointer); } return 0; } <|start_filename|>scripts/cmd.js<|end_filename|> const env = require('dotenv').config().parsed; const rimraf = require('rimraf'); const path = require('path'); const fs = require('fs'); const handlebars = require('handlebars'); const spawn = require('child_process').spawn; class Context { static buildDir = path.normalize(__dirname + '\\..\\build\\'); static cheatEngineBinary = env.CHAMD_CHEAT_ENGINE_BINARY_DIR; static driverName = env.CHAMD_DBK_DRIVER_NAME; static seed = env.CHAMD_SEED; static vcvarsCommunityPath = 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Auxiliary\\Build\\vcvarsall.bat'; static vcvarsEnterprisePath = 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\VC\\Auxiliary\\Build\\vcvarsall.bat'; static vcPath = null; static cmakeTplPath = path.normalize(__dirname + '\\..\\templates\\CMakeLists.txt.tpl'); static infTplPath = path.normalize(__dirname + '\\..\\templates\\chamd.inf.tpl'); static datTplPath = path.normalize(__dirname + '\\..\\templates\\driver64.dat.tpl'); static datPath = `${this.buildDir}driver64.dat`; static srcDir = path.normalize(__dirname + '\\..\\src\\'); static distDir = path.normalize(__dirname + '\\..\\dist\\'); static cmakeConfigPath = this.srcDir + 'CMakeLists.txt'; static infPath = `${this.buildDir}${this.driverName}.inf`; static inf2CatPath = "C:\\Program Files (x86)\\Windows Kits\\10\\bin\\x86\\inf2cat.exe" static async all() { console.log(`Generating ${this.driverName} driver ...`); await this.purge(); await this.generateCmakeFile(); await this.compile(); await this.createInfFile(); await this.stampInfFile(); await this.signDriver(); await this.createDriverDatFile(); await this.install(); await this.clearBuildDir(); console.log(`Success!!!`); console.log(`Now copy all files from ${this.distDir} to directory where cheatengine.exe is located`); } static async purge() { await this.clearBuildDir(); await this.purgeDir(this.distDir); if (!fs.existsSync(this.cmakeConfigPath)) { return; } fs.rmSync(this.cmakeConfigPath); } static async purgeDir(dir) { if (!fs.existsSync(dir)) { return; } console.log(`Clearing ${dir}* and other files ...`); return new Promise((res, rej) => { rimraf(`${dir}\\*`, () => { res(); }); }); } static async generateCmakeFile() { await this.templateToFile( this.cmakeTplPath, this.cmakeConfigPath, { DRIVER_NAME: this.driverName, } ); } static async templateToFile(src, dist, vars) { const templateContent = fs.readFileSync(src, 'utf-8'); const template = handlebars.compile(templateContent); const res = template(vars) fs.writeFileSync(dist, res); } static async compile() { console.log('Compiling'); if (this.vcPath === null) { throw new Error('Visual studio not found'); } const cmd = `"${this.vcPath}" amd64 && cd "${this.buildDir}" && cmake -G "Visual Studio 16 2019" "${this.srcDir}" && cmake --build . --config Release`; await this.execute(cmd, this.buildDir); } static async createInfFile() { console.log('Creating inf file'); await this.templateToFile( this.infTplPath, this.infPath, { DRIVER_NAME: this.driverName, }, ); } static async stampInfFile() { console.log('Stamping inf file'); const cmd = `"${this.vcPath}" amd64 && stampinf.exe -f .\\${this.driverName}.inf -a "amd64" -k "1.15" -v "*" -d "*"` await this.execute(cmd, this.buildDir); } static async signDriver() { console.log('Signing driver'); const vc = `"${this.vcPath}" amd64`; const inf2cat = `"${this.inf2CatPath}" /driver:"./" /os:10_X64 /verbose`; const makecert = `makecert -r -sv "./${this.driverName}.pvk" -n CN="${this.driverName} Inc." "./${this.driverName}.cer"`; const cert2spc = `cert2spc "./${this.driverName}.cer" "./${this.driverName}.spc"`; const pvk2pfx = `pvk2pfx -f -pvk "./${this.driverName}.pvk" -spc "./${this.driverName}.spc" -pfx "./${this.driverName}.pfx"`; const signtool = `signtool sign -f "./${this.driverName}.pfx" -t "http://timestamp.digicert.com" -v "./${this.driverName}.cat"`; const cmd = `${vc} && ${inf2cat} && ${makecert} && ${cert2spc} && ${pvk2pfx} && ${signtool}`; await this.execute(cmd, this.buildDir); } static async execute(cmd, cwd, params = []) { console.log(`!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!`); console.log(`Executing: ${cmd}`); return new Promise((res, rej) => { const proc = spawn(cmd, params, { cwd, shell: true, }); proc.stderr.setEncoding('utf-8'); proc.stdout.pipe(process.stdout); proc.stderr.pipe(process.stderr); proc.on('close', (code) => { code == 0 ? res() : rej(); }); }); } static async createDriverDatFile() { console.log('Creating dat file'); await this.templateToFile( this.datTplPath, this.datPath, { DRIVER_NAME: this.driverName, }, ); } static async install() { console.log('Installing'); if (!fs.existsSync(this.distDir)) { fs.mkdirSync(this.distDir); } fs.copyFileSync( `${this.buildDir}${this.driverName}.sys`, `${this.distDir}${this.driverName}.sys` ); fs.copyFileSync( `${this.buildDir}${this.driverName}.inf`, `${this.distDir}${this.driverName}.inf` ); fs.copyFileSync( `${this.buildDir}${this.driverName}.cat`, `${this.distDir}${this.driverName}.cat` ); fs.copyFileSync( `${this.buildDir}driver64.dat`, `${this.distDir}driver64.dat` ); } static async clearBuildDir() { await this.purgeDir(this.buildDir); } } const communityVs = fs.existsSync(Context.vcvarsCommunityPath); const enterpriseVs = fs.existsSync(Context.vcvarsEnterprisePath); if (communityVs) { Context.vcPath = Context.vcvarsCommunityPath; } if (enterpriseVs) { Context.vcPath = Context.vcvarsEnterprisePath; } const args = process.argv.slice(2); const command = args[0]; if (command == 'all') { (async () => { await Context.all(); })(); } else if (command === 'purge') { (async () => { await Context.purge(); })(); } else if (command === 'compile') { (async () => { await Context.generateCmakeFile(); await Context.compile(); })(); } else if (command === 'geninf') { (async () => { await Context.createInfFile(); await Context.stampInfFile(); })(); } else if (command === 'selfsign') { (async () => { await Context.signDriver(); await Context.createInfFile(); })(); } <|start_filename|>src/interruptHook.h<|end_filename|> #ifndef INTERRUPTHOOK_H #define INTERRUPTHOOK_H #include <windef.h> //assuming the standard interrupt hook routine is used this stackindex will be valid #ifdef AMD64 typedef enum {si_eax=0, si_ebx=1, si_ecx=2, si_edx=3, si_esi=4, si_edi=5, si_ebp=6, si_stack_esp=7, si_r8=8, si_r9=9, si_r10=10, si_r11=11, si_r12=12, si_r13=13, si_r14=14, si_r15=15, si_es=16, si_ds=17, si_stack_ss=18, si_xmm=19, si_errorcode=19+(4096/8)+(512/8), si_eip=20+(4096/8) + (512 / 8), si_cs=21+(4096/8) + (512 / 8), si_eflags=22+(4096/8) + (512 / 8), si_esp=23+(4096/8) + (512 / 8), si_ss=24+(4096/8) + (512 / 8)} stackindex; #else typedef enum {si_gs=-12, si_fs=-11, si_es=-10, si_ds=-9, si_edi=-8, si_esi=-7, si_stack_ebp=-6, si_stack_esp=-5, si_ebx=-4, si_edx=-3, si_ecx=-2, si_eax=-1, si_ebp=0, si_errorcode=1, si_eip=2, si_cs=3, si_eflags=4, si_esp=5, si_ss=6} stackindex; #endif #pragma pack(1) //allignment of 1 byte typedef struct tagINT_VECTOR { WORD wLowOffset; WORD wSelector; BYTE bUnused; BYTE bAccessFlags; /* unsigned gatetype : 3; //101=Task, 110=interrupt, 111=trap unsigned gatesize : 1; //1=32bit, 0=16bit unsigned zero : 1; unsigned DPL : 2; unsigned P : 1; */ WORD wHighOffset; #ifdef AMD64 DWORD TopOffset; DWORD Reserved; #endif } INT_VECTOR, *PINT_VECTOR; #pragma pack() #pragma pack(2) //allignemnt of 2 byte typedef struct tagIDT { WORD wLimit; PINT_VECTOR vector; } IDT, *PIDT; #pragma pack() #ifdef AMD64 typedef #pragma pack(1) //allignemnt of 1 byte struct { UINT64 eip; WORD cs; } JUMPBACK, *PJUMPBACK; #pragma pack() #else typedef #pragma pack(1) //allignemnt of 1 byte struct { DWORD eip; WORD cs; } JUMPBACK, *PJUMPBACK; #pragma pack() #endif int inthook_HookInterrupt(unsigned char intnr, int newCS, ULONG_PTR newEIP, PJUMPBACK jumpback); int inthook_UnhookInterrupt(unsigned char intnr); int inthook_isHooked(unsigned char intnr); int inthook_isDBVMHook(unsigned char intnr); ULONG_PTR inthook_getOriginalEIP(unsigned char intnr); WORD inthook_getOriginalCS(unsigned char intnr); #endif <|start_filename|>src/DBKDrvr.c<|end_filename|> #pragma warning( disable: 4100 4101 4103 4189) #include "DBKFunc.h" #include <ntifs.h> #include <windef.h> #include "DBKDrvr.h" #include "deepkernel.h" #include "processlist.h" #include "memscan.h" #include "threads.h" #include "vmxhelper.h" #include "debugger.h" #include "vmxoffload.h" #include "IOPLDispatcher.h" #include "interruptHook.h" #include "ultimap.h" #include "ultimap2.h" #include "noexceptions.h" #include "ultimap2\apic.h" #if (AMD64 && TOBESIGNED) #include "sigcheck.h" #endif #ifdef CETC #include "cetc.h" #endif void UnloadDriver(PDRIVER_OBJECT DriverObject); NTSTATUS DispatchCreate(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp); NTSTATUS DispatchClose(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp); #ifndef AMD64 //no api hooks for x64 //-----NtUserSetWindowsHookEx----- //prevent global hooks typedef ULONG (NTUSERSETWINDOWSHOOKEX)( IN HANDLE hmod, IN PUNICODE_STRING pstrLib OPTIONAL, IN DWORD idThread, IN int nFilterType, IN PVOID pfnFilterProc, IN DWORD dwFlags ); NTUSERSETWINDOWSHOOKEX OldNtUserSetWindowsHookEx; ULONG NtUserSetWindowsHookEx_callnumber; //HHOOK NewNtUserSetWindowsHookEx(IN HANDLE hmod,IN PUNICODE_STRING pstrLib OPTIONAL,IN DWORD idThread,IN int nFilterType, IN PROC pfnFilterProc,IN DWORD dwFlags); typedef NTSTATUS (*ZWSUSPENDPROCESS) ( IN ULONG ProcessHandle // Handle to the process ); ZWSUSPENDPROCESS ZwSuspendProcess; NTSTATUS ZwCreateThread( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN HANDLE ProcessHandle, OUT PCLIENT_ID ClientId, IN PCONTEXT ThreadContext, IN PVOID UserStack, IN BOOLEAN CreateSuspended); //PVOID GetApiEntry(ULONG FunctionNumber); #endif typedef NTSTATUS(*PSRCTNR)(__in PCREATE_THREAD_NOTIFY_ROUTINE NotifyRoutine); PSRCTNR PsRemoveCreateThreadNotifyRoutine2; typedef NTSTATUS(*PSRLINR)(__in PLOAD_IMAGE_NOTIFY_ROUTINE NotifyRoutine); PSRLINR PsRemoveLoadImageNotifyRoutine2; UNICODE_STRING uszDeviceString; PVOID BufDeviceString=NULL; void hideme(PDRIVER_OBJECT DriverObject) { #ifndef AMD64 typedef struct _MODULE_ENTRY { LIST_ENTRY le_mod; DWORD unknown[4]; DWORD base; DWORD driver_start; DWORD unk1; UNICODE_STRING driver_Path; UNICODE_STRING driver_Name; } MODULE_ENTRY, *PMODULE_ENTRY; PMODULE_ENTRY pm_current; pm_current = *((PMODULE_ENTRY*)((DWORD)DriverObject + 0x14)); //eeeeew *((PDWORD)pm_current->le_mod.Blink) = (DWORD) pm_current->le_mod.Flink; pm_current->le_mod.Flink->Blink = pm_current->le_mod.Blink; HiddenDriver=TRUE; #endif } int testfunction(int p1,int p2) { DbgPrint("Hello\nParam1=%d\nParam2=%d\n",p1,p2); return 0x666; } void* functionlist[1]; char paramsizes[1]; int registered=0; #ifdef DEBUG1 VOID TestPassive(UINT_PTR param) { DbgPrint("passive cpu call for cpu %d\n", KeGetCurrentProcessorNumber()); } VOID TestDPC(IN struct _KDPC *Dpc, IN PVOID DeferredContext, IN PVOID SystemArgument1, IN PVOID SystemArgument2) { EFLAGS e=getEflags(); DbgPrint("Defered cpu call for cpu %d (Dpc=%p IF=%d IRQL=%d)\n", KeGetCurrentProcessorNumber(), Dpc, e.IF, KeGetCurrentIrql()); } #endif NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath) /*++ Routine Description: This routine is called when the driver is loaded by NT. Arguments: DriverObject - Pointer to driver object created by system. RegistryPath - Pointer to the name of the services node for this driver. Return Value: The function value is the final status from the initialization operation. --*/ { NTSTATUS ntStatus; PVOID BufDriverString = NULL, BufProcessEventString = NULL, BufThreadEventString = NULL; UNICODE_STRING uszDriverString; UNICODE_STRING uszProcessEventString; UNICODE_STRING uszThreadEventString; PDEVICE_OBJECT pDeviceObject; HANDLE reg = 0; OBJECT_ATTRIBUTES oa; UNICODE_STRING temp; char wbuf[100]; WORD this_cs, this_ss, this_ds, this_es, this_fs, this_gs; ULONG cr4reg; criticalSection csTest; HANDLE Ultimap2Handle; KernelCodeStepping = 0; KernelWritesIgnoreWP = 0; this_cs = getCS(); this_ss = getSS(); this_ds = getDS(); this_es = getES(); this_fs = getFS(); this_gs = getGS(); temp.Buffer = (PWCH)wbuf; temp.Length = 0; temp.MaximumLength = 100; //DbgPrint("Loading driver\n"); if (RegistryPath) { //DbgPrint("Registry path = %S\n", RegistryPath->Buffer); InitializeObjectAttributes(&oa, RegistryPath, OBJ_KERNEL_HANDLE, NULL, NULL); ntStatus = ZwOpenKey(&reg, KEY_QUERY_VALUE, &oa); if (ntStatus == STATUS_SUCCESS) { UNICODE_STRING A, B, C, D; PKEY_VALUE_PARTIAL_INFORMATION bufA, bufB, bufC, bufD; ULONG ActualSize; //DbgPrint("Opened the key\n"); BufDriverString = ExAllocatePool(PagedPool, sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 100); BufDeviceString = ExAllocatePool(PagedPool, sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 100); BufProcessEventString = ExAllocatePool(PagedPool, sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 100); BufThreadEventString = ExAllocatePool(PagedPool, sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 100); bufA = BufDriverString; bufB = BufDeviceString; bufC = BufProcessEventString; bufD = BufThreadEventString; RtlInitUnicodeString(&A, L"A"); RtlInitUnicodeString(&B, L"B"); RtlInitUnicodeString(&C, L"C"); RtlInitUnicodeString(&D, L"D"); if (ntStatus == STATUS_SUCCESS) ntStatus = ZwQueryValueKey(reg, &A, KeyValuePartialInformation, bufA, sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 100, &ActualSize); if (ntStatus == STATUS_SUCCESS) ntStatus = ZwQueryValueKey(reg, &B, KeyValuePartialInformation, bufB, sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 100, &ActualSize); if (ntStatus == STATUS_SUCCESS) ntStatus = ZwQueryValueKey(reg, &C, KeyValuePartialInformation, bufC, sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 100, &ActualSize); if (ntStatus == STATUS_SUCCESS) ntStatus = ZwQueryValueKey(reg, &D, KeyValuePartialInformation, bufD, sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 100, &ActualSize); if (ntStatus == STATUS_SUCCESS) { //DbgPrint("Read ok\n"); RtlInitUnicodeString(&uszDriverString, (PCWSTR)bufA->Data); RtlInitUnicodeString(&uszDeviceString, (PCWSTR)bufB->Data); RtlInitUnicodeString(&uszProcessEventString, (PCWSTR)bufC->Data); RtlInitUnicodeString(&uszThreadEventString, (PCWSTR)bufD->Data); //DbgPrint("DriverString=%S\n", uszDriverString.Buffer); //DbgPrint("DeviceString=%S\n", uszDeviceString.Buffer); //DbgPrint("ProcessEventString=%S\n", uszProcessEventString.Buffer); //DbgPrint("ThreadEventString=%S\n", uszThreadEventString.Buffer); } else { ExFreePool(bufA); ExFreePool(bufB); ExFreePool(bufC); ExFreePool(bufD); //DbgPrint("Failed reading the value\n"); ZwClose(reg); return STATUS_UNSUCCESSFUL;; } } else { //DbgPrint("Failed opening the key\n"); return STATUS_UNSUCCESSFUL;; } } else loadedbydbvm = TRUE; ntStatus = STATUS_SUCCESS; if (!loadedbydbvm) { // Point uszDriverString at the driver name #ifndef CETC // Create and initialize device object ntStatus = IoCreateDevice(DriverObject, 0, &uszDriverString, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject); if (ntStatus != STATUS_SUCCESS) { //DbgPrint("IoCreateDevice failed\n"); ExFreePool(BufDriverString); ExFreePool(BufDeviceString); ExFreePool(BufProcessEventString); ExFreePool(BufThreadEventString); if (reg) ZwClose(reg); return ntStatus; } // Point uszDeviceString at the device name // Create symbolic link to the user-visible name ntStatus = IoCreateSymbolicLink(&uszDeviceString, &uszDriverString); if (ntStatus != STATUS_SUCCESS) { //DbgPrint("IoCreateSymbolicLink failed: %x\n", ntStatus); // Delete device object if not successful IoDeleteDevice(pDeviceObject); ExFreePool(BufDriverString); ExFreePool(BufDeviceString); ExFreePool(BufProcessEventString); ExFreePool(BufThreadEventString); if (reg) ZwClose(reg); return ntStatus; } #endif } //when loaded by dbvm driver object is 'valid' so store the function addresses //DbgPrint("DriverObject=%p\n", DriverObject); // Load structure to point to IRP handlers... DriverObject->DriverUnload = UnloadDriver; DriverObject->MajorFunction[IRP_MJ_CREATE] = DispatchCreate; DriverObject->MajorFunction[IRP_MJ_CLOSE] = DispatchClose; if (loadedbydbvm) DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = (PDRIVER_DISPATCH)DispatchIoctlDBVM; else DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchIoctl; //Processlist init #ifndef CETC ProcessEventCount = 0; ExInitializeResourceLite(&ProcesslistR); #endif CreateProcessNotifyRoutineEnabled = FALSE; //threadlist init ThreadEventCount = 0; processlist = NULL; #ifndef AMD64 //determine if PAE is used cr4reg=(ULONG)getCR4(); if ((cr4reg & 0x20)==0x20) { PTESize=8; //pae PAGE_SIZE_LARGE=0x200000; MAX_PDE_POS=0xC0604000; MAX_PTE_POS=0xC07FFFF8; } else { PTESize=4; PAGE_SIZE_LARGE=0x400000; MAX_PDE_POS=0xC0301000; MAX_PTE_POS=0xC03FFFFC; } #else PTESize = 8; //pae PAGE_SIZE_LARGE = 0x200000; //base was 0xfffff68000000000ULL //to MAX_PTE_POS = 0xFFFFF6FFFFFFFFF8ULL; // base + 0x7FFFFFFFF8 MAX_PDE_POS = 0xFFFFF6FB7FFFFFF8ULL; // base + 0x7B7FFFFFF8 #endif #ifdef CETC DbgPrint("Going to initialice CETC\n"); InitializeCETC(); #endif //hideme(DriverObject); //ok, for those that see this, enabling this WILL fuck up try except routines, even in usermode you'll get a blue sreen DbgPrint("Initializing debugger\n"); debugger_initialize(); // Return success (don't do the devicestring, I need it for unload) DbgPrint("Cleaning up initialization buffers\n"); if (BufDriverString) { ExFreePool(BufDriverString); BufDriverString = NULL; } if (BufProcessEventString) { ExFreePool(BufProcessEventString); BufProcessEventString = NULL; } if (BufThreadEventString) { ExFreePool(BufThreadEventString); BufThreadEventString = NULL; } if (reg) { ZwClose(reg); reg = 0; } //fetch cpu info { DWORD r[4]; DWORD a; __cpuid(r, 0); DbgPrint("cpuid.0: r[1]=%x", r[1]); if (r[1] == 0x756e6547) //GenuineIntel { __cpuid(r, 1); a = r[0]; cpu_stepping = a & 0xf; cpu_model = (a >> 4) & 0xf; cpu_familyID = (a >> 8) & 0xf; cpu_type = (a >> 12) & 0x3; cpu_ext_modelID = (a >> 16) & 0xf; cpu_ext_familyID = (a >> 20) & 0xff; cpu_model = cpu_model + (cpu_ext_modelID << 4); cpu_familyID = cpu_familyID + (cpu_ext_familyID << 4); vmx_init_dovmcall(1); setup_APIC_BASE(); //for ultimap } else { DbgPrint("Not an intel cpu"); if (r[1] == 0x68747541) { DbgPrint("This is an AMD\n"); vmx_init_dovmcall(0); } } } #ifdef DEBUG1 { APIC y; DebugStackState x; DbgPrint("offset of LBR_Count=%d\n", (UINT_PTR)&x.LBR_Count - (UINT_PTR)&x); DbgPrint("Testing forEachCpu(...)\n"); forEachCpu(TestDPC, NULL, NULL, NULL, NULL); DbgPrint("Testing forEachCpuAsync(...)\n"); forEachCpuAsync(TestDPC, NULL, NULL, NULL, NULL); DbgPrint("Testing forEachCpuPassive(...)\n"); forEachCpuPassive(TestPassive, 0); DbgPrint("LVT_Performance_Monitor=%x\n", (UINT_PTR)&y.LVT_Performance_Monitor - (UINT_PTR)&y); } #endif #ifdef DEBUG2 DbgPrint("No exceptions test:"); if (NoExceptions_Enter()) { int o = 45678; int x = 0, r = 0; //r=NoExceptions_CopyMemory(&x, &o, sizeof(x)); r = NoExceptions_CopyMemory(&x, (PVOID)0, sizeof(x)); DbgPrint("o=%d x=%d r=%d", o, x, r); DbgPrint("Leaving NoExceptions mode"); NoExceptions_Leave(); } #endif RtlInitUnicodeString(&temp, L"PsSuspendProcess"); PsSuspendProcess = (PSSUSPENDPROCESS)MmGetSystemRoutineAddress(&temp); RtlInitUnicodeString(&temp, L"PsResumeProcess"); PsResumeProcess = (PSSUSPENDPROCESS)MmGetSystemRoutineAddress(&temp); return STATUS_SUCCESS; } NTSTATUS DispatchCreate(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { // Check for SeDebugPrivilege. (So only processes with admin rights can use it) LUID sedebugprivUID; sedebugprivUID.LowPart=SE_DEBUG_PRIVILEGE; sedebugprivUID.HighPart=0; Irp->IoStatus.Status = STATUS_UNSUCCESSFUL; if (SeSinglePrivilegeCheck(sedebugprivUID, UserMode)) { Irp->IoStatus.Status = STATUS_SUCCESS; #ifdef AMD64 #ifdef TOBESIGNED { NTSTATUS s=SecurityCheck(); Irp->IoStatus.Status = s; } // DbgPrint("Returning %x (and %x)\n", Irp->IoStatus.Status, s); #endif #endif } else { DbgPrint("A process without SeDebugPrivilege tried to open the dbk driver\n"); Irp->IoStatus.Status = STATUS_UNSUCCESSFUL; } Irp->IoStatus.Information=0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return Irp->IoStatus.Status; } NTSTATUS DispatchClose(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information=0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return Irp->IoStatus.Status; } void UnloadDriver(PDRIVER_OBJECT DriverObject) { cleanupDBVM(); if (!debugger_stopDebugging()) { DbgPrint("Can not unload the driver because of debugger\n"); return; // } debugger_shutdown(); ultimap_disable(); DisableUltimap2(); UnregisterUltimapPMI(); clean_APIC_BASE(); NoExceptions_Cleanup(); if ((CreateProcessNotifyRoutineEnabled) || (ImageNotifyRoutineLoaded)) { PVOID x; UNICODE_STRING temp; RtlInitUnicodeString(&temp, L"PsRemoveCreateThreadNotifyRoutine"); PsRemoveCreateThreadNotifyRoutine2 = (PSRCTNR)MmGetSystemRoutineAddress(&temp); RtlInitUnicodeString(&temp, L"PsRemoveCreateThreadNotifyRoutine"); PsRemoveLoadImageNotifyRoutine2 = (PSRLINR)MmGetSystemRoutineAddress(&temp); RtlInitUnicodeString(&temp, L"ObOpenObjectByName"); x=MmGetSystemRoutineAddress(&temp); DbgPrint("ObOpenObjectByName=%p\n",x); if ((PsRemoveCreateThreadNotifyRoutine2) && (PsRemoveLoadImageNotifyRoutine2)) { DbgPrint("Stopping processwatch\n"); if (CreateProcessNotifyRoutineEnabled) { DbgPrint("Removing process watch"); #if (NTDDI_VERSION >= NTDDI_VISTASP1) PsSetCreateProcessNotifyRoutineEx(CreateProcessNotifyRoutineEx,TRUE); #else PsSetCreateProcessNotifyRoutine(CreateProcessNotifyRoutine,TRUE); #endif DbgPrint("Removing thread watch"); PsRemoveCreateThreadNotifyRoutine2(CreateThreadNotifyRoutine); } if (ImageNotifyRoutineLoaded) PsRemoveLoadImageNotifyRoutine2(LoadImageNotifyRoutine); } else return; //leave now!!!!! } DbgPrint("Driver unloading\n"); IoDeleteDevice(DriverObject->DeviceObject); #ifdef CETC #ifndef CETC_RELEASE UnloadCETC(); //not possible in the final build #endif #endif #ifndef CETC_RELEASE DbgPrint("DeviceString=%S\n",uszDeviceString.Buffer); { NTSTATUS r = IoDeleteSymbolicLink(&uszDeviceString); DbgPrint("IoDeleteSymbolicLink: %x\n", r); } ExFreePool(BufDeviceString); #endif CleanProcessList(); ExDeleteResourceLite(&ProcesslistR); RtlZeroMemory(&ProcesslistR, sizeof(ProcesslistR)); #if (NTDDI_VERSION >= NTDDI_VISTA) if (DRMHandle) { DbgPrint("Unregistering DRM handle"); ObUnRegisterCallbacks(DRMHandle); DRMHandle = NULL; } #endif } <|start_filename|>src/amd64/vmxoffloada.asm<|end_filename|> ;RCX: 1st integer argument ;RDX: 2nd integer argument ;R8: 3rd integer argument ;R9: 4th integer argument GDTDesc STRUCT Limit WORD ? Base QWORD ? GDTDesc ENDS S_ORIGINALSTATE STRUCT _cpucount QWORD ? _originalEFER QWORD ? _originalLME QWORD ? _idtbase QWORD ? _idtlimit QWORD ? _gdtbase QWORD ? _gdtlimit QWORD ? _cr0 QWORD ? _cr2 QWORD ? _cr3 QWORD ? _cr4 QWORD ? _dr7 QWORD ? _rip QWORD ? _rax QWORD ? _rbx QWORD ? _rcx QWORD ? _rdx QWORD ? _rsi QWORD ? _rdi QWORD ? _rbp QWORD ? _rsp QWORD ? _r8 QWORD ? _r9 QWORD ? _r10 QWORD ? _r11 QWORD ? _r12 QWORD ? _r13 QWORD ? _r14 QWORD ? _r15 QWORD ? _rflags QWORD ? _cs QWORD ? _ss QWORD ? _ds QWORD ? _es QWORD ? _fs QWORD ? _gs QWORD ? _tr QWORD ? _ldt QWORD ? _cs_AccessRights QWORD ? _ss_AccessRights QWORD ? _ds_AccessRights QWORD ? _es_AccessRights QWORD ? _fs_AccessRights QWORD ? _gs_AccessRights QWORD ? _cs_Limit QWORD ? _ss_Limit QWORD ? _ds_Limit QWORD ? _es_Limit QWORD ? _fs_Limit QWORD ? _gs_Limit QWORD ? _fsbase QWORD ? _gsbase QWORD ? S_ORIGINALSTATE ENDS PS_ORIGNALSTATE TYPEDEF PTR S_ORIGINALSTATE EXTERN NewGDTDescriptor: GDTDesc EXTERN NewGDTDescriptorVA: QWORD EXTERN DBVMPML4PA: QWORD EXTERN TemporaryPagingSetupPA: QWORD EXTERN enterVMM2PA: QWORD EXTERN originalstatePA: QWORD EXTERN enterVMM2: QWORD EXTERN originalstate: PS_ORIGNALSTATE EXTERN vmmPA: QWORD _TEXT SEGMENT 'CODE' PUBLIC JTAGBP JTAGBP: db 0f1h ret PUBLIC enterVMM enterVMM: begin: ;switch to identity mapped pagetable mov cr3,rdx jmp short weee weee: nop nop ;now jump to the physical address (identity mapped to the same virtual address) mov rax,secondentry mov r8,enterVMM sub rax,r8 add rax,rsi ;add the physical address to the offset location jmp rax secondentry: ;contrary to the 32-bit setup, we don't disable paging to make the switch to 64-bit, we're already there ;we can just set the CR3 value ;----------TEST---------- ; waitforready: ; mov dx,0ec05h ; in al,dx ; and al,20h ; cmp al,20h ; jne waitforready ; ; mov dx,0ec00h ; mov al,'1' ; out dx,al ;^^^^^^^^TEST^^^^^^^^ ;enable PAE and PSE (just to make sure) mov eax,30h mov cr4,rax mov cr3,rcx nop nop jmp short weee2 weee2: nop nop mov rbx,0 mov ds,bx mov es,bx mov fs,bx mov gs,bx mov ss,bx mov rax,cr0 or eax,10000h mov cr0,rax ;enable WP bit nop nop nop nop ;db 0f1h ;jtag nop nop nop jmp fword ptr [vmmjump] ;jmp fword ptr [vmmjump] ;one thing that I don't mind about x64, relative addressing, so no need to change it by me extrastorage: nop nop nop nop nop vmmjump: dd 00400000h dw 50h detectionstring: db 0ceh db 0ceh db 0ceh db 0ceh db 0ceh db 0ceh db 0ceh PUBLIC enterVMMPrologue enterVMMPrologue: cli ;goodbye interrupts push rbx mov rbx,originalstate mov (S_ORIGINALSTATE PTR [rbx])._rax,rax pop rbx mov rax,originalstate mov (S_ORIGINALSTATE PTR [rax])._rbx,rbx mov (S_ORIGINALSTATE PTR [rax])._rcx,rcx mov (S_ORIGINALSTATE PTR [rax])._rdx,rdx mov (S_ORIGINALSTATE PTR [rax])._rsi,rsi mov (S_ORIGINALSTATE PTR [rax])._rdi,rdi mov (S_ORIGINALSTATE PTR [rax])._rbp,rbp mov (S_ORIGINALSTATE PTR [rax])._rsp,rsp mov (S_ORIGINALSTATE PTR [rax])._r8,r8 mov (S_ORIGINALSTATE PTR [rax])._r9,r9 mov (S_ORIGINALSTATE PTR [rax])._r10,r10 mov (S_ORIGINALSTATE PTR [rax])._r11,r11 mov (S_ORIGINALSTATE PTR [rax])._r12,r12 mov (S_ORIGINALSTATE PTR [rax])._r13,r13 mov (S_ORIGINALSTATE PTR [rax])._r14,r14 mov (S_ORIGINALSTATE PTR [rax])._r15,r15 mov rbx,enterVMMEpilogue mov (S_ORIGINALSTATE PTR [rax])._rip,rbx ;jmp enterVMMEpilogue ;test to see if the loader is bugged ;still here, loader didn't crash, start executing the move to the dbvm environment xchg bx,bx ;bochs break mov rbx,NewGDTDescriptorVA lgdt fword ptr [rbx] mov rcx,DBVMPML4PA mov rdx,TemporaryPagingSetupPA mov rsi,enterVMM2PA jmp [enterVMM2] PUBLIC enterVMMEpilogue enterVMMEpilogue: nop nop push rax push rbx push rcx push rdx cpuid pop rdx pop rcx pop rbx pop rax nop nop nop mov r8,originalstate ;mov rbx,(S_ORIGINALSTATE PTR [r8])._tr ;ltr bx mov rbx,(S_ORIGINALSTATE PTR [r8])._ss mov ss,bx mov rbx,(S_ORIGINALSTATE PTR [r8])._ds mov ds,bx mov rbx,(S_ORIGINALSTATE PTR [r8])._es mov es,bx mov rbx,(S_ORIGINALSTATE PTR [r8])._fs mov fs,bx mov rbx,(S_ORIGINALSTATE PTR [r8])._gs mov gs,bx mov rcx,0c0000100h mov rax,(S_ORIGINALSTATE PTR [r8])._fsbase mov rdx,rax shr rdx,32 wrmsr mov rcx,0c0000101h mov rax,(S_ORIGINALSTATE PTR [r8])._gsbase mov rdx,rax shr rdx,32 wrmsr mov rax,originalstate mov rbx,(S_ORIGINALSTATE PTR [rax])._rbx mov rcx,(S_ORIGINALSTATE PTR [rax])._rcx mov rdx,(S_ORIGINALSTATE PTR [rax])._rdx mov rsi,(S_ORIGINALSTATE PTR [rax])._rsi mov rdi,(S_ORIGINALSTATE PTR [rax])._rdi mov rbp,(S_ORIGINALSTATE PTR [rax])._rbp mov rsp,(S_ORIGINALSTATE PTR [rax])._rsp mov r8,(S_ORIGINALSTATE PTR [rax])._r8 mov r9,(S_ORIGINALSTATE PTR [rax])._r9 mov r10,(S_ORIGINALSTATE PTR [rax])._r10 mov r11,(S_ORIGINALSTATE PTR [rax])._r11 mov r12,(S_ORIGINALSTATE PTR [rax])._r12 mov r13,(S_ORIGINALSTATE PTR [rax])._r13 mov r14,(S_ORIGINALSTATE PTR [rax])._r14 mov r15,(S_ORIGINALSTATE PTR [rax])._r15 mov rax,(S_ORIGINALSTATE PTR [rax])._rax ;crashtest ;mov rax,0deadh ;mov [rax],rax ;sti ret nop nop nop _TEXT ENDS END <|start_filename|>src/ultimap2.h<|end_filename|> #ifndef ULTIMAP2_H #define ULTIMAP2_H #include <ntifs.h> //MSR's #define IA32_PERF_GLOBAL_STATUS 0x38e #define IA32_PERF_GLOBAL_OVF_CTRL 0x390 #define IA32_RTIT_CTL 0x570 #define IA32_RTIT_STATUS 0x571 #define IA32_RTIT_CR3_MATCH 0x572 #define IA32_RTIT_OUTPUT_BASE 0x560 #define IA32_RTIT_OUTPUT_MASK_PTRS 0x561 #define IA32_RTIT_ADDR0_A 0x580 #define IA32_RTIT_ADDR0_B 0x581 #define IA32_RTIT_ADDR1_A 0x582 #define IA32_RTIT_ADDR1_B 0x583 #define IA32_RTIT_ADDR2_A 0x584 #define IA32_RTIT_ADDR2_B 0x585 #define IA32_RTIT_ADDR3_A 0x586 #define IA32_RTIT_ADDR3_B 0x587 typedef struct { UINT64 StartAddress; UINT64 EndAddress; UINT64 IsStopAddress; } URANGE, *PURANGE; #pragma pack(push) #pragma pack(1) typedef union { struct{ ULONG TraceEn : 1; //0 ULONG Reserved_0 : 1; //1 ULONG OS : 1; //2 ULONG USER : 1; //3 ULONG Reserved_1 : 2; //4,5 ULONG FabricEn : 1; //6 ULONG CR3Filter : 1; //7 ULONG ToPA : 1; //8 ULONG MTCEn : 1; //9 ULONG TSCEn : 1; //10 ULONG DisRETC : 1; //11 ULONG Reserved_2 : 1; //12 ULONG BranchEn : 1; //13 ULONG MTCFreq : 4; //14,15,16,17 ULONG Reserved_3 : 1; //18 ULONG CycThresh : 4; //19,20,21,22 ULONG Reserved_4 : 1; //32 ULONG PSBFreq : 4; //24,25,26,27 ULONG Reserved_5 : 4; //28,29,30,31 ULONG ADDR0_CFG : 4; ULONG ADDR1_CFG : 4; ULONG ADDR2_CFG : 4; ULONG ADDR3_CFG : 4; ULONG Reserved_6 : 16; } Bits; UINT64 Value; } RTIT_CTL, *PRTIT_CTL; typedef union { struct{ UINT64 FilterEn : 1; UINT64 ContextEn : 1; UINT64 TriggerEn : 1; UINT64 Reserved_1 : 1; UINT64 Error : 1; UINT64 Stopped : 1; UINT64 Reserved_2 : 58; } Bits; UINT64 Value; } RTIT_STATUS, *PRTIT_STATUS; typedef union { struct{ UINT64 END : 1; UINT64 Reserved_0 : 1; UINT64 INT : 1; UINT64 Reserved_1 : 1; UINT64 STOP : 1; UINT64 Reserved_2 : 1; UINT64 Size : 4; UINT64 Reserved_3 : 2; UINT64 PhysicalFrameNr : 52; } Bits; UINT64 Value; } ToPA_ENTRY, *PToPA_ENTRY; typedef struct{ UINT64 PhysicalAddress; int index; } ToPA_LOOKUP, *PToPA_LOOKUP; typedef struct { UINT64 Address; UINT64 Size; UINT64 CpuID; } ULTIMAP2DATAEVENT, *PULTIMAP2DATAEVENT; #pragma pack(pop) void SetupUltimap2(UINT32 PID, UINT32 BufferSize, WCHAR *Path, int rangeCount, PURANGE Ranges, int NoPMI, int UserMode, int KernelMode); void DisableUltimap2(void); NTSTATUS ultimap2_waitForData(ULONG timeout, PULTIMAP2DATAEVENT data); NTSTATUS ultimap2_continue(int cpunr); NTSTATUS ultimap2_flushBuffers(); NTSTATUS ultimap2_pause(); NTSTATUS ultimap2_resume(); void ultimap2_LockFile(int cpunr); void ultimap2_ReleaseFile(int cpunr); UINT64 ultimap2_GetTraceFileSize(); void ultimap2_ResetTraceFileSize(); void UnregisterUltimapPMI(); typedef NTSTATUS(*PSSUSPENDPROCESS)(PEPROCESS p); extern PSSUSPENDPROCESS PsSuspendProcess; extern PSSUSPENDPROCESS PsResumeProcess; #endif
dmarov/chamd
<|start_filename|>test/unit/multi-input/child-4.js<|end_filename|> const fs = require('fs') const { join } = require('path') fs.readFileSync(join(__dirname, 'style.module.css')) <|start_filename|>test/unit/multi-input/input-4.js<|end_filename|> import style from './style.module.css'; import child4 from './child-4'; <|start_filename|>test/unit/pixelmatch/output.js<|end_filename|> [ "node_modules/pixelmatch/bin/pixelmatch", "node_modules/pixelmatch/index.js", "node_modules/pixelmatch/node_modules/pngjs/lib/bitmapper.js", "node_modules/pixelmatch/node_modules/pngjs/lib/bitpacker.js", "node_modules/pixelmatch/node_modules/pngjs/lib/chunkstream.js", "node_modules/pixelmatch/node_modules/pngjs/lib/constants.js", "node_modules/pixelmatch/node_modules/pngjs/lib/crc.js", "node_modules/pixelmatch/node_modules/pngjs/lib/filter-pack.js", "node_modules/pixelmatch/node_modules/pngjs/lib/filter-parse-async.js", "node_modules/pixelmatch/node_modules/pngjs/lib/filter-parse-sync.js", "node_modules/pixelmatch/node_modules/pngjs/lib/filter-parse.js", "node_modules/pixelmatch/node_modules/pngjs/lib/format-normaliser.js", "node_modules/pixelmatch/node_modules/pngjs/lib/interlace.js", "node_modules/pixelmatch/node_modules/pngjs/lib/packer-async.js", "node_modules/pixelmatch/node_modules/pngjs/lib/packer-sync.js", "node_modules/pixelmatch/node_modules/pngjs/lib/packer.js", "node_modules/pixelmatch/node_modules/pngjs/lib/paeth-predictor.js", "node_modules/pixelmatch/node_modules/pngjs/lib/parser-async.js", "node_modules/pixelmatch/node_modules/pngjs/lib/parser-sync.js", "node_modules/pixelmatch/node_modules/pngjs/lib/parser.js", "node_modules/pixelmatch/node_modules/pngjs/lib/png-sync.js", "node_modules/pixelmatch/node_modules/pngjs/lib/png.js", "node_modules/pixelmatch/node_modules/pngjs/lib/sync-inflate.js", "node_modules/pixelmatch/node_modules/pngjs/lib/sync-reader.js", "node_modules/pixelmatch/node_modules/pngjs/package.json", "node_modules/pixelmatch/package.json", "package.json", "test/unit/pixelmatch/input.js" ] <|start_filename|>test/unit.test.js<|end_filename|> const fs = require('fs'); const { join, relative } = require('path'); const { nodeFileTrace } = require('../out/node-file-trace'); global._unit = true; const skipOnWindows = ['yarn-workspaces', 'yarn-workspaces-base-root', 'yarn-workspace-esm', 'asset-symlink', 'require-symlink']; const unitTestDirs = fs.readdirSync(join(__dirname, 'unit')); const unitTests = [ ...unitTestDirs.map(testName => ({testName, isRoot: false})), ...unitTestDirs.map(testName => ({testName, isRoot: true})), ]; for (const { testName, isRoot } of unitTests) { const testSuffix = `${testName} from ${isRoot ? 'root' : 'cwd'}`; if (process.platform === 'win32' && (isRoot || skipOnWindows.includes(testName))) { console.log(`Skipping unit test on Windows: ${testSuffix}`); continue; }; const unitPath = join(__dirname, 'unit', testName); it(`should correctly trace ${testSuffix}`, async () => { // We mock readFile because when node-file-trace is integrated into @now/node // this is the hook that triggers TypeScript compilation. So if this doesn't // get called, the TypeScript files won't get compiled: Currently this is only // used in the tsx-input test: const readFileMock = jest.fn(function() { const [id] = arguments; if (id.startsWith('custom-resolution-')) { return '' } // ensure sync readFile works as expected since default is // async now if (testName === 'wildcard') { try { return fs.readFileSync(id).toString() } catch (err) { return null } } return this.constructor.prototype.readFile.apply(this, arguments); }); const nftCache = {} const doTrace = async (cached = false) => { let inputFileNames = ["input.js"]; let outputFileName = "output.js"; if (testName === "tsx-input") { inputFileNames = ["input.tsx"]; } if (testName === "processed-dependency" && cached) { inputFileNames = ["input-cached.js"] outputFileName = "output-cached.js" } if (testName === 'multi-input') { inputFileNames.push('input-2.js', 'input-3.js', 'input-4.js'); } const { fileList, reasons } = await nodeFileTrace( inputFileNames.map(file => join(unitPath, file)), { base: isRoot ? '/' : `${__dirname}/../`, processCwd: unitPath, paths: { dep: `${__dirname}/../test/unit/esm-paths/esm-dep.js`, 'dep/': `${__dirname}/../test/unit/esm-paths-trailer/` }, cache: nftCache, exportsOnly: testName.startsWith('exports-only'), ts: true, log: true, // disable analysis for basic-analysis unit tests analysis: !testName.startsWith('basic-analysis'), mixedModules: true, // Ignore unit test output "actual.js", and ignore GitHub Actions preinstalled packages ignore: (str) => str.endsWith('/actual.js') || str.startsWith('usr/local'), readFile: readFileMock, resolve: testName.startsWith('resolve-hook') ? (id, parent) => `custom-resolution-${id}` : undefined, } ); if (testName === 'multi-input') { const collectFiles = (parent, files = new Set()) => { fileList.forEach(file => { if (files.has(file)) return const reason = reasons.get(file) if (reason.parents && reason.parents.has(parent)) { files.add(file) collectFiles(file, files) } }) return files } const normalizeFilesRoot = file => (isRoot ? relative(join('./', __dirname, '..'), file) : file).replace(/\\/g, '/') const normalizeInputRoot = file => isRoot ? join('./', unitPath, file) : join('test/unit', testName, file) const getReasonType = file => reasons.get(normalizeInputRoot(file)).type expect([...collectFiles(normalizeInputRoot('input.js'))].map(normalizeFilesRoot).sort()).toEqual([ "package.json", "test/unit/multi-input/asset-2.txt", "test/unit/multi-input/asset.txt", "test/unit/multi-input/child-1.js", "test/unit/multi-input/child-2.js", "test/unit/multi-input/input-2.js", ]) expect([...collectFiles(normalizeInputRoot('input-2.js'))].map(normalizeFilesRoot).sort()).toEqual([ "package.json", "test/unit/multi-input/asset-2.txt", "test/unit/multi-input/asset.txt", "test/unit/multi-input/child-1.js", "test/unit/multi-input/child-2.js", "test/unit/multi-input/input-2.js", ]) expect([...collectFiles(normalizeInputRoot('input-3.js'))].map(normalizeFilesRoot).sort()).toEqual([ "package.json", "test/unit/multi-input/asset.txt", "test/unit/multi-input/child-3.js", ]) expect([...collectFiles(normalizeInputRoot('input-4.js'))].map(normalizeFilesRoot).sort()).toEqual([ "package.json", "test/unit/multi-input/child-4.js", "test/unit/multi-input/style.module.css", ]) expect(getReasonType('input.js')).toEqual(['initial', 'dependency']) expect(getReasonType('input-2.js')).toEqual(['initial', 'dependency']) expect(getReasonType('input-3.js')).toEqual(['initial', 'dependency']) expect(getReasonType('input-4.js')).toEqual(['initial', 'dependency']) expect(getReasonType('child-1.js')).toEqual(['dependency']) expect(getReasonType('child-2.js')).toEqual(['dependency']) expect(getReasonType('child-3.js')).toEqual(['dependency']) expect(getReasonType('child-4.js')).toEqual(['dependency']) expect(getReasonType('asset.txt')).toEqual(['asset']) expect(getReasonType('asset-2.txt')).toEqual(['asset']) expect(getReasonType('style.module.css')).toEqual(['dependency', 'asset']) } let expected; try { expected = JSON.parse(fs.readFileSync(join(unitPath, outputFileName)).toString()); if (process.platform === 'win32') { // When using Windows, the expected output should use backslash expected = expected.map(str => str.replace(/\//g, '\\')); } if (isRoot) { // We set `base: "/"` but we can't hardcode an absolute path because // CI will look different than a local machine so we fix the path here. expected = expected.map(str => join(__dirname, '..', str).slice(1)); } } catch (e) { console.warn(e); expected = []; } try { expect([...fileList].sort()).toEqual(expected); } catch (e) { console.warn(reasons); fs.writeFileSync(join(unitPath, 'actual.js'), JSON.stringify([...fileList].sort(), null, 2)); throw e; } } await doTrace() // test tracing again with a populated nftTrace expect(nftCache.fileCache).toBeDefined() expect(nftCache.statCache).toBeDefined() expect(nftCache.symlinkCache).toBeDefined() expect(nftCache.analysisCache).toBeDefined() await doTrace(true) if (testName === "tsx-input") { expect(readFileMock.mock.calls.length).toBe(2); } }); } <|start_filename|>test/unit/pixelmatch/input.js<|end_filename|> const pixelmatch = require('pixelmatch'); pixelmatch(new Uint8Array(), new Uint8Array(), null, 0, 0); <|start_filename|>test/cli.test.js<|end_filename|> const { promisify } = require('util'); const { existsSync } = require('fs'); const { join } = require('path'); const cp = require('child_process'); const exec = promisify(cp.exec); jest.setTimeout(15_000); const inputjs = 'unit/wildcard/input.js'; const outputjs = 'unit/wildcard/assets/asset1.txt'; function normalizeOutput(output) { if (process.platform === 'win32') { // When using Windows, the expected output should use backslash output = output.replace(/\//g, '\\'); } return output; } it('should correctly print trace from cli', async () => { const { stderr, stdout } = await exec(`node ../out/cli.js print ${inputjs}`, { cwd: __dirname }); if (stderr) { throw new Error(stderr); } expect(stdout).toMatch(normalizeOutput(outputjs)); }); it('should correctly build dist from cli', async () => { const { stderr } = await exec(`node ../out/cli.js build ${inputjs}`, { cwd: __dirname }); if (stderr) { throw new Error(stderr); } const found = existsSync(join(__dirname, outputjs)); expect(found).toBe(true); }); it('should correctly show size from cli', async () => { const { stderr, stdout } = await exec(`node ../out/cli.js size ${inputjs}`, { cwd: __dirname }); if (stderr) { throw new Error(stderr); } expect(stdout).toMatch('bytes total'); }); it('should correctly show why from cli', async () => { const { stderr, stdout } = await exec(`node ../out/cli.js why ${inputjs} ${outputjs}`, { cwd: __dirname }); if (stderr) { throw new Error(stderr); } expect(stdout.replace(/\\/g, '/')).toMatch('unit/wildcard/assets/asset1.txt\nunit/wildcard/input.js'); }); it('should correctly print help when unknown action is used', async () => { const { stderr, stdout } = await exec(`node ../out/cli.js unknown ${inputjs}`, { cwd: __dirname }); if (stderr) { throw new Error(stderr); } expect(stdout).toMatch('$ nft [command] <file>'); }); it('[codecov] should correctly print trace from required cli', async () => { // This test is only here to satisfy code coverage const cli = require('../out/cli.js') const files = join(__dirname, inputjs); const stdout = await cli('print', files); expect(stdout).toMatch(normalizeOutput(outputjs)); }); it('[codecov] should correctly build dist from required cli', async () => { // This test is only here to satisfy code coverage const cli = require('../out/cli.js') const files = join(__dirname, inputjs); await cli('build', files); const found = existsSync(join(__dirname, outputjs)); expect(found).toBe(true); }); it('[codecov] should correctly show size in bytes from required cli', async () => { // This test is only here to satisfy code coverage const cli = require('../out/cli.js') const files = join(__dirname, inputjs); const stdout = await cli('size', files); expect(stdout).toMatch('bytes total'); }); it('[codecov] should correctly show why from required cli', async () => { // This test is only here to satisfy code coverage const cli = require('../out/cli.js') const entrypoint = join(__dirname, inputjs); const exitpoint = join(__dirname, outputjs); const cwd = __dirname; const stdout = await cli('why', entrypoint, exitpoint, 'dist', cwd); expect(stdout.replace(/\\/g, '/')).toMatch('unit/wildcard/assets/asset1.txt\nunit/wildcard/input.js'); }); it('[codecov] should correctly print help when unknown action is used', async () => { // This test is only here to satisfy code coverage const cli = require('../out/cli.js') const files = join(__dirname, inputjs); const stdout = await cli('unknown', files); expect(stdout).toMatch('$ nft [command] <file>'); });
vercel/node-file-trace
<|start_filename|>Code/BBearEditor/Engine/Render/Lighting/GameObject/BBSpotLight.cpp<|end_filename|> #include "BBSpotLight.h" #include "3D/BBLightIndicator.h" BBSpotLight::BBSpotLight(BBScene *pScene) : BBSpotLight(pScene, QVector3D(0, 0, 0), QVector3D(0, 0, 0)) { } BBSpotLight::BBSpotLight(BBScene *pScene, const QVector3D &position, const QVector3D &rotation) : BBPointLight(pScene, position, rotation) { m_eType = Spot; m_pIndicator = new BBSpotLightIndicator(position, rotation); // Mark as spot light m_Setting0[0] = 2.0f; // m_Setting0[1] : Intensity setIntensity(4.0f); // m_Setting0[2] : Angle setAngle(30.0f); // m_Setting0[3] : Level setLevel(48.0f); // m_Setting1[0] : radius setRadius(5.0f); // m_Setting1[1] : constant factor // m_Setting1[2] : linear factor // m_Setting1[3] : quadric factor // The light shines downward // m_Setting2 setDirection(); } void BBSpotLight::setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform) { BBLight::setRotation(nAngle, axis, bUpdateLocalTransform); setDirection(); } void BBSpotLight::setRotation(const QVector3D &rotation, bool bUpdateLocalTransform) { BBLight::setRotation(rotation, bUpdateLocalTransform); setDirection(); } bool BBSpotLight::cull(BBCamera *pCamera, const QRectF &displayBox) { } bool BBSpotLight::cull(BBCamera *pCamera, int nFrustumIndexX, int nFrustumIndexY) { } void BBSpotLight::setDirection() { QVector3D dir = m_Quaternion * QVector3D(0.0f, -1.0f, 0.0f); m_Setting2[0] = dir.x(); m_Setting2[1] = dir.y(); m_Setting2[2] = dir.z(); m_Setting2[3] = 1.0f; } <|start_filename|>Resources/shaders/Shadow/VSM_ScreenQuad.frag<|end_filename|> #version 430 core in vec2 v2f_texcoord; out vec4 FragColor; uniform sampler2D AlbedoAndMetallicTex; uniform sampler2D NormalAndDoubleRoughnessTex; uniform sampler2D PositionTex; uniform sampler2D BBShadowMap; uniform vec4 BBCameraParameters; uniform mat4 BBViewMatrix; uniform mat4 BBViewMatrix_I; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; uniform mat4 BBLightProjectionMatrix; uniform mat4 BBLightViewMatrix; float linearizeDepth(float depth) { float z_near = BBCameraParameters.z; float z_far = BBCameraParameters.w; float z = depth * 2.0 - 1.0; return (2.0 * z_near * z_far) / (z_far + z_near - z * (z_far - z_near)); } void main(void) { vec3 albedo = texture(AlbedoAndMetallicTex, v2f_texcoord).rgb; vec3 normal = texture(NormalAndDoubleRoughnessTex, v2f_texcoord).xyz; vec4 world_space_pos = texture(PositionTex, v2f_texcoord); if ((abs(normal.x) < 0.0001f) && (abs(normal.y) < 0.0001f) && (abs(normal.z) < 0.0001f)) { FragColor = vec4(0.0, 0.0, 0.0, 1.0); } normal = normalize(normal); vec4 light_space_pos = BBLightProjectionMatrix * BBLightViewMatrix * world_space_pos; // light_space_pos.xyz /= 10.0; // 0~1 light_space_pos.xyz = light_space_pos.xyz * vec3(0.5f) + vec3(0.5f); float current_depth = light_space_pos.z; // the position of directional light is dir vec3 view_space_light_dir = normalize(vec3(BBViewMatrix * BBLightPosition)); // get mean, E, by mipmap vec2 E = textureLod(BBShadowMap, light_space_pos.xy, 2).rg; // E(d) float Ed = E.x; // E(d^2) float Ed2 = E.y; float variance = Ed2 - Ed * Ed; float visibility = 0.0f; if (current_depth - 0.0001 < Ed) { visibility = 1.0f; } else { visibility = variance / (variance + pow(current_depth - Ed, 2.0f)); } float final_color = max(dot(view_space_light_dir, normal), 0.0) * visibility; FragColor = vec4(albedo * final_color, 1.0); } <|start_filename|>Code/BBearEditor/Engine/Serializer/BBVector.pb.cc<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBVector.proto #include "BBVector.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace BBSerializer { constexpr BBVector2f::BBVector2f( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : x_(0) , y_(0){} struct BBVector2fDefaultTypeInternal { constexpr BBVector2fDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBVector2fDefaultTypeInternal() {} union { BBVector2f _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBVector2fDefaultTypeInternal _BBVector2f_default_instance_; constexpr BBVector2i::BBVector2i( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : x_(0) , y_(0){} struct BBVector2iDefaultTypeInternal { constexpr BBVector2iDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBVector2iDefaultTypeInternal() {} union { BBVector2i _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBVector2iDefaultTypeInternal _BBVector2i_default_instance_; constexpr BBVector3f::BBVector3f( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : x_(0) , y_(0) , z_(0){} struct BBVector3fDefaultTypeInternal { constexpr BBVector3fDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBVector3fDefaultTypeInternal() {} union { BBVector3f _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBVector3fDefaultTypeInternal _BBVector3f_default_instance_; constexpr BBVector3i::BBVector3i( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : x_(0) , y_(0) , z_(0){} struct BBVector3iDefaultTypeInternal { constexpr BBVector3iDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBVector3iDefaultTypeInternal() {} union { BBVector3i _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBVector3iDefaultTypeInternal _BBVector3i_default_instance_; constexpr BBVector4f::BBVector4f( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : x_(0) , y_(0) , z_(0) , w_(0){} struct BBVector4fDefaultTypeInternal { constexpr BBVector4fDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBVector4fDefaultTypeInternal() {} union { BBVector4f _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBVector4fDefaultTypeInternal _BBVector4f_default_instance_; constexpr BBVector4i::BBVector4i( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : x_(0) , y_(0) , z_(0) , w_(0){} struct BBVector4iDefaultTypeInternal { constexpr BBVector4iDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBVector4iDefaultTypeInternal() {} union { BBVector4i _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBVector4iDefaultTypeInternal _BBVector4i_default_instance_; constexpr BBMatrix4f::BBMatrix4f( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : data_(){} struct BBMatrix4fDefaultTypeInternal { constexpr BBMatrix4fDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBMatrix4fDefaultTypeInternal() {} union { BBMatrix4f _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBMatrix4fDefaultTypeInternal _BBMatrix4f_default_instance_; constexpr BBMatrix4fB::BBMatrix4fB( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : data_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string){} struct BBMatrix4fBDefaultTypeInternal { constexpr BBMatrix4fBDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBMatrix4fBDefaultTypeInternal() {} union { BBMatrix4fB _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBMatrix4fBDefaultTypeInternal _BBMatrix4fB_default_instance_; } // namespace BBSerializer static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_BBVector_2eproto[8]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_BBVector_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_BBVector_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_BBVector_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector2f, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector2f, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector2f, x_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector2f, y_), 0, 1, PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector2i, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector2i, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector2i, x_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector2i, y_), 0, 1, PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector3f, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector3f, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector3f, x_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector3f, y_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector3f, z_), 0, 1, 2, PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector3i, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector3i, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector3i, x_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector3i, y_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector3i, z_), 0, 1, 2, PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4f, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4f, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4f, x_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4f, y_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4f, z_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4f, w_), 0, 1, 2, 3, PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4i, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4i, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4i, x_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4i, y_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4i, z_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBVector4i, w_), 0, 1, 2, 3, ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMatrix4f, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMatrix4f, data_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMatrix4fB, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMatrix4fB, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMatrix4fB, data_), 0, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 7, sizeof(::BBSerializer::BBVector2f)}, { 9, 16, sizeof(::BBSerializer::BBVector2i)}, { 18, 26, sizeof(::BBSerializer::BBVector3f)}, { 29, 37, sizeof(::BBSerializer::BBVector3i)}, { 40, 49, sizeof(::BBSerializer::BBVector4f)}, { 53, 62, sizeof(::BBSerializer::BBVector4i)}, { 66, -1, sizeof(::BBSerializer::BBMatrix4f)}, { 72, 78, sizeof(::BBSerializer::BBMatrix4fB)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBVector2f_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBVector2i_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBVector3f_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBVector3i_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBVector4f_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBVector4i_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBMatrix4f_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBMatrix4fB_default_instance_), }; const char descriptor_table_protodef_BBVector_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\016BBVector.proto\022\014BBSerializer\"8\n\nBBVect" "or2f\022\016\n\001x\030\001 \001(\002H\000\210\001\001\022\016\n\001y\030\002 \001(\002H\001\210\001\001B\004\n\002" "_xB\004\n\002_y\"8\n\nBBVector2i\022\016\n\001x\030\001 \001(\005H\000\210\001\001\022\016" "\n\001y\030\002 \001(\005H\001\210\001\001B\004\n\002_xB\004\n\002_y\"N\n\nBBVector3f" "\022\016\n\001x\030\001 \001(\002H\000\210\001\001\022\016\n\001y\030\002 \001(\002H\001\210\001\001\022\016\n\001z\030\003 " "\001(\002H\002\210\001\001B\004\n\002_xB\004\n\002_yB\004\n\002_z\"N\n\nBBVector3i" "\022\016\n\001x\030\001 \001(\005H\000\210\001\001\022\016\n\001y\030\002 \001(\005H\001\210\001\001\022\016\n\001z\030\003 " "\001(\005H\002\210\001\001B\004\n\002_xB\004\n\002_yB\004\n\002_z\"d\n\nBBVector4f" "\022\016\n\001x\030\001 \001(\002H\000\210\001\001\022\016\n\001y\030\002 \001(\002H\001\210\001\001\022\016\n\001z\030\003 " "\001(\002H\002\210\001\001\022\016\n\001w\030\004 \001(\002H\003\210\001\001B\004\n\002_xB\004\n\002_yB\004\n\002" "_zB\004\n\002_w\"d\n\nBBVector4i\022\016\n\001x\030\001 \001(\005H\000\210\001\001\022\016" "\n\001y\030\002 \001(\005H\001\210\001\001\022\016\n\001z\030\003 \001(\005H\002\210\001\001\022\016\n\001w\030\004 \001(" "\005H\003\210\001\001B\004\n\002_xB\004\n\002_yB\004\n\002_zB\004\n\002_w\"\032\n\nBBMatr" "ix4f\022\014\n\004data\030\001 \003(\002\")\n\013BBMatrix4fB\022\021\n\004dat" "a\030\001 \001(\014H\000\210\001\001B\007\n\005_datab\006proto3" ; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_BBVector_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBVector_2eproto = { false, false, 589, descriptor_table_protodef_BBVector_2eproto, "BBVector.proto", &descriptor_table_BBVector_2eproto_once, nullptr, 0, 8, schemas, file_default_instances, TableStruct_BBVector_2eproto::offsets, file_level_metadata_BBVector_2eproto, file_level_enum_descriptors_BBVector_2eproto, file_level_service_descriptors_BBVector_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_BBVector_2eproto_getter() { return &descriptor_table_BBVector_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_BBVector_2eproto(&descriptor_table_BBVector_2eproto); namespace BBSerializer { // =================================================================== class BBVector2f::_Internal { public: using HasBits = decltype(std::declval<BBVector2f>()._has_bits_); static void set_has_x(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_y(HasBits* has_bits) { (*has_bits)[0] |= 2u; } }; BBVector2f::BBVector2f(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBVector2f) } BBVector2f::BBVector2f(const BBVector2f& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&x_, &from.x_, static_cast<size_t>(reinterpret_cast<char*>(&y_) - reinterpret_cast<char*>(&x_)) + sizeof(y_)); // @@protoc_insertion_point(copy_constructor:BBSerializer.BBVector2f) } void BBVector2f::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&x_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&y_) - reinterpret_cast<char*>(&x_)) + sizeof(y_)); } BBVector2f::~BBVector2f() { // @@protoc_insertion_point(destructor:BBSerializer.BBVector2f) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBVector2f::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void BBVector2f::ArenaDtor(void* object) { BBVector2f* _this = reinterpret_cast< BBVector2f* >(object); (void)_this; } void BBVector2f::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBVector2f::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBVector2f::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBVector2f) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { ::memset(&x_, 0, static_cast<size_t>( reinterpret_cast<char*>(&y_) - reinterpret_cast<char*>(&x_)) + sizeof(y_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBVector2f::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // float x = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 13)) { _Internal::set_has_x(&has_bits); x_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); ptr += sizeof(float); } else goto handle_unusual; continue; // float y = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 21)) { _Internal::set_has_y(&has_bits); y_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); ptr += sizeof(float); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBVector2f::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBVector2f) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // float x = 1; if (_internal_has_x()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(1, this->_internal_x(), target); } // float y = 2; if (_internal_has_y()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(2, this->_internal_y(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBVector2f) return target; } size_t BBVector2f::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBVector2f) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { // float x = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + 4; } // float y = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + 4; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBVector2f::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBVector2f) GOOGLE_DCHECK_NE(&from, this); const BBVector2f* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBVector2f>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBVector2f) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBVector2f) MergeFrom(*source); } } void BBVector2f::MergeFrom(const BBVector2f& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBVector2f) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { x_ = from.x_; } if (cached_has_bits & 0x00000002u) { y_ = from.y_; } _has_bits_[0] |= cached_has_bits; } } void BBVector2f::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBVector2f) if (&from == this) return; Clear(); MergeFrom(from); } void BBVector2f::CopyFrom(const BBVector2f& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBVector2f) if (&from == this) return; Clear(); MergeFrom(from); } bool BBVector2f::IsInitialized() const { return true; } void BBVector2f::InternalSwap(BBVector2f* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(BBVector2f, y_) + sizeof(BBVector2f::y_) - PROTOBUF_FIELD_OFFSET(BBVector2f, x_)>( reinterpret_cast<char*>(&x_), reinterpret_cast<char*>(&other->x_)); } ::PROTOBUF_NAMESPACE_ID::Metadata BBVector2f::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBVector_2eproto_getter, &descriptor_table_BBVector_2eproto_once, file_level_metadata_BBVector_2eproto[0]); } // =================================================================== class BBVector2i::_Internal { public: using HasBits = decltype(std::declval<BBVector2i>()._has_bits_); static void set_has_x(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_y(HasBits* has_bits) { (*has_bits)[0] |= 2u; } }; BBVector2i::BBVector2i(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBVector2i) } BBVector2i::BBVector2i(const BBVector2i& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&x_, &from.x_, static_cast<size_t>(reinterpret_cast<char*>(&y_) - reinterpret_cast<char*>(&x_)) + sizeof(y_)); // @@protoc_insertion_point(copy_constructor:BBSerializer.BBVector2i) } void BBVector2i::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&x_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&y_) - reinterpret_cast<char*>(&x_)) + sizeof(y_)); } BBVector2i::~BBVector2i() { // @@protoc_insertion_point(destructor:BBSerializer.BBVector2i) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBVector2i::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void BBVector2i::ArenaDtor(void* object) { BBVector2i* _this = reinterpret_cast< BBVector2i* >(object); (void)_this; } void BBVector2i::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBVector2i::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBVector2i::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBVector2i) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { ::memset(&x_, 0, static_cast<size_t>( reinterpret_cast<char*>(&y_) - reinterpret_cast<char*>(&x_)) + sizeof(y_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBVector2i::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // int32 x = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_x(&has_bits); x_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 y = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_y(&has_bits); y_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBVector2i::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBVector2i) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 x = 1; if (_internal_has_x()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->_internal_x(), target); } // int32 y = 2; if (_internal_has_y()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(2, this->_internal_y(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBVector2i) return target; } size_t BBVector2i::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBVector2i) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { // int32 x = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_x()); } // int32 y = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_y()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBVector2i::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBVector2i) GOOGLE_DCHECK_NE(&from, this); const BBVector2i* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBVector2i>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBVector2i) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBVector2i) MergeFrom(*source); } } void BBVector2i::MergeFrom(const BBVector2i& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBVector2i) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { x_ = from.x_; } if (cached_has_bits & 0x00000002u) { y_ = from.y_; } _has_bits_[0] |= cached_has_bits; } } void BBVector2i::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBVector2i) if (&from == this) return; Clear(); MergeFrom(from); } void BBVector2i::CopyFrom(const BBVector2i& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBVector2i) if (&from == this) return; Clear(); MergeFrom(from); } bool BBVector2i::IsInitialized() const { return true; } void BBVector2i::InternalSwap(BBVector2i* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(BBVector2i, y_) + sizeof(BBVector2i::y_) - PROTOBUF_FIELD_OFFSET(BBVector2i, x_)>( reinterpret_cast<char*>(&x_), reinterpret_cast<char*>(&other->x_)); } ::PROTOBUF_NAMESPACE_ID::Metadata BBVector2i::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBVector_2eproto_getter, &descriptor_table_BBVector_2eproto_once, file_level_metadata_BBVector_2eproto[1]); } // =================================================================== class BBVector3f::_Internal { public: using HasBits = decltype(std::declval<BBVector3f>()._has_bits_); static void set_has_x(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_y(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_z(HasBits* has_bits) { (*has_bits)[0] |= 4u; } }; BBVector3f::BBVector3f(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBVector3f) } BBVector3f::BBVector3f(const BBVector3f& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&x_, &from.x_, static_cast<size_t>(reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_)) + sizeof(z_)); // @@protoc_insertion_point(copy_constructor:BBSerializer.BBVector3f) } void BBVector3f::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&x_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_)) + sizeof(z_)); } BBVector3f::~BBVector3f() { // @@protoc_insertion_point(destructor:BBSerializer.BBVector3f) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBVector3f::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void BBVector3f::ArenaDtor(void* object) { BBVector3f* _this = reinterpret_cast< BBVector3f* >(object); (void)_this; } void BBVector3f::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBVector3f::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBVector3f::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBVector3f) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000007u) { ::memset(&x_, 0, static_cast<size_t>( reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_)) + sizeof(z_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBVector3f::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // float x = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 13)) { _Internal::set_has_x(&has_bits); x_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); ptr += sizeof(float); } else goto handle_unusual; continue; // float y = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 21)) { _Internal::set_has_y(&has_bits); y_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); ptr += sizeof(float); } else goto handle_unusual; continue; // float z = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 29)) { _Internal::set_has_z(&has_bits); z_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); ptr += sizeof(float); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBVector3f::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBVector3f) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // float x = 1; if (_internal_has_x()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(1, this->_internal_x(), target); } // float y = 2; if (_internal_has_y()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(2, this->_internal_y(), target); } // float z = 3; if (_internal_has_z()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(3, this->_internal_z(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBVector3f) return target; } size_t BBVector3f::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBVector3f) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000007u) { // float x = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + 4; } // float y = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + 4; } // float z = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + 4; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBVector3f::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBVector3f) GOOGLE_DCHECK_NE(&from, this); const BBVector3f* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBVector3f>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBVector3f) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBVector3f) MergeFrom(*source); } } void BBVector3f::MergeFrom(const BBVector3f& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBVector3f) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { x_ = from.x_; } if (cached_has_bits & 0x00000002u) { y_ = from.y_; } if (cached_has_bits & 0x00000004u) { z_ = from.z_; } _has_bits_[0] |= cached_has_bits; } } void BBVector3f::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBVector3f) if (&from == this) return; Clear(); MergeFrom(from); } void BBVector3f::CopyFrom(const BBVector3f& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBVector3f) if (&from == this) return; Clear(); MergeFrom(from); } bool BBVector3f::IsInitialized() const { return true; } void BBVector3f::InternalSwap(BBVector3f* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(BBVector3f, z_) + sizeof(BBVector3f::z_) - PROTOBUF_FIELD_OFFSET(BBVector3f, x_)>( reinterpret_cast<char*>(&x_), reinterpret_cast<char*>(&other->x_)); } ::PROTOBUF_NAMESPACE_ID::Metadata BBVector3f::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBVector_2eproto_getter, &descriptor_table_BBVector_2eproto_once, file_level_metadata_BBVector_2eproto[2]); } // =================================================================== class BBVector3i::_Internal { public: using HasBits = decltype(std::declval<BBVector3i>()._has_bits_); static void set_has_x(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_y(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_z(HasBits* has_bits) { (*has_bits)[0] |= 4u; } }; BBVector3i::BBVector3i(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBVector3i) } BBVector3i::BBVector3i(const BBVector3i& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&x_, &from.x_, static_cast<size_t>(reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_)) + sizeof(z_)); // @@protoc_insertion_point(copy_constructor:BBSerializer.BBVector3i) } void BBVector3i::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&x_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_)) + sizeof(z_)); } BBVector3i::~BBVector3i() { // @@protoc_insertion_point(destructor:BBSerializer.BBVector3i) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBVector3i::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void BBVector3i::ArenaDtor(void* object) { BBVector3i* _this = reinterpret_cast< BBVector3i* >(object); (void)_this; } void BBVector3i::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBVector3i::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBVector3i::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBVector3i) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000007u) { ::memset(&x_, 0, static_cast<size_t>( reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_)) + sizeof(z_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBVector3i::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // int32 x = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_x(&has_bits); x_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 y = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_y(&has_bits); y_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 z = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { _Internal::set_has_z(&has_bits); z_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBVector3i::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBVector3i) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 x = 1; if (_internal_has_x()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->_internal_x(), target); } // int32 y = 2; if (_internal_has_y()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(2, this->_internal_y(), target); } // int32 z = 3; if (_internal_has_z()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(3, this->_internal_z(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBVector3i) return target; } size_t BBVector3i::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBVector3i) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000007u) { // int32 x = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_x()); } // int32 y = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_y()); } // int32 z = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_z()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBVector3i::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBVector3i) GOOGLE_DCHECK_NE(&from, this); const BBVector3i* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBVector3i>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBVector3i) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBVector3i) MergeFrom(*source); } } void BBVector3i::MergeFrom(const BBVector3i& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBVector3i) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { x_ = from.x_; } if (cached_has_bits & 0x00000002u) { y_ = from.y_; } if (cached_has_bits & 0x00000004u) { z_ = from.z_; } _has_bits_[0] |= cached_has_bits; } } void BBVector3i::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBVector3i) if (&from == this) return; Clear(); MergeFrom(from); } void BBVector3i::CopyFrom(const BBVector3i& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBVector3i) if (&from == this) return; Clear(); MergeFrom(from); } bool BBVector3i::IsInitialized() const { return true; } void BBVector3i::InternalSwap(BBVector3i* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(BBVector3i, z_) + sizeof(BBVector3i::z_) - PROTOBUF_FIELD_OFFSET(BBVector3i, x_)>( reinterpret_cast<char*>(&x_), reinterpret_cast<char*>(&other->x_)); } ::PROTOBUF_NAMESPACE_ID::Metadata BBVector3i::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBVector_2eproto_getter, &descriptor_table_BBVector_2eproto_once, file_level_metadata_BBVector_2eproto[3]); } // =================================================================== class BBVector4f::_Internal { public: using HasBits = decltype(std::declval<BBVector4f>()._has_bits_); static void set_has_x(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_y(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_z(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_w(HasBits* has_bits) { (*has_bits)[0] |= 8u; } }; BBVector4f::BBVector4f(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBVector4f) } BBVector4f::BBVector4f(const BBVector4f& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&x_, &from.x_, static_cast<size_t>(reinterpret_cast<char*>(&w_) - reinterpret_cast<char*>(&x_)) + sizeof(w_)); // @@protoc_insertion_point(copy_constructor:BBSerializer.BBVector4f) } void BBVector4f::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&x_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&w_) - reinterpret_cast<char*>(&x_)) + sizeof(w_)); } BBVector4f::~BBVector4f() { // @@protoc_insertion_point(destructor:BBSerializer.BBVector4f) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBVector4f::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void BBVector4f::ArenaDtor(void* object) { BBVector4f* _this = reinterpret_cast< BBVector4f* >(object); (void)_this; } void BBVector4f::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBVector4f::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBVector4f::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBVector4f) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000000fu) { ::memset(&x_, 0, static_cast<size_t>( reinterpret_cast<char*>(&w_) - reinterpret_cast<char*>(&x_)) + sizeof(w_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBVector4f::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // float x = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 13)) { _Internal::set_has_x(&has_bits); x_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); ptr += sizeof(float); } else goto handle_unusual; continue; // float y = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 21)) { _Internal::set_has_y(&has_bits); y_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); ptr += sizeof(float); } else goto handle_unusual; continue; // float z = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 29)) { _Internal::set_has_z(&has_bits); z_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); ptr += sizeof(float); } else goto handle_unusual; continue; // float w = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 37)) { _Internal::set_has_w(&has_bits); w_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); ptr += sizeof(float); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBVector4f::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBVector4f) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // float x = 1; if (_internal_has_x()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(1, this->_internal_x(), target); } // float y = 2; if (_internal_has_y()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(2, this->_internal_y(), target); } // float z = 3; if (_internal_has_z()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(3, this->_internal_z(), target); } // float w = 4; if (_internal_has_w()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(4, this->_internal_w(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBVector4f) return target; } size_t BBVector4f::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBVector4f) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000000fu) { // float x = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + 4; } // float y = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + 4; } // float z = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + 4; } // float w = 4; if (cached_has_bits & 0x00000008u) { total_size += 1 + 4; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBVector4f::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBVector4f) GOOGLE_DCHECK_NE(&from, this); const BBVector4f* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBVector4f>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBVector4f) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBVector4f) MergeFrom(*source); } } void BBVector4f::MergeFrom(const BBVector4f& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBVector4f) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { x_ = from.x_; } if (cached_has_bits & 0x00000002u) { y_ = from.y_; } if (cached_has_bits & 0x00000004u) { z_ = from.z_; } if (cached_has_bits & 0x00000008u) { w_ = from.w_; } _has_bits_[0] |= cached_has_bits; } } void BBVector4f::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBVector4f) if (&from == this) return; Clear(); MergeFrom(from); } void BBVector4f::CopyFrom(const BBVector4f& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBVector4f) if (&from == this) return; Clear(); MergeFrom(from); } bool BBVector4f::IsInitialized() const { return true; } void BBVector4f::InternalSwap(BBVector4f* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(BBVector4f, w_) + sizeof(BBVector4f::w_) - PROTOBUF_FIELD_OFFSET(BBVector4f, x_)>( reinterpret_cast<char*>(&x_), reinterpret_cast<char*>(&other->x_)); } ::PROTOBUF_NAMESPACE_ID::Metadata BBVector4f::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBVector_2eproto_getter, &descriptor_table_BBVector_2eproto_once, file_level_metadata_BBVector_2eproto[4]); } // =================================================================== class BBVector4i::_Internal { public: using HasBits = decltype(std::declval<BBVector4i>()._has_bits_); static void set_has_x(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_y(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_z(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_w(HasBits* has_bits) { (*has_bits)[0] |= 8u; } }; BBVector4i::BBVector4i(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBVector4i) } BBVector4i::BBVector4i(const BBVector4i& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&x_, &from.x_, static_cast<size_t>(reinterpret_cast<char*>(&w_) - reinterpret_cast<char*>(&x_)) + sizeof(w_)); // @@protoc_insertion_point(copy_constructor:BBSerializer.BBVector4i) } void BBVector4i::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&x_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&w_) - reinterpret_cast<char*>(&x_)) + sizeof(w_)); } BBVector4i::~BBVector4i() { // @@protoc_insertion_point(destructor:BBSerializer.BBVector4i) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBVector4i::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void BBVector4i::ArenaDtor(void* object) { BBVector4i* _this = reinterpret_cast< BBVector4i* >(object); (void)_this; } void BBVector4i::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBVector4i::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBVector4i::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBVector4i) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000000fu) { ::memset(&x_, 0, static_cast<size_t>( reinterpret_cast<char*>(&w_) - reinterpret_cast<char*>(&x_)) + sizeof(w_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBVector4i::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // int32 x = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_x(&has_bits); x_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 y = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_y(&has_bits); y_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 z = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { _Internal::set_has_z(&has_bits); z_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 w = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_w(&has_bits); w_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBVector4i::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBVector4i) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 x = 1; if (_internal_has_x()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->_internal_x(), target); } // int32 y = 2; if (_internal_has_y()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(2, this->_internal_y(), target); } // int32 z = 3; if (_internal_has_z()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(3, this->_internal_z(), target); } // int32 w = 4; if (_internal_has_w()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_w(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBVector4i) return target; } size_t BBVector4i::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBVector4i) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000000fu) { // int32 x = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_x()); } // int32 y = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_y()); } // int32 z = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_z()); } // int32 w = 4; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_w()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBVector4i::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBVector4i) GOOGLE_DCHECK_NE(&from, this); const BBVector4i* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBVector4i>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBVector4i) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBVector4i) MergeFrom(*source); } } void BBVector4i::MergeFrom(const BBVector4i& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBVector4i) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { x_ = from.x_; } if (cached_has_bits & 0x00000002u) { y_ = from.y_; } if (cached_has_bits & 0x00000004u) { z_ = from.z_; } if (cached_has_bits & 0x00000008u) { w_ = from.w_; } _has_bits_[0] |= cached_has_bits; } } void BBVector4i::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBVector4i) if (&from == this) return; Clear(); MergeFrom(from); } void BBVector4i::CopyFrom(const BBVector4i& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBVector4i) if (&from == this) return; Clear(); MergeFrom(from); } bool BBVector4i::IsInitialized() const { return true; } void BBVector4i::InternalSwap(BBVector4i* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(BBVector4i, w_) + sizeof(BBVector4i::w_) - PROTOBUF_FIELD_OFFSET(BBVector4i, x_)>( reinterpret_cast<char*>(&x_), reinterpret_cast<char*>(&other->x_)); } ::PROTOBUF_NAMESPACE_ID::Metadata BBVector4i::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBVector_2eproto_getter, &descriptor_table_BBVector_2eproto_once, file_level_metadata_BBVector_2eproto[5]); } // =================================================================== class BBMatrix4f::_Internal { public: }; BBMatrix4f::BBMatrix4f(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), data_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBMatrix4f) } BBMatrix4f::BBMatrix4f(const BBMatrix4f& from) : ::PROTOBUF_NAMESPACE_ID::Message(), data_(from.data_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:BBSerializer.BBMatrix4f) } void BBMatrix4f::SharedCtor() { } BBMatrix4f::~BBMatrix4f() { // @@protoc_insertion_point(destructor:BBSerializer.BBMatrix4f) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBMatrix4f::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void BBMatrix4f::ArenaDtor(void* object) { BBMatrix4f* _this = reinterpret_cast< BBMatrix4f* >(object); (void)_this; } void BBMatrix4f::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBMatrix4f::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBMatrix4f::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBMatrix4f) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; data_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBMatrix4f::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // repeated float data = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedFloatParser(_internal_mutable_data(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 13) { _internal_add_data(::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr)); ptr += sizeof(float); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBMatrix4f::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBMatrix4f) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated float data = 1; if (this->_internal_data_size() > 0) { target = stream->WriteFixedPacked(1, _internal_data(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBMatrix4f) return target; } size_t BBMatrix4f::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBMatrix4f) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated float data = 1; { unsigned int count = static_cast<unsigned int>(this->_internal_data_size()); size_t data_size = 4UL * count; if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } total_size += data_size; } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBMatrix4f::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBMatrix4f) GOOGLE_DCHECK_NE(&from, this); const BBMatrix4f* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBMatrix4f>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBMatrix4f) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBMatrix4f) MergeFrom(*source); } } void BBMatrix4f::MergeFrom(const BBMatrix4f& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBMatrix4f) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; data_.MergeFrom(from.data_); } void BBMatrix4f::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBMatrix4f) if (&from == this) return; Clear(); MergeFrom(from); } void BBMatrix4f::CopyFrom(const BBMatrix4f& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBMatrix4f) if (&from == this) return; Clear(); MergeFrom(from); } bool BBMatrix4f::IsInitialized() const { return true; } void BBMatrix4f::InternalSwap(BBMatrix4f* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); data_.InternalSwap(&other->data_); } ::PROTOBUF_NAMESPACE_ID::Metadata BBMatrix4f::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBVector_2eproto_getter, &descriptor_table_BBVector_2eproto_once, file_level_metadata_BBVector_2eproto[6]); } // =================================================================== class BBMatrix4fB::_Internal { public: using HasBits = decltype(std::declval<BBMatrix4fB>()._has_bits_); static void set_has_data(HasBits* has_bits) { (*has_bits)[0] |= 1u; } }; BBMatrix4fB::BBMatrix4fB(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBMatrix4fB) } BBMatrix4fB::BBMatrix4fB(const BBMatrix4fB& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); data_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_data()) { data_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_data(), GetArena()); } // @@protoc_insertion_point(copy_constructor:BBSerializer.BBMatrix4fB) } void BBMatrix4fB::SharedCtor() { data_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } BBMatrix4fB::~BBMatrix4fB() { // @@protoc_insertion_point(destructor:BBSerializer.BBMatrix4fB) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBMatrix4fB::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); data_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void BBMatrix4fB::ArenaDtor(void* object) { BBMatrix4fB* _this = reinterpret_cast< BBMatrix4fB* >(object); (void)_this; } void BBMatrix4fB::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBMatrix4fB::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBMatrix4fB::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBMatrix4fB) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { data_.ClearNonDefaultToEmpty(); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBMatrix4fB::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // bytes data = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_data(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBMatrix4fB::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBMatrix4fB) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // bytes data = 1; if (_internal_has_data()) { target = stream->WriteBytesMaybeAliased( 1, this->_internal_data(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBMatrix4fB) return target; } size_t BBMatrix4fB::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBMatrix4fB) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // bytes data = 1; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_data()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBMatrix4fB::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBMatrix4fB) GOOGLE_DCHECK_NE(&from, this); const BBMatrix4fB* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBMatrix4fB>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBMatrix4fB) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBMatrix4fB) MergeFrom(*source); } } void BBMatrix4fB::MergeFrom(const BBMatrix4fB& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBMatrix4fB) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from._internal_has_data()) { _internal_set_data(from._internal_data()); } } void BBMatrix4fB::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBMatrix4fB) if (&from == this) return; Clear(); MergeFrom(from); } void BBMatrix4fB::CopyFrom(const BBMatrix4fB& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBMatrix4fB) if (&from == this) return; Clear(); MergeFrom(from); } bool BBMatrix4fB::IsInitialized() const { return true; } void BBMatrix4fB::InternalSwap(BBMatrix4fB* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); data_.Swap(&other->data_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } ::PROTOBUF_NAMESPACE_ID::Metadata BBMatrix4fB::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBVector_2eproto_getter, &descriptor_table_BBVector_2eproto_once, file_level_metadata_BBVector_2eproto[7]); } // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::BBSerializer::BBVector2f* Arena::CreateMaybeMessage< ::BBSerializer::BBVector2f >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBVector2f >(arena); } template<> PROTOBUF_NOINLINE ::BBSerializer::BBVector2i* Arena::CreateMaybeMessage< ::BBSerializer::BBVector2i >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBVector2i >(arena); } template<> PROTOBUF_NOINLINE ::BBSerializer::BBVector3f* Arena::CreateMaybeMessage< ::BBSerializer::BBVector3f >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBVector3f >(arena); } template<> PROTOBUF_NOINLINE ::BBSerializer::BBVector3i* Arena::CreateMaybeMessage< ::BBSerializer::BBVector3i >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBVector3i >(arena); } template<> PROTOBUF_NOINLINE ::BBSerializer::BBVector4f* Arena::CreateMaybeMessage< ::BBSerializer::BBVector4f >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBVector4f >(arena); } template<> PROTOBUF_NOINLINE ::BBSerializer::BBVector4i* Arena::CreateMaybeMessage< ::BBSerializer::BBVector4i >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBVector4i >(arena); } template<> PROTOBUF_NOINLINE ::BBSerializer::BBMatrix4f* Arena::CreateMaybeMessage< ::BBSerializer::BBMatrix4f >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBMatrix4f >(arena); } template<> PROTOBUF_NOINLINE ::BBSerializer::BBMatrix4fB* Arena::CreateMaybeMessage< ::BBSerializer::BBMatrix4fB >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBMatrix4fB >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> <|start_filename|>Resources/shaders/Volumetric/GBuffer.vert<|end_filename|> #version 430 core in vec4 BBPosition; in vec4 BBTexcoord; in vec4 BBNormal; out vec2 v2f_texcoord; out vec3 v2f_normal; out vec3 v2f_view_space_pos; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { vec4 view_space_pos = BBViewMatrix * BBModelMatrix * BBPosition; gl_Position = BBProjectionMatrix * view_space_pos; v2f_texcoord = BBTexcoord.xy; v2f_normal = normalize(mat3(transpose(inverse(BBViewMatrix * BBModelMatrix))) * BBNormal.xyz); v2f_view_space_pos = view_space_pos.xyz; } <|start_filename|>Resources/shaders/DeferredPosition.vert<|end_filename|> attribute vec4 BBPosition; varying vec4 V_WorldPos; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { V_WorldPos = BBModelMatrix * BBPosition; gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * BBPosition; } <|start_filename|>Code/BBearEditor/Engine/3D/BBIcon.cpp<|end_filename|> #include "BBIcon.h" #include "Geometry/BBBoundingBox.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BBMaterial.h" #include "Render/BBRenderPass.h" #include "Render/Texture/BBTexture.h" #include "Render/BBDrawCall.h" BBIcon::BBIcon() : BBIcon(QVector3D(0, 0, 0), QVector3D(0, 0, 0), QVector3D(1, 1, 1)) { } BBIcon::BBIcon(const QVector3D &position, const QVector3D &rotation, const QVector3D &scale) : BBRenderableObject(position, rotation, scale) { m_pBoundingBox = new BBRectBoundingBox3D(0.0f, 0.0f, 0.0f, 0.25f, 0.25f, 0.0f); m_pBoundingBox->setPosition(position, false); } BBIcon::~BBIcon() { BB_SAFE_DELETE(m_pBoundingBox); } void BBIcon::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { BBRenderableObject::setPosition(position, bUpdateLocalTransform); m_pBoundingBox->setPosition(position, bUpdateLocalTransform); } void BBIcon::setRotation(const QQuaternion &quaternion, bool bUpdateLocalTransform) { BBRenderableObject::setRotation(quaternion, bUpdateLocalTransform); m_pBoundingBox->setRotation(quaternion, bUpdateLocalTransform); } void BBIcon::setScale(const QVector3D &scale, bool bUpdateLocalTransform) { BBRenderableObject::setScale(scale, bUpdateLocalTransform); m_pBoundingBox->setScale(scale, bUpdateLocalTransform); } void BBIcon::init(const QString &path) { m_pVBO = new BBVertexBufferObject(4); m_pVBO->setPosition(0, 0.25f, 0.25f, 0); m_pVBO->setPosition(1, -0.25f, 0.25f, 0); m_pVBO->setPosition(2, -0.25f, -0.25f, 0); m_pVBO->setPosition(3, 0.25f, -0.25f, 0); m_pVBO->setTexcoord(0, 1.0f, 1.0f); m_pVBO->setTexcoord(1, 0.0f, 1.0f); m_pVBO->setTexcoord(2, 0.0f, 0.0f); m_pVBO->setTexcoord(3, 1.0f, 0.0f); for (int i = 0; i < m_pVBO->getVertexCount(); i++) { m_pVBO->setColor(i, 1.0f, 1.0f, 1.0f); } m_pCurrentMaterial->init("texture", BB_PATH_RESOURCE_SHADER(texture.vert), BB_PATH_RESOURCE_SHADER(texture.frag)); BBTexture texture; m_pCurrentMaterial->getBaseRenderPass()->setSampler2D(LOCATION_TEXTURE(0), texture.createTexture2D(path), path); m_pCurrentMaterial->getBaseRenderPass()->setBlendState(true); m_pCurrentMaterial->getBaseRenderPass()->setZTestState(false); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, GL_QUADS, 0, 4); appendDrawCall(pDrawCall); } bool BBIcon::hit(const BBRay &ray, float &fDistance) { return m_pBoundingBox->hit(ray, fDistance); } bool BBIcon::belongToSelectionRegion(const BBFrustum &frustum) { // Eliminate objects whose the center point of the bounding box is on the outside QVector3D center = getModelMatrix() * m_pBoundingBox->getCenter(); return frustum.contain(center); } <|start_filename|>Resources/shaders/Cartoon/Outline.frag<|end_filename|> uniform vec4 BBColor_OutlineColor; void main(void) { gl_FragColor = BBColor_OutlineColor; } <|start_filename|>Resources/shaders/DeferredColor.frag<|end_filename|> varying vec4 V_Color; varying vec4 V_texcoord; uniform sampler2D BBTexture0; uniform vec4 BBTextureSettings; void main(void) { vec4 color = V_Color; if (BBTextureSettings.x != 0) { // there is a texture color = texture2D(BBTexture0, V_texcoord.xy); } gl_FragColor = color; } <|start_filename|>Resources/shaders/SkyBox/Cubemap.vert<|end_filename|> #version 330 core in vec4 BBPosition; out vec3 v2f_local_pos; uniform mat4 ProjectionMatrix; uniform mat4 ViewMatrix; void main() { v2f_local_pos = BBPosition.xyz; gl_Position = ProjectionMatrix * ViewMatrix * BBPosition; } <|start_filename|>Code/BBearEditor/Engine/Geometry/BBFrustum.cpp<|end_filename|> #include "BBFrustum.h" #include "Utils/BBUtils.h" #include "Render/BBCamera.h" #include "BBPlane.h" #include "BBRay.h" #include "BBBoundingBox.h" /** * @brief BBFrustum::BBFrustum * @param pCamera * @param x screen coordinate top-left * @param y original point is in the top-left * @param nWidth * @param nHeight */ BBFrustum::BBFrustum(BBCamera *pCamera, int nTopLeftX, int nTopLeftY, int nWidth, int nHeight) { m_nTopLeftX = nTopLeftX; m_nTopLeftY = nTopLeftY; m_nWidth = nWidth; m_nHeight = nHeight; // 3D ray of the 4 vertexes BBRay topLeft = pCamera->createRayFromScreen(nTopLeftX, nTopLeftY); BBRay topRight = pCamera->createRayFromScreen(nTopLeftX + nWidth, nTopLeftY); BBRay bottomRight = pCamera->createRayFromScreen(nTopLeftX + nWidth, nTopLeftY + nHeight); BBRay bottomLeft = pCamera->createRayFromScreen(nTopLeftX, nTopLeftY + nHeight); m_pLeft = new BBPlane(topLeft.getNearPoint(), bottomLeft.getNearPoint(), topLeft.getFarPoint()); m_pRight = new BBPlane(topRight.getNearPoint(), topRight.getFarPoint(), bottomRight.getNearPoint()); m_pTop = new BBPlane(topLeft.getNearPoint(), topLeft.getFarPoint(), topRight.getNearPoint()); m_pBottom = new BBPlane(bottomLeft.getNearPoint(), bottomRight.getNearPoint(), bottomLeft.getFarPoint()); m_pFront = new BBPlane(topLeft.getNearPoint(), topRight.getNearPoint(), bottomRight.getNearPoint()); m_pBack = new BBPlane(topLeft.getFarPoint(), bottomLeft.getFarPoint(), bottomRight.getFarPoint()); } BBFrustum::~BBFrustum() { BB_SAFE_DELETE(m_pLeft); BB_SAFE_DELETE(m_pRight); BB_SAFE_DELETE(m_pTop); BB_SAFE_DELETE(m_pBottom); BB_SAFE_DELETE(m_pFront); BB_SAFE_DELETE(m_pBack); } bool BBFrustum::contain(const QVector3D &point) const { if (m_pLeft->distance(point) < 0) return false; if (m_pRight->distance(point) < 0) return false; if (m_pTop->distance(point) < 0) return false; if (m_pBottom->distance(point) < 0) return false; return true; } bool BBFrustum::contain(const BBPlane &left, const BBPlane &right, const BBPlane &top, const BBPlane &bottom, const BBPlane &front, const BBPlane &back, const QVector3D &point) { if (left.distance(point) < 0) return false; if (right.distance(point) < 0) return false; if (top.distance(point) < 0) return false; if (bottom.distance(point) < 0) return false; if (front.distance(point) < 0) return false; if (back.distance(point) < 0) return false; return true; } /** * @brief BBFrustum::containWithInvertedRightAndBottom invert direction of right and bottom * @param left * @param right * @param top * @param bottom * @param front * @param back * @param point * @return */ bool BBFrustum::containWithInvertedRightAndTop(const BBPlane &left, const BBPlane &right, const BBPlane &top, const BBPlane &bottom, const QVector3D &pointOnFront, const QVector3D &pointOnBack, const QVector3D &point) { if (left.distance(point) < 0) return false; if (right.distance(point) > 0) return false; if (top.distance(point) > 0) return false; if (bottom.distance(point) < 0) return false; if (BBPlane::distance(pointOnFront, m_pFront->getNormal(), point) < 0) return false; if (BBPlane::distance(pointOnBack, m_pBack->getNormal(), point) < 0) return false; return true; } /** * @brief BBFrustumCluster::BBFrustumCluster * @param pFrustum * @param nCountX * @param nCountY * @param nCountZ */ BBFrustumCluster::BBFrustumCluster(BBCamera *pCamera, int x, int y, int nWidth, int nHeight, int nCountX, int nCountY, int nCountZ) : BBFrustum(pCamera, x, y, nWidth, nHeight) { m_pXCrossSections = nullptr; m_pYCrossSections = nullptr; m_pZCrossSectionPoints = nullptr; // Divide pFrustum into nCountX parts along X and save nCountX-1 planes calculateXCrossSections(pCamera, nCountX - 1); calculateYCrossSections(pCamera, nCountY - 1); calculateZCrossSectionPoints(pCamera, nCountZ - 1); } BBFrustumCluster::~BBFrustumCluster() { BB_SAFE_DELETE_ARRAY(m_pXCrossSections); BB_SAFE_DELETE_ARRAY(m_pYCrossSections); BB_SAFE_DELETE_ARRAY(m_pZCrossSectionPoints); } void BBFrustumCluster::collectPlanes(int nFrustumIndexX, int nFrustumIndexY, int nFrustumIndexZ, BBPlane &left, BBPlane &right, BBPlane &top, BBPlane &bottom, QVector3D &pointOnFront, QVector3D &pointOnBack) { left = m_pXCrossSections[nFrustumIndexX]; right = m_pXCrossSections[nFrustumIndexX + 1]; top = m_pYCrossSections[nFrustumIndexY]; bottom = m_pYCrossSections[nFrustumIndexY + 1]; pointOnFront = m_pZCrossSectionPoints[nFrustumIndexZ]; pointOnBack = m_pZCrossSectionPoints[nFrustumIndexZ + 1]; } /** * @brief BBFrustumCluster::contain whether point is contained in the frustum specified by index * @param nIndexX * @param nIndexY * @param nIndexZ * @param point * @return */ bool BBFrustumCluster::contain(int nFrustumIndexX, int nFrustumIndexY, int nFrustumIndexZ, const QVector3D &point) { BBPlane left; BBPlane right; BBPlane top; BBPlane bottom; QVector3D pointOnFront; QVector3D pointOnBack; collectPlanes(nFrustumIndexX, nFrustumIndexY, nFrustumIndexZ, left, right, top, bottom, pointOnFront, pointOnBack); return containWithInvertedRightAndTop(left, right, top, bottom, pointOnFront, pointOnBack, point); } bool BBFrustumCluster::containedInSphere(int nFrustumIndexX, int nFrustumIndexY, int nFrustumIndexZ, const QVector3D &sphereCenter, float fSphereRadius) { // to do return true; } bool BBFrustumCluster::computeIntersectWithAABB(int nFrustumIndexX, int nFrustumIndexY, int nFrustumIndexZ, BBAABBBoundingBox3D *pAABB) { BBPlane left; BBPlane right; BBPlane top; BBPlane bottom; QVector3D pointOnFront; QVector3D pointOnBack; collectPlanes(nFrustumIndexX, nFrustumIndexY, nFrustumIndexZ, left, right, top, bottom, pointOnFront, pointOnBack); // Determine whether the bounding box is outside or inside the plane // right and top need to invert, since just saving positive direction if (pAABB->computeIntersectWithPlane(left.getPoint1(), left.getNormal())) return true; if (pAABB->computeIntersectWithPlane(right.getPoint1(), -right.getNormal())) return true; if (pAABB->computeIntersectWithPlane(top.getPoint1(), -top.getNormal())) return true; if (pAABB->computeIntersectWithPlane(bottom.getPoint1(), bottom.getNormal())) return true; if (pAABB->computeIntersectWithPlane(pointOnFront, m_pFront->getNormal())) return true; if (pAABB->computeIntersectWithPlane(pointOnBack, m_pBack->getNormal())) return true; return false; } void BBFrustumCluster::calculateXCrossSections(BBCamera *pCamera, int nCount) { // +2 save m_pLeft and m_pRight for more convenient calculation m_pXCrossSections = new BBPlane[nCount + 2]; m_pXCrossSections[0] = *m_pLeft; m_pXCrossSections[nCount + 1] = BBPlane::invert(*m_pRight); int nStep = m_nWidth / (nCount + 1); int x = m_nTopLeftX; for (int i = 1; i < nCount + 1; i++) { x += nStep; BBRay topRay = pCamera->createRayFromScreen(x, m_nTopLeftY); BBRay bottomRay = pCamera->createRayFromScreen(x, m_nTopLeftY + m_nHeight); // just save positive direction m_pXCrossSections[i] = BBPlane(topRay.getFarPoint(), topRay.getNearPoint(), bottomRay.getNearPoint()); } } void BBFrustumCluster::calculateYCrossSections(BBCamera *pCamera, int nCount) { m_pYCrossSections = new BBPlane[nCount + 2]; m_pYCrossSections[0] = BBPlane::invert(*m_pTop); m_pYCrossSections[nCount + 1] = *m_pBottom; int nStep = m_nHeight / (nCount + 1); int y = m_nTopLeftY; for (int i = 1; i < nCount + 1; i++) { y += nStep; BBRay leftRay = pCamera->createRayFromScreen(m_nTopLeftX, y); BBRay rightRay = pCamera->createRayFromScreen(m_nTopLeftX + m_nWidth, y); // just save positive direction m_pYCrossSections[i] = BBPlane(leftRay.getNearPoint(), rightRay.getNearPoint(), rightRay.getFarPoint()); } } void BBFrustumCluster::calculateZCrossSectionPoints(BBCamera *pCamera, int nCount) { int nStep = pCamera->getDepth() / (nCount + 1); BBRay ray = pCamera->createRayFromScreen(pCamera->getViewportWidth() / 2, pCamera->getViewportHeight() / 2); QVector3D dir = ray.getDirection(); m_pZCrossSectionPoints = new QVector3D[nCount + 2]; for (int i = 0; i < nCount + 2; i++) { m_pZCrossSectionPoints[i] = ray.getNearPoint() + nStep * i * dir; } } <|start_filename|>Code/BBearEditor/Editor/Tools/FBX2BBear/BBFBXSkeletonGPU.cpp<|end_filename|> #include "BBFBXSkeletonGPU.h" BBFBXSkeletonGPU::BBFBXSkeletonGPU() { // m_pScene = nullptr; } void BBFBXSkeletonGPU::init(const char *path) { // FbxManager *pFbxManager = FbxManager::Create(); // FbxIOSettings *pSettings = FbxIOSettings::Create(pFbxManager, IOSROOT); // FbxImporter *pFbxImporter = FbxImporter::Create(pFbxManager, ""); // pFbxManager->SetIOSettings(pSettings); // if (pFbxImporter->Initialize(path, -1, pFbxManager->GetIOSettings())) // { // m_pScene = FbxScene::Create(pFbxManager, ""); // pFbxImporter->Import(m_pScene); // } // pFbxImporter->Destroy(); } <|start_filename|>Code/BBearEditor/Engine/Render/BufferObject/BBFrameBufferObject.h<|end_filename|> #ifndef BBFRAMEBUFFEROBJECT_H #define BBFRAMEBUFFEROBJECT_H #include "../BBBaseRenderComponent.h" class BBFrameBufferObject : public BBBaseRenderComponent { public: BBFrameBufferObject(); /* one or more */ void attachColorBuffer(const QString &bufferName, GLenum attachment, int nWidth, int nHeight, GLenum format = GL_RGBA); /* only one */ void attachDepthBuffer(const QString &bufferName, int nWidth, int nHeight); /* make the settings take effect */ void finish(); void bind(); void bind(int nWidth, int nHeight); void unbind(); GLuint getBuffer(const QString &bufferName); private: GLuint m_FrameBufferObject; GLint m_PreFrameBufferObject; /* each buffer and its name */ QMap<QString, GLuint> m_Buffers; /* buffer in which FBO need to render */ QList<GLenum> m_DrawBuffers; int m_nWidth; int m_nHeight; }; #endif // BBFRAMEBUFFEROBJECT_H <|start_filename|>Code/BBearEditor/Editor/Render/BBPreviewOpenGLWidget.h<|end_filename|> #ifndef BBPREVIEWOPENGLWIDGET_H #define BBPREVIEWOPENGLWIDGET_H #include "BBOpenGLWidget.h" class BBModel; class BBMaterial; class BBPreviewOpenGLWidget : public BBOpenGLWidget { Q_OBJECT public: BBPreviewOpenGLWidget(QWidget *pParent = 0); public: void updateMaterialSphere(BBMaterial *pMaterial); private slots: void showMaterialPreview(const QString &filePath); void removeMaterialPreview(); private: void initializeGL() override; void createSphere(); BBModel *m_pSphere; }; #endif // BBPREVIEWOPENGLWIDGET_H <|start_filename|>Resources/shaders/GI/SSDO.frag<|end_filename|> #version 430 core in vec2 v2f_texcoord; layout (location = 0) out float SSAOTex; layout (location = 1) out vec4 SSDOTex; uniform vec4 BBCameraParameters; uniform mat4 BBProjectionMatrix; uniform sampler2D LightTex; uniform sampler2D NormalTex; uniform sampler2D PositionTex; uniform sampler2D NoiseTex; uniform vec4 Samples[64]; const int kernel_size = 64; const float radius = 1.0; float linearizeDepth(float depth) { float z_near = BBCameraParameters.z; float z_far = BBCameraParameters.w; float z = depth * 2.0 - 1.0; return (2.0 * z_near * z_far) / (z_far + z_near - z * (z_far - z_near)); } void main(void) { float width = BBCameraParameters.x; float height = BBCameraParameters.y; vec3 pos = texture(PositionTex, v2f_texcoord).xyz; vec2 noise_scale = vec2(width, height) / 4.0; vec3 N = texture(NormalTex, v2f_texcoord).xyz; vec3 random_vec = texture(NoiseTex, noise_scale * v2f_texcoord).xyz; vec3 T = normalize(random_vec - N * dot(random_vec, N)); vec3 B = cross(N, T); mat3 TBN = mat3(T, B, N); float occlusion = 0.0; vec3 indirect_light = vec3(0.0); for (int i = 0; i < kernel_size; i++) { vec3 sample_point = TBN * Samples[i].xyz; sample_point = pos + sample_point * radius; vec4 offset = vec4(sample_point, 1.0); offset = BBProjectionMatrix * offset; offset.xyz /= offset.w; offset.xyz = offset.xyz * 0.5 + 0.5; if (offset.x > 1.0 || offset.x < 0.0 || offset.y > 1.0 || offset.y < 0.0) { continue; } vec4 position_tex = texture(PositionTex, offset.xy); float sample_depth = -position_tex.w; float tag = sample_depth >= sample_point.z ? 1.0 : 0.0; float weight = smoothstep(0.0, 1.0, radius / abs(pos.z - sample_depth)); occlusion += tag * weight; vec3 sample_normal = texture(NormalTex, offset.xy).xyz; vec3 sample_pos = position_tex.xyz; vec3 sample_color = texture(LightTex, offset.xy).xyz; indirect_light += (1 - tag) * max(dot(N, normalize(pos - sample_pos)), 0.0) * sample_color; } occlusion = 1.0 - (occlusion / kernel_size); indirect_light /= kernel_size; SSAOTex = occlusion; SSDOTex = vec4(indirect_light * 5.0, 1.0); } <|start_filename|>Code/BBearEditor/Engine/Scene/BBRendererManager.cpp<|end_filename|> #include "BBRendererManager.h" #include <QDir> #include "Utils/BBUtils.h" #include <QDirIterator> #include "Render/BBMaterial.h" #include "Render/BBPreviewOpenGLWidget.h" #include "Render/BBRenderPass.h" #include "Render/Texture/BBTexture.h" #include <QUuid> BBPreviewOpenGLWidget* BBRendererManager::m_pPreviewOpenGLWidget = nullptr; QMap<QString, BBMaterial*> BBRendererManager::m_CachedMaterials; BBMaterial* BBRendererManager::m_pDeferredRenderingMaterial[3] = {0}; QStringList BBRendererManager::loadVShaderList() { return loadShaderList("*.vert"); } QStringList BBRendererManager::loadFShaderList() { return loadShaderList("*.frag"); } void BBRendererManager::saveDefaultMaterial(const QString &filePath) { BBSerializer::BBMaterial material; QUuid id = QUuid::createUuid(); material.set_shadername(id.toString().toStdString().c_str()); material.set_vshaderpath(BB_PATH_RESOURCE_SHADER(diffuse.vert)); material.set_fshaderpath(BB_PATH_RESOURCE_SHADER(diffuse.frag)); serialize(material, filePath); } BBMaterial* BBRendererManager::loadMaterial(const QString &filePath) { auto it = m_CachedMaterials.find(filePath); if (it != m_CachedMaterials.end()) { return it.value(); } BBMaterial* pMaterial = new BBMaterial(); loadMaterialContent(filePath, pMaterial); m_CachedMaterials.insert(filePath, pMaterial); return pMaterial; } QString BBRendererManager::getMaterialPath(BBMaterial *pMaterial) { return m_CachedMaterials.key(pMaterial); } void BBRendererManager::changeVShader(BBMaterial *pMaterial, const QString &name) { QString materialPath = m_CachedMaterials.key(pMaterial); BB_PROCESS_ERROR_RETURN(!materialPath.isEmpty()); BBSerializer::BBMaterial material = deserialize(materialPath); material.set_vshaderpath(getShaderFilePath(name).toStdString().c_str()); serialize(material, materialPath); } void BBRendererManager::changeFShader(BBMaterial *pMaterial, const QString &name) { QString materialPath = m_CachedMaterials.key(pMaterial); BB_PROCESS_ERROR_RETURN(!materialPath.isEmpty()); BBSerializer::BBMaterial material = deserialize(materialPath); material.set_fshaderpath(getShaderFilePath(name).toStdString().c_str()); serialize(material, materialPath); } void BBRendererManager::changeSampler2D(BBMaterial *pMaterial, const QString &uniformName, const QString &texturePath) { QString materialPath = m_CachedMaterials.key(pMaterial); BB_PROCESS_ERROR_RETURN(!materialPath.isEmpty()); BBSerializer::BBMaterial material = deserialize(materialPath); material.add_texturename(uniformName.toStdString().c_str()); material.add_texturepath(texturePath.toStdString().c_str()); serialize(material, materialPath); } void BBRendererManager::changeSamplerCube(BBMaterial *pMaterial, const QString &uniformName, const QString resourcePaths[]) { QString materialPath = m_CachedMaterials.key(pMaterial); BB_PROCESS_ERROR_RETURN(!materialPath.isEmpty()); BBSerializer::BBMaterial material = deserialize(materialPath); material.set_cubemapname(uniformName.toStdString().c_str()); BBSerializer::BBCubeMap *pCubeMap = material.mutable_cubemappaths(); pCubeMap->set_positivex(resourcePaths[0].toStdString().c_str()); pCubeMap->set_negativex(resourcePaths[1].toStdString().c_str()); pCubeMap->set_positivey(resourcePaths[2].toStdString().c_str()); pCubeMap->set_negativey(resourcePaths[3].toStdString().c_str()); pCubeMap->set_positivez(resourcePaths[4].toStdString().c_str()); pCubeMap->set_negativez(resourcePaths[5].toStdString().c_str()); serialize(material, materialPath); } void BBRendererManager::changeFloat(BBMaterial *pMaterial, const QString &floatName, float fValue) { QString materialPath = m_CachedMaterials.key(pMaterial); BB_PROCESS_ERROR_RETURN(!materialPath.isEmpty()); BBSerializer::BBMaterial material = deserialize(materialPath); material.add_floatname(floatName.toStdString().c_str()); material.add_floatvalue(fValue); serialize(material, materialPath); } void BBRendererManager::changeVector4(BBMaterial *pMaterial, const std::string &name, float *fValue) { QString materialPath = m_CachedMaterials.key(pMaterial); BB_PROCESS_ERROR_RETURN(!materialPath.isEmpty()); BBSerializer::BBMaterial material = deserialize(materialPath); material.add_vec4name(name); BBSerializer::BBVector4f *pVec4 = material.add_vec4value(); pVec4->set_x(fValue[0]); pVec4->set_y(fValue[1]); pVec4->set_z(fValue[2]); pVec4->set_w(fValue[3]); serialize(material, materialPath); } void BBRendererManager::changeBlendState(BBMaterial *pMaterial, bool bEnable) { QString materialPath = m_CachedMaterials.key(pMaterial); BB_PROCESS_ERROR_RETURN(!materialPath.isEmpty()); BBSerializer::BBMaterial material = deserialize(materialPath); material.set_blendstate(bEnable); serialize(material, materialPath); } void BBRendererManager::changeSRCBlendFunc(BBMaterial *pMaterial, int src) { QString materialPath = m_CachedMaterials.key(pMaterial); BB_PROCESS_ERROR_RETURN(!materialPath.isEmpty()); BBSerializer::BBMaterial material = deserialize(materialPath); material.set_srcblendfunc(src); serialize(material, materialPath); } void BBRendererManager::changeDSTBlendFunc(BBMaterial *pMaterial, int dst) { QString materialPath = m_CachedMaterials.key(pMaterial); BB_PROCESS_ERROR_RETURN(!materialPath.isEmpty()); BBSerializer::BBMaterial material = deserialize(materialPath); material.set_dstblendfunc(dst); serialize(material, materialPath); } void BBRendererManager::changeCullState(BBMaterial *pMaterial, bool bEnable) { QString materialPath = m_CachedMaterials.key(pMaterial); BB_PROCESS_ERROR_RETURN(!materialPath.isEmpty()); BBSerializer::BBMaterial material = deserialize(materialPath); material.set_cullstate(bEnable); serialize(material, materialPath); } void BBRendererManager::changeCullFace(BBMaterial *pMaterial, int face) { QString materialPath = m_CachedMaterials.key(pMaterial); BB_PROCESS_ERROR_RETURN(!materialPath.isEmpty()); BBSerializer::BBMaterial material = deserialize(materialPath); material.set_cullface(face); serialize(material, materialPath); } QString BBRendererManager::getShaderFilePath(const QString &name) { QString filePath = BB_PATH_RESOURCE_SHADER() + name; return filePath; } BBMaterial* BBRendererManager::getDeferredRenderingMaterial(int nIndex) { if (!m_pDeferredRenderingMaterial[0]) { createDeferredRenderingMaterial(); } return m_pDeferredRenderingMaterial[nIndex]; } BBMaterial* BBRendererManager::createCoordinateUIMaterial() { BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("coordinate2D", BB_PATH_RESOURCE_SHADER(coordinate2D.vert), BB_PATH_RESOURCE_SHADER(coordinate.frag)); pMaterial->getBaseRenderPass()->setBlendState(true); pMaterial->getBaseRenderPass()->setZFunc(GL_ALWAYS); pMaterial->setVector4(LOCATION_CAMERA_PARAMETERS0, 800.0f, 600.0f, 0.0f, 0.0f); return pMaterial; } BBMaterial* BBRendererManager::createUIMaterial() { BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("UI", BB_PATH_RESOURCE_SHADER(UI.vert), BB_PATH_RESOURCE_SHADER(UI.frag)); pMaterial->getBaseRenderPass()->setBlendState(true); pMaterial->setVector4(LOCATION_CANVAS, 800.0f, 600.0, 0.0f, 0.0f); return pMaterial; } BBMaterial* BBRendererManager::createStencilUIMaterial() { BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("stencilUI", BB_PATH_RESOURCE_SHADER(stencilUI.vert), BB_PATH_RESOURCE_SHADER(stencilUI.frag)); pMaterial->setBlendState(true); pMaterial->setZTestState(false); pMaterial->setZMask(false); pMaterial->setStencilMask(true); pMaterial->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); return pMaterial; } void BBRendererManager::serialize(BBSerializer::BBMaterial material, const QString &filePath) { int nLength = material.ByteSizeLong() + 1; char szBuffer[nLength] = {0}; material.SerializeToArray(szBuffer, nLength); BBUtils::saveToFile(filePath.toStdString().c_str(), szBuffer, nLength); } BBSerializer::BBMaterial BBRendererManager::deserialize(const QString &filePath) { BBSerializer::BBMaterial material; int nLength = -1; char *pData = BBUtils::loadFileContent(filePath.toStdString().c_str(), nLength); if (!pData) return material; material.ParseFromArray(pData, nLength); BB_SAFE_DELETE_ARRAY(pData); return material; } QStringList BBRendererManager::loadShaderList(const QString &filter) { QStringList nameList; QDir dir; QStringList filters; filters << filter; dir.setPath(BB_PATH_RESOURCE_SHADER()); dir.setNameFilters(filters); QDirIterator iter(dir, QDirIterator::Subdirectories); while (iter.hasNext()) { iter.next(); QFileInfo info = iter.fileInfo(); if (info.isFile()) { // relative to BB_PATH_RESOURCE_SHADER QString name = QDir(BB_PATH_RESOURCE_SHADER()).relativeFilePath(info.absolutePath()); if (name.length() == 1) { // in the shader dir root name = info.baseName(); } else { name = name + "/" + info.baseName(); } nameList.append(name); } } return nameList; } void BBRendererManager::loadMaterialContent(const QString &filePath, BBMaterial *pMaterial) { BBSerializer::BBMaterial material = deserialize(filePath); pMaterial->init(material.shadername().data(), QString::fromStdString(material.vshaderpath()), QString::fromStdString(material.fshaderpath())); // render state pMaterial->setBlendState(material.blendstate()); pMaterial->setBlendFunc(BBUtils::getBlendFunc(material.srcblendfunc()), BBUtils::getBlendFunc(material.dstblendfunc())); pMaterial->setCullState(material.cullstate()); pMaterial->setCullFace(material.cullface()); // uniform int nTextureCount = material.texturename_size(); for (int i = 0; i < nTextureCount; i++) { BBTexture texture; QString texturePath = QString::fromStdString(material.texturepath(i)); pMaterial->setSampler2D(material.texturename(i), texture.createTexture2D(texturePath), texturePath); } BBTexture texture; BBSerializer::BBCubeMap cubeMapPath = material.cubemappaths(); QString paths[6] = {QString::fromStdString(cubeMapPath.positivex()), QString::fromStdString(cubeMapPath.negativex()), QString::fromStdString(cubeMapPath.positivey()), QString::fromStdString(cubeMapPath.negativey()), QString::fromStdString(cubeMapPath.positivez()), QString::fromStdString(cubeMapPath.negativez())}; pMaterial->setSamplerCube(material.cubemapname(), texture.createTextureCube(paths), paths); int nFloatCount = material.floatname_size(); for (int i = 0; i < nFloatCount; i++) { pMaterial->setFloat(material.floatname(i), material.floatvalue(i)); } int nVec4Count = material.vec4name_size(); for (int i = 0; i < nVec4Count; i++) { BBSerializer::BBVector4f vec4 = material.vec4value(i); pMaterial->setVector4(material.vec4name(i), vec4.x(), vec4.y(), vec4.z(), vec4.w()); } // test float *pLightPosition = new float[4] {1.0f, 1.0f, 0.0f, 0.0f}; float *pLightColor = new float[4] {1.0f, 1.0f, 1.0f, 1.0f}; pMaterial->setVector4(LOCATION_LIGHT_POSITION, pLightPosition); pMaterial->setVector4(LOCATION_LIGHT_COLOR, pLightColor); } void BBRendererManager::createDeferredRenderingMaterial() { m_pDeferredRenderingMaterial[0] = new BBMaterial(); m_pDeferredRenderingMaterial[0]->init("DeferredPosition", BB_PATH_RESOURCE_SHADER(DeferredPosition.vert), BB_PATH_RESOURCE_SHADER(DeferredPosition.frag)); m_pDeferredRenderingMaterial[1] = new BBMaterial(); m_pDeferredRenderingMaterial[1]->init("DeferredNormal", BB_PATH_RESOURCE_SHADER(DeferredNormal.vert), BB_PATH_RESOURCE_SHADER(DeferredNormal.frag)); m_pDeferredRenderingMaterial[2] = new BBMaterial(); m_pDeferredRenderingMaterial[2]->init("DeferredColor", BB_PATH_RESOURCE_SHADER(DeferredColor.vert), BB_PATH_RESOURCE_SHADER(DeferredColor.frag)); // default float *pTextureSettings = new float[4] {0.0f, 0.0f, 0.0f, 0.0f}; m_pDeferredRenderingMaterial[2]->setVector4(LOCATION_TEXTURE_SETTING0, pTextureSettings); } <|start_filename|>Code/BBearEditor/Engine/Render/RayTracing/BBScreenSpaceRayTracker.cpp<|end_filename|> #include "BBScreenSpaceRayTracker.h" #include "Render/BBMaterial.h" #include "Scene/BBScene.h" #include "Base/BBGameObject.h" #include "2D/BBFullScreenQuad.h" #include "Render/Texture/BBTexture.h" void BBScreenSpaceRayTracker::open(BBScene *pScene) { setGBufferPass(pScene); setRayTracingPass(pScene); } void BBScreenSpaceRayTracker::setGBufferPass(BBScene *pScene) { BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("Efficient GPU Screen-Space Ray Tracing_GBuffer", BB_PATH_RESOURCE_SHADER(RayTracing/0_GBuffer.vert), BB_PATH_RESOURCE_SHADER(RayTracing/0_GBuffer.frag)); BBTexture texture; pMaterial->setSampler2D("DiffuseTex", texture.createTexture2D(BB_PATH_RESOURCE_TEXTURE(gold.jpg))); QList<BBGameObject*> objects = pScene->getModels(); for (QList<BBGameObject*>::Iterator itr = objects.begin(); itr != objects.end(); itr++) { BBGameObject *pObject = *itr; pObject->setCurrentMaterial(pMaterial->clone()); } } void BBScreenSpaceRayTracker::setRayTracingPass(BBScene *pScene) { BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("Efficient GPU Screen-Space Ray Tracing_RayTracing", BB_PATH_RESOURCE_SHADER(RayTracing/0_RayTracing.vert), BB_PATH_RESOURCE_SHADER(RayTracing/0_RayTracing.frag)); QList<BBGameObject*> objects = pScene->getModels(); for (QList<BBGameObject*>::Iterator itr = objects.begin(); itr != objects.end(); itr++) { BBGameObject *pObject = *itr; BBMaterial *pMaterialInstance = pMaterial->clone(); BBTexture texture; pMaterialInstance->setSampler2D("DiffuseTex", texture.createTexture2D(BB_PATH_RESOURCE_TEXTURE(gold.jpg))); pObject->setCurrentMaterial(pMaterialInstance); } } <|start_filename|>External/ProtoBuffer/lib/CMakeFiles/libprotobuf.dir/DependInfo.cmake<|end_filename|> # Consider dependencies only in project. set(CMAKE_DEPENDS_IN_PROJECT_ONLY OFF) # The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES ) # The set of dependency files which are needed: set(CMAKE_DEPENDS_DEPENDENCY_FILES "D:/workspace/protobuf-3.16.0/src/google/protobuf/any.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/map.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/message.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/service.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.obj" "gcc" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.obj.d" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <|start_filename|>Code/BBearEditor/Engine/Scene/CoordinateSystem/BBCoordinateSystem2D.h<|end_filename|> #ifndef BBCOORDINATESYSTEM2D_H #define BBCOORDINATESYSTEM2D_H #include "Base/BBGameObject.h" class BBCoordinateComponent2D; class BBBoundingBox2D; class BBCoordinateCircle2D; class BBCoordinateTickMark2D; class BBCoordinateSector2D; class BBCoordinateSystem2D : public BBGameObject { public: BBCoordinateSystem2D(); ~BBCoordinateSystem2D(); void init() override; void render(BBCamera *pCamera) override; void setScreenCoordinate(int x, int y) override; void translate(int nDeltaX, int nDeltaY) override; void setScale(float scale, bool bUpdateLocalTransform = true) override; bool hitAxis(int x, int y); bool hitFace(int x, int y); virtual void transform(int x, int y) = 0; void setSelectedObject(BBGameObject *pObject); virtual void setSelectedAxis(const BBAxisFlags &axis); virtual bool mouseMoveEvent(int x, int y, bool bMousePressed); virtual void stopTransform(); protected: BBAxisFlags m_SelectedAxis; QPoint m_LastMousePos; BBGameObject *m_pSelectedObject; bool m_bTransforming; BBCoordinateComponent2D *m_pCoordinateComponent; BBBoundingBox2D *m_pBoundingBoxX; BBBoundingBox2D *m_pBoundingBoxY; BBBoundingBox2D *m_pBoundingBoxXOY; }; class BBPositionCoordinateSystem2D : public BBCoordinateSystem2D { public: BBPositionCoordinateSystem2D(); private: void transform(int x, int y) override; }; class BBRotationCoordinateSystem2D : public BBCoordinateSystem2D { public: BBRotationCoordinateSystem2D(); ~BBRotationCoordinateSystem2D(); void init() override; void render(BBCamera *pCamera) override; void setScreenCoordinate(int x, int y) override; void stopTransform() override; private: void transform(int x, int y) override; BBCoordinateCircle2D *m_pCoordinateCircle; BBCoordinateTickMark2D *m_pCoordinateTickMark; BBCoordinateSector2D *m_pCoordinateSector; }; class BBScaleCoordinateSystem2D : public BBCoordinateSystem2D { public: BBScaleCoordinateSystem2D(); void setRotation(const QVector3D &rotation, bool bUpdateLocalTransform = true) override; bool mouseMoveEvent(int x, int y, bool bMousePressed) override; void stopTransform() override; private: void transform(int x, int y) override; // current - start int m_nDeltaX; int m_nDeltaY; }; #endif // BBCOORDINATESYSTEM2D_H <|start_filename|>Code/BBearEditor/Engine/Render/BufferObject/BBTranslateFeedbackObject.h<|end_filename|> #ifndef BBTRANSLATEFEEDBACKOBJECT_H #define BBTRANSLATEFEEDBACKOBJECT_H #include "BBBufferObject.h" class BBTranslateFeedbackObject : public BBBufferObject { public: BBTranslateFeedbackObject(int nVertexCount, GLenum hint, GLenum eDrawPrimitiveType); void bind() override; void unbind() override; void debug(); private: GLuint createTFO(); GLuint m_TFO; int m_nVertexCount; GLenum m_eDrawPrimitiveType; }; #endif // BBTRANSLATEFEEDBACKOBJECT_H <|start_filename|>Code/BBearEditor/Engine/Serializer/BBBuildDataSerializer.bat<|end_filename|> protoc --cpp_out=. BBVector.proto protoc --cpp_out=. BBGameObject.proto protoc --cpp_out=. BBHierarchyTreeWidgetItem.proto protoc --cpp_out=. BBScene.proto protoc --cpp_out=. BBMaterial.proto protoc --cpp_out=. BBCubeMap.proto @pause <|start_filename|>Resources/shaders/coordinate2D.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBColor; varying vec4 V_Color; uniform mat4 BBModelMatrix; uniform vec4 BBCameraParameters; void main() { V_Color = BBColor; vec4 screen_pos = BBModelMatrix * BBPosition; // Scaling to NDC coordinates // Z is any value of -1 ~ 1 gl_Position = vec4(screen_pos.x / BBCameraParameters.x * 2.0, screen_pos.y / BBCameraParameters.y * 2.0, 0.0, 1.0); } <|start_filename|>Code/BBearEditor/Engine/Render/Texture/BBTexture.cpp<|end_filename|> #include "BBTexture.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" BBTexture::BBTexture() : BBBaseRenderComponent() { } /** * @brief BBTexture::createTexture2D * @param pPixelData * @param nWidth * @param nHeight * @param eType RGB or RGBA ... * @return */ GLuint BBTexture::createTexture2D(unsigned char *pPixelData, int nWidth, int nHeight, GLenum eType) { GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);// GL_CLAMP glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // from CPU to GPU // 3: GUP // 6: = 0 // 7: CPU glTexImage2D(GL_TEXTURE_2D, 0, eType, nWidth, nHeight, 0, eType, GL_UNSIGNED_BYTE, pPixelData); glBindTexture(GL_TEXTURE_2D, 0); return texture; } GLuint BBTexture::createTexture2D(float *pPixelData, int nWidth, int nHeight, GLenum eType) { GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);// GL_CLAMP glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // from CPU to GPU // 3: GUP // 6: = 0 // 7: CPU glTexImage2D(GL_TEXTURE_2D, 0, eType, nWidth, nHeight, 0, GL_RGB, GL_FLOAT, pPixelData); glBindTexture(GL_TEXTURE_2D, 0); return texture; } GLuint BBTexture::createTexture2D(QImage image, GLenum eType) { return createTexture2D(image.bits(), image.width(), image.height(), eType); } GLuint BBTexture::createTexture2D(const QString &path, GLenum eType) { QImage image(path); if (image.isNull()) { image = QImage(128, 128, QImage::Format_RGB32); image.fill(QColor(255, 255, 255)); } image = image.mirrored(false, true); image = image.rgbSwapped(); return createTexture2D(image.bits(), image.width(), image.height(), eType); } GLuint BBTexture::createTexture2DFromBMP(const char *path) { // black GLuint texture = 0; unsigned char *pBmpFileContent = NULL; do { int nFileSize = 0; pBmpFileContent = (unsigned char*) BBUtils::loadFileContent(path, nFileSize); BB_PROCESS_ERROR(pBmpFileContent); int nBmpWidth = 0; int nBmpHeight = 0; unsigned char *pPixelData = BBUtils::decodeBMP(pBmpFileContent, nBmpWidth, nBmpHeight); BB_PROCESS_ERROR(pPixelData); texture = createTexture2D(pPixelData, nBmpWidth, nBmpHeight, GL_RGB); } while(0); BB_SAFE_DELETE(pBmpFileContent); return texture; } GLuint BBTexture::createHDRTexture2D(const char *pFilePath) { stbi_set_flip_vertically_on_load(true); int nWidth; int nHeight; int nrComponents; float *pData = stbi_loadf(pFilePath, &nWidth, &nHeight, &nrComponents, 0); GLuint hdrTexture = 0; if (pData) { glGenTextures(1, &hdrTexture); glBindTexture(GL_TEXTURE_2D, hdrTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, nWidth, nHeight, 0, GL_RGB, GL_FLOAT, pData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(pData); } else { qDebug() << "Failed to load HDR image."; } return hdrTexture; } GLuint BBTexture::createTexture3D(unsigned char *pData, int nWidth, int nHeight, int nDepth, GLenum eType) { GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_3D, texture); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT);// GL_CLAMP glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8_SNORM, nWidth, nHeight, nDepth, 0, eType, GL_UNSIGNED_BYTE, pData); glBindTexture(GL_TEXTURE_3D, 0); return texture; } GLuint BBTexture::createTextureCube(const QString paths[], GLenum eType) { GLuint texture = 0; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_CUBE_MAP, texture); for (int i = 0; i < 6; i++) { QImage image(paths[i]); image = image.mirrored(false, true); image = image.rgbSwapped(); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, eType, image.width(), image.height(), 0, eType, GL_UNSIGNED_BYTE, image.bits()); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); return texture; } GLuint BBTexture::allocateTexture2D(int nWidth, int nHeight, GLint internalFormat, GLenum format, GLint minFilter) { GLuint texture = 0; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, nWidth, nHeight, 0, format, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); return texture; } void BBTexture::startWritingTexture2D(GLuint texture) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); // Subsequent rendering code } void BBTexture::generateTexture2DMipmap(GLuint texture) { glBindTexture(GL_TEXTURE_2D, texture); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); } GLuint BBTexture::allocateTexture2DMipmap(int nWidth, int nHeight, GLint internalFormat, GLenum format) { GLuint texture = 0; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); gluBuild2DMipmaps(GL_TEXTURE_2D, internalFormat, nWidth, nHeight, format, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Enable trilinear filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // To ensure that enough memory is allocated for Mipmap // glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); return texture; } void BBTexture::startWritingTexture2DMipmap(GLuint texture, int nMipLevel) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, nMipLevel); // Subsequent rendering code } /** * @brief BBTexture::allocateTextureCube Allocate memory for cube map * @param nWidth * @param nHeight * @param eType * @return */ GLuint BBTexture::allocateTextureCube(int nWidth, int nHeight, GLint internalFormat, GLenum format, GLint minFilter) { GLuint texture = 0; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_CUBE_MAP, texture); for (int i = 0; i < 6; i++) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalFormat, nWidth, nHeight, 0, format, GL_FLOAT, nullptr); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, minFilter); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); return texture; } /** * @brief BBTexture::startWritingTextureCube start writing mode, write into the memory that is allocated by BBTexture::allocateTextureCube * @param texture */ void BBTexture::startWritingTextureCube(GLuint texture, int nSideIndex) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + nSideIndex, texture, 0); // Subsequent rendering code } void BBTexture::generateTextureCubeMipmap(GLuint texture) { glBindTexture(GL_TEXTURE_CUBE_MAP, texture); glGenerateMipmap(GL_TEXTURE_CUBE_MAP); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); } GLuint BBTexture::allocateTextureCubeMipmap(int nWidth, int nHeight, GLint internalFormat, GLenum format) { GLuint texture = 0; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_CUBE_MAP, texture); for (int i = 0; i < 6; i++) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalFormat, nWidth, nHeight, 0, format, GL_FLOAT, nullptr); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Enable trilinear filtering glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); // To ensure that enough memory is allocated for Mipmap glGenerateMipmap(GL_TEXTURE_CUBE_MAP); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); return texture; } void BBTexture::startWritingTextureCubeMipmap(GLuint texture, int nSideIndex, int nMipLevel) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + nSideIndex, texture, nMipLevel); // Subsequent rendering code } <|start_filename|>Resources/shaders/KajiyaKayHair.vert<|end_filename|> #version 330 core in vec4 BBPosition; in vec4 BBTexcoord; in vec4 BBNormal; out vec2 v2f_texcoords; out vec3 v2f_world_pos; out vec3 v2f_normal; out vec3 v2f_view_dir; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; uniform vec4 BBCameraPosition; void main() { vec4 world_pos = BBModelMatrix * BBPosition; gl_Position = BBProjectionMatrix * BBViewMatrix * world_pos; v2f_texcoords = BBTexcoord.xy; v2f_world_pos = world_pos.xyz; v2f_normal = mat3(BBModelMatrix) * BBNormal.xyz; v2f_view_dir = BBCameraPosition.xyz - v2f_world_pos; } <|start_filename|>Code/BBearEditor/Engine/Serializer/BBVector.pb.h<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBVector.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_BBVector_2eproto #define GOOGLE_PROTOBUF_INCLUDED_BBVector_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3016000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3016000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_BBVector_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_BBVector_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[8] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBVector_2eproto; namespace BBSerializer { class BBMatrix4f; struct BBMatrix4fDefaultTypeInternal; extern BBMatrix4fDefaultTypeInternal _BBMatrix4f_default_instance_; class BBMatrix4fB; struct BBMatrix4fBDefaultTypeInternal; extern BBMatrix4fBDefaultTypeInternal _BBMatrix4fB_default_instance_; class BBVector2f; struct BBVector2fDefaultTypeInternal; extern BBVector2fDefaultTypeInternal _BBVector2f_default_instance_; class BBVector2i; struct BBVector2iDefaultTypeInternal; extern BBVector2iDefaultTypeInternal _BBVector2i_default_instance_; class BBVector3f; struct BBVector3fDefaultTypeInternal; extern BBVector3fDefaultTypeInternal _BBVector3f_default_instance_; class BBVector3i; struct BBVector3iDefaultTypeInternal; extern BBVector3iDefaultTypeInternal _BBVector3i_default_instance_; class BBVector4f; struct BBVector4fDefaultTypeInternal; extern BBVector4fDefaultTypeInternal _BBVector4f_default_instance_; class BBVector4i; struct BBVector4iDefaultTypeInternal; extern BBVector4iDefaultTypeInternal _BBVector4i_default_instance_; } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> ::BBSerializer::BBMatrix4f* Arena::CreateMaybeMessage<::BBSerializer::BBMatrix4f>(Arena*); template<> ::BBSerializer::BBMatrix4fB* Arena::CreateMaybeMessage<::BBSerializer::BBMatrix4fB>(Arena*); template<> ::BBSerializer::BBVector2f* Arena::CreateMaybeMessage<::BBSerializer::BBVector2f>(Arena*); template<> ::BBSerializer::BBVector2i* Arena::CreateMaybeMessage<::BBSerializer::BBVector2i>(Arena*); template<> ::BBSerializer::BBVector3f* Arena::CreateMaybeMessage<::BBSerializer::BBVector3f>(Arena*); template<> ::BBSerializer::BBVector3i* Arena::CreateMaybeMessage<::BBSerializer::BBVector3i>(Arena*); template<> ::BBSerializer::BBVector4f* Arena::CreateMaybeMessage<::BBSerializer::BBVector4f>(Arena*); template<> ::BBSerializer::BBVector4i* Arena::CreateMaybeMessage<::BBSerializer::BBVector4i>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace BBSerializer { // =================================================================== class BBVector2f PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBVector2f) */ { public: inline BBVector2f() : BBVector2f(nullptr) {} ~BBVector2f() override; explicit constexpr BBVector2f(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBVector2f(const BBVector2f& from); BBVector2f(BBVector2f&& from) noexcept : BBVector2f() { *this = ::std::move(from); } inline BBVector2f& operator=(const BBVector2f& from) { CopyFrom(from); return *this; } inline BBVector2f& operator=(BBVector2f&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBVector2f& default_instance() { return *internal_default_instance(); } static inline const BBVector2f* internal_default_instance() { return reinterpret_cast<const BBVector2f*>( &_BBVector2f_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(BBVector2f& a, BBVector2f& b) { a.Swap(&b); } inline void Swap(BBVector2f* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBVector2f* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBVector2f* New() const final { return CreateMaybeMessage<BBVector2f>(nullptr); } BBVector2f* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBVector2f>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBVector2f& from); void MergeFrom(const BBVector2f& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBVector2f* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBVector2f"; } protected: explicit BBVector2f(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kXFieldNumber = 1, kYFieldNumber = 2, }; // float x = 1; bool has_x() const; private: bool _internal_has_x() const; public: void clear_x(); float x() const; void set_x(float value); private: float _internal_x() const; void _internal_set_x(float value); public: // float y = 2; bool has_y() const; private: bool _internal_has_y() const; public: void clear_y(); float y() const; void set_y(float value); private: float _internal_y() const; void _internal_set_y(float value); public: // @@protoc_insertion_point(class_scope:BBSerializer.BBVector2f) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; float x_; float y_; friend struct ::TableStruct_BBVector_2eproto; }; // ------------------------------------------------------------------- class BBVector2i PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBVector2i) */ { public: inline BBVector2i() : BBVector2i(nullptr) {} ~BBVector2i() override; explicit constexpr BBVector2i(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBVector2i(const BBVector2i& from); BBVector2i(BBVector2i&& from) noexcept : BBVector2i() { *this = ::std::move(from); } inline BBVector2i& operator=(const BBVector2i& from) { CopyFrom(from); return *this; } inline BBVector2i& operator=(BBVector2i&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBVector2i& default_instance() { return *internal_default_instance(); } static inline const BBVector2i* internal_default_instance() { return reinterpret_cast<const BBVector2i*>( &_BBVector2i_default_instance_); } static constexpr int kIndexInFileMessages = 1; friend void swap(BBVector2i& a, BBVector2i& b) { a.Swap(&b); } inline void Swap(BBVector2i* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBVector2i* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBVector2i* New() const final { return CreateMaybeMessage<BBVector2i>(nullptr); } BBVector2i* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBVector2i>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBVector2i& from); void MergeFrom(const BBVector2i& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBVector2i* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBVector2i"; } protected: explicit BBVector2i(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kXFieldNumber = 1, kYFieldNumber = 2, }; // int32 x = 1; bool has_x() const; private: bool _internal_has_x() const; public: void clear_x(); ::PROTOBUF_NAMESPACE_ID::int32 x() const; void set_x(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_x() const; void _internal_set_x(::PROTOBUF_NAMESPACE_ID::int32 value); public: // int32 y = 2; bool has_y() const; private: bool _internal_has_y() const; public: void clear_y(); ::PROTOBUF_NAMESPACE_ID::int32 y() const; void set_y(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_y() const; void _internal_set_y(::PROTOBUF_NAMESPACE_ID::int32 value); public: // @@protoc_insertion_point(class_scope:BBSerializer.BBVector2i) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::int32 x_; ::PROTOBUF_NAMESPACE_ID::int32 y_; friend struct ::TableStruct_BBVector_2eproto; }; // ------------------------------------------------------------------- class BBVector3f PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBVector3f) */ { public: inline BBVector3f() : BBVector3f(nullptr) {} ~BBVector3f() override; explicit constexpr BBVector3f(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBVector3f(const BBVector3f& from); BBVector3f(BBVector3f&& from) noexcept : BBVector3f() { *this = ::std::move(from); } inline BBVector3f& operator=(const BBVector3f& from) { CopyFrom(from); return *this; } inline BBVector3f& operator=(BBVector3f&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBVector3f& default_instance() { return *internal_default_instance(); } static inline const BBVector3f* internal_default_instance() { return reinterpret_cast<const BBVector3f*>( &_BBVector3f_default_instance_); } static constexpr int kIndexInFileMessages = 2; friend void swap(BBVector3f& a, BBVector3f& b) { a.Swap(&b); } inline void Swap(BBVector3f* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBVector3f* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBVector3f* New() const final { return CreateMaybeMessage<BBVector3f>(nullptr); } BBVector3f* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBVector3f>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBVector3f& from); void MergeFrom(const BBVector3f& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBVector3f* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBVector3f"; } protected: explicit BBVector3f(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kXFieldNumber = 1, kYFieldNumber = 2, kZFieldNumber = 3, }; // float x = 1; bool has_x() const; private: bool _internal_has_x() const; public: void clear_x(); float x() const; void set_x(float value); private: float _internal_x() const; void _internal_set_x(float value); public: // float y = 2; bool has_y() const; private: bool _internal_has_y() const; public: void clear_y(); float y() const; void set_y(float value); private: float _internal_y() const; void _internal_set_y(float value); public: // float z = 3; bool has_z() const; private: bool _internal_has_z() const; public: void clear_z(); float z() const; void set_z(float value); private: float _internal_z() const; void _internal_set_z(float value); public: // @@protoc_insertion_point(class_scope:BBSerializer.BBVector3f) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; float x_; float y_; float z_; friend struct ::TableStruct_BBVector_2eproto; }; // ------------------------------------------------------------------- class BBVector3i PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBVector3i) */ { public: inline BBVector3i() : BBVector3i(nullptr) {} ~BBVector3i() override; explicit constexpr BBVector3i(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBVector3i(const BBVector3i& from); BBVector3i(BBVector3i&& from) noexcept : BBVector3i() { *this = ::std::move(from); } inline BBVector3i& operator=(const BBVector3i& from) { CopyFrom(from); return *this; } inline BBVector3i& operator=(BBVector3i&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBVector3i& default_instance() { return *internal_default_instance(); } static inline const BBVector3i* internal_default_instance() { return reinterpret_cast<const BBVector3i*>( &_BBVector3i_default_instance_); } static constexpr int kIndexInFileMessages = 3; friend void swap(BBVector3i& a, BBVector3i& b) { a.Swap(&b); } inline void Swap(BBVector3i* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBVector3i* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBVector3i* New() const final { return CreateMaybeMessage<BBVector3i>(nullptr); } BBVector3i* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBVector3i>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBVector3i& from); void MergeFrom(const BBVector3i& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBVector3i* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBVector3i"; } protected: explicit BBVector3i(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kXFieldNumber = 1, kYFieldNumber = 2, kZFieldNumber = 3, }; // int32 x = 1; bool has_x() const; private: bool _internal_has_x() const; public: void clear_x(); ::PROTOBUF_NAMESPACE_ID::int32 x() const; void set_x(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_x() const; void _internal_set_x(::PROTOBUF_NAMESPACE_ID::int32 value); public: // int32 y = 2; bool has_y() const; private: bool _internal_has_y() const; public: void clear_y(); ::PROTOBUF_NAMESPACE_ID::int32 y() const; void set_y(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_y() const; void _internal_set_y(::PROTOBUF_NAMESPACE_ID::int32 value); public: // int32 z = 3; bool has_z() const; private: bool _internal_has_z() const; public: void clear_z(); ::PROTOBUF_NAMESPACE_ID::int32 z() const; void set_z(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_z() const; void _internal_set_z(::PROTOBUF_NAMESPACE_ID::int32 value); public: // @@protoc_insertion_point(class_scope:BBSerializer.BBVector3i) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::int32 x_; ::PROTOBUF_NAMESPACE_ID::int32 y_; ::PROTOBUF_NAMESPACE_ID::int32 z_; friend struct ::TableStruct_BBVector_2eproto; }; // ------------------------------------------------------------------- class BBVector4f PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBVector4f) */ { public: inline BBVector4f() : BBVector4f(nullptr) {} ~BBVector4f() override; explicit constexpr BBVector4f(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBVector4f(const BBVector4f& from); BBVector4f(BBVector4f&& from) noexcept : BBVector4f() { *this = ::std::move(from); } inline BBVector4f& operator=(const BBVector4f& from) { CopyFrom(from); return *this; } inline BBVector4f& operator=(BBVector4f&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBVector4f& default_instance() { return *internal_default_instance(); } static inline const BBVector4f* internal_default_instance() { return reinterpret_cast<const BBVector4f*>( &_BBVector4f_default_instance_); } static constexpr int kIndexInFileMessages = 4; friend void swap(BBVector4f& a, BBVector4f& b) { a.Swap(&b); } inline void Swap(BBVector4f* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBVector4f* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBVector4f* New() const final { return CreateMaybeMessage<BBVector4f>(nullptr); } BBVector4f* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBVector4f>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBVector4f& from); void MergeFrom(const BBVector4f& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBVector4f* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBVector4f"; } protected: explicit BBVector4f(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kXFieldNumber = 1, kYFieldNumber = 2, kZFieldNumber = 3, kWFieldNumber = 4, }; // float x = 1; bool has_x() const; private: bool _internal_has_x() const; public: void clear_x(); float x() const; void set_x(float value); private: float _internal_x() const; void _internal_set_x(float value); public: // float y = 2; bool has_y() const; private: bool _internal_has_y() const; public: void clear_y(); float y() const; void set_y(float value); private: float _internal_y() const; void _internal_set_y(float value); public: // float z = 3; bool has_z() const; private: bool _internal_has_z() const; public: void clear_z(); float z() const; void set_z(float value); private: float _internal_z() const; void _internal_set_z(float value); public: // float w = 4; bool has_w() const; private: bool _internal_has_w() const; public: void clear_w(); float w() const; void set_w(float value); private: float _internal_w() const; void _internal_set_w(float value); public: // @@protoc_insertion_point(class_scope:BBSerializer.BBVector4f) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; float x_; float y_; float z_; float w_; friend struct ::TableStruct_BBVector_2eproto; }; // ------------------------------------------------------------------- class BBVector4i PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBVector4i) */ { public: inline BBVector4i() : BBVector4i(nullptr) {} ~BBVector4i() override; explicit constexpr BBVector4i(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBVector4i(const BBVector4i& from); BBVector4i(BBVector4i&& from) noexcept : BBVector4i() { *this = ::std::move(from); } inline BBVector4i& operator=(const BBVector4i& from) { CopyFrom(from); return *this; } inline BBVector4i& operator=(BBVector4i&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBVector4i& default_instance() { return *internal_default_instance(); } static inline const BBVector4i* internal_default_instance() { return reinterpret_cast<const BBVector4i*>( &_BBVector4i_default_instance_); } static constexpr int kIndexInFileMessages = 5; friend void swap(BBVector4i& a, BBVector4i& b) { a.Swap(&b); } inline void Swap(BBVector4i* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBVector4i* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBVector4i* New() const final { return CreateMaybeMessage<BBVector4i>(nullptr); } BBVector4i* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBVector4i>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBVector4i& from); void MergeFrom(const BBVector4i& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBVector4i* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBVector4i"; } protected: explicit BBVector4i(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kXFieldNumber = 1, kYFieldNumber = 2, kZFieldNumber = 3, kWFieldNumber = 4, }; // int32 x = 1; bool has_x() const; private: bool _internal_has_x() const; public: void clear_x(); ::PROTOBUF_NAMESPACE_ID::int32 x() const; void set_x(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_x() const; void _internal_set_x(::PROTOBUF_NAMESPACE_ID::int32 value); public: // int32 y = 2; bool has_y() const; private: bool _internal_has_y() const; public: void clear_y(); ::PROTOBUF_NAMESPACE_ID::int32 y() const; void set_y(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_y() const; void _internal_set_y(::PROTOBUF_NAMESPACE_ID::int32 value); public: // int32 z = 3; bool has_z() const; private: bool _internal_has_z() const; public: void clear_z(); ::PROTOBUF_NAMESPACE_ID::int32 z() const; void set_z(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_z() const; void _internal_set_z(::PROTOBUF_NAMESPACE_ID::int32 value); public: // int32 w = 4; bool has_w() const; private: bool _internal_has_w() const; public: void clear_w(); ::PROTOBUF_NAMESPACE_ID::int32 w() const; void set_w(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_w() const; void _internal_set_w(::PROTOBUF_NAMESPACE_ID::int32 value); public: // @@protoc_insertion_point(class_scope:BBSerializer.BBVector4i) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::int32 x_; ::PROTOBUF_NAMESPACE_ID::int32 y_; ::PROTOBUF_NAMESPACE_ID::int32 z_; ::PROTOBUF_NAMESPACE_ID::int32 w_; friend struct ::TableStruct_BBVector_2eproto; }; // ------------------------------------------------------------------- class BBMatrix4f PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBMatrix4f) */ { public: inline BBMatrix4f() : BBMatrix4f(nullptr) {} ~BBMatrix4f() override; explicit constexpr BBMatrix4f(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBMatrix4f(const BBMatrix4f& from); BBMatrix4f(BBMatrix4f&& from) noexcept : BBMatrix4f() { *this = ::std::move(from); } inline BBMatrix4f& operator=(const BBMatrix4f& from) { CopyFrom(from); return *this; } inline BBMatrix4f& operator=(BBMatrix4f&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBMatrix4f& default_instance() { return *internal_default_instance(); } static inline const BBMatrix4f* internal_default_instance() { return reinterpret_cast<const BBMatrix4f*>( &_BBMatrix4f_default_instance_); } static constexpr int kIndexInFileMessages = 6; friend void swap(BBMatrix4f& a, BBMatrix4f& b) { a.Swap(&b); } inline void Swap(BBMatrix4f* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBMatrix4f* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBMatrix4f* New() const final { return CreateMaybeMessage<BBMatrix4f>(nullptr); } BBMatrix4f* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBMatrix4f>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBMatrix4f& from); void MergeFrom(const BBMatrix4f& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBMatrix4f* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBMatrix4f"; } protected: explicit BBMatrix4f(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kDataFieldNumber = 1, }; // repeated float data = 1; int data_size() const; private: int _internal_data_size() const; public: void clear_data(); private: float _internal_data(int index) const; const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& _internal_data() const; void _internal_add_data(float value); ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* _internal_mutable_data(); public: float data(int index) const; void set_data(int index, float value); void add_data(float value); const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& data() const; ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* mutable_data(); // @@protoc_insertion_point(class_scope:BBSerializer.BBMatrix4f) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::RepeatedField< float > data_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_BBVector_2eproto; }; // ------------------------------------------------------------------- class BBMatrix4fB PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBMatrix4fB) */ { public: inline BBMatrix4fB() : BBMatrix4fB(nullptr) {} ~BBMatrix4fB() override; explicit constexpr BBMatrix4fB(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBMatrix4fB(const BBMatrix4fB& from); BBMatrix4fB(BBMatrix4fB&& from) noexcept : BBMatrix4fB() { *this = ::std::move(from); } inline BBMatrix4fB& operator=(const BBMatrix4fB& from) { CopyFrom(from); return *this; } inline BBMatrix4fB& operator=(BBMatrix4fB&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBMatrix4fB& default_instance() { return *internal_default_instance(); } static inline const BBMatrix4fB* internal_default_instance() { return reinterpret_cast<const BBMatrix4fB*>( &_BBMatrix4fB_default_instance_); } static constexpr int kIndexInFileMessages = 7; friend void swap(BBMatrix4fB& a, BBMatrix4fB& b) { a.Swap(&b); } inline void Swap(BBMatrix4fB* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBMatrix4fB* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBMatrix4fB* New() const final { return CreateMaybeMessage<BBMatrix4fB>(nullptr); } BBMatrix4fB* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBMatrix4fB>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBMatrix4fB& from); void MergeFrom(const BBMatrix4fB& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBMatrix4fB* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBMatrix4fB"; } protected: explicit BBMatrix4fB(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kDataFieldNumber = 1, }; // bytes data = 1; bool has_data() const; private: bool _internal_has_data() const; public: void clear_data(); const std::string& data() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_data(ArgT0&& arg0, ArgT... args); std::string* mutable_data(); std::string* release_data(); void set_allocated_data(std::string* data); private: const std::string& _internal_data() const; void _internal_set_data(const std::string& value); std::string* _internal_mutable_data(); public: // @@protoc_insertion_point(class_scope:BBSerializer.BBMatrix4fB) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr data_; friend struct ::TableStruct_BBVector_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // BBVector2f // float x = 1; inline bool BBVector2f::_internal_has_x() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool BBVector2f::has_x() const { return _internal_has_x(); } inline void BBVector2f::clear_x() { x_ = 0; _has_bits_[0] &= ~0x00000001u; } inline float BBVector2f::_internal_x() const { return x_; } inline float BBVector2f::x() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector2f.x) return _internal_x(); } inline void BBVector2f::_internal_set_x(float value) { _has_bits_[0] |= 0x00000001u; x_ = value; } inline void BBVector2f::set_x(float value) { _internal_set_x(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector2f.x) } // float y = 2; inline bool BBVector2f::_internal_has_y() const { bool value = (_has_bits_[0] & 0x00000002u) != 0; return value; } inline bool BBVector2f::has_y() const { return _internal_has_y(); } inline void BBVector2f::clear_y() { y_ = 0; _has_bits_[0] &= ~0x00000002u; } inline float BBVector2f::_internal_y() const { return y_; } inline float BBVector2f::y() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector2f.y) return _internal_y(); } inline void BBVector2f::_internal_set_y(float value) { _has_bits_[0] |= 0x00000002u; y_ = value; } inline void BBVector2f::set_y(float value) { _internal_set_y(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector2f.y) } // ------------------------------------------------------------------- // BBVector2i // int32 x = 1; inline bool BBVector2i::_internal_has_x() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool BBVector2i::has_x() const { return _internal_has_x(); } inline void BBVector2i::clear_x() { x_ = 0; _has_bits_[0] &= ~0x00000001u; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector2i::_internal_x() const { return x_; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector2i::x() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector2i.x) return _internal_x(); } inline void BBVector2i::_internal_set_x(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000001u; x_ = value; } inline void BBVector2i::set_x(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_x(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector2i.x) } // int32 y = 2; inline bool BBVector2i::_internal_has_y() const { bool value = (_has_bits_[0] & 0x00000002u) != 0; return value; } inline bool BBVector2i::has_y() const { return _internal_has_y(); } inline void BBVector2i::clear_y() { y_ = 0; _has_bits_[0] &= ~0x00000002u; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector2i::_internal_y() const { return y_; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector2i::y() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector2i.y) return _internal_y(); } inline void BBVector2i::_internal_set_y(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000002u; y_ = value; } inline void BBVector2i::set_y(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_y(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector2i.y) } // ------------------------------------------------------------------- // BBVector3f // float x = 1; inline bool BBVector3f::_internal_has_x() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool BBVector3f::has_x() const { return _internal_has_x(); } inline void BBVector3f::clear_x() { x_ = 0; _has_bits_[0] &= ~0x00000001u; } inline float BBVector3f::_internal_x() const { return x_; } inline float BBVector3f::x() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector3f.x) return _internal_x(); } inline void BBVector3f::_internal_set_x(float value) { _has_bits_[0] |= 0x00000001u; x_ = value; } inline void BBVector3f::set_x(float value) { _internal_set_x(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector3f.x) } // float y = 2; inline bool BBVector3f::_internal_has_y() const { bool value = (_has_bits_[0] & 0x00000002u) != 0; return value; } inline bool BBVector3f::has_y() const { return _internal_has_y(); } inline void BBVector3f::clear_y() { y_ = 0; _has_bits_[0] &= ~0x00000002u; } inline float BBVector3f::_internal_y() const { return y_; } inline float BBVector3f::y() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector3f.y) return _internal_y(); } inline void BBVector3f::_internal_set_y(float value) { _has_bits_[0] |= 0x00000002u; y_ = value; } inline void BBVector3f::set_y(float value) { _internal_set_y(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector3f.y) } // float z = 3; inline bool BBVector3f::_internal_has_z() const { bool value = (_has_bits_[0] & 0x00000004u) != 0; return value; } inline bool BBVector3f::has_z() const { return _internal_has_z(); } inline void BBVector3f::clear_z() { z_ = 0; _has_bits_[0] &= ~0x00000004u; } inline float BBVector3f::_internal_z() const { return z_; } inline float BBVector3f::z() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector3f.z) return _internal_z(); } inline void BBVector3f::_internal_set_z(float value) { _has_bits_[0] |= 0x00000004u; z_ = value; } inline void BBVector3f::set_z(float value) { _internal_set_z(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector3f.z) } // ------------------------------------------------------------------- // BBVector3i // int32 x = 1; inline bool BBVector3i::_internal_has_x() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool BBVector3i::has_x() const { return _internal_has_x(); } inline void BBVector3i::clear_x() { x_ = 0; _has_bits_[0] &= ~0x00000001u; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector3i::_internal_x() const { return x_; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector3i::x() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector3i.x) return _internal_x(); } inline void BBVector3i::_internal_set_x(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000001u; x_ = value; } inline void BBVector3i::set_x(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_x(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector3i.x) } // int32 y = 2; inline bool BBVector3i::_internal_has_y() const { bool value = (_has_bits_[0] & 0x00000002u) != 0; return value; } inline bool BBVector3i::has_y() const { return _internal_has_y(); } inline void BBVector3i::clear_y() { y_ = 0; _has_bits_[0] &= ~0x00000002u; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector3i::_internal_y() const { return y_; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector3i::y() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector3i.y) return _internal_y(); } inline void BBVector3i::_internal_set_y(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000002u; y_ = value; } inline void BBVector3i::set_y(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_y(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector3i.y) } // int32 z = 3; inline bool BBVector3i::_internal_has_z() const { bool value = (_has_bits_[0] & 0x00000004u) != 0; return value; } inline bool BBVector3i::has_z() const { return _internal_has_z(); } inline void BBVector3i::clear_z() { z_ = 0; _has_bits_[0] &= ~0x00000004u; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector3i::_internal_z() const { return z_; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector3i::z() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector3i.z) return _internal_z(); } inline void BBVector3i::_internal_set_z(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000004u; z_ = value; } inline void BBVector3i::set_z(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_z(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector3i.z) } // ------------------------------------------------------------------- // BBVector4f // float x = 1; inline bool BBVector4f::_internal_has_x() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool BBVector4f::has_x() const { return _internal_has_x(); } inline void BBVector4f::clear_x() { x_ = 0; _has_bits_[0] &= ~0x00000001u; } inline float BBVector4f::_internal_x() const { return x_; } inline float BBVector4f::x() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector4f.x) return _internal_x(); } inline void BBVector4f::_internal_set_x(float value) { _has_bits_[0] |= 0x00000001u; x_ = value; } inline void BBVector4f::set_x(float value) { _internal_set_x(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector4f.x) } // float y = 2; inline bool BBVector4f::_internal_has_y() const { bool value = (_has_bits_[0] & 0x00000002u) != 0; return value; } inline bool BBVector4f::has_y() const { return _internal_has_y(); } inline void BBVector4f::clear_y() { y_ = 0; _has_bits_[0] &= ~0x00000002u; } inline float BBVector4f::_internal_y() const { return y_; } inline float BBVector4f::y() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector4f.y) return _internal_y(); } inline void BBVector4f::_internal_set_y(float value) { _has_bits_[0] |= 0x00000002u; y_ = value; } inline void BBVector4f::set_y(float value) { _internal_set_y(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector4f.y) } // float z = 3; inline bool BBVector4f::_internal_has_z() const { bool value = (_has_bits_[0] & 0x00000004u) != 0; return value; } inline bool BBVector4f::has_z() const { return _internal_has_z(); } inline void BBVector4f::clear_z() { z_ = 0; _has_bits_[0] &= ~0x00000004u; } inline float BBVector4f::_internal_z() const { return z_; } inline float BBVector4f::z() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector4f.z) return _internal_z(); } inline void BBVector4f::_internal_set_z(float value) { _has_bits_[0] |= 0x00000004u; z_ = value; } inline void BBVector4f::set_z(float value) { _internal_set_z(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector4f.z) } // float w = 4; inline bool BBVector4f::_internal_has_w() const { bool value = (_has_bits_[0] & 0x00000008u) != 0; return value; } inline bool BBVector4f::has_w() const { return _internal_has_w(); } inline void BBVector4f::clear_w() { w_ = 0; _has_bits_[0] &= ~0x00000008u; } inline float BBVector4f::_internal_w() const { return w_; } inline float BBVector4f::w() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector4f.w) return _internal_w(); } inline void BBVector4f::_internal_set_w(float value) { _has_bits_[0] |= 0x00000008u; w_ = value; } inline void BBVector4f::set_w(float value) { _internal_set_w(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector4f.w) } // ------------------------------------------------------------------- // BBVector4i // int32 x = 1; inline bool BBVector4i::_internal_has_x() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool BBVector4i::has_x() const { return _internal_has_x(); } inline void BBVector4i::clear_x() { x_ = 0; _has_bits_[0] &= ~0x00000001u; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector4i::_internal_x() const { return x_; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector4i::x() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector4i.x) return _internal_x(); } inline void BBVector4i::_internal_set_x(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000001u; x_ = value; } inline void BBVector4i::set_x(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_x(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector4i.x) } // int32 y = 2; inline bool BBVector4i::_internal_has_y() const { bool value = (_has_bits_[0] & 0x00000002u) != 0; return value; } inline bool BBVector4i::has_y() const { return _internal_has_y(); } inline void BBVector4i::clear_y() { y_ = 0; _has_bits_[0] &= ~0x00000002u; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector4i::_internal_y() const { return y_; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector4i::y() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector4i.y) return _internal_y(); } inline void BBVector4i::_internal_set_y(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000002u; y_ = value; } inline void BBVector4i::set_y(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_y(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector4i.y) } // int32 z = 3; inline bool BBVector4i::_internal_has_z() const { bool value = (_has_bits_[0] & 0x00000004u) != 0; return value; } inline bool BBVector4i::has_z() const { return _internal_has_z(); } inline void BBVector4i::clear_z() { z_ = 0; _has_bits_[0] &= ~0x00000004u; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector4i::_internal_z() const { return z_; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector4i::z() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector4i.z) return _internal_z(); } inline void BBVector4i::_internal_set_z(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000004u; z_ = value; } inline void BBVector4i::set_z(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_z(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector4i.z) } // int32 w = 4; inline bool BBVector4i::_internal_has_w() const { bool value = (_has_bits_[0] & 0x00000008u) != 0; return value; } inline bool BBVector4i::has_w() const { return _internal_has_w(); } inline void BBVector4i::clear_w() { w_ = 0; _has_bits_[0] &= ~0x00000008u; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector4i::_internal_w() const { return w_; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBVector4i::w() const { // @@protoc_insertion_point(field_get:BBSerializer.BBVector4i.w) return _internal_w(); } inline void BBVector4i::_internal_set_w(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000008u; w_ = value; } inline void BBVector4i::set_w(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_w(value); // @@protoc_insertion_point(field_set:BBSerializer.BBVector4i.w) } // ------------------------------------------------------------------- // BBMatrix4f // repeated float data = 1; inline int BBMatrix4f::_internal_data_size() const { return data_.size(); } inline int BBMatrix4f::data_size() const { return _internal_data_size(); } inline void BBMatrix4f::clear_data() { data_.Clear(); } inline float BBMatrix4f::_internal_data(int index) const { return data_.Get(index); } inline float BBMatrix4f::data(int index) const { // @@protoc_insertion_point(field_get:BBSerializer.BBMatrix4f.data) return _internal_data(index); } inline void BBMatrix4f::set_data(int index, float value) { data_.Set(index, value); // @@protoc_insertion_point(field_set:BBSerializer.BBMatrix4f.data) } inline void BBMatrix4f::_internal_add_data(float value) { data_.Add(value); } inline void BBMatrix4f::add_data(float value) { _internal_add_data(value); // @@protoc_insertion_point(field_add:BBSerializer.BBMatrix4f.data) } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& BBMatrix4f::_internal_data() const { return data_; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& BBMatrix4f::data() const { // @@protoc_insertion_point(field_list:BBSerializer.BBMatrix4f.data) return _internal_data(); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* BBMatrix4f::_internal_mutable_data() { return &data_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* BBMatrix4f::mutable_data() { // @@protoc_insertion_point(field_mutable_list:BBSerializer.BBMatrix4f.data) return _internal_mutable_data(); } // ------------------------------------------------------------------- // BBMatrix4fB // bytes data = 1; inline bool BBMatrix4fB::_internal_has_data() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool BBMatrix4fB::has_data() const { return _internal_has_data(); } inline void BBMatrix4fB::clear_data() { data_.ClearToEmpty(); _has_bits_[0] &= ~0x00000001u; } inline const std::string& BBMatrix4fB::data() const { // @@protoc_insertion_point(field_get:BBSerializer.BBMatrix4fB.data) return _internal_data(); } template <typename ArgT0, typename... ArgT> PROTOBUF_ALWAYS_INLINE inline void BBMatrix4fB::set_data(ArgT0&& arg0, ArgT... args) { _has_bits_[0] |= 0x00000001u; data_.SetBytes(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArena()); // @@protoc_insertion_point(field_set:BBSerializer.BBMatrix4fB.data) } inline std::string* BBMatrix4fB::mutable_data() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBMatrix4fB.data) return _internal_mutable_data(); } inline const std::string& BBMatrix4fB::_internal_data() const { return data_.Get(); } inline void BBMatrix4fB::_internal_set_data(const std::string& value) { _has_bits_[0] |= 0x00000001u; data_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline std::string* BBMatrix4fB::_internal_mutable_data() { _has_bits_[0] |= 0x00000001u; return data_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* BBMatrix4fB::release_data() { // @@protoc_insertion_point(field_release:BBSerializer.BBMatrix4fB.data) if (!_internal_has_data()) { return nullptr; } _has_bits_[0] &= ~0x00000001u; return data_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void BBMatrix4fB::set_allocated_data(std::string* data) { if (data != nullptr) { _has_bits_[0] |= 0x00000001u; } else { _has_bits_[0] &= ~0x00000001u; } data_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), data, GetArena()); // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBMatrix4fB.data) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_BBVector_2eproto <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBLightManager.h<|end_filename|> #ifndef BBLIGHTMANAGER_H #define BBLIGHTMANAGER_H #include "BBGroupManager.h" class BBPointLight; class BBSpotLight; class BBPointLightManager : public BBGroupManager { Q_OBJECT public: BBPointLightManager(BBPointLight *pLight, QWidget *pParent = 0); ~BBPointLightManager(); protected slots: void setRadius(float fRadius); void setConstantFactor(float fValue); void setLinearFactor(float fValue); void setQuadricFactor(float fValue); protected: BBPointLight *m_pLight; }; class BBSpotLightManager : public BBPointLightManager { Q_OBJECT public: BBSpotLightManager(BBSpotLight *pLight, QWidget *pParent = 0); ~BBSpotLightManager(); }; #endif // BBLIGHTMANAGER_H <|start_filename|>Resources/shaders/PBR/FromUnity.frag<|end_filename|> varying vec4 V_Texcoord; varying vec4 V_World_pos; varying mat3 V_TBN; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; uniform vec4 BBCameraPosition; uniform vec4 BBColor_Color; uniform sampler2D Albedo_Map; uniform sampler2D Normal_Map; uniform sampler2D Metallic_R_Roughness_G_AO_B; uniform float Roughness; uniform float Metallic; // uniform float AO; uniform samplerCube Environment_Cube; struct PBR { vec3 albedo; vec3 normal; float metallic; float glossiness; float roughness; float occlusion; float alpha; vec3 reflect_uvw; vec3 view_dir; }; struct Light { vec3 color; vec3 dir; }; struct IndirectLight { vec3 diffuse; vec3 specular; }; struct GI { Light light; IndirectLight indirect_light; }; vec3 computeSpecular(PBR pbr) { vec3 specular = vec3(0.0); // Sample a small cube map to simulate blur pbr.roughness = pbr.roughness * (1.7 - 0.7 * pbr.roughness); // Sample level float mip = pbr.roughness * 6; // Sample LOD, to do ... specular = textureCube(Environment_Cube, pbr.reflect_uvw).xyz; specular *= pbr.occlusion; return specular; } void standardLightingGI(PBR pbr, inout GI gi) { // diffuse, to do ... Spherical Harmonic Lighting gi.indirect_light.diffuse *= pbr.occlusion; // specular, cube map gi.indirect_light.specular = computeSpecular(pbr); } vec3 computeDiffuseAndSpecularFromMetallic(vec3 albedo, float metallic, inout vec3 specular_color, inout float one_minus_reflectivity) { // The non-metallic specular reflection is gray, while the metal has various bright colors // depend on metallic // gamma // vec4 color_space_dielectric_specular = vec4(0.220916301, 0.220916301, 0.220916301, 1.0 - 0.220916301); // linear // Generally, the reflectivity of non-metallic materials is about 4% vec4 color_space_dielectric_specular = vec4(0.04, 0.04, 0.04, 1.0 - 0.04); specular_color = mix(color_space_dielectric_specular.xyz, albedo, metallic); // the reflectivity of diffuse by the reflectivity of metallic // 1 - mix(dielectric_specular, 1, metallic) // mix(1 - color_space_dielectric_specular.a, 0, metallic) // mix(A, B, v) = A + v * (B - A) one_minus_reflectivity = color_space_dielectric_specular.a - metallic * color_space_dielectric_specular.a; return albedo * one_minus_reflectivity; } // Disney float computeDisneyDiffuse(float NdotV, float NdotL, float LdotH, float roughness) { // F d90 : fresnel, view from 90d float fd90 = 0.5 + 2 * LdotH * LdotH * roughness; float light_scatter = 1 + (fd90 - 1) * pow(1 - NdotL, 5); float view_scatter = 1 + (fd90 - 1) * pow(1 - NdotV, 5); return light_scatter * view_scatter; } vec3 safeNormalize(vec3 v) { // Avoid negative return v / sqrt(max(0.001, dot(v, v))); } float computeSmithJointGGXVisibilityTerm(float NdotL, float NdotV, float roughness) { // approximation float a = roughness; float lambdaV = NdotL * (NdotV * (1 - a) + a); float lambdaL = NdotV * (NdotL * (1 - a) + a); return 0.5 / (lambdaV + lambdaL + 0.00001); } float computeGGXTerm(float NdotH, float roughness) { float a2 = roughness * roughness; float d = (NdotH * a2 - NdotH) * NdotH + 1.0; return 1.0 / 3.1415926 * a2 / (d * d + 0.0000001); } vec3 computeFresnelTerm(vec3 F0, float cosA) { // F0 = when view_dir and normal overlap, e.g. view water surface from top, small // cosA = v, h float t = pow(1 - cosA, 5.0); return F0 + (1 - F0) * t; } vec3 computeFresnelLerp(vec3 F0, vec3 F90, float cosA) { // F0 = when view_dir and normal overlap, e.g. view water surface from top, small // F90 = view from the side float t = pow(1 - cosA, 5.0); return mix(F0, F90, t); } vec4 computeBRDF(PBR pbr, GI gi, vec3 specular_color, float one_minus_reflectivity) { // Bidirectional Reflectance Distribution Function // Bidirectional: light_dir and view_dir // diffuse + gi_diffuse + specular + gi_specular float perceptual_roughness = pbr.roughness; vec3 half_dir = safeNormalize(gi.light.dir + pbr.view_dir); // generally, NdotV should not be negative for visible pixels, but it can happen due to perspective projection and normal mapping // can modify with more operation // or use abs, but there are a few errors float NdotV = abs(dot(pbr.normal, pbr.view_dir)); float NdotL = clamp(dot(pbr.normal, gi.light.dir), 0.0, 1.0); float NdotH = clamp(dot(pbr.normal, half_dir), 0.0, 1.0); float LdotV = clamp(dot(gi.light.dir, pbr.view_dir), 0.0, 1.0); float LdotH = clamp(dot(gi.light.dir, half_dir), 0.0, 1.0); vec3 diffuse = pbr.albedo; // Theoretically, we should divide diffuse_term by Pi and not multiply specular_term float diffuse_term = computeDisneyDiffuse(NdotV, NdotL, LdotH, perceptual_roughness) * NdotL; diffuse = diffuse * (gi.indirect_light.diffuse + gi.light.color * diffuse_term); // D : Normal Distribution Function when half_dir and normal overlap, valid // DFG / (4 * cosl * cosv) // V = F / (4 * cosl * cosv) // * Pi, because we do not divide Pi when computing diffuse // better roughness float roughness = perceptual_roughness * perceptual_roughness; roughness = max(roughness, 0.002); float V = computeSmithJointGGXVisibilityTerm(NdotL, NdotV, roughness); float D = computeGGXTerm(NdotH, roughness); // DG = specular_term float specular_term = V * D * 3.1415926; // gamma correction // specular_term = sqrt(max(0.0001, specular_term)); specular_term = max(0.0, specular_term * NdotL); // handle metallic = 1 and albedo is black if (specular_color.r == 0.0 && specular_color.g == 0.0 && specular_color.b == 0.0) { specular_term *= 0.0; } else { specular_term *= 1.0; } // F = fresnel_term float fresnel_term = computeFresnelTerm(specular_color, LdotH); vec3 specular = specular_term * gi.light.color * fresnel_term; // Image Based Lighting // surface_reduction : gi specular is different with reduction // fresnel_lerp : The transition of specular at different angles (F0 - F90) // reduction = 1 / (roughness ^ 2 + 1) // gamma space // float surface_reduction = 1.0 - 0.28 * roughness * perceptual_roughness; // linear space // 0.5 ~ 1 float surface_reduction = 1.0 / (roughness * roughness + 1.0); float grazing_term = clamp(pbr.glossiness + (1 - one_minus_reflectivity), 0.0, 1.0); vec3 fresnel_lerp = computeFresnelLerp(specular_color, grazing_term, NdotV); vec3 ibl = surface_reduction * gi.indirect_light.specular * fresnel_lerp; vec3 c = diffuse + specular + ibl; return vec4(c, 1.0); } vec4 standardLighting(PBR pbr, GI gi) { vec4 c = vec4(0.0); vec3 specular_color = vec3(0.0); float one_minus_reflectivity = 0.0; pbr.albedo = computeDiffuseAndSpecularFromMetallic(pbr.albedo, pbr.metallic, specular_color, one_minus_reflectivity); // transparent, to do ... // BRDF c = computeBRDF(pbr, gi, specular_color, one_minus_reflectivity); return c; } void main(void) { PBR pbr; pbr.albedo = BBColor_Color.rgb * texture2D(Albedo_Map, V_Texcoord.xy).rgb; pbr.normal = vec3(texture2D(Normal_Map, V_Texcoord.xy)); // 0~1 -> -1~1 pbr.normal = pbr.normal * 2.0 - vec3(1.0); pbr.normal = normalize(pbr.normal); pbr.normal = V_TBN * pbr.normal; pbr.normal = normalize(pbr.normal); // non-metal = 0, metal = 1 vec4 metallic_tex = texture2D(Metallic_R_Roughness_G_AO_B, V_Texcoord.xy); pbr.metallic = metallic_tex.r * Metallic; pbr.roughness = metallic_tex.g * Roughness; pbr.glossiness = 1 - pbr.roughness; // pbr.occlusion = metallic_tex.b * AO; pbr.occlusion = 1.0; pbr.alpha = 1.0; pbr.view_dir = normalize(BBCameraPosition.xyz - V_World_pos.xyz); pbr.reflect_uvw = reflect(-pbr.view_dir, pbr.normal); GI gi; gi.light.dir = normalize(BBLightPosition.xyz); gi.light.color = BBLightColor.xyz; standardLightingGI(pbr, gi); gl_FragColor = standardLighting(pbr, gi); } <|start_filename|>Resources/shaders/test_GS.shader<|end_filename|> #version 430 core layout (triangles) in; layout (triangle_strip, max_vertices = 12) out; in V2G { vec3 world_pos; vec4 color; vec3 normal; } v2g[]; out G2F { vec4 color; vec3 normal; } g2f; void main() { g2f.color = v2g[0].color; g2f.normal = v2g[0].normal; gl_Position = vec4(v2g[0].world_pos, 1.0); EmitVertex(); g2f.color = v2g[1].color; g2f.normal = v2g[1].normal; gl_Position = vec4(v2g[1].world_pos, 1.0); EmitVertex(); g2f.color = v2g[2].color; g2f.normal = v2g[2].normal; gl_Position = vec4(v2g[2].world_pos, 1.0); EmitVertex(); g2f.color = v2g[2].color; g2f.normal = v2g[2].normal; gl_Position = vec4(0.0, 0.0, 0.0, 1.0); EmitVertex(); EndPrimitive(); } <|start_filename|>Resources/shaders/RayTracing/0_RayTracing.vert<|end_filename|> #version 430 core in vec4 BBPosition; in vec4 BBTexcoord; out vec3 v2f_world_space_pos; out vec2 v2f_texcoord; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { v2f_texcoord = BBTexcoord.xy; vec4 world_space_pos = BBModelMatrix * BBPosition; gl_Position = BBProjectionMatrix * BBViewMatrix * world_space_pos; v2f_world_space_pos = world_space_pos.xyz; } <|start_filename|>Code/BBearEditor/Engine/Render/BBBaseRenderComponent.h<|end_filename|> #pragma once #ifndef BBBASERENDERCOMPONENT_H #define BBBASERENDERCOMPONENT_H #include <GL/glu.h> #include <QOpenGLExtraFunctions> #include <QOpenGLFunctions_4_5_Core> #include <QVector2D> #include <QVector3D> #include <QVector4D> #include <QMatrix4x4> #include <QRgb> #include <QImage> #include <QMap> #include "Utils/BBUtils.h" #define LOCATION_POSITION "BBPosition" #define LOCATION_COLOR "BBColor" #define LOCATION_TEXCOORD "BBTexcoord" #define LOCATION_NORMAL "BBNormal" #define LOCATION_TANGENT "BBTangent" #define LOCATION_BITANGENT "BBBiTangent" #define LOCATION_SMOOTHNORMAL "BBSmoothNormal" #define LOCATION_PROJECTIONMATRIX "BBProjectionMatrix" #define LOCATION_PROJECTIONMATRIX_I "BBProjectionMatrix_I" #define LOCATION_VIEWMATRIX "BBViewMatrix" #define LOCATION_VIEWMATRIX_I "BBViewMatrix_I" #define LOCATION_MODELMATRIX "BBModelMatrix" #define LOCATION_MODELMATRIX_IT "BBModelMatrix_IT" #define LOCATION_VIEWMODELMATRIX_IT "BBViewModelMatrix_IT" #define LOCATION_CAMERA_POSITION "BBCameraPosition" #define LOCATION_CANVAS "BBCanvas" #define LOCATION_TEXTURE(x) "BBTexture"#x #define LOCATION_TEXTURE_SETTING0 "BBTextureSettings" #define LOCATION_LIGHT_POSITION "BBLightPosition" #define LOCATION_LIGHT_COLOR "BBLightColor" #define LOCATION_LIGHT_PROJECTIONMATRIX "BBLightProjectionMatrix" #define LOCATION_LIGHT_VIEWMATRIX "BBLightViewMatrix" #define LOCATION_LIGHT_SETTINGS(x) "BBLightSettings"#x #define LOCATION_CAMERA_PARAMETERS0 "BBCameraParameters" #define LOCATION_CAMERA_PARAMETERS1 "BBCameraParameters1" #define LOCATION_TIME "BBTime" #define LOCATION_CAMERA_COLOR_TEXTURE "BBCameraColorTexture" #define LOCATION_CAMERA_DEPTH_TEXTURE "BBCameraDepthTexture" #define LOCATION_SHADOWMAP "BBShadowMap" #define LOCATION_SKYBOX_MAP "BBSkyBox" #define LOCATION_SKYBOX_BACKGROUND "BBSkyBoxBackground" #define LOCATION_IRRADIANCE_MAP "BBIrradianceMap" #define LOCATION_PREFILTER_MAP_MIPMAP "BBPrefilterMapMipmap" #define LOCATION_SKYBOX_EQUIRECTANGULAR_MAP "BBSkyBoxEquirectangularMap" #define LOCATION_BRDF_LUT_TEXTURE "BBBRDFLUTTexture" #define LOCATION_SPHERICAL_HARMONIC_LIGHTING "BBSphericalHarmonicLightingCoefficients[0]" #define LOCATION_COLOR_PREFIX "BBColor_" #define LOCATION_COLOR_PREFIX_CHAR_COUNT 8 #define LOCATION_TILINGANDOFFSET_PREFIX "BBTO_" #define LOCATION_TILINGANDOFFSET_PREFIX_CHAR_COUNT 5 #define FBO_COLOR_BUFFER_NAME(x) "BBFBOColor"#x #define FBO_DEPTH_BUFFER_NAME "BBFBODepth" #define INDEX_SHADOWMAP 2 class BBBaseRenderComponent : protected QOpenGLFunctions_4_5_Core { public: BBBaseRenderComponent() { initializeOpenGLFunctions(); } }; #endif // BBBASERENDERCOMPONENT_H <|start_filename|>Code/BBearEditor/Engine/ParticleSystem/BBParticleSystem.h<|end_filename|> #ifndef BBPARTICLESYSTEM_H #define BBPARTICLESYSTEM_H #include "Base/BBGameObject.h" class BBParticle; class BBParticleSystem : public BBGameObject { public: BBParticleSystem(const QVector3D &position = QVector3D(0, 0, 0)); ~BBParticleSystem(); void init() override; void render(BBCamera *pCamera) override; void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; private: BBParticle *m_pParticle; }; #endif // BBPARTICLESYSTEM_H <|start_filename|>Code/BBearEditor/Engine/Render/BBMaterial.cpp<|end_filename|> #include "BBMaterial.h" #include "BBCamera.h" #include "BBRenderPass.h" #include "Shader/BBShader.h" #include "BBDrawCall.h" BBMaterial::BBMaterial() { m_pBaseRenderPass = nullptr; m_pAdditiveRenderPass = nullptr; m_pDrawCallInstance = nullptr; } BBMaterial::~BBMaterial() { BB_SAFE_DELETE(m_pBaseRenderPass); BB_SAFE_DELETE(m_pAdditiveRenderPass); } void BBMaterial::init(const char *shaderName, const QString &vShaderPath, const QString &fShaderPath, const QString &gShaderPath) { m_pBaseRenderPass = new BBRenderPass(); m_pBaseRenderPass->setShader(BBShader::loadShader(shaderName, vShaderPath, fShaderPath, gShaderPath)); } void BBMaterial::initMultiPass(const char *shaderName, const QString &vShaderPath, const QString &fShaderPath, const QString &gShaderPath) { init(shaderName, vShaderPath, fShaderPath, gShaderPath); m_pAdditiveRenderPass = new BBRenderPass(); m_pAdditiveRenderPass->setShader(BBShader::loadShader(shaderName, vShaderPath, fShaderPath, gShaderPath)); } void BBMaterial::initMultiPass(const char *shaderName1, const QString &vShaderPath1, const QString &fShaderPath1, const char *shaderName2, const QString &vShaderPath2, const QString &fShaderPath2, const QString &gShaderPath1, const QString &gShaderPath2) { init(shaderName1, vShaderPath1, fShaderPath1, gShaderPath1); m_pAdditiveRenderPass = new BBRenderPass(); m_pAdditiveRenderPass->setShader(BBShader::loadShader(shaderName2, vShaderPath2, fShaderPath2, gShaderPath2)); } void BBMaterial::setBlendState(bool bEnable) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setBlendState(bEnable); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setBlendState(bEnable); } if (m_pDrawCallInstance) { m_pDrawCallInstance->updateMaterialBlendState(bEnable); } } void BBMaterial::setSRCBlendFunc(unsigned int src) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setSRCBlendFunc(src); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setSRCBlendFunc(src); } } void BBMaterial::setDSTBlendFunc(unsigned int dst) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setDSTBlendFunc(dst); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setDSTBlendFunc(dst); } } void BBMaterial::setBlendFunc(unsigned int src, unsigned int dst) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setBlendFunc(src, dst); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setBlendFunc(src, dst); } } void BBMaterial::setZTestState(bool bEnable) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setZTestState(bEnable); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setZTestState(bEnable); } } void BBMaterial::setZFunc(unsigned int func) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setZFunc(func); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setZFunc(func); } } void BBMaterial::setZMask(bool bEnable) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setZMask(bEnable); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setZMask(bEnable); } } void BBMaterial::setStencilMask(bool bEnable) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setStencilMask(bEnable); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setStencilMask(bEnable); } } void BBMaterial::setCullState(bool bEnable) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setCullState(bEnable); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setCullState(bEnable); } } void BBMaterial::setCullFace(int face) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setCullFace(face); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setCullFace(face); } } bool BBMaterial::getBlendState() { return m_pBaseRenderPass->getBlendState(); } unsigned int BBMaterial::getSRCBlendFunc() { return m_pBaseRenderPass->getSRCBlendFunc(); } unsigned int BBMaterial::getDSTBlendFunc() { return m_pBaseRenderPass->getDSTBlendFunc(); } bool BBMaterial::getCullState() { return m_pBaseRenderPass->getCullState(); } int BBMaterial::getCullFace() { return m_pBaseRenderPass->getCullFace(); } void BBMaterial::setFloat(const std::string &uniformName, const float fValue) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setFloat(uniformName, fValue); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setFloat(uniformName, fValue); } } void BBMaterial::setFloatArray(const std::string &uniformName, const float *pFloatArray, int nArrayCount) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setFloatArray(uniformName, pFloatArray, nArrayCount); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setFloatArray(uniformName, pFloatArray, nArrayCount); } } void BBMaterial::setMatrix4(const std::string &uniformName, const float *pMatrix4) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setMatrix4(uniformName, pMatrix4); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setMatrix4(uniformName, pMatrix4); } } void BBMaterial::setVector4(const std::string &uniformName, float x, float y, float z, float w) { float *value = new float[4] {x, y, z, w}; setVector4(uniformName, value); } void BBMaterial::setVector4(const std::string &uniformName, const float *pVector4) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setVector4(uniformName, pVector4); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setVector4(uniformName, pVector4); } } void BBMaterial::setVector4Array(const std::string &uniformName, const float *pVector4Array, int nArrayCount) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setVector4Array(uniformName, pVector4Array, nArrayCount); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setVector4Array(uniformName, pVector4Array, nArrayCount); } } void BBMaterial::setSampler2D(const std::string &uniformName, GLuint textureName, const QString &resourcePath) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setSampler2D(uniformName, textureName, resourcePath); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setSampler2D(uniformName, textureName, resourcePath); } } void BBMaterial::setSampler3D(const std::string &uniformName, GLuint textureName, const QString &resourcePath) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setSampler3D(uniformName, textureName, resourcePath); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setSampler3D(uniformName, textureName, resourcePath); } } void BBMaterial::setSamplerCube(const std::string &uniformName, GLuint textureName) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setSamplerCube(uniformName, textureName); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setSamplerCube(uniformName, textureName); } } void BBMaterial::setSamplerCube(const std::string &uniformName, GLuint textureName, const QString resourcePaths[]) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->setSamplerCube(uniformName, textureName, resourcePaths); } if (m_pAdditiveRenderPass != nullptr) { m_pAdditiveRenderPass->setSamplerCube(uniformName, textureName, resourcePaths); } } BBMaterial* BBMaterial::clone() { BBMaterial *pRet = new BBMaterial(); if (m_pBaseRenderPass != nullptr) { pRet->setBaseRenderPass(m_pBaseRenderPass->clone()); } if (m_pAdditiveRenderPass != nullptr) { pRet->setAdditiveRenderPass(m_pAdditiveRenderPass->clone()); } return pRet; } void BBMaterial::getEditableProperties(QList<std::string> &outNames, QList<BBMaterialProperty*> &outProperties) { if (m_pBaseRenderPass != nullptr) { m_pBaseRenderPass->getEditableProperties(outNames, outProperties); } } BBShader* BBMaterial::getShader() { if (m_pBaseRenderPass != nullptr) { return m_pBaseRenderPass->getShader(); } return nullptr; } bool BBMaterial::isWriteFBO() { return getShader()->isWriteFBO(); } <|start_filename|>Code/BBearEditor/Engine/Physics/Constraint/BBBaseConstraint.cpp<|end_filename|> #include "BBBaseConstraint.h" #include "../Body/BBBaseBody.h" #include "Utils/BBUtils.h" BBBaseConstraint::BBBaseConstraint(BBBaseBody *pBody) { m_pBody = pBody; } BBBaseConstraint::~BBBaseConstraint() { BB_SAFE_DELETE(m_pBody); } <|start_filename|>Code/BBearEditor/Engine/Render/BufferObject/BBBufferObject.cpp<|end_filename|> #include "BBBufferObject.h" BBBufferObject::BBBufferObject() : BBBaseRenderComponent() { m_Name = 0; m_BufferType = GL_ARRAY_BUFFER; } BBBufferObject::~BBBufferObject() { if (m_Name != 0) { glDeleteBuffers(1, &m_Name); } } void BBBufferObject::updateData(GLenum bufferType, GLsizeiptr size, const void *pData) { glBindBuffer(bufferType, m_Name); glBufferSubData(bufferType, 0, size, pData); glBindBuffer(bufferType, 0); } void BBBufferObject::bind() { glBindBuffer(m_BufferType, m_Name); } void BBBufferObject::unbind() { glBindBuffer(m_BufferType, 0); } GLuint BBBufferObject::createBufferObject(GLenum bufferType, GLsizeiptr size, GLenum usage, void *pData) { m_BufferType = bufferType; glGenBuffers(1, &m_Name); glBindBuffer(bufferType, m_Name); glBufferData(bufferType, size, pData, usage); glBindBuffer(bufferType, 0); return m_Name; } <|start_filename|>Resources/shaders/RayTracing/0_GBuffer.vert<|end_filename|> #version 430 core in vec4 BBPosition; in vec4 BBTexcoord; out vec2 v2f_texcoord; out vec3 v2f_view_space_pos; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { vec4 view_space_pos = BBViewMatrix * BBModelMatrix * BBPosition; gl_Position = BBProjectionMatrix * view_space_pos; v2f_texcoord = BBTexcoord.xy; v2f_view_space_pos = view_space_pos.xyz; } <|start_filename|>Code/BBearEditor/Engine/3D/BBHorizontalPlane.h<|end_filename|> #ifndef BBHORIZONTALPLANE_H #define BBHORIZONTALPLANE_H #include "Base/BBRenderableObject.h" class BBHorizontalPlane : public BBRenderableObject { public: BBHorizontalPlane(); void init() override; void render(BBCamera *pCamera) override; }; #endif // BBHORIZONTALPLANE_H <|start_filename|>Code/BBearEditor/Engine/3D/Mesh/BBTerrain.h<|end_filename|> #ifndef BBTERRAIN_H #define BBTERRAIN_H #include "BBMesh.h" class BBTerrain : public BBMesh { public: BBTerrain(); BBTerrain(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init(const QString &path, BBBoundingBox3D *&pOutBoundingBox) override; private: void load(const QString &path, QList<QVector4D> &outPositions) override; float getHeight(const QImage &image, int x, int z); QVector3D getNormal(const QImage &image, int x, int z); float m_fHeight; const static int m_nUnitCount; const static float m_fStep; }; #endif // BBTERRAIN_H <|start_filename|>Resources/shaders/CubeMap.frag<|end_filename|> varying vec4 V_world_pos; varying vec4 V_Position; varying vec4 V_Normal; uniform vec4 BBCameraPosition; uniform samplerCube Cube; void main(void) { // V view, N normal, R reflect vec3 V = normalize(BBCameraPosition.xyz - V_world_pos.xyz); vec3 N = normalize(V_Normal); vec3 R = reflect(-V, N); R.y = -R.y; gl_FragColor = textureCube(Cube, R); } <|start_filename|>Resources/shaders/RayTracing/0_RayTracing.frag<|end_filename|> #version 430 core out vec3 v2f_world_space_pos; out vec2 v2f_texcoord; layout (location = 0) out vec4 FragColor; uniform sampler2D BBCameraColorTexture; uniform sampler2D BBCameraDepthTexture; uniform vec4 BBCameraParameters; uniform vec4 BBCameraPosition; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform sampler2D DiffuseTex; float RayLength = 10000; float stride = 1.0; float linearizeDepth(float depth) { float z_near = BBCameraParameters.z; float z_far = BBCameraParameters.w; float z = depth * 2.0 - 1.0; return (2.0 * z_near * z_far) / (z_far + z_near - z * (z_far - z_near)); } struct Ray { vec3 origin; vec3 direction; }; struct Result { bool is_hit; vec2 uv; vec3 position; int iteration_count; }; vec4 projectToScreenSpace(vec3 point) { return BBProjectionMatrix * vec4(point, 1.0); } vec3 projectToViewSpace(vec3 point) { return vec3(BBViewMatrix * vec4(point, 1.0)); } float distanceSquared(vec2 A, vec2 B) { A = A - B; return dot(A, A); } bool query(vec2 z, vec2 uv) { float depth = texture(BBCameraDepthTexture, uv / BBCameraParameters.xy).r; depth = -linearizeDepth(depth); // Before marching, it is before the depth value of the depth map // but after marching, it is in the back of depth value, indicating intersection return z.y < depth && z.x > depth; } Result computeRayMarching(Ray ray) { Result result; // world space vec3 begin = ray.origin; vec3 end = ray.origin + ray.direction * RayLength; // view space vec3 V0 = projectToViewSpace(begin); vec3 V1 = projectToViewSpace(end); // clip space vec4 H0 = projectToScreenSpace(V0); vec4 H1 = projectToScreenSpace(V1); float k0 = 1.0 / H0.w; float k1 = 1.0 / H1.w; vec3 Q0 = V0 * k0; vec3 Q1 = V1 * k1; // NDC space vec2 P0 = H0.xy * k0; vec2 P1 = H1.xy * k1; vec2 screen_size = BBCameraParameters.xy; // -1~1 -> 0~1 P0 = (P0 + 1) / 2; P1 = (P1 + 1) / 2; // screen space P0 *= screen_size; P1 *= screen_size; // if the distance between P0 and P1 is too small P1 += vec2((distanceSquared(P0, P1) < 0.0001) ? 0.01 : 0.0); // DDA vec2 delta = P1 - P0; bool permute = false; if (abs(delta.x) < abs(delta.y)) { permute = true; delta = delta.yx; P0 = P0.yx; P1 = P1.yx; } float step_dir = sign(delta.x); float dx = step_dir / delta.x; vec3 dQ = (Q1 - Q0) * dx; float dk = (k1 - k0) * dx; vec2 dP = vec2(step_dir, delta.y * dx); dP *= stride; dQ *= stride; dk *= stride; P0 += dP; Q0 += dQ; k0 += dk; int step = 0; int max_step = 5000; float k = k0; vec3 Q = Q0; float prev_z = V0.z; for (vec2 P = P0; step < max_step; step++, P += dP, Q.z += dQ.z, k += dk) { result.uv = permute ? P.yx : P; vec2 depths; // origin z depths.x = prev_z; // z after marching depths.y = (dQ.z * 0.5 + Q.z) / (dk * 0.5 + k); prev_z = depths.y; if (depths.x < depths.y) depths.xy = depths.yx; if (result.uv.x > BBCameraParameters.x || result.uv.x < 0.0 || result.uv.y > BBCameraParameters.y || result.uv.y < 0.0) break; result.is_hit = query(depths, result.uv); if (result.is_hit) break; } return result; } void main(void) { vec3 origin_point = v2f_world_space_pos; vec3 view_dir = normalize(BBCameraPosition.xyz - origin_point); vec3 normal = vec3(0.0, 1.0, 0.0); vec3 reflect_dir = normalize(reflect(-view_dir, normal)); Ray ray; ray.origin = origin_point; ray.direction = reflect_dir; Result result = computeRayMarching(ray); if (result.is_hit) { // Reflected color FragColor = vec4(texture(BBCameraColorTexture, result.uv / BBCameraParameters.xy).xyz, 1.0); } else { // original color vec4 screen_space_pos = BBProjectionMatrix * BBViewMatrix * vec4(origin_point, 1.0); screen_space_pos.xy /= screen_space_pos.w; // -1~1 -> 0~1 screen_space_pos.xy = screen_space_pos.xy * 0.5 + 0.5; FragColor = vec4(texture(BBCameraColorTexture, screen_space_pos.xy).xyz, 1.0); // FragColor = vec4(texture(DiffuseTex, v2f_texcoord).xyz, 1.0); } } <|start_filename|>Code/BBearEditor/Engine/Geometry/BBPhotonMap.cpp<|end_filename|> #include "BBPhotonMap.h" #include "Math/BBMath.h" #include "OfflineRenderer/BBScatterMaterial.h" #include "3D/BBModel.h" #include "Render/Lighting/GameObject/BBAreaLight.h" int BBPhotonMap::m_nMaxTraceDepth = 4; BBPhotonMap::BBPhotonMap(int nMaxPhotonNum) { m_nMaxPhotonNum = nMaxPhotonNum; m_nPhotonNum = 0; // For easy calculation, the index starts from 1 m_pPhoton = new BBPhoton[nMaxPhotonNum + 1]; m_BoxMin = QVector3D(1000000.0f, 1000000.0f, 1000000.0f); m_BoxMax = QVector3D(-1000000.0f, -1000000.0f, -1000000.0f); } BBPhotonMap::~BBPhotonMap() { BB_SAFE_DELETE_ARRAY(m_pPhoton); } BBPhotonMap BBPhotonMap::operator=(const BBPhotonMap &photonMap) { m_nPhotonNum = photonMap.getPhotonNum(); m_nMaxPhotonNum = photonMap.getMaxPhotonNum(); m_pPhoton = photonMap.getPhoton(); m_BoxMin = photonMap.getBoxMin(); m_BoxMax = photonMap.getBoxMax(); } void BBPhotonMap::store(const BBPhoton &photon) { BB_PROCESS_ERROR_RETURN((m_nPhotonNum <= m_nMaxPhotonNum)); m_pPhoton[++m_nPhotonNum] = photon; m_BoxMin = QVector3D(std::min(m_BoxMin.x(), photon.m_Position.x()), std::min(m_BoxMin.y(), photon.m_Position.y()), std::min(m_BoxMin.z(), photon.m_Position.z())); m_BoxMax = QVector3D(std::max(m_BoxMax.x(), photon.m_Position.x()), std::max(m_BoxMax.y(), photon.m_Position.y()), std::max(m_BoxMax.z(), photon.m_Position.z())); } void BBPhotonMap::balance() { // For easy calculation, the index starts from 1 BBPhoton *pTmpPhoton = new BBPhoton[m_nPhotonNum + 1]; for (int i = 1; i <= m_nPhotonNum; i++) { pTmpPhoton[i] = m_pPhoton[i]; } balanceSegment(pTmpPhoton, 1, 1, m_nPhotonNum); BB_SAFE_DELETE_ARRAY(pTmpPhoton); } void BBPhotonMap::getKNearestPhotons(BBNearestPhotons *pNearestPhotons, int nParentIndex) { if (nParentIndex > m_nPhotonNum) return; BBPhoton *pCurrentPhoton = &m_pPhoton[nParentIndex]; // 1 // 2 3 // 4 5 6 7 // 8 9 // The index starts from 1, the index of the left subtree is 2 times if (nParentIndex * 2 <= m_nPhotonNum) { // There are sub nodes // The distance between detection photon and the dividing axis of current photon float d = pNearestPhotons->m_DetectionPosition[pCurrentPhoton->m_Axis] - pCurrentPhoton->m_Position[pCurrentPhoton->m_Axis]; if (d < 0) { // The detection point is in the left of the dividing axis, search left subtree getKNearestPhotons(pNearestPhotons, nParentIndex * 2); if (d * d < pNearestPhotons->m_pDistanceSquare[0]) { // search right subtree // When the distance is greater than detection scope, all nodes on the right subtree will be farther getKNearestPhotons(pNearestPhotons, nParentIndex * 2 + 1); } } else { // search right subtree getKNearestPhotons(pNearestPhotons, nParentIndex * 2 + 1); if (d * d < pNearestPhotons->m_pDistanceSquare[0]) { // search left subtree getKNearestPhotons(pNearestPhotons, nParentIndex * 2); } } } // process itself float fDistanceSquare = (pNearestPhotons->m_DetectionPosition - pCurrentPhoton->m_Position).lengthSquared(); if (fDistanceSquare > pNearestPhotons->m_pDistanceSquare[0]) return; if (pNearestPhotons->m_nCurrentCount < pNearestPhotons->m_nMaxPhotonCount) { // When the heap is not full, qualified photons are inserted into the tail pNearestPhotons->m_nCurrentCount++; pNearestPhotons->m_pDistanceSquare[pNearestPhotons->m_nCurrentCount] = fDistanceSquare; pNearestPhotons->m_ppPhotons[pNearestPhotons->m_nCurrentCount] = pCurrentPhoton; } else { // When the heap is full if (!pNearestPhotons->m_bFulled) { // Just full, init maximum heap // Start from the parent node of the maximum sequence number to check whether the maximum heap is met. If not, adjust it // If yes, continue to check whether the previous parent node meets the requirements until node 1. for (int i = pNearestPhotons->m_nCurrentCount >> 1; i >= 1; i--) { int nParent = i; BBPhoton *pParentPhoton = pNearestPhotons->m_ppPhotons[nParent]; float fParentParentPhoton = pNearestPhotons->m_pDistanceSquare[nParent]; // Also check whether the adjusted node still meets the maximum heap property. If not, you need to traverse downward while ((nParent << 1) <= pNearestPhotons->m_nCurrentCount) { // If parent has child // nChild is left sub node int nChild = nParent << 1; // If the right sub node exists and is larger than the left sub node, nChild points to the right sub node if (nChild + 1 <= pNearestPhotons->m_nCurrentCount && pNearestPhotons->m_pDistanceSquare[nChild] < pNearestPhotons->m_pDistanceSquare[nChild + 1]) { nChild++; } // The larger sub node is compared with the parent node. If the parent node is large, it will not be processed. if (fParentParentPhoton >= pNearestPhotons->m_pDistanceSquare[nChild]) { break; } // Otherwise, the data of the larger sub node give the parent pNearestPhotons->m_ppPhotons[nParent] = pNearestPhotons->m_ppPhotons[nChild]; pNearestPhotons->m_pDistanceSquare[nParent] = pNearestPhotons->m_pDistanceSquare[nChild]; // Traverse downward nParent = nChild; } // Give remaining node data pNearestPhotons->m_ppPhotons[nParent] = pParentPhoton; pNearestPhotons->m_pDistanceSquare[nParent] = fParentParentPhoton; } // Change flag, When you insert data later, this code is no longer executed pNearestPhotons->m_bFulled = true; } // Insert new node in the maximum heap, Original node 1 (maximum) is removed, traverse downward int nParent = 1; while ((nParent << 1) <= pNearestPhotons->m_nCurrentCount) { int nChild = nParent << 1; if (nChild + 1 <= pNearestPhotons->m_nCurrentCount && pNearestPhotons->m_pDistanceSquare[nChild] < pNearestPhotons->m_pDistanceSquare[nChild + 1]) { nChild++; } if (fDistanceSquare >= pNearestPhotons->m_pDistanceSquare[nChild]) { break; } // Otherwise, the data of the larger sub node give the parent pNearestPhotons->m_ppPhotons[nParent] = pNearestPhotons->m_ppPhotons[nChild]; pNearestPhotons->m_pDistanceSquare[nParent] = pNearestPhotons->m_pDistanceSquare[nChild]; nParent = nChild; } pNearestPhotons->m_ppPhotons[nParent] = pCurrentPhoton; pNearestPhotons->m_pDistanceSquare[nParent] = fDistanceSquare; // [0] store the maximum pNearestPhotons->m_pDistanceSquare[0] = pNearestPhotons->m_pDistanceSquare[1]; } } QVector3D BBPhotonMap::getIrradiance(const QVector3D &detectionPosition, const QVector3D &detectionNormal, float fDetectionDistance, int nMaxPhotonCount) { QVector3D irradiance(0, 0, 0); BBNearestPhotons nearestPhotons(detectionPosition, nMaxPhotonCount, fDetectionDistance); getKNearestPhotons(&nearestPhotons, 1); // ignore if (nearestPhotons.m_nCurrentCount < 10) return irradiance; for (int i = 0; i < nearestPhotons.m_nCurrentCount; i++) { QVector3D dir = nearestPhotons.m_ppPhotons[i]->m_Direction; if (QVector3D::dotProduct(dir, detectionNormal) < 0) { irradiance += nearestPhotons.m_ppPhotons[i]->m_Power; } } // choose circle irradiance /= PI * nearestPhotons.m_pDistanceSquare[0]; // test irradiance /= 1000; return irradiance; } void BBPhotonMap::debug() { for (int i = 1; i <= m_nPhotonNum; i++) { qDebug() << m_pPhoton[i].m_Position; qDebug() << m_pPhoton[i].m_Axis; } } void BBPhotonMap::debug(BBNearestPhotons *pNearestPhotons) { for (int i = 1; i <= pNearestPhotons->m_nCurrentCount; i++) { qDebug() << pNearestPhotons->m_ppPhotons[i]->m_Position; } } void BBPhotonMap::markKNearestPhotons(BBNearestPhotons *pNearestPhotons) { for (int i = 1; i <= pNearestPhotons->m_nCurrentCount; i++) { pNearestPhotons->m_ppPhotons[i]->m_bKNearestPhotons = true; } } bool BBPhotonMap::isMarkedKNearestPhotons(int nIndex) { return m_pPhoton[nIndex].m_bKNearestPhotons; } QVector3D* BBPhotonMap::getPhotonPositions() { QVector3D *pPositions = new QVector3D[m_nPhotonNum + 1]; for (int i = 1; i <= m_nPhotonNum; i++) { pPositions[i] = m_pPhoton[i].m_Position; } return pPositions; } void BBPhotonMap::tracePhoton(const BBRay &ray, BBModel *pSceneModels[], int nModelCount, int depth, const QVector3D &power, BBPhotonMap *pPhotonMap, bool bOnlyStoreCausticsPhoton) { // After tracing many times, end BB_PROCESS_ERROR_RETURN((depth < m_nMaxTraceDepth)); // need to record the info of hit point BBHitInfo nearHitInfo; // Find the nearest hit point and the corresponding model for (int i = 0; i < nModelCount; i++) { BBHitInfo hitInfo; if (pSceneModels[i]->hit(ray, 0.001f, FLT_MAX, hitInfo)) { if (hitInfo.m_fDistance < nearHitInfo.m_fDistance) { nearHitInfo = hitInfo; nearHitInfo.m_pModel = pSceneModels[i]; } } } if (nearHitInfo.m_pModel) { BBScatterInfo scatterInfo; if (nearHitInfo.m_pModel->getMesh()->getScatterMaterial()->scatter(ray, nearHitInfo, scatterInfo)) { // if it is specular, continue to trace photon, reflection or refraction if (scatterInfo.m_bSpecular) { tracePhoton(scatterInfo.m_ScatteredRay, pSceneModels, nModelCount, depth + 1, power, pPhotonMap, bOnlyStoreCausticsPhoton); } else { // It is assumed that the medium does not absorb photons if (bOnlyStoreCausticsPhoton) { if (depth == 0) { // If only need to store caustics photon, do not store the photons emitted directly to the diffuse surface return; } } BBPhoton photon; photon.m_Position = nearHitInfo.m_Position; photon.m_Direction = ray.getDirection(); photon.m_Power = power; pPhotonMap->store(photon); } } } } QVector3D BBPhotonMap::traceRay(const BBRay &ray, BBModel *pSceneModels[], int nModelCount, int depth, BBPhotonMap *pPhotonMap) { // need to record the info of hit point BBHitInfo nearHitInfo; // Find the nearest hit point and the corresponding model for (int i = 0; i < nModelCount; i++) { BBHitInfo hitInfo; if (pSceneModels[i]->hit(ray, 0.001f, FLT_MAX, hitInfo)) { if (hitInfo.m_fDistance < nearHitInfo.m_fDistance) { nearHitInfo = hitInfo; nearHitInfo.m_pModel = pSceneModels[i]; } } } if (nearHitInfo.m_pModel) { BBScatterInfo scatterInfo; BBScatterMaterial* pMaterial = nearHitInfo.m_pModel->getMesh()->getScatterMaterial(); QVector3D color = pMaterial->emitted(nearHitInfo.m_Position, nearHitInfo.m_Texcoords); if (depth < m_nMaxTraceDepth && pMaterial->scatter(ray, nearHitInfo, scatterInfo)) { if (scatterInfo.m_bSpecular) { color += scatterInfo.m_Attenuation * traceRay(scatterInfo.m_ScatteredRay, pSceneModels, nModelCount, depth + 1, pPhotonMap); } else { color += scatterInfo.m_Attenuation * pPhotonMap->getIrradiance(nearHitInfo.m_Position, nearHitInfo.m_Normal, 0.3f, 100); } } return color; } else { return QVector3D(0, 0, 0); } } /** * @brief BBPhotonMap::splitMedian * @param pPhoton * @param start * @param end * @param median * @param axis 0, 1, 2 : x, y, z */ void BBPhotonMap::splitMedian(BBPhoton pPhoton[], int start, int end, int median, int axis) { int l = start; int r = end; while (l < r) { // sort, less than key, key, greater than key float key = pPhoton[r].m_Position[axis]; int i = l - 1; int j = r; while (1) { while (pPhoton[++i].m_Position[axis] < key); while (pPhoton[--j].m_Position[axis] > key && j > l); if (i >= j) break; std::swap(pPhoton[i], pPhoton[j]); } std::swap(pPhoton[i], pPhoton[r]); // Make key in the middle if (i >= median) r = i - 1; if (i <= median) l = i + 1; } } void BBPhotonMap::balanceSegment(BBPhoton pPhoton[], int index, int start, int end) { if (start == end) { m_pPhoton[index] = pPhoton[start]; return; } int median = getMedian(start, end); // Select which axis to use for bifurcation int axis = 2; if ((m_BoxMax.x() - m_BoxMin.x() > m_BoxMax.y() - m_BoxMin.y()) && (m_BoxMax.x() - m_BoxMin.x() > m_BoxMax.z() - m_BoxMin.z())) axis = 0; else if (m_BoxMax.y() - m_BoxMin.y() > m_BoxMax.z() - m_BoxMin.z()) axis = 1; // The median is calculated correctly, but the nodes on the left and right subtrees still need to be processed splitMedian(pPhoton, start, end, median, axis); m_pPhoton[index] = pPhoton[median]; m_pPhoton[index].m_Axis = axis; if (start < median) { float tmp = m_BoxMax[axis]; m_BoxMax[axis] = m_pPhoton[index].m_Position[axis]; // index * 2 : Index of left subtree root balanceSegment(pPhoton, index * 2, start, median - 1); m_BoxMax[axis] = tmp; } if (end > median) { float tmp = m_BoxMin[axis]; m_BoxMin[axis] = m_pPhoton[index].m_Position[axis]; balanceSegment(pPhoton, index * 2 + 1, median + 1, end); m_BoxMin[axis] = tmp; } } <|start_filename|>Code/BBearEditor/Engine/Serializer/BBScene.pb.h<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBScene.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_BBScene_2eproto #define GOOGLE_PROTOBUF_INCLUDED_BBScene_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3016000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3016000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> #include "BBHierarchyTreeWidgetItem.pb.h" #include "BBGameObject.pb.h" // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_BBScene_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_BBScene_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBScene_2eproto; namespace BBSerializer { class BBScene; struct BBSceneDefaultTypeInternal; extern BBSceneDefaultTypeInternal _BBScene_default_instance_; } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> ::BBSerializer::BBScene* Arena::CreateMaybeMessage<::BBSerializer::BBScene>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace BBSerializer { // =================================================================== class BBScene PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBScene) */ { public: inline BBScene() : BBScene(nullptr) {} ~BBScene() override; explicit constexpr BBScene(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBScene(const BBScene& from); BBScene(BBScene&& from) noexcept : BBScene() { *this = ::std::move(from); } inline BBScene& operator=(const BBScene& from) { CopyFrom(from); return *this; } inline BBScene& operator=(BBScene&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBScene& default_instance() { return *internal_default_instance(); } static inline const BBScene* internal_default_instance() { return reinterpret_cast<const BBScene*>( &_BBScene_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(BBScene& a, BBScene& b) { a.Swap(&b); } inline void Swap(BBScene* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBScene* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBScene* New() const final { return CreateMaybeMessage<BBScene>(nullptr); } BBScene* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBScene>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBScene& from); void MergeFrom(const BBScene& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBScene* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBScene"; } protected: explicit BBScene(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kItemFieldNumber = 1, kGameObjectFieldNumber = 2, }; // repeated .BBSerializer.BBHierarchyTreeWidgetItem item = 1; int item_size() const; private: int _internal_item_size() const; public: void clear_item(); ::BBSerializer::BBHierarchyTreeWidgetItem* mutable_item(int index); ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::BBSerializer::BBHierarchyTreeWidgetItem >* mutable_item(); private: const ::BBSerializer::BBHierarchyTreeWidgetItem& _internal_item(int index) const; ::BBSerializer::BBHierarchyTreeWidgetItem* _internal_add_item(); public: const ::BBSerializer::BBHierarchyTreeWidgetItem& item(int index) const; ::BBSerializer::BBHierarchyTreeWidgetItem* add_item(); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::BBSerializer::BBHierarchyTreeWidgetItem >& item() const; // repeated .BBSerializer.BBGameObject gameObject = 2; int gameobject_size() const; private: int _internal_gameobject_size() const; public: void clear_gameobject(); ::BBSerializer::BBGameObject* mutable_gameobject(int index); ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::BBSerializer::BBGameObject >* mutable_gameobject(); private: const ::BBSerializer::BBGameObject& _internal_gameobject(int index) const; ::BBSerializer::BBGameObject* _internal_add_gameobject(); public: const ::BBSerializer::BBGameObject& gameobject(int index) const; ::BBSerializer::BBGameObject* add_gameobject(); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::BBSerializer::BBGameObject >& gameobject() const; // @@protoc_insertion_point(class_scope:BBSerializer.BBScene) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::BBSerializer::BBHierarchyTreeWidgetItem > item_; ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::BBSerializer::BBGameObject > gameobject_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_BBScene_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // BBScene // repeated .BBSerializer.BBHierarchyTreeWidgetItem item = 1; inline int BBScene::_internal_item_size() const { return item_.size(); } inline int BBScene::item_size() const { return _internal_item_size(); } inline ::BBSerializer::BBHierarchyTreeWidgetItem* BBScene::mutable_item(int index) { // @@protoc_insertion_point(field_mutable:BBSerializer.BBScene.item) return item_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::BBSerializer::BBHierarchyTreeWidgetItem >* BBScene::mutable_item() { // @@protoc_insertion_point(field_mutable_list:BBSerializer.BBScene.item) return &item_; } inline const ::BBSerializer::BBHierarchyTreeWidgetItem& BBScene::_internal_item(int index) const { return item_.Get(index); } inline const ::BBSerializer::BBHierarchyTreeWidgetItem& BBScene::item(int index) const { // @@protoc_insertion_point(field_get:BBSerializer.BBScene.item) return _internal_item(index); } inline ::BBSerializer::BBHierarchyTreeWidgetItem* BBScene::_internal_add_item() { return item_.Add(); } inline ::BBSerializer::BBHierarchyTreeWidgetItem* BBScene::add_item() { // @@protoc_insertion_point(field_add:BBSerializer.BBScene.item) return _internal_add_item(); } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::BBSerializer::BBHierarchyTreeWidgetItem >& BBScene::item() const { // @@protoc_insertion_point(field_list:BBSerializer.BBScene.item) return item_; } // repeated .BBSerializer.BBGameObject gameObject = 2; inline int BBScene::_internal_gameobject_size() const { return gameobject_.size(); } inline int BBScene::gameobject_size() const { return _internal_gameobject_size(); } inline ::BBSerializer::BBGameObject* BBScene::mutable_gameobject(int index) { // @@protoc_insertion_point(field_mutable:BBSerializer.BBScene.gameObject) return gameobject_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::BBSerializer::BBGameObject >* BBScene::mutable_gameobject() { // @@protoc_insertion_point(field_mutable_list:BBSerializer.BBScene.gameObject) return &gameobject_; } inline const ::BBSerializer::BBGameObject& BBScene::_internal_gameobject(int index) const { return gameobject_.Get(index); } inline const ::BBSerializer::BBGameObject& BBScene::gameobject(int index) const { // @@protoc_insertion_point(field_get:BBSerializer.BBScene.gameObject) return _internal_gameobject(index); } inline ::BBSerializer::BBGameObject* BBScene::_internal_add_gameobject() { return gameobject_.Add(); } inline ::BBSerializer::BBGameObject* BBScene::add_gameobject() { // @@protoc_insertion_point(field_add:BBSerializer.BBScene.gameObject) return _internal_add_gameobject(); } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::BBSerializer::BBGameObject >& BBScene::gameobject() const { // @@protoc_insertion_point(field_list:BBSerializer.BBScene.gameObject) return gameobject_; } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_BBScene_2eproto <|start_filename|>Code/BBearEditor/Engine/Render/Volumetric/BBVolumetricCloud.cpp<|end_filename|> #include "BBVolumetricCloud.h" #include "Scene/BBSceneManager.h" #include "Scene/BBScene.h" #include "Base/BBGameObject.h" #include "2D/BBFullScreenQuad.h" #include "Render/BBMaterial.h" #include "Render/Texture/BBProcedureTexture.h" void BBVolumetricCloud::enable(int nAlgorithmIndex, bool bEnable) { BBScene *pScene = BBSceneManager::getScene(); if (bEnable) { pScene->setRenderingFunc(&BBScene::deferredRendering1_1); open(pScene); } else { pScene->setRenderingFunc(&BBScene::defaultRendering); // objects go back original materials QList<BBGameObject*> objects = pScene->getModels(); for (QList<BBGameObject*>::Iterator itr = objects.begin(); itr != objects.end(); itr++) { BBGameObject *pObject = *itr; pObject->restoreMaterial(); } } } void BBVolumetricCloud::open(BBScene *pScene) { setGBufferPass(pScene); setScreenQuadPass(pScene); } void BBVolumetricCloud::setGBufferPass(BBScene *pScene) { BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("VolumetricCloud_GBuffer", BB_PATH_RESOURCE_SHADER(Volumetric/GBuffer.vert), BB_PATH_RESOURCE_SHADER(Volumetric/GBuffer.frag)); QList<BBGameObject*> objects = pScene->getModels(); for (QList<BBGameObject*>::Iterator itr = objects.begin(); itr != objects.end(); itr++) { BBGameObject *pObject = *itr; pObject->setCurrentMaterial(pMaterial->clone()); } } void BBVolumetricCloud::setScreenQuadPass(BBScene *pScene) { BBFullScreenQuad *pFullScreenQuad = pScene->getFullScreenQuad(0); BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("VolumetricCloud_ScreenQuad", BB_PATH_RESOURCE_SHADER(Volumetric/Cloud.vert), BB_PATH_RESOURCE_SHADER(Volumetric/Cloud.frag)); pMaterial->setBlendState(true); pMaterial->setSampler2D("AlbedoTex", pScene->getColorFBO(0, 0)); pMaterial->setSampler2D("NormalTex", pScene->getColorFBO(0, 1)); pMaterial->setSampler2D("PositionTex", pScene->getColorFBO(0, 2)); pMaterial->setSampler2D("WeatherTex", BBTexture().createTexture2D(BB_PATH_RESOURCE_TEXTURE(Noise/weather.png))); pMaterial->setSampler2D("PerlinNoiseTex2D", BBProcedureTexture().createPerlinNoiseTexture2D(32, 0.0625f)); pMaterial->setSampler3D("PerlinNoiseTex3D", BBProcedureTexture().createPerlinNoiseTexture3D(32, 32, 32, 0.125f)); pMaterial->setSampler2D("DistortTex", BBTexture().createTexture2D(BB_PATH_RESOURCE_TEXTURE(Noise/dissolveTex1.jpg))); pFullScreenQuad->setCurrentMaterial(pMaterial); } <|start_filename|>Resources/shaders/ParticleSystem/Particles2-0.vert<|end_filename|> #version 430 attribute vec4 BBPosition; uniform mat4 BBModelMatrix; void main() { gl_Position = BBModelMatrix * BBPosition; } <|start_filename|>Code/BBearEditor/Editor/Debugger/BBConsoleDockWidget.cpp<|end_filename|> #include "BBConsoleDockWidget.h" #include <QDragEnterEvent> #include <QMimeData> #include <QFileInfo> #include "FileSystem/BBFileSystemDataManager.h" #include "Python/BBPythonVM.h" BBConsoleDockWidget::BBConsoleDockWidget(QWidget *pParent) : QDockWidget(pParent) { setAcceptDrops(true); } BBConsoleDockWidget::~BBConsoleDockWidget() { } void BBConsoleDockWidget::dragEnterEvent(QDragEnterEvent *event) { QByteArray data; if ((data = event->mimeData()->data(BB_MIMETYPE_FILELISTWIDGET)) != nullptr) { QDataStream dataStream(&data, QIODevice::ReadOnly); m_CurrentDragFilePath.clear(); dataStream >> m_CurrentDragFilePath; QString suffix = QFileInfo(m_CurrentDragFilePath).suffix(); if (BBFileSystemDataManager::m_ScriptSuffixs.contains(suffix)) { event->accept(); } else { event->ignore(); } } else { event->ignore(); } } void BBConsoleDockWidget::dragMoveEvent(QDragMoveEvent *event) { event->accept(); } void BBConsoleDockWidget::dragLeaveEvent(QDragLeaveEvent *event) { } void BBConsoleDockWidget::dropEvent(QDropEvent *event) { BBPythonVM::runScript(m_CurrentDragFilePath); } <|start_filename|>Code/BBearEditor/Engine/Render/Lighting/GI/BBFLCGlobalIllumination.h<|end_filename|> #ifndef BBFLCGLOBALILLUMINATION_H #define BBFLCGLOBALILLUMINATION_H class BBScene; class BBShaderStorageBufferObject; class BBAtomicCounterBufferObject; class BBFLCGlobalIllumination { public: static void open(BBScene *pScene); static void setTriangleCutPass(BBScene *pScene); static void setIndirectShadingPass(BBScene *pScene); private: static void clear(BBScene *pScene); static float* generateS(); static float* generateSp(float *pS); static float* generateNoise(); static float* m_S; static float* m_Sp; static float* m_Noise; static int m_nNoiseCount; // Divided into N stacks according to the size of the triangle static int m_SNum; static BBShaderStorageBufferObject *m_pTriangleCutSSBOSet; static int m_nSSBOCount; static BBAtomicCounterBufferObject *m_pTriangleIdACBO; }; #endif // BBFLCGLOBALILLUMINATION_H <|start_filename|>Code/BBearEditor/Engine/Physics/ClothSystem/BBClothMesh.h<|end_filename|> #ifndef BBCLOTHMESH_H #define BBCLOTHMESH_H #include "Base/BBRenderableObject.h" class BBClothBody; class BBClothMesh : public BBRenderableObject { public: BBClothMesh(float fWidth = 10.0f, float fHeight = 6.0f, float fUnitStep = 0.125f); void init() override; void updatePhysicsCalculatedPositions(BBClothBody *pClothBody); public: inline std::vector<int> getLeftVertexIndexes() { return m_LeftVertexIndexes; } inline int getTopLeftVertexIndex() { return 0; } private: float m_fWidth; float m_fHeight; float m_fUnitStep; int m_nColumn; int m_nRow; std::vector<int> m_LeftVertexIndexes; }; #endif // BBCLOTHMESH_H <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBGlobalSettingsGroupManager.h<|end_filename|> #ifndef BBGLOBALSETTINGSGROUPMANAGER_H #define BBGLOBALSETTINGSGROUPMANAGER_H #include "BBGroupManager.h" class BBEnumExpansionFactory; class BBGlobalSettingsGroupManager : public BBGroupManager { Q_OBJECT public: BBGlobalSettingsGroupManager(BBScene *pScene, QWidget *pParent = 0); ~BBGlobalSettingsGroupManager(); private slots: void switchSkyBoxAlgorithm(int nAlgorithmIndex); void switchRayTracing(bool bEnable); void bakeSphericalHarmonicLightingMap(); void switchGlobalIllumination(bool bEnable); void switchShadow(bool bEnable); void switchVolumetricCloud(bool bEnable); signals: void updateFileList(); private: void initSkyBoxFactory(); void initRayTracingFactory(); void initSphericalHarmonicLightingFactory(); void initGlobalIlluminationFactory(); void initShadowFactory(); void initVolumetricCloudFactory(); BBScene *m_pScene; BBEnumFactory *m_pSkyBoxFactory; BBEnumExpansionFactory *m_pRayTracingFactory; BBEnumExpansionFactory *m_pSphericalHarmonicLightingFactory; BBEnumExpansionFactory *m_pGlobalIlluminationFactory; BBEnumExpansionFactory *m_pShadowFactory; }; #endif // BBGLOBALSETTINGSGROUPMANAGER_H <|start_filename|>Resources/shaders/DeferredPosition.frag<|end_filename|> varying vec4 V_WorldPos; void main(void) { // float scale = 1.0; // float w = 1.0 / scale; // vec3 world_pos_scaled = V_WorldPos.xyz / scale; // vec3 world_pos_encoded = 0.5 * (world_pos_scaled + vec3(1.0)); // gl_FragColor = vec4(world_pos_encoded, w); gl_FragColor = V_WorldPos; } <|start_filename|>Code/BBearEditor/Engine/2D/BBSelectionRegion.cpp<|end_filename|> #include "BBSelectionRegion.h" #include <QtOpenGL> BBSelectionRegion::BBSelectionRegion() { m_bVisible = false; } void BBSelectionRegion::setRect(float x, float y, float w, float h) { // x y means left-bottom m_Vertexes[0].setX(x); m_Vertexes[0].setY(y); m_Vertexes[1].setX(x + w); m_Vertexes[1].setY(y); m_Vertexes[2].setX(x + w); m_Vertexes[2].setY(y + h); m_Vertexes[3].setX(x); m_Vertexes[3].setY(y + h); } void BBSelectionRegion::render() { if (m_bVisible) { glEnable(GL_BLEND); // Rect glColor4ub(214, 223, 235, 50); glBegin(GL_QUADS); glVertex3f(m_Vertexes[0].x(), m_Vertexes[0].y(), m_Vertexes[0].z()); glVertex3f(m_Vertexes[1].x(), m_Vertexes[1].y(), m_Vertexes[1].z()); glVertex3f(m_Vertexes[2].x(), m_Vertexes[2].y(), m_Vertexes[2].z()); glVertex3f(m_Vertexes[3].x(), m_Vertexes[3].y(), m_Vertexes[3].z()); glEnd(); glDisable(GL_BLEND); } } void BBSelectionRegion::setVisibility(bool bVisible) { m_bVisible = bVisible; } <|start_filename|>Code/BBearEditor/Engine/Scene/BBRendererManager.h<|end_filename|> #ifndef BBRENDERERMANAGER_H #define BBRENDERERMANAGER_H #include <QStringList> #include "Serializer/BBMaterial.pb.h" class BBMaterial; class BBPreviewOpenGLWidget; class BBRendererManager { public: static void bindPreviewOpenGLWidget(BBPreviewOpenGLWidget *pPreviewOpenGLWidget) { m_pPreviewOpenGLWidget = pPreviewOpenGLWidget; } static QStringList loadVShaderList(); static QStringList loadFShaderList(); static void saveDefaultMaterial(const QString &filePath); static BBMaterial* loadMaterial(const QString &filePath); static QString getMaterialPath(BBMaterial *pMaterial); public: /* change cached materials and save changes */ static void changeVShader(BBMaterial *pMaterial, const QString &name); static void changeFShader(BBMaterial *pMaterial, const QString &name); static void changeSampler2D(BBMaterial *pMaterial, const QString &uniformName, const QString &texturePath); static void changeSamplerCube(BBMaterial *pMaterial, const QString &uniformName, const QString resourcePaths[]); static void changeFloat(BBMaterial *pMaterial, const QString &floatName, float fValue); static void changeVector4(BBMaterial *pMaterial, const std::string &name, float *fValue); static void changeBlendState(BBMaterial *pMaterial, bool bEnable); static void changeSRCBlendFunc(BBMaterial *pMaterial, int src); static void changeDSTBlendFunc(BBMaterial *pMaterial, int dst); static void changeCullState(BBMaterial *pMaterial, bool bEnable); static void changeCullFace(BBMaterial *pMaterial, int face); public: static QString getShaderFilePath(const QString &name); static BBMaterial* getDeferredRenderingMaterial(int nIndex); static BBMaterial* createCoordinateUIMaterial(); static BBMaterial* createUIMaterial(); static BBMaterial* createStencilUIMaterial(); private: static void serialize(BBSerializer::BBMaterial material, const QString &filePath); static BBSerializer::BBMaterial deserialize(const QString &filePath); static QStringList loadShaderList(const QString &filter); static void loadMaterialContent(const QString &filePath, BBMaterial *pMaterial); static void createDeferredRenderingMaterial(); private: static BBPreviewOpenGLWidget *m_pPreviewOpenGLWidget; static QMap<QString, BBMaterial*> m_CachedMaterials; static BBMaterial *m_pDeferredRenderingMaterial[3]; }; #endif // BBRENDERERMANAGER_H <|start_filename|>Code/BBearEditor/Editor/PropertyManager/BBFactoryComponent.cpp<|end_filename|> #include "BBFactoryComponent.h" #include "Utils/BBUtils.h" #include <QPixmap> #include <QMouseEvent> #include <QHBoxLayout> #include <QLabel> #include <QApplication> #include <QDesktopWidget> #include <QScreen> #include <QMimeData> #include <QFileInfo> /** * @brief BBSliderLabel::BBSliderLabel * @param pParent */ BBSliderLabel::BBSliderLabel(QWidget *pParent) : QPushButton(pParent) { m_bPressed = false; setMouseTracking(true); } void BBSliderLabel::mouseMoveEvent(QMouseEvent *event) { QPixmap pix(BB_PATH_RESOURCE_ICON(arrows_stretch_horizontal.png)); pix.setDevicePixelRatio(devicePixelRatio()); pix = pix.scaled(32 * devicePixelRatio(), 32 * devicePixelRatio(), Qt::KeepAspectRatio, Qt::SmoothTransformation); setCursor(QCursor(pix)); if (m_bPressed) { QPoint currentPos = event->globalPos(); int nDeltaX = currentPos.x() - m_LastPos.x(); m_LastPos = currentPos; if (nDeltaX != 0) { slide(nDeltaX); } } } void BBSliderLabel::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { m_bPressed = true; m_LastPos = event->globalPos(); } } void BBSliderLabel::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { m_bPressed = false; m_LastPos = QPoint(0, 0); } } /** * @brief BBColorButton::BBColorButton * @param pParent */ BBColorButton::BBColorButton(QWidget *pParent) : QPushButton(pParent) { // white main background setStyleSheet("border: none; border-radius: 2px; padding: 2px 4px; background: white;"); // add real color widget into white background for observing transparent color m_pWhiteBackGroundContent = new QWidget(this); QHBoxLayout *pLayout = new QHBoxLayout(this); pLayout->setMargin(1); pLayout->addWidget(m_pWhiteBackGroundContent); QHBoxLayout *pWhiteLayout = new QHBoxLayout(m_pWhiteBackGroundContent); pWhiteLayout->setMargin(2); pWhiteLayout->setSpacing(0); // black background QWidget *pBlackBackGround = new QWidget(this); pBlackBackGround->setStyleSheet("background: black;"); pWhiteLayout->addWidget(pBlackBackGround); // add another black background for observing transparent color m_pBlackBackGroundContent = new QWidget(pBlackBackGround); QHBoxLayout *pBlackLayout = new QHBoxLayout(pBlackBackGround); pBlackLayout->setMargin(1); pBlackLayout->addWidget(m_pBlackBackGroundContent); // placeholder QWidget *pTransparent = new QWidget(m_pWhiteBackGroundContent); pTransparent->setStyleSheet("background: transparent;"); pWhiteLayout->addWidget(pTransparent); // default setColor(255, 255, 255, 255); QObject::connect(this, SIGNAL(clicked()), this, SLOT(click())); } BBColorButton::~BBColorButton() { BB_SAFE_DELETE(m_pBlackBackGroundContent); BB_SAFE_DELETE(m_pWhiteBackGroundContent); } void BBColorButton::setColor(int r, int g, int b, int a) { QString styleSheet = "background: rgba(" + QString::number(r) + ", " + QString::number(g) + ", " + QString::number(b) + ", " + QString::number(a) + ");"; m_pBlackBackGroundContent->setStyleSheet(styleSheet); m_pWhiteBackGroundContent->setStyleSheet(styleSheet); } void BBColorButton::setColor(float *color) { setColor(color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255); } void BBColorButton::click() { qDebug() << "BBColorButton::click()"; } /** * @brief BBScreenDialog::BBScreenDialog * @param pParent */ int BBScreenDialog::m_nCursorSize = 19; BBScreenDialog::BBScreenDialog(QWidget *pParent) : QDialog(pParent) { // frame setWindowFlags(Qt::FramelessWindowHint | windowFlags()); setWindowState(Qt::WindowMaximized); // Capture the screen and set the background of the dialog to be consistent with the screen QVBoxLayout *pLayout = new QVBoxLayout(this); pLayout->setMargin(0); m_pBackground = new QLabel(this); pLayout->addWidget(m_pBackground); // Capture the screen setBackground(); // Remove pop-up animation // hide(); // show(); // Set cursor as dropper QPixmap pix(BB_PATH_RESOURCE_ICON(eyedropper.png)); pix.setDevicePixelRatio(devicePixelRatio()); pix = pix.scaled(m_nCursorSize * devicePixelRatio(), m_nCursorSize * devicePixelRatio(), Qt::KeepAspectRatio, Qt::SmoothTransformation); setCursor(QCursor(pix)); } BBScreenDialog::~BBScreenDialog() { BB_SAFE_DELETE(m_pBackground); } void BBScreenDialog::setBackground() { // Capture the screen m_PixBackground = QApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId()); m_PixBackground.setDevicePixelRatio(devicePixelRatio()); #if defined(Q_OS_WIN32) // remove task bar that is in the bottom int y = QApplication::desktop()->availableGeometry().height() - QApplication::desktop()->screenGeometry().height(); m_PixBackground = m_PixBackground.copy(0, y * devicePixelRatio(), m_PixBackground.width(), m_PixBackground.height()); #elif defined(Q_OS_MAC) // if it is mac, need to remove menu bar that is in the top m_PixBackground = m_PixBackground.copy(0, QApplication::desktop()->availableGeometry().y() * devicePixelRatio(), m_PixBackground.width(), m_PixBackground.height()); #endif m_pBackground->setPixmap(m_PixBackground); } void BBScreenDialog::mousePressEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { QColor color = m_PixBackground.toImage().pixelColor((event->pos() + m_nCursorSize / 2 * QPoint(-1, 1)) * devicePixelRatio()); // Set the color of the color button as the currently selected value emit setColor(color.redF(), color.greenF(), color.blueF()); accept(); } else { reject(); } } /** * @brief BBDragAcceptedEdit::BBDragAcceptedLabel * @param pParent */ BBDragAcceptedEdit::BBDragAcceptedEdit(QWidget *pParent) : QLineEdit(pParent) { setAcceptDrops(true); setFocusPolicy(Qt::NoFocus); setText("None"); } void BBDragAcceptedEdit::dragEnterEvent(QDragEnterEvent *event) { QByteArray data; if ((data = event->mimeData()->data(BB_MIMETYPE_FILELISTWIDGET)) != nullptr) { QDataStream dataStream(&data, QIODevice::ReadOnly); dataStream >> m_CurrentFilePath; QString suffix = QFileInfo(m_CurrentFilePath).suffix(); if (m_Filter.contains(suffix)) { event->accept(); } else { event->ignore(); } } else { event->ignore(); } } void BBDragAcceptedEdit::dropEvent(QDropEvent *event) { emit currentFilePathChanged(m_CurrentFilePath); event->accept(); } /** * @brief BBIconLabel::BBIconLabel * @param pParent */ QSize BBIconLabel::m_DefaultSize = QSize(64, 64); BBIconLabel::BBIconLabel(QWidget *pParent) : BBDragAcceptedEdit(pParent) { setAlignment(Qt::AlignCenter); setMinimumSize(m_DefaultSize * devicePixelRatio()); setMaximumSize(m_DefaultSize * devicePixelRatio()); setStyleSheet("color: #d6dfeb; font: 9pt \"Arial\"; border-radius: 2px;"); } void BBIconLabel::setIcon(const QString &filePath) { setStyleSheet("color: #d6dfeb; font: 9pt \"Arial\"; " "border-image: url(" + filePath + "); border-radius: 2px;"); } <|start_filename|>Code/BBearEditor/Engine/Render/BBRenderQueue.h<|end_filename|> #ifndef BBRENDERQUEUE_H #define BBRENDERQUEUE_H class BBDrawCall; class BBCamera; class BBMaterial; class BBRenderQueue { public: BBRenderQueue(BBCamera *pCamera); ~BBRenderQueue(); void appendOpaqueDrawCall(BBDrawCall *pDC); void appendTransparentDrawCall(BBDrawCall *pDC); void appendUIDrawCall(BBDrawCall *pDC); void removeOpaqueDrawCall(BBDrawCall *pDC); void removeTransparentDrawCall(BBDrawCall *pDC); void removeUIDrawCall(BBDrawCall *pDC); void render(); void renderOpaque(); void renderTransparent(); void renderUI(); void updateAllDrawCallOrder(); void updateOpaqueDrawCallOrder(BBDrawCall *pNode); void updateTransparentDrawCallOrder(BBDrawCall *pNode); void switchQueue(BBMaterial *pPrevious, BBMaterial *pCurrent, BBDrawCall *pDrawCall); void switchQueue(bool bEnableBlend, BBDrawCall *pDrawCall); private: void updateAllOpaqueDrawCallOrder(); void updateAllTransparentDrawCallOrder(); BBDrawCall* appendAscendingRenderQueue(BBDrawCall *pHead, BBDrawCall *pNewNode); BBDrawCall* appendDescendingRenderQueue(BBDrawCall *pHead, BBDrawCall *pNewNode); BBCamera *m_pCamera; BBDrawCall *m_pOpaqueDrawCall; BBDrawCall *m_pTransparentDrawCall; BBDrawCall *m_pUIDrawCall; }; #endif // BBRENDERQUEUE_H <|start_filename|>Code/BBearEditor/Editor/Debugger/BBConsoleDockWidget.h<|end_filename|> #ifndef BBCONSOLEDOCKWIDGET_H #define BBCONSOLEDOCKWIDGET_H #include <QDockWidget> class BBConsoleDockWidget : public QDockWidget { public: BBConsoleDockWidget(QWidget *pParent = 0); ~BBConsoleDockWidget(); private: void dragEnterEvent(QDragEnterEvent *event) override; void dragMoveEvent(QDragMoveEvent *event) override; void dragLeaveEvent(QDragLeaveEvent *event) override; void dropEvent(QDropEvent *event) override; private: QString m_CurrentDragFilePath; }; #endif // BBCONSOLEDOCKWIDGET_H <|start_filename|>Resources/shaders/Volumetric/GBuffer.frag<|end_filename|> #version 430 core in vec2 v2f_texcoord; in vec3 v2f_normal; in vec3 v2f_view_space_pos; layout (location = 0) out vec4 Albedo; layout (location = 1) out vec4 Normal; layout (location = 2) out vec4 Position; uniform vec4 BBCameraParameters; uniform sampler2D ObjectDiffuseTexture; uniform vec4 BBLightColor; uniform vec4 BBLightPosition; uniform mat4 BBViewMatrix; float linearizeDepth(float depth) { float z_near = BBCameraParameters.z; float z_far = BBCameraParameters.w; float z = depth * 2.0 - 1.0; return (2.0 * z_near * z_far) / (z_far + z_near - z * (z_far - z_near)); } void main(void) { Position = vec4(v2f_view_space_pos, linearizeDepth(gl_FragCoord.z)); Normal.xyz = normalize(v2f_normal); Normal.a = 1.0; vec3 view_space_light_pos = vec3(BBViewMatrix * BBLightPosition); vec3 L = vec3(0.0); float intensity = 0.0; if (BBLightPosition.w == 0.0) { // directional light L = normalize(BBLightPosition.xyz); intensity = max(dot(Normal.xyz, normalize(L)), 0.0); } else { L = view_space_light_pos - Position.xyz; intensity = max(dot(Normal.xyz, normalize(L)), 0.0) / dot(L, L) * 50.0; } // Albedo = texture(ObjectDiffuseTexture, v2f_texcoord).rgb * max(dot(Normal.xyz, normalize(L)), 0.0) / dot(L, L) * 50.0; Albedo = vec4(intensity, intensity, intensity, 1.0); } <|start_filename|>Code/BBearEditor/Engine/Base/BBRenderableObject.h<|end_filename|> #ifndef BBRENDERABLEOBJECT_H #define BBRENDERABLEOBJECT_H #include "BBGameObject.h" #include <QtOpenGL> #define EXTRA_MATERIAL_COUNT 5 #define EXTRA_MATERIAL_INDEX_2 3 class BBDrawCall; class BBMaterial; class BBCamera; class BBVertexBufferObject; class BBShaderStorageBufferObject; class BBAtomicCounterBufferObject; class BBElementBufferObject; class BBScatterMaterial; class BBRenderableObject : public BBGameObject { public: BBRenderableObject(); BBRenderableObject(const QVector3D &position, const QVector3D &rotation, const QVector3D &scale); BBRenderableObject(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); BBRenderableObject(int x, int y, int nWidth, int nHeight); virtual ~BBRenderableObject(); void init() override; void render(BBCamera *pCamera) override; void render(const QMatrix4x4 &modelMatrix, BBCamera *pCamera) override; void insertInRenderQueue(BBRenderQueue *pQueue) override; void removeFromRenderQueue(BBRenderQueue *pQueue) override; void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; void setModelMatrix(float px, float py, float pz, const QQuaternion &r, float sx, float sy, float sz) override; void setVisibility(bool bVisible) override; void setCurrentMaterial(BBMaterial *pMaterial) override; void setCurrentMaterial(int nExtraMaterialIndex) override; void setExtraMaterial(int nMaterialIndex, BBMaterial *pMaterial) override; void rollbackMaterial() override; void restoreMaterial() override; void setMatrix4(const std::string &uniformName, const float *pMatrix4) override; void setVector4(const std::string &uniformName, float x, float y, float z, float w) override; void setArrayVector4(const std::string &uniformName, const float *pArrayVector4, int nArrayCount); void setTexture(const std::string &uniformName, GLuint textureName) override; void openLight() override; void closeLight() override; void appendSSBO(BBShaderStorageBufferObject *pSSBO); void removeSSBO(BBShaderStorageBufferObject *pSSBO); void appendACBO(BBAtomicCounterBufferObject *pACBO, bool bClear); void removeACBO(); void setScatterMaterial(BBScatterMaterial *pScatterMaterial) override; inline BBMaterial* getMaterial() { return m_pCurrentMaterial; } inline BBMaterial* getExtraMaterial(int nMaterialIndex) { return m_pExtraMaterial[nMaterialIndex]; } inline BBScatterMaterial* getScatterMaterial() { return m_pScatterMaterial; } inline BBVertexBufferObject* getVBO() { return m_pVBO; } inline BBElementBufferObject* getEBO() { return m_pEBO; } inline int getVertexCount() { return m_nVertexCount; } inline unsigned short* getVertexIndexes() { return m_pIndexes; } inline int getIndexCount() { return m_nIndexCount; } protected: void appendDrawCall(BBDrawCall *pDrawCall); bool m_bInRenderQueue; BBDrawCall *m_pDrawCalls; BBMaterial *m_pCurrentMaterial; BBMaterial *m_pLastMaterial; BBMaterial *m_pDefaultMaterial; BBMaterial *m_pExtraMaterial[EXTRA_MATERIAL_COUNT]; BBVertexBufferObject *m_pVBO; BBShaderStorageBufferObject *m_pSSBO; BBAtomicCounterBufferObject *m_pACBO; BBElementBufferObject *m_pEBO; unsigned short *m_pIndexes; int m_nIndexCount; int m_nVertexCount; QVector3D m_DefaultColor; BBScatterMaterial *m_pScatterMaterial; private: void sharedInit(); }; #endif // BBRENDERABLEOBJECT_H <|start_filename|>Code/BBearEditor/Engine/Render/Volumetric/BBVolumetricCloud.h<|end_filename|> #ifndef BBVOLUMETRICCLOUD_H #define BBVOLUMETRICCLOUD_H class BBScene; class BBVolumetricCloud { public: static void enable(int nAlgorithmIndex, bool bEnable); static void open(BBScene *pScene); static void setGBufferPass(BBScene *pScene); static void setScreenQuadPass(BBScene *pScene); }; #endif // BBVOLUMETRICCLOUD_H <|start_filename|>Resources/shaders/ParticleSystem/Particles0.frag<|end_filename|> #version 120 varying vec4 V_color; uniform sampler2D BBTexture0; void main(void) { gl_FragColor = texture2D(BBTexture0, gl_PointCoord.xy) * V_color; } <|start_filename|>Resources/shaders/texture.frag<|end_filename|> varying vec4 V_Texcoord; uniform sampler2D BBTexture0; void main(void) { gl_FragColor = texture2D(BBTexture0, V_Texcoord); } <|start_filename|>Resources/shaders/SkyBox/Common.vert<|end_filename|> #version 430 core in vec4 BBPosition; out vec4 v2f_local_pos; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { v2f_local_pos = BBPosition; v2f_local_pos.y = -v2f_local_pos.y; gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * BBPosition; } <|start_filename|>Code/BBearEditor/Engine/Serializer/BBGameObject.pb.h<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBGameObject.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_BBGameObject_2eproto #define GOOGLE_PROTOBUF_INCLUDED_BBGameObject_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3016000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3016000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> #include "BBVector.pb.h" // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_BBGameObject_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_BBGameObject_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBGameObject_2eproto; namespace BBSerializer { class BBGameObject; struct BBGameObjectDefaultTypeInternal; extern BBGameObjectDefaultTypeInternal _BBGameObject_default_instance_; } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> ::BBSerializer::BBGameObject* Arena::CreateMaybeMessage<::BBSerializer::BBGameObject>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace BBSerializer { // =================================================================== class BBGameObject PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBGameObject) */ { public: inline BBGameObject() : BBGameObject(nullptr) {} ~BBGameObject() override; explicit constexpr BBGameObject(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBGameObject(const BBGameObject& from); BBGameObject(BBGameObject&& from) noexcept : BBGameObject() { *this = ::std::move(from); } inline BBGameObject& operator=(const BBGameObject& from) { CopyFrom(from); return *this; } inline BBGameObject& operator=(BBGameObject&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBGameObject& default_instance() { return *internal_default_instance(); } static inline const BBGameObject* internal_default_instance() { return reinterpret_cast<const BBGameObject*>( &_BBGameObject_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(BBGameObject& a, BBGameObject& b) { a.Swap(&b); } inline void Swap(BBGameObject* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBGameObject* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBGameObject* New() const final { return CreateMaybeMessage<BBGameObject>(nullptr); } BBGameObject* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBGameObject>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBGameObject& from); void MergeFrom(const BBGameObject& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBGameObject* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBGameObject"; } protected: explicit BBGameObject(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kNameFieldNumber = 1, kClassNameFieldNumber = 2, kFilePathFieldNumber = 3, kPositionFieldNumber = 4, kLocalPositionFieldNumber = 5, kRotationFieldNumber = 6, kLocalRotationFieldNumber = 7, kScaleFieldNumber = 8, kLocalScaleFieldNumber = 9, }; // string name = 1; bool has_name() const; private: bool _internal_has_name() const; public: void clear_name(); const std::string& name() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_name(ArgT0&& arg0, ArgT... args); std::string* mutable_name(); std::string* release_name(); void set_allocated_name(std::string* name); private: const std::string& _internal_name() const; void _internal_set_name(const std::string& value); std::string* _internal_mutable_name(); public: // string className = 2; bool has_classname() const; private: bool _internal_has_classname() const; public: void clear_classname(); const std::string& classname() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_classname(ArgT0&& arg0, ArgT... args); std::string* mutable_classname(); std::string* release_classname(); void set_allocated_classname(std::string* classname); private: const std::string& _internal_classname() const; void _internal_set_classname(const std::string& value); std::string* _internal_mutable_classname(); public: // string filePath = 3; bool has_filepath() const; private: bool _internal_has_filepath() const; public: void clear_filepath(); const std::string& filepath() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_filepath(ArgT0&& arg0, ArgT... args); std::string* mutable_filepath(); std::string* release_filepath(); void set_allocated_filepath(std::string* filepath); private: const std::string& _internal_filepath() const; void _internal_set_filepath(const std::string& value); std::string* _internal_mutable_filepath(); public: // .BBSerializer.BBVector3f position = 4; bool has_position() const; private: bool _internal_has_position() const; public: void clear_position(); const ::BBSerializer::BBVector3f& position() const; ::BBSerializer::BBVector3f* release_position(); ::BBSerializer::BBVector3f* mutable_position(); void set_allocated_position(::BBSerializer::BBVector3f* position); private: const ::BBSerializer::BBVector3f& _internal_position() const; ::BBSerializer::BBVector3f* _internal_mutable_position(); public: void unsafe_arena_set_allocated_position( ::BBSerializer::BBVector3f* position); ::BBSerializer::BBVector3f* unsafe_arena_release_position(); // .BBSerializer.BBVector3f localPosition = 5; bool has_localposition() const; private: bool _internal_has_localposition() const; public: void clear_localposition(); const ::BBSerializer::BBVector3f& localposition() const; ::BBSerializer::BBVector3f* release_localposition(); ::BBSerializer::BBVector3f* mutable_localposition(); void set_allocated_localposition(::BBSerializer::BBVector3f* localposition); private: const ::BBSerializer::BBVector3f& _internal_localposition() const; ::BBSerializer::BBVector3f* _internal_mutable_localposition(); public: void unsafe_arena_set_allocated_localposition( ::BBSerializer::BBVector3f* localposition); ::BBSerializer::BBVector3f* unsafe_arena_release_localposition(); // .BBSerializer.BBVector3f rotation = 6; bool has_rotation() const; private: bool _internal_has_rotation() const; public: void clear_rotation(); const ::BBSerializer::BBVector3f& rotation() const; ::BBSerializer::BBVector3f* release_rotation(); ::BBSerializer::BBVector3f* mutable_rotation(); void set_allocated_rotation(::BBSerializer::BBVector3f* rotation); private: const ::BBSerializer::BBVector3f& _internal_rotation() const; ::BBSerializer::BBVector3f* _internal_mutable_rotation(); public: void unsafe_arena_set_allocated_rotation( ::BBSerializer::BBVector3f* rotation); ::BBSerializer::BBVector3f* unsafe_arena_release_rotation(); // .BBSerializer.BBVector3f localRotation = 7; bool has_localrotation() const; private: bool _internal_has_localrotation() const; public: void clear_localrotation(); const ::BBSerializer::BBVector3f& localrotation() const; ::BBSerializer::BBVector3f* release_localrotation(); ::BBSerializer::BBVector3f* mutable_localrotation(); void set_allocated_localrotation(::BBSerializer::BBVector3f* localrotation); private: const ::BBSerializer::BBVector3f& _internal_localrotation() const; ::BBSerializer::BBVector3f* _internal_mutable_localrotation(); public: void unsafe_arena_set_allocated_localrotation( ::BBSerializer::BBVector3f* localrotation); ::BBSerializer::BBVector3f* unsafe_arena_release_localrotation(); // .BBSerializer.BBVector3f scale = 8; bool has_scale() const; private: bool _internal_has_scale() const; public: void clear_scale(); const ::BBSerializer::BBVector3f& scale() const; ::BBSerializer::BBVector3f* release_scale(); ::BBSerializer::BBVector3f* mutable_scale(); void set_allocated_scale(::BBSerializer::BBVector3f* scale); private: const ::BBSerializer::BBVector3f& _internal_scale() const; ::BBSerializer::BBVector3f* _internal_mutable_scale(); public: void unsafe_arena_set_allocated_scale( ::BBSerializer::BBVector3f* scale); ::BBSerializer::BBVector3f* unsafe_arena_release_scale(); // .BBSerializer.BBVector3f localScale = 9; bool has_localscale() const; private: bool _internal_has_localscale() const; public: void clear_localscale(); const ::BBSerializer::BBVector3f& localscale() const; ::BBSerializer::BBVector3f* release_localscale(); ::BBSerializer::BBVector3f* mutable_localscale(); void set_allocated_localscale(::BBSerializer::BBVector3f* localscale); private: const ::BBSerializer::BBVector3f& _internal_localscale() const; ::BBSerializer::BBVector3f* _internal_mutable_localscale(); public: void unsafe_arena_set_allocated_localscale( ::BBSerializer::BBVector3f* localscale); ::BBSerializer::BBVector3f* unsafe_arena_release_localscale(); // @@protoc_insertion_point(class_scope:BBSerializer.BBGameObject) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr classname_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr filepath_; ::BBSerializer::BBVector3f* position_; ::BBSerializer::BBVector3f* localposition_; ::BBSerializer::BBVector3f* rotation_; ::BBSerializer::BBVector3f* localrotation_; ::BBSerializer::BBVector3f* scale_; ::BBSerializer::BBVector3f* localscale_; friend struct ::TableStruct_BBGameObject_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // BBGameObject // string name = 1; inline bool BBGameObject::_internal_has_name() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool BBGameObject::has_name() const { return _internal_has_name(); } inline void BBGameObject::clear_name() { name_.ClearToEmpty(); _has_bits_[0] &= ~0x00000001u; } inline const std::string& BBGameObject::name() const { // @@protoc_insertion_point(field_get:BBSerializer.BBGameObject.name) return _internal_name(); } template <typename ArgT0, typename... ArgT> PROTOBUF_ALWAYS_INLINE inline void BBGameObject::set_name(ArgT0&& arg0, ArgT... args) { _has_bits_[0] |= 0x00000001u; name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArena()); // @@protoc_insertion_point(field_set:BBSerializer.BBGameObject.name) } inline std::string* BBGameObject::mutable_name() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBGameObject.name) return _internal_mutable_name(); } inline const std::string& BBGameObject::_internal_name() const { return name_.Get(); } inline void BBGameObject::_internal_set_name(const std::string& value) { _has_bits_[0] |= 0x00000001u; name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline std::string* BBGameObject::_internal_mutable_name() { _has_bits_[0] |= 0x00000001u; return name_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* BBGameObject::release_name() { // @@protoc_insertion_point(field_release:BBSerializer.BBGameObject.name) if (!_internal_has_name()) { return nullptr; } _has_bits_[0] &= ~0x00000001u; return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void BBGameObject::set_allocated_name(std::string* name) { if (name != nullptr) { _has_bits_[0] |= 0x00000001u; } else { _has_bits_[0] &= ~0x00000001u; } name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, GetArena()); // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBGameObject.name) } // string className = 2; inline bool BBGameObject::_internal_has_classname() const { bool value = (_has_bits_[0] & 0x00000002u) != 0; return value; } inline bool BBGameObject::has_classname() const { return _internal_has_classname(); } inline void BBGameObject::clear_classname() { classname_.ClearToEmpty(); _has_bits_[0] &= ~0x00000002u; } inline const std::string& BBGameObject::classname() const { // @@protoc_insertion_point(field_get:BBSerializer.BBGameObject.className) return _internal_classname(); } template <typename ArgT0, typename... ArgT> PROTOBUF_ALWAYS_INLINE inline void BBGameObject::set_classname(ArgT0&& arg0, ArgT... args) { _has_bits_[0] |= 0x00000002u; classname_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArena()); // @@protoc_insertion_point(field_set:BBSerializer.BBGameObject.className) } inline std::string* BBGameObject::mutable_classname() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBGameObject.className) return _internal_mutable_classname(); } inline const std::string& BBGameObject::_internal_classname() const { return classname_.Get(); } inline void BBGameObject::_internal_set_classname(const std::string& value) { _has_bits_[0] |= 0x00000002u; classname_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline std::string* BBGameObject::_internal_mutable_classname() { _has_bits_[0] |= 0x00000002u; return classname_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* BBGameObject::release_classname() { // @@protoc_insertion_point(field_release:BBSerializer.BBGameObject.className) if (!_internal_has_classname()) { return nullptr; } _has_bits_[0] &= ~0x00000002u; return classname_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void BBGameObject::set_allocated_classname(std::string* classname) { if (classname != nullptr) { _has_bits_[0] |= 0x00000002u; } else { _has_bits_[0] &= ~0x00000002u; } classname_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), classname, GetArena()); // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBGameObject.className) } // string filePath = 3; inline bool BBGameObject::_internal_has_filepath() const { bool value = (_has_bits_[0] & 0x00000004u) != 0; return value; } inline bool BBGameObject::has_filepath() const { return _internal_has_filepath(); } inline void BBGameObject::clear_filepath() { filepath_.ClearToEmpty(); _has_bits_[0] &= ~0x00000004u; } inline const std::string& BBGameObject::filepath() const { // @@protoc_insertion_point(field_get:BBSerializer.BBGameObject.filePath) return _internal_filepath(); } template <typename ArgT0, typename... ArgT> PROTOBUF_ALWAYS_INLINE inline void BBGameObject::set_filepath(ArgT0&& arg0, ArgT... args) { _has_bits_[0] |= 0x00000004u; filepath_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArena()); // @@protoc_insertion_point(field_set:BBSerializer.BBGameObject.filePath) } inline std::string* BBGameObject::mutable_filepath() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBGameObject.filePath) return _internal_mutable_filepath(); } inline const std::string& BBGameObject::_internal_filepath() const { return filepath_.Get(); } inline void BBGameObject::_internal_set_filepath(const std::string& value) { _has_bits_[0] |= 0x00000004u; filepath_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline std::string* BBGameObject::_internal_mutable_filepath() { _has_bits_[0] |= 0x00000004u; return filepath_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* BBGameObject::release_filepath() { // @@protoc_insertion_point(field_release:BBSerializer.BBGameObject.filePath) if (!_internal_has_filepath()) { return nullptr; } _has_bits_[0] &= ~0x00000004u; return filepath_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void BBGameObject::set_allocated_filepath(std::string* filepath) { if (filepath != nullptr) { _has_bits_[0] |= 0x00000004u; } else { _has_bits_[0] &= ~0x00000004u; } filepath_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), filepath, GetArena()); // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBGameObject.filePath) } // .BBSerializer.BBVector3f position = 4; inline bool BBGameObject::_internal_has_position() const { bool value = (_has_bits_[0] & 0x00000008u) != 0; PROTOBUF_ASSUME(!value || position_ != nullptr); return value; } inline bool BBGameObject::has_position() const { return _internal_has_position(); } inline const ::BBSerializer::BBVector3f& BBGameObject::_internal_position() const { const ::BBSerializer::BBVector3f* p = position_; return p != nullptr ? *p : reinterpret_cast<const ::BBSerializer::BBVector3f&>( ::BBSerializer::_BBVector3f_default_instance_); } inline const ::BBSerializer::BBVector3f& BBGameObject::position() const { // @@protoc_insertion_point(field_get:BBSerializer.BBGameObject.position) return _internal_position(); } inline void BBGameObject::unsafe_arena_set_allocated_position( ::BBSerializer::BBVector3f* position) { if (GetArena() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(position_); } position_ = position; if (position) { _has_bits_[0] |= 0x00000008u; } else { _has_bits_[0] &= ~0x00000008u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:BBSerializer.BBGameObject.position) } inline ::BBSerializer::BBVector3f* BBGameObject::release_position() { _has_bits_[0] &= ~0x00000008u; ::BBSerializer::BBVector3f* temp = position_; position_ = nullptr; if (GetArena() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::unsafe_arena_release_position() { // @@protoc_insertion_point(field_release:BBSerializer.BBGameObject.position) _has_bits_[0] &= ~0x00000008u; ::BBSerializer::BBVector3f* temp = position_; position_ = nullptr; return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::_internal_mutable_position() { _has_bits_[0] |= 0x00000008u; if (position_ == nullptr) { auto* p = CreateMaybeMessage<::BBSerializer::BBVector3f>(GetArena()); position_ = p; } return position_; } inline ::BBSerializer::BBVector3f* BBGameObject::mutable_position() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBGameObject.position) return _internal_mutable_position(); } inline void BBGameObject::set_allocated_position(::BBSerializer::BBVector3f* position) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena(); if (message_arena == nullptr) { delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(position_); } if (position) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(position)->GetArena(); if (message_arena != submessage_arena) { position = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, position, submessage_arena); } _has_bits_[0] |= 0x00000008u; } else { _has_bits_[0] &= ~0x00000008u; } position_ = position; // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBGameObject.position) } // .BBSerializer.BBVector3f localPosition = 5; inline bool BBGameObject::_internal_has_localposition() const { bool value = (_has_bits_[0] & 0x00000010u) != 0; PROTOBUF_ASSUME(!value || localposition_ != nullptr); return value; } inline bool BBGameObject::has_localposition() const { return _internal_has_localposition(); } inline const ::BBSerializer::BBVector3f& BBGameObject::_internal_localposition() const { const ::BBSerializer::BBVector3f* p = localposition_; return p != nullptr ? *p : reinterpret_cast<const ::BBSerializer::BBVector3f&>( ::BBSerializer::_BBVector3f_default_instance_); } inline const ::BBSerializer::BBVector3f& BBGameObject::localposition() const { // @@protoc_insertion_point(field_get:BBSerializer.BBGameObject.localPosition) return _internal_localposition(); } inline void BBGameObject::unsafe_arena_set_allocated_localposition( ::BBSerializer::BBVector3f* localposition) { if (GetArena() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(localposition_); } localposition_ = localposition; if (localposition) { _has_bits_[0] |= 0x00000010u; } else { _has_bits_[0] &= ~0x00000010u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:BBSerializer.BBGameObject.localPosition) } inline ::BBSerializer::BBVector3f* BBGameObject::release_localposition() { _has_bits_[0] &= ~0x00000010u; ::BBSerializer::BBVector3f* temp = localposition_; localposition_ = nullptr; if (GetArena() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::unsafe_arena_release_localposition() { // @@protoc_insertion_point(field_release:BBSerializer.BBGameObject.localPosition) _has_bits_[0] &= ~0x00000010u; ::BBSerializer::BBVector3f* temp = localposition_; localposition_ = nullptr; return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::_internal_mutable_localposition() { _has_bits_[0] |= 0x00000010u; if (localposition_ == nullptr) { auto* p = CreateMaybeMessage<::BBSerializer::BBVector3f>(GetArena()); localposition_ = p; } return localposition_; } inline ::BBSerializer::BBVector3f* BBGameObject::mutable_localposition() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBGameObject.localPosition) return _internal_mutable_localposition(); } inline void BBGameObject::set_allocated_localposition(::BBSerializer::BBVector3f* localposition) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena(); if (message_arena == nullptr) { delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(localposition_); } if (localposition) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(localposition)->GetArena(); if (message_arena != submessage_arena) { localposition = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, localposition, submessage_arena); } _has_bits_[0] |= 0x00000010u; } else { _has_bits_[0] &= ~0x00000010u; } localposition_ = localposition; // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBGameObject.localPosition) } // .BBSerializer.BBVector3f rotation = 6; inline bool BBGameObject::_internal_has_rotation() const { bool value = (_has_bits_[0] & 0x00000020u) != 0; PROTOBUF_ASSUME(!value || rotation_ != nullptr); return value; } inline bool BBGameObject::has_rotation() const { return _internal_has_rotation(); } inline const ::BBSerializer::BBVector3f& BBGameObject::_internal_rotation() const { const ::BBSerializer::BBVector3f* p = rotation_; return p != nullptr ? *p : reinterpret_cast<const ::BBSerializer::BBVector3f&>( ::BBSerializer::_BBVector3f_default_instance_); } inline const ::BBSerializer::BBVector3f& BBGameObject::rotation() const { // @@protoc_insertion_point(field_get:BBSerializer.BBGameObject.rotation) return _internal_rotation(); } inline void BBGameObject::unsafe_arena_set_allocated_rotation( ::BBSerializer::BBVector3f* rotation) { if (GetArena() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(rotation_); } rotation_ = rotation; if (rotation) { _has_bits_[0] |= 0x00000020u; } else { _has_bits_[0] &= ~0x00000020u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:BBSerializer.BBGameObject.rotation) } inline ::BBSerializer::BBVector3f* BBGameObject::release_rotation() { _has_bits_[0] &= ~0x00000020u; ::BBSerializer::BBVector3f* temp = rotation_; rotation_ = nullptr; if (GetArena() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::unsafe_arena_release_rotation() { // @@protoc_insertion_point(field_release:BBSerializer.BBGameObject.rotation) _has_bits_[0] &= ~0x00000020u; ::BBSerializer::BBVector3f* temp = rotation_; rotation_ = nullptr; return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::_internal_mutable_rotation() { _has_bits_[0] |= 0x00000020u; if (rotation_ == nullptr) { auto* p = CreateMaybeMessage<::BBSerializer::BBVector3f>(GetArena()); rotation_ = p; } return rotation_; } inline ::BBSerializer::BBVector3f* BBGameObject::mutable_rotation() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBGameObject.rotation) return _internal_mutable_rotation(); } inline void BBGameObject::set_allocated_rotation(::BBSerializer::BBVector3f* rotation) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena(); if (message_arena == nullptr) { delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(rotation_); } if (rotation) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(rotation)->GetArena(); if (message_arena != submessage_arena) { rotation = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, rotation, submessage_arena); } _has_bits_[0] |= 0x00000020u; } else { _has_bits_[0] &= ~0x00000020u; } rotation_ = rotation; // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBGameObject.rotation) } // .BBSerializer.BBVector3f localRotation = 7; inline bool BBGameObject::_internal_has_localrotation() const { bool value = (_has_bits_[0] & 0x00000040u) != 0; PROTOBUF_ASSUME(!value || localrotation_ != nullptr); return value; } inline bool BBGameObject::has_localrotation() const { return _internal_has_localrotation(); } inline const ::BBSerializer::BBVector3f& BBGameObject::_internal_localrotation() const { const ::BBSerializer::BBVector3f* p = localrotation_; return p != nullptr ? *p : reinterpret_cast<const ::BBSerializer::BBVector3f&>( ::BBSerializer::_BBVector3f_default_instance_); } inline const ::BBSerializer::BBVector3f& BBGameObject::localrotation() const { // @@protoc_insertion_point(field_get:BBSerializer.BBGameObject.localRotation) return _internal_localrotation(); } inline void BBGameObject::unsafe_arena_set_allocated_localrotation( ::BBSerializer::BBVector3f* localrotation) { if (GetArena() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(localrotation_); } localrotation_ = localrotation; if (localrotation) { _has_bits_[0] |= 0x00000040u; } else { _has_bits_[0] &= ~0x00000040u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:BBSerializer.BBGameObject.localRotation) } inline ::BBSerializer::BBVector3f* BBGameObject::release_localrotation() { _has_bits_[0] &= ~0x00000040u; ::BBSerializer::BBVector3f* temp = localrotation_; localrotation_ = nullptr; if (GetArena() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::unsafe_arena_release_localrotation() { // @@protoc_insertion_point(field_release:BBSerializer.BBGameObject.localRotation) _has_bits_[0] &= ~0x00000040u; ::BBSerializer::BBVector3f* temp = localrotation_; localrotation_ = nullptr; return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::_internal_mutable_localrotation() { _has_bits_[0] |= 0x00000040u; if (localrotation_ == nullptr) { auto* p = CreateMaybeMessage<::BBSerializer::BBVector3f>(GetArena()); localrotation_ = p; } return localrotation_; } inline ::BBSerializer::BBVector3f* BBGameObject::mutable_localrotation() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBGameObject.localRotation) return _internal_mutable_localrotation(); } inline void BBGameObject::set_allocated_localrotation(::BBSerializer::BBVector3f* localrotation) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena(); if (message_arena == nullptr) { delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(localrotation_); } if (localrotation) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(localrotation)->GetArena(); if (message_arena != submessage_arena) { localrotation = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, localrotation, submessage_arena); } _has_bits_[0] |= 0x00000040u; } else { _has_bits_[0] &= ~0x00000040u; } localrotation_ = localrotation; // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBGameObject.localRotation) } // .BBSerializer.BBVector3f scale = 8; inline bool BBGameObject::_internal_has_scale() const { bool value = (_has_bits_[0] & 0x00000080u) != 0; PROTOBUF_ASSUME(!value || scale_ != nullptr); return value; } inline bool BBGameObject::has_scale() const { return _internal_has_scale(); } inline const ::BBSerializer::BBVector3f& BBGameObject::_internal_scale() const { const ::BBSerializer::BBVector3f* p = scale_; return p != nullptr ? *p : reinterpret_cast<const ::BBSerializer::BBVector3f&>( ::BBSerializer::_BBVector3f_default_instance_); } inline const ::BBSerializer::BBVector3f& BBGameObject::scale() const { // @@protoc_insertion_point(field_get:BBSerializer.BBGameObject.scale) return _internal_scale(); } inline void BBGameObject::unsafe_arena_set_allocated_scale( ::BBSerializer::BBVector3f* scale) { if (GetArena() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(scale_); } scale_ = scale; if (scale) { _has_bits_[0] |= 0x00000080u; } else { _has_bits_[0] &= ~0x00000080u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:BBSerializer.BBGameObject.scale) } inline ::BBSerializer::BBVector3f* BBGameObject::release_scale() { _has_bits_[0] &= ~0x00000080u; ::BBSerializer::BBVector3f* temp = scale_; scale_ = nullptr; if (GetArena() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::unsafe_arena_release_scale() { // @@protoc_insertion_point(field_release:BBSerializer.BBGameObject.scale) _has_bits_[0] &= ~0x00000080u; ::BBSerializer::BBVector3f* temp = scale_; scale_ = nullptr; return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::_internal_mutable_scale() { _has_bits_[0] |= 0x00000080u; if (scale_ == nullptr) { auto* p = CreateMaybeMessage<::BBSerializer::BBVector3f>(GetArena()); scale_ = p; } return scale_; } inline ::BBSerializer::BBVector3f* BBGameObject::mutable_scale() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBGameObject.scale) return _internal_mutable_scale(); } inline void BBGameObject::set_allocated_scale(::BBSerializer::BBVector3f* scale) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena(); if (message_arena == nullptr) { delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(scale_); } if (scale) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(scale)->GetArena(); if (message_arena != submessage_arena) { scale = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, scale, submessage_arena); } _has_bits_[0] |= 0x00000080u; } else { _has_bits_[0] &= ~0x00000080u; } scale_ = scale; // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBGameObject.scale) } // .BBSerializer.BBVector3f localScale = 9; inline bool BBGameObject::_internal_has_localscale() const { bool value = (_has_bits_[0] & 0x00000100u) != 0; PROTOBUF_ASSUME(!value || localscale_ != nullptr); return value; } inline bool BBGameObject::has_localscale() const { return _internal_has_localscale(); } inline const ::BBSerializer::BBVector3f& BBGameObject::_internal_localscale() const { const ::BBSerializer::BBVector3f* p = localscale_; return p != nullptr ? *p : reinterpret_cast<const ::BBSerializer::BBVector3f&>( ::BBSerializer::_BBVector3f_default_instance_); } inline const ::BBSerializer::BBVector3f& BBGameObject::localscale() const { // @@protoc_insertion_point(field_get:BBSerializer.BBGameObject.localScale) return _internal_localscale(); } inline void BBGameObject::unsafe_arena_set_allocated_localscale( ::BBSerializer::BBVector3f* localscale) { if (GetArena() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(localscale_); } localscale_ = localscale; if (localscale) { _has_bits_[0] |= 0x00000100u; } else { _has_bits_[0] &= ~0x00000100u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:BBSerializer.BBGameObject.localScale) } inline ::BBSerializer::BBVector3f* BBGameObject::release_localscale() { _has_bits_[0] &= ~0x00000100u; ::BBSerializer::BBVector3f* temp = localscale_; localscale_ = nullptr; if (GetArena() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::unsafe_arena_release_localscale() { // @@protoc_insertion_point(field_release:BBSerializer.BBGameObject.localScale) _has_bits_[0] &= ~0x00000100u; ::BBSerializer::BBVector3f* temp = localscale_; localscale_ = nullptr; return temp; } inline ::BBSerializer::BBVector3f* BBGameObject::_internal_mutable_localscale() { _has_bits_[0] |= 0x00000100u; if (localscale_ == nullptr) { auto* p = CreateMaybeMessage<::BBSerializer::BBVector3f>(GetArena()); localscale_ = p; } return localscale_; } inline ::BBSerializer::BBVector3f* BBGameObject::mutable_localscale() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBGameObject.localScale) return _internal_mutable_localscale(); } inline void BBGameObject::set_allocated_localscale(::BBSerializer::BBVector3f* localscale) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena(); if (message_arena == nullptr) { delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(localscale_); } if (localscale) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(localscale)->GetArena(); if (message_arena != submessage_arena) { localscale = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, localscale, submessage_arena); } _has_bits_[0] |= 0x00000100u; } else { _has_bits_[0] &= ~0x00000100u; } localscale_ = localscale; // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBGameObject.localScale) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_BBGameObject_2eproto <|start_filename|>Resources/shaders/fullscreenquad_ray_tracing.frag<|end_filename|> varying vec4 V_Position; varying vec4 V_Texcoord; uniform sampler2D texture0; uniform sampler2D texture1; uniform sampler2D texture3; uniform mat4 projectionMatrix_I; uniform mat4 viewMatrix_I; vec4 UV2PointOnPlane(vec4 point) { point = 2 * point; point = point - vec4(1.0); point = viewMatrix_I * projectionMatrix_I * point; point = vec4(point.xyz / point.w, 1.0); return point; } bool hitObject(vec2 coord, float min_distance, float max_distance, out vec2 hit_point) { vec3 model_normal = texture2D(texture1, coord); return length(model_normal) != 0.0; } vec3 hash3(vec2 coord) { vec3 rand = vec3(dot(coord, vec2(127.1, 311.7)), dot(coord, vec2(269.5, 183.3)), dot(coord, vec2(419.2, 371.9))); rand = fract(sin(rand) * 43758.5453); rand = normalize(rand); return rand; } vec3 getWorldPosition(vec2 coord) { return texture2D(texture0, coord); } vec3 getObjectNormal(vec2 coord) { return texture2D(texture1, coord); } vec3 getBackGroundColor(vec2 coord) { return texture2D(texture3, coord); } vec3 scatter(vec2 coord, vec3 input_ray) { vec3 rand_direction = hash3(coord); vec3 new_direction = getObjectNormal(coord) + rand_direction; return new_direction; } vec3 getColor(vec2 coord, vec3 input_ray) { vec2 hit_point; if (hitObject(coord, 0.0, 100.0, hit_point)) { vec3 scatter_ray = scatter(coord, input_ray); return getColor(hit_point, scatter_ray); } return getBackGroundColor(coord); } void main(void) { vec3 final_color = vec3(0.0); vec4 point_near_plane = UV2PointOnPlane(vec4(V_Texcoord.xy, 0.0, 1.0)); vec4 point_far_plane = UV2PointOnPlane(vec4(V_Texcoord.xy, 1.0, 1.0)); vec3 ray_direction = normalize(point_far_plane.xyz - point_near_plane.xyz); if (ray_direction.x < 0.0) ray_direction.x = -ray_direction.x; if (ray_direction.y < 0.0) ray_direction.y = -ray_direction.y; if (ray_direction.z < 0.0) ray_direction.z = -ray_direction.z; vec3 model_normal = texture2D(texture1, V_Texcoord.xy); // 0~1 model_normal = model_normal * 0.5 + 0.5; gl_FragColor = vec4(texture2D(texture3, V_Texcoord.xy).xyz, 1.0); } <|start_filename|>Code/BBearEditor/Engine/3D/Mesh/BBMesh.cpp<|end_filename|> #include "BBMesh.h" #include "Render/BBMaterial.h" #include "Utils/BBUtils.h" #include "Geometry/BBBoundingBox.h" #include <cfloat> #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BufferObject/BBElementBufferObject.h" #include "Render/BBRenderPass.h" #include "Render/BBDrawCall.h" #include "Render/Texture/BBTexture.h" #include "Math/BBMath.h" #include "Render/Texture/BBProcedureTexture.h" BBMesh::BBMesh() : BBMesh(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBMesh::BBMesh(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBRenderableObject(px, py, pz, rx, ry, rz, sx, sy, sz) { setClassName(BB_CLASSNAME_MESH); m_eDrawPrimitiveType = GL_QUADS; m_pEBO2 = nullptr; m_pIndexes2 = nullptr; m_nIndexCount2 = 0; } void BBMesh::init(const QString &path, BBBoundingBox3D *&pOutBoundingBox) { QList<QVector4D> positions; load(path, positions); m_pVBO->computeTangent(m_pIndexes, m_nIndexCount); m_pVBO->computeSmoothNormal(); // create bounding box pOutBoundingBox = new BBAABBBoundingBox3D(m_Position.x(), m_Position.y(), m_Position.z(), m_Rotation.x(), m_Rotation.y(), m_Rotation.z(), m_Scale.x(), m_Scale.y(), m_Scale.z(), positions); pOutBoundingBox->init(); m_pCurrentMaterial->initMultiPass("standard", BB_PATH_RESOURCE_SHADER(standard.vert), BB_PATH_RESOURCE_SHADER(standard.frag)); m_pCurrentMaterial->getAdditiveRenderPass()->setBlendState(true); // default float *pLightPosition = new float[4] {0.8f, 1.0f, 0.5f, 0.0f}; float *pLightColor = new float[4] {1.0f, 1.0f, 1.0f, 1.0f}; m_pCurrentMaterial->setVector4(LOCATION_LIGHT_POSITION, pLightPosition); m_pCurrentMaterial->setVector4(LOCATION_LIGHT_COLOR, pLightColor); BBTexture texture; m_pCurrentMaterial->setSampler2D(LOCATION_TEXTURE(0), texture.createTexture2D()); // test perlin noise m_pCurrentMaterial->setSampler2D("PerlinNoiseTex2D", BBProcedureTexture().createPerlinNoiseTexture2D(512, 0.0625f)); m_pCurrentMaterial->setSampler3D("PerlinNoiseTex3D", BBProcedureTexture().createPerlinNoiseTexture3D(64, 64, 64, 0.125f)); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_TRIANGLES, m_nIndexCount, 0); appendDrawCall(pDrawCall); if (m_nIndexCount2 > 0) { m_pEBO2 = new BBElementBufferObject(m_nIndexCount2); m_pEBO2->submitData(m_pIndexes2, m_nIndexCount2); BBDrawCall *pDrawCall2 = new BBDrawCall; pDrawCall2->setMaterial(m_pCurrentMaterial); pDrawCall2->setVBO(m_pVBO); pDrawCall2->setEBO(m_pEBO2, GL_QUADS, m_nIndexCount2, 0); appendDrawCall(pDrawCall2); } } void BBMesh::init(BBVertexBufferObject *pVBO, GLenum eDrawPrimitiveType, int nDrawStartIndex, int nDrawCount, BBBoundingBox3D *&pOutBoundingBox) { m_pVBO = pVBO; // create bounding box pOutBoundingBox = new BBAABBBoundingBox3D(m_Position.x(), m_Position.y(), m_Position.z(), m_Rotation.x(), m_Rotation.y(), m_Rotation.z(), m_Scale.x(), m_Scale.y(), m_Scale.z(), pVBO->getPositions()); pOutBoundingBox->init(); m_pCurrentMaterial->init("base", BB_PATH_RESOURCE_SHADER(base.vert), BB_PATH_RESOURCE_SHADER(base.frag)); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, eDrawPrimitiveType, nDrawStartIndex, nDrawCount); appendDrawCall(pDrawCall); } void BBMesh::setExtraMaterial(int nMaterialIndex, BBMaterial *pMaterial) { BBRenderableObject::setExtraMaterial(nMaterialIndex, pMaterial); // multi pass rendering if (nMaterialIndex == EXTRA_MATERIAL_INDEX_2) { pMaterial->setMatrix4(LOCATION_MODELMATRIX, m_ModelMatrix.data()); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(pMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_TRIANGLES, m_nIndexCount, 0); appendDrawCall(pDrawCall); } } bool BBMesh::hit(const BBRay &ray, float &fDistance) { QVector3D intersection; bool bResult = false; fDistance = FLT_MAX; for (int i = 0; i < m_nIndexCount; i += 3) { if (ray.computeIntersectWithTriangle(m_ModelMatrix * m_pVBO->getPosition(m_pIndexes[i]), m_ModelMatrix * m_pVBO->getPosition(m_pIndexes[i + 1]), m_ModelMatrix * m_pVBO->getPosition(m_pIndexes[i + 2]), intersection)) { float temp = ray.computeIntersectDistance(intersection); if (temp >= 0.0f) { if (temp < fDistance) fDistance = temp; bResult = true; } } } return bResult; } bool BBMesh::hit(const BBRay &ray, float fMinDistance, float fMaxDistance, BBHitInfo &hitInfo) { QVector3D intersectionNormal; QVector3D intersectionPos; float fIntersectionU; float fIntersectionV; float fNearestIntersectionU; float fNearestIntersectionV; hitInfo.m_fDistance = fMaxDistance; int nNearestStartIndex = -1; bool bResult = false; for (int i = 0; i < m_nIndexCount; i += 3) { if (ray.computeIntersectWithTriangle(m_ModelMatrix * m_pVBO->getPosition(m_pIndexes[i]), m_ModelMatrix * m_pVBO->getPosition(m_pIndexes[i + 1]), m_ModelMatrix * m_pVBO->getPosition(m_pIndexes[i + 2]), intersectionNormal, intersectionPos, fIntersectionU, fIntersectionV)) { float temp = ray.computeIntersectDistance(intersectionPos); if (temp >= 0.0f) { if (temp < hitInfo.m_fDistance && temp > fMinDistance) { // Record the information of the nearest intersection point and face hitInfo.m_Position = intersectionPos; hitInfo.m_Normal = intersectionNormal; fNearestIntersectionU = fIntersectionU; fNearestIntersectionV = fIntersectionV; hitInfo.m_fDistance = temp; nNearestStartIndex = i; bResult = true; } } } } if (bResult) { hitInfo.m_Texcoords = lerp(m_pVBO->getTexcoord(m_pIndexes[nNearestStartIndex]), m_pVBO->getTexcoord(m_pIndexes[nNearestStartIndex + 1]), m_pVBO->getTexcoord(m_pIndexes[nNearestStartIndex + 2]), fNearestIntersectionU, fNearestIntersectionV); } return bResult; } //void BBMesh::draw() //{ // if (mMeshType == MeshType::fbx) // { // //动画 // mFbx->update(); // mVertexPositions = mFbx->getVertexPositions(); // for (int i = 0; i < mVertexCount; i++) // { // mVertexBuffer->setPosition(i, mVertexPositions.at(i)); // mVertexBuffer->setColor(i, mColor); // } // } //} //void Mesh::loadFbx(QString path) //{ // mFbx = new FBX(path); // mFbx->load(); // mIndexes = mFbx->getIndexes(); // mIndexCount = mFbx->getIndexCount(); // //计算包围盒的数据 // mVertexPositions = mFbx->getVertexPositions(); // //顶点数据 // QList<QVector2D> texcoords = mFbx->getVertexTexcoords(); // QList<QVector4D> normals = mFbx->getVertexNormals(); // //shader buffer // mVertexCount = mVertexPositions.count(); // mVertexBuffer = new VertexBuffer(); // mVertexBuffer->setSize(mVertexCount); // for (int i = 0; i < mVertexCount; i++) // { // mVertexBuffer->setPosition(i, mVertexPositions.at(i)); // mVertexBuffer->setTexcoord(i, texcoords.at(i)); // mVertexBuffer->setNormal(i, normals.at(i)); // mVertexBuffer->setColor(i, mColor); // } // mFbx->closeLoad(); //} <|start_filename|>Code/BBearEditor/Engine/Geometry/BBBoundingBox.h<|end_filename|> #ifndef BBBOUNDINGBOX_H #define BBBOUNDINGBOX_H #include "Base/BBRenderableObject.h" #include "BBRay.h" #include <QMatrix4x4> struct FloatData { float v[3]; }; class BBBoundingBox : public BBRenderableObject { public: BBBoundingBox(); BBBoundingBox(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); virtual ~BBBoundingBox(); bool hit(const BBRay &ray, float &fDistance) override; QVector3D getCenter(); protected: void setModelMatrix(float px, float py, float pz, const QQuaternion &r, float sx, float sy, float sz) override; float m_Center[3]; int m_nBoxVertexCount; QVector3D *m_pOriginalBoxVertexes; QVector3D *m_pTransformedBoxVertexes; }; // Parallel to the coordinate plane class BBRectBoundingBox3D : public BBBoundingBox { public: BBRectBoundingBox3D(float fCenterX, float fCenterY, float fCenterZ, float fHalfLengthX, float fHalfLengthY, float fHalfLengthZ); virtual ~BBRectBoundingBox3D(); void init() override; bool hit(const BBRay &ray, float &fDistance) override; }; // Not necessarily parallel to the coordinate plane class BBTriangleBoundingBox3D : public BBBoundingBox { public: BBTriangleBoundingBox3D(const QVector3D &point1, const QVector3D &point2, const QVector3D &point3); bool hit(const BBRay &ray, float &fDistance) override; }; // Parallel to the coordinate plane class BBQuarterCircleBoundingBox3D : public BBBoundingBox { public: BBQuarterCircleBoundingBox3D(float fCenterX, float fCenterY, float fCenterZ, float fRadius, const BBPlaneName &ePlaneName); bool hit(const BBRay &ray, float &fDistance) override; inline void setQuadrantFlag(const QVector3D &flag) { m_QuadrantFlag = flag; } private: BBPlaneName m_eSelectedPlaneName; QVector3D m_QuadrantFlag; }; class BBBoundingBox3D : public BBBoundingBox { public: BBBoundingBox3D(const QList<QVector4D> &vertexes = QList<QVector4D>()); BBBoundingBox3D(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz, const QList<QVector4D> &vertexes = QList<QVector4D>()); BBBoundingBox3D(const QVector3D &position, const QVector3D &rotation, const QVector3D &scale, const QVector3D &center, const QVector3D &halfLength); BBBoundingBox3D(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz, float fCenterX, float fCenterY, float fCenterZ, float fHalfLengthX, float fHalfLengthY, float fHalfLengthZ); virtual ~BBBoundingBox3D(); void init() override; bool hit(const BBRay &ray, float &fDistance) override; bool belongToSelectionRegion(const BBFrustum &frustum) override; QVector3D getHalfLength(); protected: virtual void computeBoxVertexes(const QList<QVector4D> &vertexes); float m_Axis[3][3]; float m_HalfLength[3]; }; class BBAABBBoundingBox3D : public BBBoundingBox3D { public: BBAABBBoundingBox3D(const QList<QVector4D> &vertexes = QList<QVector4D>()); BBAABBBoundingBox3D(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz, const QList<QVector4D> &vertexes = QList<QVector4D>()); BBAABBBoundingBox3D(const QVector3D &position, const QVector3D &rotation, const QVector3D &scale, const QVector3D &center, const QVector3D &halfLength); bool computeIntersectWithPlane(const QVector3D &point, const QVector3D &normal); private: void computeBoxVertexes(const QList<QVector4D> &vertexes) override; QVector3D getMax(); QVector3D getMin(); }; #endif // BBBOUNDINGBOX_H <|start_filename|>Code/BBearEditor/Engine/3D/BBNormalIndicator.h<|end_filename|> #ifndef BBNORMALINDICATOR_H #define BBNORMALINDICATOR_H #include "Base/BBRenderableObject.h" class BBNormalIndicator : public BBRenderableObject { public: BBNormalIndicator(); void init(BBRenderableObject *pObject); private: void clear(); }; #endif // BBNORMALINDICATOR_H <|start_filename|>Resources/shaders/GI/SSDO_Blur.frag<|end_filename|> #version 430 core in vec2 v2f_texcoord; layout (location = 0) out vec4 FragColor; uniform sampler2D SSAOTex; uniform sampler2D SSDOTex; uniform sampler2D AlbedoTex; void main(void) { vec2 texel_size = 1.0 / vec2(textureSize(SSDOTex, 0)); vec3 result = vec3(0.0); for (int x = -2; x < 2; x++) { for (int y = -2; y < 2; y++) { vec2 offset = vec2(float(x), float(y)) * texel_size; result += texture(SSDOTex, v2f_texcoord + offset).rgb; } } result = result / (4.0 * 4.0); float ambient = texture(SSAOTex, v2f_texcoord).r; vec3 albedo = texture(AlbedoTex, v2f_texcoord).rgb; vec3 indirect_light = result; FragColor = vec4(albedo * ambient + indirect_light, 1.0); } <|start_filename|>Code/BBearEditor/Engine/Render/Texture/BBProcedureTexture.h<|end_filename|> #ifndef BBPROCEDURETEXTURE_H #define BBPROCEDURETEXTURE_H #include "BBTexture.h" class BBProcedureTexture : public BBTexture { public: BBProcedureTexture(); GLuint create0(int nSize); GLuint create3D0(int nWidth, int nHeight, int nDepth); GLuint createPerlinNoiseTexture2D(int nSize, float fScale = 1.0f); GLuint createCamouflagePerlinNoiseTexture2D(int nSize, float fScale = 1.0f); GLuint createPerlinNoiseTexture3D(int nWidth, int nHeight, int nDepth, float fScale = 1.0f); }; #endif // BBPROCEDURETEXTURE_H <|start_filename|>Resources/shaders/Cartoon/Outline.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBSmoothNormal; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; uniform vec4 BBCameraPosition; uniform float OutlineWidth; void main() { // When it is far away, the outline width will not decrease vec3 world_pos = (BBModelMatrix * BBPosition).xyz; float d = length(BBCameraPosition.xyz - world_pos); vec3 object_pos = BBPosition.xyz; vec3 w = normalize(BBSmoothNormal) * OutlineWidth * 0.0001; w *= d; object_pos += w; gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * vec4(object_pos, 1.0); } <|start_filename|>Code/BBearEditor/Editor/Render/BBEditViewOpenGLWidget.h<|end_filename|> #ifndef BBEDITVIEWOPENGLWIDGET_H #define BBEDITVIEWOPENGLWIDGET_H #include "BBOpenGLWidget.h" #include <QVector3D> #include "Serializer/BBGameObject.pb.h" class QMouseEvent; class BBGameObject; class BBGameObjectSet; class QTreeWidgetItem; class BBCanvas; class BBModel; class BBEditViewOpenGLWidget : public BBOpenGLWidget { Q_OBJECT public: explicit BBEditViewOpenGLWidget(QWidget *pParent = 0); virtual ~BBEditViewOpenGLWidget(); BBGameObject* createModel(const BBSerializer::BBGameObject &gameObject); public: void startRenderThread(); void stopRenderThread(); private: QThread *m_pRenderThread; QTimer *m_pRenderTimer; private slots: void pressESC(); void pressMoveKey(char key); void releaseMoveKey(char key); void pressTransform(char key); void setCoordinateSystemSelectedObject(BBGameObject *pGameObject); void setCoordinateSystemSelectedObjects(const QList<BBGameObject*> &gameObjects, BBGameObjectSet *pSet); void pressMultipleSelectionKey(bool bPressed); void updateCoordinateSystem(); void createModelAtOrigin(const QString &filePath); void createLightAtOrigin(const QString &fileName); void deleteGameObject(BBGameObject *pGameObject); void copyGameObject(BBGameObject *pSourceObject, QTreeWidgetItem *pTranscriptItem); void lookAtGameObject(BBGameObject *pGameObject); void createPreviewModel(); signals: void updateEditViewTitle(); // create QTreeWidgetItem void addGameObject(BBGameObject *pGameObject); // specified QTreeWidgetItem void addGameObject(BBGameObject *pGameObject, QTreeWidgetItem *pItem); void pickObject(BBGameObject *pGameObject); void pickObjects(const QList<BBGameObject*> &gameObjects); void updateMultipleSelectedObjects(BBGameObject *pGameObject); void updateTransformInPropertyManager(BBGameObject *pGameObject, char transformModeKey); private: void mousePressEvent(QMouseEvent *e) override; void mouseMoveEvent(QMouseEvent *e) override; void mouseReleaseEvent(QMouseEvent *e) override; void wheelEvent(QWheelEvent *event) override; void dragEnterEvent(QDragEnterEvent *event) override; void dragMoveEvent(QDragMoveEvent *event) override; void dragLeaveEvent(QDragLeaveEvent *event) override; void dropEvent(QDropEvent *event) override; private: void openThreadToCreatePreviewModel(const QString &userData, int x, int y); QString m_UserDataInThread; int m_nXInThread; int m_nYInThread; private: // Whether the right mouse button is pressed bool m_bRightPressed; QPoint m_OriginalMousePos; BBCanvas *m_pCurrentCanvas; BBGameObject *m_pPreviewObject; QPoint m_SelectionRegionStartingPoint; bool m_bRegionSelecting; bool m_bMultipleSelecting; QString m_DragType; }; #endif // BBEDITVIEWOPENGLWIDGET_H <|start_filename|>Resources/shaders/dissolve.vert<|end_filename|> #version 450 core in vec4 BBPosition; in vec4 BBTexcoord; out vec4 V_Texcoord; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { V_Texcoord = BBTexcoord; gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * BBPosition; } <|start_filename|>Resources/shaders/SkyBox/PrefilterMap.frag<|end_filename|> #version 330 core #extension GL_NV_shadow_samplers_cube : enable in vec3 v2f_local_pos; layout (location = 0) out vec4 FragColor; uniform samplerCube EnvironmentMap; uniform float Roughness; const float PI = 3.14159265359; const uint SAMPLE_COUNT = 1024u; // resolution of source cubemap (per face) const float Resolution = 512.0; float computeDistributionGGX(vec3 N, vec3 H, float roughness) { float a = roughness * roughness; float a2 = a * a; float NdotH = max(dot(N, H), 0.0); float NdotH2 = NdotH * NdotH; float nom = a2; float denom = (NdotH2 * (a2 - 1.0) + 1.0); denom = PI * denom * denom; return nom / denom; } // http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html // efficient VanDerCorpus calculation. float computeRadicalInverse_VdC(uint bits) { bits = (bits << 16u) | (bits >> 16u); bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); return float(bits) * 2.3283064365386963e-10; // / 0x100000000 } vec2 computeHammersley(uint i, uint N) { return vec2(float(i) / float(N), computeRadicalInverse_VdC(i)); } vec3 computeImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) { float a = roughness * roughness; float phi = 2.0 * PI * Xi.x; float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y)); float sinTheta = sqrt(1.0 - cosTheta * cosTheta); // from spherical coordinates to cartesian coordinates - halfway vector // r = 1 vec3 H; H.x = cos(phi) * sinTheta; H.y = sin(phi) * sinTheta; H.z = cosTheta; // from tangent-space H vector to world-space sample vector vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); vec3 tangent = normalize(cross(up, N)); vec3 bitangent = cross(N, tangent); vec3 sample_vec = tangent * H.x + bitangent * H.y + N * H.z; return normalize(sample_vec); } void main(void) { vec3 N = normalize(v2f_local_pos); // make the simplyfying assumption that V equals R equals the normal vec3 R = N; vec3 V = R; vec3 prefiltered_color = vec3(0.0); float total_weight = 0.0; // Monte Carlo for (uint i = 0u; i < SAMPLE_COUNT; i++) { // generates a sample vector that's biased towards the preferred alignment direction (importance sampling). vec2 Xi = computeHammersley(i, SAMPLE_COUNT); vec3 H = computeImportanceSampleGGX(Xi, N, Roughness); vec3 L = normalize(2.0 * dot(V, H) * H - V); float NdotL = max(dot(N, L), 0.0); if (NdotL > 0.0) { // it may still be insufficient at some coarser MIP levels, resulting in dot patterns around bright areas // We do not sample the environment map directly // sample from the environment's mip level based on roughness/pdf float D = computeDistributionGGX(N, H, Roughness); float NdotH = max(dot(N, H), 0.0); float HdotV = max(dot(H, V), 0.0); float pdf = D * NdotH / (4.0 * HdotV) + 0.0001; float saTexel = 4.0 * PI / (6.0 * Resolution * Resolution); float saSample = 1.0 / (float(SAMPLE_COUNT) * pdf + 0.0001); float mip_level = Roughness == 0.0 ? 0.0 : 0.5 * log2(saSample / saTexel); prefiltered_color += textureLod(EnvironmentMap, L, mip_level).rgb * NdotL; total_weight += NdotL; } } prefiltered_color = prefiltered_color / total_weight; FragColor = vec4(prefiltered_color, 1.0); } <|start_filename|>Resources/shaders/Physics/FluidSystem/SSF_FS_2_Screen_Filter.frag<|end_filename|> #version 430 core in vec2 v2f_texcoords; layout (location = 0) out float Depth; layout (location = 1) out float Thickness; uniform vec4 BBCameraParameters; uniform sampler2D DepthMap; uniform sampler2D ThicknessMap; uniform float FilterRadius; uniform float SpatialScale; uniform float RangeScale; uniform vec4 BlurDir; void computeGaussianFilter(vec2 blur_dir, float depth) { float sum_depth = 0.0; float w_sum_depth = 0.0; float sum_thickness = 0.0; float w_sum_thickness = 0.0; for (float x = -FilterRadius; x <= FilterRadius; x += 1.0) { float sample_depth = texture(DepthMap, v2f_texcoords + x * blur_dir.xy).r; float sample_thickness = texture(ThicknessMap, v2f_texcoords + x * blur_dir.xy).r; // Spatial weight float s = x * SpatialScale; s = exp(-s * s); // Range weight float r = (sample_depth - depth) * RangeScale; r = exp(-r * r); // Gaussian filter thickness sum_thickness += sample_thickness * s; w_sum_thickness += s; // Bilateral filter depth, Consider spatial & range, // The value with large depth difference can still save its original depth information after bilateral filtering sum_depth += sample_depth * s * r; w_sum_depth += s * r; } Depth = sum_depth / w_sum_depth; Thickness = sum_thickness / w_sum_thickness; } void main() { vec2 depth_map_size = textureSize(DepthMap, 0); vec2 thickness_map_size = textureSize(ThicknessMap, 0); float depth = texture(DepthMap, v2f_texcoords).r; float viewport_width = BBCameraParameters.x; float viewport_height = BBCameraParameters.y; vec2 blur_dir = BlurDir.xy * vec2(1.0 / viewport_width, 1.0 / viewport_height) * 1.0; computeGaussianFilter(blur_dir, depth); } <|start_filename|>Code/BBearEditor/Engine/Physics/Force/BBForce.h<|end_filename|> #ifndef BBFORCE_H #define BBFORCE_H class BBBaseBody; class BBForce { public: BBForce(); virtual ~BBForce(); virtual void applyForce(BBBaseBody *pBody, float fDeltaTime) = 0; protected: }; #endif // BBFORCE_H <|start_filename|>Resources/shaders/Cartoon/CartoonFire.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBTexcoord; varying vec4 V_Texcoord; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { V_Texcoord = BBTexcoord; gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * BBPosition; } <|start_filename|>Resources/shaders/CubeMap.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBNormal; varying vec4 V_Position; varying vec4 V_world_pos; varying vec4 V_Normal; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { V_Position = BBPosition; V_world_pos = BBModelMatrix * BBPosition; V_Normal.xyz = mat3(transpose(inverse(BBModelMatrix))) * BBNormal.xyz; gl_Position = BBProjectionMatrix * BBViewMatrix * V_world_pos; } <|start_filename|>Code/BBearEditor/Engine/Render/Lighting/GI/BBSSDOGlobalIllumination.h<|end_filename|> #ifndef BBSSDOGLOBALILLUMINATION_H #define BBSSDOGLOBALILLUMINATION_H class BBScene; class BBSSDOGlobalIllumination { public: static void open(BBScene *pScene); static void setSSDOPass(BBScene *pScene); static void setSSDOBlurPass(BBScene *pScene); }; #endif // BBSSDOGLOBALILLUMINATION_H <|start_filename|>Resources/shaders/water.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBTexcoord; attribute vec4 BBNormal; attribute vec4 BBTangent; attribute vec4 BBBiTangent; varying vec4 V_texcoord; varying vec4 V_normal_uv; varying vec4 V_world_space_pos; varying vec4 V_world_space_normal; varying vec4 V_clip_space_pos; varying vec4 V_view_space_pos; varying mat3 V_TBN; varying mat4 V_viewMatrix_I; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; uniform vec4 BBTime; uniform float Speed; uniform vec4 BBTO_Foam; uniform vec4 BBTO_Normal_Map; void main() { V_world_space_pos = BBModelMatrix * BBPosition; V_world_space_normal.xyz = mat3(transpose(inverse(BBModelMatrix))) * BBNormal.xyz; // flow vec2 offset = vec2(0.0005) * Speed * BBTime.z; // Foam uv do not use BBTexcoord, otherwise, the effect will be affected with scale V_texcoord.xy = V_world_space_pos.xz * BBTO_Foam.xy + offset; // distort uv vec2 normal_uv = BBTexcoord * BBTO_Normal_Map.xy; V_normal_uv.xy = normal_uv + offset; V_normal_uv.zw = normal_uv + offset * vec2(-1.07, 1.35); V_view_space_pos = BBViewMatrix * V_world_space_pos; V_clip_space_pos = BBProjectionMatrix * V_view_space_pos; vec3 T = normalize(vec3(BBModelMatrix * BBTangent)); vec3 B = normalize(vec3(BBModelMatrix * BBBiTangent)); vec3 N = normalize(vec3(BBModelMatrix * BBNormal)); V_TBN = mat3(T, B, N); V_viewMatrix_I = inverse(BBViewMatrix); gl_Position = V_clip_space_pos; } <|start_filename|>Code/BBearEditor/Editor/ObjectList/BBObjectListWidget.cpp<|end_filename|> #include "BBObjectListWidget.h" #include "Utils/BBUtils.h" #include "rapidxml/rapidxml.hpp" #include <QMimeData> #include <QDrag> BBObjectListWidget::BBObjectListWidget(QWidget *parent, const int pieceSize) : QListWidget(parent), m_iPieceSize(pieceSize) { setDragEnabled(true); setIconSize(QSize(m_iPieceSize, m_iPieceSize)); setSpacing(2); setAcceptDrops(false); // Show the indicator being dragged setDropIndicatorShown(true); } BBObjectListWidget::~BBObjectListWidget() { } bool BBObjectListWidget::loadListItems(const char *xmlFilePath) { // Load external resources through .xml bool bResult = false; int nFileSize = 0; char *pData = NULL; rapidxml::xml_node<> *pRoot = NULL; rapidxml::xml_node<> *pModel = NULL; rapidxml::xml_attribute<> *pAttrIcon = NULL; rapidxml::xml_attribute<> *pAttrFile = NULL; rapidxml::xml_attribute<> *pAttrName = NULL; do { pData = BBUtils::loadFileContent(xmlFilePath, nFileSize); BB_PROCESS_ERROR(pData); // Parsing xml rapidxml::xml_document<> doc; doc.parse<0>(pData); pRoot = doc.first_node(); BB_PROCESS_ERROR(pRoot); pModel = pRoot->first_node(); for (; pModel != 0; pModel = pModel->next_sibling()) { pAttrIcon = pModel->first_attribute("icon"); BB_PROCESS_ERROR(pAttrIcon); pAttrFile = pModel->first_attribute("file"); BB_PROCESS_ERROR(pAttrFile); pAttrName = pModel->first_attribute("name"); BB_PROCESS_ERROR(pAttrName); QPixmap pic; pic.load(pAttrIcon->value()); QListWidgetItem *pItem = new QListWidgetItem(this); pItem->setSizeHint(QSize(m_iPieceSize, m_iPieceSize)); pItem->setIcon(QIcon(pic)); pItem->setData(Qt::UserRole, QVariant(pic)); pItem->setData(Qt::UserRole + 1, pAttrFile->value()); pItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled); pItem->setText(pAttrName->value()); } bResult = true; } while(0); if (pData) BB_SAFE_DELETE_ARRAY(pData); // if (pRoot) // BB_SAFE_DELETE(pRoot); // if (pModel) // BB_SAFE_DELETE(pModel); // if (pAttrIcon) // BB_SAFE_DELETE(pAttrIcon); // if (pAttrFile) // BB_SAFE_DELETE(pAttrFile); // if (pAttrName) // BB_SAFE_DELETE(pAttrName); return bResult; } void BBObjectListWidget::startDrag(Qt::DropActions supportedActions) { Q_UNUSED(supportedActions); QListWidgetItem *pItem = currentItem(); QByteArray itemData; QDataStream dataStream(&itemData, QIODevice::WriteOnly); QString fileName = qvariant_cast<QString>(pItem->data(Qt::UserRole + 1)); dataStream << fileName; QMimeData *pMimeData = new QMimeData; // Give this data a unique identifying tag pMimeData->setData(m_strMimeType, itemData); QPixmap pixmap = qvariant_cast<QPixmap>(pItem->data(Qt::UserRole)); pixmap.setDevicePixelRatio(devicePixelRatio()); pixmap = pixmap.scaled(QSize(m_iPieceSize * devicePixelRatio(), m_iPieceSize * devicePixelRatio()), Qt::KeepAspectRatio, Qt::SmoothTransformation); QDrag drag(this); drag.setMimeData(pMimeData); drag.setHotSpot(QPoint(pixmap.width() / 2 / devicePixelRatio(), pixmap.height() / 2 / devicePixelRatio())); drag.setPixmap(pixmap); drag.exec(Qt::MoveAction); } void BBObjectListWidget::focusInEvent(QFocusEvent *e) { Q_UNUSED(e); emit removeCurrentItemInFileList(); } <|start_filename|>Resources/shaders/DeferredNormal.frag<|end_filename|> varying vec4 V_Normal; void main(void) { // vec3 normal_encoded = normalize(V_Normal.xyz); // normal_encoded = 0.5 * (normal_encoded + vec3(1.0)); // gl_FragColor = vec4(normal_encoded, 1.0); gl_FragColor = vec4(normalize(V_Normal.xyz), 0.0); } <|start_filename|>Code/BBearEditor/Engine/2D/BBSprite2D.cpp<|end_filename|> #include "BBSprite2D.h" #include "Geometry/BBBoundingBox.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/Texture/BBTexture.h" #include "Render/BBMaterial.h" #include "Render/BBRenderPass.h" #include "Render/BBDrawCall.h" #include "Render/BBCamera.h" BBSprite2D::BBSprite2D(int x, int y, int nWidth, int nHeight) : BBRenderableObject2D(x, y, nWidth, nHeight) { } BBSprite2D::~BBSprite2D() { } void BBSprite2D::init() { m_pVBO = new BBVertexBufferObject(4); m_pVBO->setPosition(0, 1.0f, 1.0f, 0); m_pVBO->setPosition(1, -1.0f, 1.0f, 0); m_pVBO->setPosition(2, -1.0f, -1.0f, 0); m_pVBO->setPosition(3, 1.0f, -1.0f, 0); m_pVBO->setTexcoord(0, 1.0f, 1.0f); m_pVBO->setTexcoord(1, 0.0f, 1.0f); m_pVBO->setTexcoord(2, 0.0f, 0.0f); m_pVBO->setTexcoord(3, 1.0f, 0.0f); for (int i = 0; i < m_pVBO->getVertexCount(); i++) { m_pVBO->setColor(i, 1.0f, 1.0f, 1.0f); } BBRenderableObject2D::init(); m_pCurrentMaterial->getBaseRenderPass()->setUseStencil(true); m_pCurrentMaterial->setVector4(LOCATION_TEXTURE_SETTING0, 1.0f, 0.0f, 0.0f, 0.0f); BBTexture texture; QString texturePath = BB_PATH_RESOURCE_ICON(empty2.png); m_pCurrentMaterial->setSampler2D(LOCATION_TEXTURE(0), texture.createTexture2D(texturePath), texturePath); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, GL_QUADS, 0, 4); appendDrawCall(pDrawCall); } <|start_filename|>Resources/shaders/Shadow/VSM_ShadowMap.vert<|end_filename|> #version 430 core in vec4 BBPosition; uniform mat4 BBLightProjectionMatrix; uniform mat4 BBLightViewMatrix; uniform mat4 BBModelMatrix; void main() { gl_Position = BBLightProjectionMatrix * BBLightViewMatrix * BBModelMatrix * BBPosition; } <|start_filename|>Resources/shaders/test.frag<|end_filename|> varying vec4 V_Texcoord; uniform sampler2D BBShadowMap; void main(void) { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); } <|start_filename|>Resources/shaders/Cartoon/Cartoon.frag<|end_filename|> #version 330 core in vec3 v2f_world_pos; in vec2 v2f_texcoords; in vec3 v2f_normal; out vec4 FragColor; uniform vec4 BBCameraPosition; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; uniform sampler2D Albedo; // specular uniform float SpecularStrength; uniform float SpecularFade; uniform float SpecularSmoothing; // fresnel uniform float FresnelStrength; uniform float FresnelFade; uniform float FresnelSmoothing; uniform vec4 BBColor_FresnelColor; const int Step = 3; void main(void) { vec3 final_color = vec3(0.0); vec3 N = normalize(v2f_normal); vec3 L = normalize(BBLightPosition.xyz); vec3 V = normalize(BBCameraPosition.xyz - v2f_world_pos); vec3 H = normalize(L + V); float NdotL = max(0.0, dot(N, L)); float NdotH = max(0.0, dot(N, H)); float NdotV = max(0.0, dot(N, V)); // Dichotomous coloring and multiple level coloring float level = ceil(NdotL * Step) / Step; final_color += vec3(level); // specular float specular = SpecularStrength * 5 * pow(NdotH, SpecularFade * 80); specular = smoothstep(0.5, 0.5 + SpecularSmoothing, specular); final_color += BBLightColor.rgb * specular; // fresnel float fresnel = 1 - NdotV; fresnel = FresnelStrength * 5 * pow(fresnel, FresnelFade); fresnel = smoothstep(0.5, 0.5 + FresnelSmoothing, fresnel); final_color += BBColor_FresnelColor.rgb * fresnel; vec4 base_color = texture(Albedo, v2f_texcoords); final_color += base_color.rgb; FragColor = vec4(final_color, 1.0); } <|start_filename|>Resources/shaders/diffuse_indicator.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBColor; attribute vec4 BBTexcoord; attribute vec4 BBNormal; varying vec4 V_Color; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; vec4 getLightColor() { vec3 light_pos_normalized = normalize(BBLightPosition.xyz); vec3 normal_normalized = normalize(BBNormal.xyz); return dot(light_pos_normalized, normal_normalized) * BBLightColor; } void main() { V_Color = BBColor * 0.5 * (getLightColor() + vec4(1.0)) + vec4(0.1); gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * BBPosition; } <|start_filename|>Code/BBearEditor/Engine/Render/BufferObject/BBFrameBufferObject.cpp<|end_filename|> #include "BBFrameBufferObject.h" #include <QPixmap> BBFrameBufferObject::BBFrameBufferObject() { glGenFramebuffers(1, &m_FrameBufferObject); } void BBFrameBufferObject::attachColorBuffer(const QString &bufferName, GLenum attachment, int nWidth, int nHeight, GLenum format) { m_nWidth = nWidth; m_nHeight = nHeight; glBindFramebuffer(GL_FRAMEBUFFER, m_FrameBufferObject); GLuint colorBuffer; glGenTextures(1, &colorBuffer); glBindTexture(GL_TEXTURE_2D, colorBuffer); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // open up space for texture objects on the GPU // The last parameter is NULL, only open up space in the GPU, and will not transfer data from the CPU. // The specific data is written by the GPU during rendering. glTexImage2D(GL_TEXTURE_2D, 0, format, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindTexture(GL_TEXTURE_2D, 0); // give the color buffer to the attachment node glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, colorBuffer, 0); m_Buffers.insert(bufferName, colorBuffer); m_DrawBuffers.append(attachment); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void BBFrameBufferObject::attachDepthBuffer(const QString &bufferName, int nWidth, int nHeight) { glBindFramebuffer(GL_FRAMEBUFFER, m_FrameBufferObject); GLuint depthBuffer; glGenTextures(1, &depthBuffer); glBindTexture(GL_TEXTURE_2D, depthBuffer); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, nWidth, nHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthBuffer, 0); m_Buffers.insert(bufferName, depthBuffer); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void BBFrameBufferObject::finish() { // number of draw targets int count = m_DrawBuffers.count(); if (count > 0) { GLenum *pBuffers = new GLenum[count]; for (int i = 0; i < count; i++) { pBuffers[i] = m_DrawBuffers.at(i); } glBindFramebuffer(GL_FRAMEBUFFER, m_FrameBufferObject); glDrawBuffers(count, pBuffers); glBindFramebuffer(GL_FRAMEBUFFER, 0); } } void BBFrameBufferObject::bind() { // save the previous render target glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_PreFrameBufferObject); glBindFramebuffer(GL_FRAMEBUFFER, m_FrameBufferObject); // all the things rendered afterwards will be drawn to this FBO glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // don't forget to configure the viewport to the capture dimensions glViewport(0, 0, m_nWidth, m_nHeight); } void BBFrameBufferObject::bind(int nWidth, int nHeight) { // save the previous render target glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_PreFrameBufferObject); glBindFramebuffer(GL_FRAMEBUFFER, m_FrameBufferObject); // all the things rendered afterwards will be drawn to this FBO glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_nWidth = nWidth; m_nHeight = nHeight; glRenderbufferStorage(GL_RENDERBUFFER, GL_COLOR_ATTACHMENT0, m_nWidth, m_nHeight); // don't forget to configure the viewport to the capture dimensions glViewport(0, 0, m_nWidth, m_nHeight); } void BBFrameBufferObject::unbind() { glBindFramebuffer(GL_FRAMEBUFFER, m_PreFrameBufferObject); } GLuint BBFrameBufferObject::getBuffer(const QString &bufferName) { QMap<QString, GLuint>::Iterator it = m_Buffers.find(bufferName); if (it != m_Buffers.end()) { return it.value(); } else { return 0; } } <|start_filename|>Code/BBearEditor/Engine/Render/Lighting/GameObject/BBPointLight.cpp<|end_filename|> #include "BBPointLight.h" #include "3D/BBLightIndicator.h" #include "Render/BBCamera.h" #include "Geometry/BBBoundingBox.h" BBPointLight::BBPointLight(BBScene *pScene) : BBPointLight(pScene, QVector3D(0, 0, 0)) { } BBPointLight::BBPointLight(BBScene *pScene, const QVector3D &position) : BBPointLight(pScene, position, QVector3D(0, 0, 0)) { } BBPointLight::BBPointLight(BBScene *pScene, const QVector3D &position, const QVector3D &rotation) : BBLight(pScene, position, rotation, QVector3D(1, 1, 1)) { m_eType = Point; m_pIndicator = new BBPointLightIndicator(position); m_pAABBBoundingBox3D = new BBAABBBoundingBox3D(m_Position, m_Rotation, m_Scale, m_Position, QVector3D(1.0f, 1.0f, 1.0f)); // m_Setting1[0] : radius setRadius(10.0f); // m_Setting1[1] : constant factor setConstantFactor(2.0f); // m_Setting1[2] : linear factor setLinearFactor(0.5f); // m_Setting1[3] : quadric factor setQuadricFactor(0.2f); // m_Setting0[1] : Intensity setIntensity(2.0f); } BBPointLight::~BBPointLight() { BB_SAFE_DELETE(m_pAABBBoundingBox3D); } void BBPointLight::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { BBLight::setPosition(position, bUpdateLocalTransform); m_pAABBBoundingBox3D->setPosition(position, bUpdateLocalTransform); } void BBPointLight::setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform) { Q_UNUSED(nAngle); Q_UNUSED(axis); Q_UNUSED(bUpdateLocalTransform); } void BBPointLight::setRotation(const QVector3D &rotation, bool bUpdateLocalTransform) { Q_UNUSED(rotation); Q_UNUSED(bUpdateLocalTransform); } void BBPointLight::setRadius(float fRadius) { m_Setting1[0] = fRadius; m_pIndicator->setScale(fRadius); m_pAABBBoundingBox3D->setScale(fRadius); } bool BBPointLight::cull(BBCamera *pCamera, const QRectF &displayBox) { QVector3D pointLightPosOnViewSpace = pCamera->getViewMatrix() * m_Position; QVector3D pointOnSpherePosOnViewSpace = pointLightPosOnViewSpace + QVector3D(getRadius(), 0.0f, 0.0f); QVector3D pointLightPosOnOpenGLScreenSpace = pCamera->projectPointToScreenSpace(pointLightPosOnViewSpace); QVector3D pointOnSpherePosOnOpenGLScreenSpace = pCamera->projectPointToScreenSpace(pointOnSpherePosOnViewSpace); // calculate AABB of the light on the screen space float r = pointOnSpherePosOnOpenGLScreenSpace.x() - pointLightPosOnOpenGLScreenSpace.x(); QRectF lightBox = QRectF(pointLightPosOnOpenGLScreenSpace.x() - r, pointLightPosOnOpenGLScreenSpace.y() - r, 2.0f * r, 2.0f * r); if (lightBox.intersects(displayBox)) { return false; } else { return true; } } bool BBPointLight::cull(BBCamera *pCamera, int nFrustumIndexX, int nFrustumIndexY) { // at first, detect center if (pCamera->isFrustumContainPoint(nFrustumIndexX, nFrustumIndexY, 0, m_Position)) { return false; } else { // detect bounding box and frustum return !pCamera->isFrustumIntersectWithAABB(nFrustumIndexX, nFrustumIndexY, 0, m_pAABBBoundingBox3D); } } <|start_filename|>Code/BBearEditor/Engine/Render/RayTracing/BBRayTracker.cpp<|end_filename|> #include "BBRayTracker.h" #include "Utils/BBUtils.h" #include "Scene/BBScene.h" #include "Scene/BBSceneManager.h" #include "BBScreenSpaceRayTracker.h" #include "Base/BBGameObject.h" void BBRayTracker::enable(int nAlgorithmIndex, bool bEnable) { BBScene *pScene = BBSceneManager::getScene(); if (bEnable) { switch (nAlgorithmIndex) { case 0: BBScreenSpaceRayTracker::open(pScene); break; default: break; } } else { pScene->setRenderingFunc(&BBScene::defaultRendering); // objects go back original materials QList<BBGameObject*> objects = pScene->getModels(); for (QList<BBGameObject*>::Iterator itr = objects.begin(); itr != objects.end(); itr++) { BBGameObject *pObject = *itr; pObject->restoreMaterial(); } } } //void BBRayTracker::open() //{ // // Stop refresh per frame // BBSceneManager::getEditViewOpenGLWidget()->stopRenderThread(); // m_pScene->setRenderingFunc(&BBScene::rayTracingRendering); // // open thread // m_pRenderThread = new QThread(this); // QObject::connect(m_pRenderThread, SIGNAL(started()), this, SLOT(render())); // m_pRenderThread->start(); //} //void BBRayTracker::close() //{ // BBSceneManager::getEditViewOpenGLWidget()->startRenderThread(); // m_pScene->setRenderingFunc(&BBScene::defaultRendering); // m_pRenderThread->quit(); // m_pRenderThread->wait(); // BB_SAFE_DELETE(m_pRenderThread); //} //QColor BBRayTracker::getPixelColor(int x, int y) //{ // QColor color; // BBRay inputRay = m_pScene->getCamera()->createRayFromScreen(x, y); // m_pScene->pickObjectInModels(inputRay, false); // return color; //} <|start_filename|>Code/BBearEditor/Engine/Render/Lighting/GameObject/BBAreaLight.cpp<|end_filename|> #include "BBAreaLight.h" #include "Math/BBMath.h" #include "Geometry/BBBoundingBox.h" #include "OfflineRenderer/BBScatterMaterial.h" #include "Render/BufferObject/BBVertexBufferObject.h" BBAreaLight::BBAreaLight(float fMin0, float fMax0, float fMin1, float fMax1, float fFixedValue, const QVector3D &color) : BBModel((fMax0 + fMin0) / 2, fFixedValue, (fMax1 + fMin1) / 2, 0, 0, 0, (fMax0 - fMin0) * 0.1f, 1, (fMax1 - fMin1) * 0.1f, AREALIGHT) { // At present, only xoz plane area light sources are considered, Face down m_fMin0 = fMin0; m_fMax0 = fMax0; m_fMin1 = fMin1; m_fMax1 = fMax1; m_fFixedValue = fFixedValue; m_Normal = QVector3D(0, -1, 0); m_Color = color; } BBAreaLight::~BBAreaLight() { } void BBAreaLight::init() { BBModel::init(BB_PATH_RESOURCE_MESH(plane.obj)); setScatterMaterial(new BBAreaLightMaterial(QVector3D(1, 1, 1))); } void BBAreaLight::generatePhoton(QVector3D &origin, QVector3D &direction, float &fPowerScale, const QVector3D &normal) { // At present, only xoz plane area light sources are considered // Emit photons randomly from a point on the area light source origin = QVector3D(m_fMin0 + frandom() * (m_fMax0 - m_fMin0), m_fFixedValue, m_fMin1 + frandom() * (m_fMax1 - m_fMin1)); // Randomly generated vector on hemispherical surface direction = hemisphericalRandom(normal); // The intensity of light is related to the angle fPowerScale = QVector3D::dotProduct(direction, normal); } void BBAreaLight::generatePhoton(QVector3D &origin, QVector3D &direction, float &fPowerScale, const BBHitInfo &hitInfo) { generatePhoton(origin, direction, fPowerScale, hitInfo.m_Normal); } <|start_filename|>Code/BBearEditor/Engine/Font/BBDynamicFont.h<|end_filename|> #ifndef BBDYNAMICFONT_H #define BBDYNAMICFONT_H class BBDynamicFont { public: BBDynamicFont(); }; #endif // BBDYNAMICFONT_H <|start_filename|>Code/BBearEditor/Engine/Render/BBMaterialProperty.h<|end_filename|> #ifndef BBMATERIALPROPERTY_H #define BBMATERIALPROPERTY_H #include "BBBaseRenderComponent.h" enum BBMaterialUniformPropertyType { CameraProjectionMatrix, CameraInverseProjectionMatrix, CameraViewMatrix, CameraInverseViewMatrix, LightProjectionMatrix, LightViewMatrix, Float, FloatArray, Matrix4, Vector4, Vector4Array, Sampler2D, Sampler3D, SamplerCube, Count }; enum BBVector4MaterialPropertyFactoryType { Default, Color, TilingAndOffset }; class BBMaterialProperty { public: BBMaterialProperty(const BBMaterialUniformPropertyType &eType, const char *name); virtual ~BBMaterialProperty(); virtual BBMaterialProperty* clone() = 0; BBMaterialUniformPropertyType getType() { return m_eType; } inline char* getName() { return m_Name; } inline QString getNameInPropertyManager() { return m_NameInPropertyManager; } protected: BBMaterialUniformPropertyType m_eType; char m_Name[64]; QString m_NameInPropertyManager; }; class BBFloatMaterialProperty : public BBMaterialProperty { public: BBFloatMaterialProperty(const char *name); ~BBFloatMaterialProperty(); BBMaterialProperty* clone() override; inline void setPropertyValue(const float fPropertyValue) { m_fPropertyValue = fPropertyValue; } inline const float getPropertyValue() { return m_fPropertyValue; } private: float m_fPropertyValue; }; class BBFloatArrayMaterialProperty : public BBMaterialProperty { public: BBFloatArrayMaterialProperty(const char *name, int nArrayCount); ~BBFloatArrayMaterialProperty(); BBMaterialProperty* clone() override; inline void setPropertyValue(const float *pPropertyValue) { m_pPropertyValue = pPropertyValue; } inline const float* getPropertyValue() { return m_pPropertyValue; } inline int getArrayCount() { return m_nArrayCount; } private: const float *m_pPropertyValue; int m_nArrayCount; }; class BBMatrix4MaterialProperty : public BBMaterialProperty { public: BBMatrix4MaterialProperty(const char *name); ~BBMatrix4MaterialProperty(); BBMaterialProperty* clone() override; inline void setPropertyValue(const float *pPropertyValue) { m_pPropertyValue = pPropertyValue; } inline const float* getPropertyValue() { return m_pPropertyValue; } private: // 智能指针 to do const float *m_pPropertyValue; }; class BBVector4MaterialProperty : public BBMaterialProperty { public: BBVector4MaterialProperty(const char *name); ~BBVector4MaterialProperty(); BBMaterialProperty* clone() override; inline void setPropertyValue(const float *pPropertyValue) { m_pPropertyValue = pPropertyValue; } inline const float* getPropertyValue() { return m_pPropertyValue; } BBVector4MaterialPropertyFactoryType getFactoryType() { return m_eFactoryType; } private: // 智能指针 to do const float *m_pPropertyValue; BBVector4MaterialPropertyFactoryType m_eFactoryType; }; class BBVector4ArrayMaterialProperty : public BBMaterialProperty { public: BBVector4ArrayMaterialProperty(const char *name, int nArrayCount); ~BBVector4ArrayMaterialProperty(); BBMaterialProperty* clone() override; inline void setPropertyValue(const float *pPropertyValue) { m_pPropertyValue = pPropertyValue; } inline const float* getPropertyValue() { return m_pPropertyValue; } inline int getArrayCount() { return m_nArrayCount; } private: const float *m_pPropertyValue; int m_nArrayCount; }; class BBSampler2DMaterialProperty : public BBMaterialProperty { public: BBSampler2DMaterialProperty(const char *name, int nSlotIndex); ~BBSampler2DMaterialProperty(); BBMaterialProperty* clone() override; void setTextureName(GLuint textureName, const QString &resourcePath = ""); inline GLuint getTextureName() const { return m_TextureName; } inline int getSlotIndex() { return m_nSlotIndex; } inline QString getResourcePath() { return m_ResourcePath; } private: // 智能指针 to do GLuint m_TextureName; int m_nSlotIndex; QString m_ResourcePath; }; class BBSampler3DMaterialProperty : public BBMaterialProperty { public: BBSampler3DMaterialProperty(const char *name, int nSlotIndex); ~BBSampler3DMaterialProperty(); BBMaterialProperty* clone() override; void setTextureName(GLuint textureName, const QString &resourcePath = ""); inline GLuint getTextureName() const { return m_TextureName; } inline int getSlotIndex() { return m_nSlotIndex; } inline QString getResourcePath() { return m_ResourcePath; } private: GLuint m_TextureName; int m_nSlotIndex; QString m_ResourcePath; }; class BBSamplerCubeMaterialProperty : public BBMaterialProperty { public: BBSamplerCubeMaterialProperty(const char *name, int nSlotIndex); ~BBSamplerCubeMaterialProperty(); BBMaterialProperty* clone() override; void setTextureName(GLuint textureName); void setTextureName(GLuint textureName, const QString resourcePath[6]); inline GLuint getTextureName() const { return m_TextureName; } inline int getSlotIndex() { return m_nSlotIndex; } QString getResourcePath(int nIndex) { return m_ResourcePath[nIndex]; } QString* getResourcePaths() { return m_ResourcePath; } private: GLuint m_TextureName; int m_nSlotIndex; QString m_ResourcePath[6]; }; #endif // BBMATERIALPROPERTY_H <|start_filename|>External/ProtoBuffer/lib/CMakeFiles/libprotobuf-lite.dir/cmake_clean.cmake<|end_filename|> file(REMOVE_RECURSE "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj.d" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj.d" "libprotobuf-lite.a" "libprotobuf-lite.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/libprotobuf-lite.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <|start_filename|>Code/BBearEditor/Engine/Physics/FluidSystem/BBSPHParticleSystem.cpp<|end_filename|> #include "BBSPHParticleSystem.h" #include "Utils/BBUtils.h" BBSPHParticleSystem::BBSPHParticleSystem() { m_pParticleBuffer = nullptr; m_nParticleCount = 0; m_nBufferCapacity = 0; } BBSPHParticleSystem::~BBSPHParticleSystem() { BB_SAFE_DELETE_ARRAY(m_pParticleBuffer); } void BBSPHParticleSystem::reset(unsigned int nCapacity) { m_nBufferCapacity = nCapacity; if (m_pParticleBuffer) { BB_SAFE_DELETE(m_pParticleBuffer); } if (m_nBufferCapacity > 0) { m_pParticleBuffer = new BBSPHParticle[m_nBufferCapacity]; } m_nParticleCount = 0; } BBSPHParticle* BBSPHParticleSystem::addParticle(float x, float y, float z) { if (m_nParticleCount >= m_nBufferCapacity) { // Extend space if (m_nBufferCapacity * 2 > MAX_PARTICLE) { // When the upper limit is exceeded, the last value is returned return m_pParticleBuffer + m_nParticleCount - 1; } m_nBufferCapacity *= 2; BBSPHParticle *pNewData = new BBSPHParticle[m_nBufferCapacity]; memcpy(pNewData, m_pParticleBuffer, m_nParticleCount * sizeof(BBSPHParticle)); BB_SAFE_DELETE_ARRAY(m_pParticleBuffer); m_pParticleBuffer = pNewData; } // insert new particle BBSPHParticle *pParticle = m_pParticleBuffer + m_nParticleCount; m_nParticleCount++; pParticle->m_Position = QVector3D(x, y, z); // The next of the last particle points to the header pParticle->m_nNextIndex = -1; return pParticle; } BBSPHParticle* BBSPHParticleSystem::getParticle(unsigned int nIndex) { return m_pParticleBuffer + nIndex; } <|start_filename|>Code/BBearEditor/Engine/Render/OfflineRenderer/BBScatterMaterial.h<|end_filename|> #ifndef BBSCATTERMATERIAL_H #define BBSCATTERMATERIAL_H #include "Geometry/BBRay.h" struct BBScatterInfo { BBScatterInfo() { m_bSpecular = false; } bool m_bSpecular; BBRay m_ScatteredRay; QVector3D m_Attenuation; }; // Ray changes that occur on the surface of a material in ray tracing class BBScatterMaterial { public: BBScatterMaterial(); virtual ~BBScatterMaterial(); virtual bool scatter(const BBRay &ray, const BBHitInfo &hitInfo, BBScatterInfo &scatterInfo) = 0; virtual QVector3D emitted(const QVector3D &position, const QVector2D &texcoords) = 0; }; class BBAreaLightMaterial : public BBScatterMaterial { public: BBAreaLightMaterial(const QVector3D &color); ~BBAreaLightMaterial(); bool scatter(const BBRay &ray, const BBHitInfo &hitInfo, BBScatterInfo &scatterInfo) override; QVector3D emitted(const QVector3D &position, const QVector2D &texcoords) override; private: QVector3D m_Color; }; // diffuse class BBLambertian : public BBScatterMaterial { public: BBLambertian(const QVector3D &albedo); ~BBLambertian(); bool scatter(const BBRay &ray, const BBHitInfo &hitInfo, BBScatterInfo &scatterInfo) override; QVector3D emitted(const QVector3D &position, const QVector2D &texcoords) override; private: QVector3D m_Albedo; }; // specular class BBMetal : public BBScatterMaterial { public: BBMetal(const QVector3D &albedo, float fFuzz = 0.0f); ~BBMetal(); bool scatter(const BBRay &ray, const BBHitInfo &hitInfo, BBScatterInfo &scatterInfo) override; QVector3D emitted(const QVector3D &position, const QVector2D &texcoords) override; private: QVector3D m_Albedo; float m_fFuzz; }; // Transparent refraction model class BBDielectric : public BBScatterMaterial { public: BBDielectric(float fRefractivity); ~BBDielectric(); bool scatter(const BBRay &ray, const BBHitInfo &hitInfo, BBScatterInfo &scatterInfo) override; QVector3D emitted(const QVector3D &position, const QVector2D &texcoords) override; private: float m_fRefractivity; }; #endif // BBSCATTERMATERIAL_H <|start_filename|>Code/BBearEditor/Engine/Render/BBRenderState.h<|end_filename|> #ifndef BBRENDERSTATE_H #define BBRENDERSTATE_H #include "BBBaseRenderComponent.h" struct BBRenderState { BBRenderState(); void operator =(const BBRenderState &rs); GLenum m_PrimitiveType; bool m_bBlend; bool m_bZTest; bool m_bAlphaTest; bool m_bWriteR; bool m_bWriteG; bool m_bWriteB; bool m_bWriteA; bool m_bWriteZ; bool m_bWriteStencil; bool m_bUseStencil; bool m_bCull; // Draw points as point sprites bool m_bEnablePointSprite; // Use the program to set the size of the point sprite bool m_bEnableProgramPointSize; int m_CullFace; unsigned int m_AlphaTestFunc; float m_fAlphaTestValue; float m_fOffsetFactor; float m_fOffsetUnit; unsigned int m_SRCBlendFunc; unsigned int m_DSTBlendFunc; unsigned int m_ZTestFunc; int m_ClearStencilValue; unsigned int m_DrawFace; unsigned int m_PolygonMode; float m_fLineWidth; bool m_bCubeMapSeamless; }; class BBGlobalRenderState { public: static void init(); static void updateBlendState(bool bEnable); static void updateBlendFunc(unsigned int src, unsigned int dst); static void updateZTestState(bool bEnable); static void updateAlphaTestState(bool bEnable); static void updateColorMask(bool r, bool g, bool b, bool a); static void updateStencilMask(bool bEnable); static void updateZMask(bool bEnable); static void updateZFunc(unsigned int func); static void updatePolygonMode(unsigned int face, unsigned int mode); static void updateAlphaFunc(unsigned int func, float value); static void updateLineWidth(float fWidth); static void updateCullState(bool bEnable); static void updateCullFace(int face); static void updatePointSpriteState(bool bEnable); static void updateProgramPointSizeState(bool bEnable); static void clearStencil(int value); private: static BBRenderState m_RenderState; }; #endif // BBRENDERSTATE_H <|start_filename|>Resources/shaders/UI.frag<|end_filename|> varying vec4 V_Color; varying vec4 V_Texcoord; varying vec4 V_Light; varying vec4 V_Dark; uniform vec4 BBTextureSettings; uniform sampler2D BBTexture0; void main(void) { vec4 final_color = V_Color; if (BBTextureSettings.x == 1.0) { final_color *= texture2D(BBTexture0, V_Texcoord.xy); float alpha = final_color.a * V_Light.a; final_color.a = alpha; final_color.rgb = ((vec3(alpha - 1.0) * V_Dark.a + 1.0) - final_color.rgb) * V_Dark.rgb + final_color.rgb * V_Light.rgb; } gl_FragColor = final_color; } <|start_filename|>Code/BBearEditor/Engine/Render/BufferObject/BBShaderStorageBufferObject.cpp<|end_filename|> #include "BBShaderStorageBufferObject.h" BBShaderStorageBufferObject::BBShaderStorageBufferObject() : BBVertexBufferObject(), BBLinkedList() { m_Location = 0; m_BufferType = GL_SHADER_STORAGE_BUFFER; } BBShaderStorageBufferObject::BBShaderStorageBufferObject(BBVertexBufferObject *pVBO) : BBShaderStorageBufferObject(pVBO->getVertexCount()) { // copy the content of VBO for (int i = 0; i < m_nVertexCount; i++) { setPosition(i, pVBO->getPosition(i)); setColor(i, pVBO->getColor(i)); setTexcoord(i, pVBO->getTexcoord(i)); setNormal(i, pVBO->getNormal(i)); setTangent(i, pVBO->getTangent(i)); setBiTangent(i, pVBO->getBiTangent(i)); } } BBShaderStorageBufferObject::BBShaderStorageBufferObject(int nVertexCount) : BBVertexBufferObject() { m_Location = 0; m_BufferType = GL_SHADER_STORAGE_BUFFER; setSize(nVertexCount); } BBShaderStorageBufferObject::~BBShaderStorageBufferObject() { } void BBShaderStorageBufferObject::bind() { // Parameter 2 corresponds to the binding tag in the shader glBindBufferBase(m_BufferType, m_Location, m_Name); if (m_pNext != nullptr) { next<BBShaderStorageBufferObject>()->bind(); } } void BBShaderStorageBufferObject::bind(int location) { glBindBufferBase(m_BufferType, location, m_Name); } void BBShaderStorageBufferObject::unbind() { glBindBufferBase(m_BufferType, 0, 0); } <|start_filename|>Code/BBearEditor/Engine/Physics/FluidSystem/BBSPHFluidSystem.cpp<|end_filename|> #include "BBSPHFluidSystem.h" #include "BBSPHParticleSystem.h" #include "BBSPHGridContainer.h" #include "BBSPHParticleNeighborTable.h" #include "Utils/BBUtils.h" #include "BBSPHFluidRenderer.h" #include "Geometry/BBMarchingCubeMesh.h" #include "Math/BBMatrix.h" #include "Math/BBMath.h" BBSPHFluidSystem::BBSPHFluidSystem(const QVector3D &position) : BBGameObject(position, QVector3D(0, 0, 0), QVector3D(1, 1, 1)) { m_pParticleSystem = new BBSPHParticleSystem(); m_pGridContainer = new BBSPHGridContainer(); m_pParticleNeighborTable = new BBSPHParticleNeighborTable(); m_fParticleRadius = 0.0f; m_fParticleMass = 0.0003f; m_fUnitScale = 0.02f; m_fViscosity = 0.2f; m_fStaticDensity = 1000.0f; m_fSmoothRadius = 0.01f; m_fGasConstantK = 1.0f; m_fBoundingStiffness = 10000.0f; m_fBoundingDamping = 256; m_fSpeedLimiting = 200; m_fKernelPoly6 = 315.0f / (64.0f * 3.141592f * pow(m_fSmoothRadius, 9)); m_fKernelSpiky = -45.0f / (3.141592f * pow(m_fSmoothRadius, 6)); m_fKernelViscosity = 45.0f / (3.141592f * pow(m_fSmoothRadius, 6)); m_fDeltaTime = BB_CONSTANT_UPDATE_RATE / 10000.0f; m_pFluidRenderer = new BBSPHFluidRenderer(position); m_pMCMesh = nullptr; m_pDensityField = nullptr; m_fDensityThreshold = 0.5f; m_bAnisotropic = false; m_fPCISPHDensityErrorFactor = 0.0f; m_bPredictCorrection = true; } BBSPHFluidSystem::~BBSPHFluidSystem() { BB_SAFE_DELETE(m_pParticleSystem); BB_SAFE_DELETE(m_pGridContainer); BB_SAFE_DELETE(m_pParticleNeighborTable); BB_SAFE_DELETE(m_pFluidRenderer); BB_SAFE_DELETE(m_pMCMesh); BB_SAFE_DELETE_ARRAY(m_pDensityField); } void BBSPHFluidSystem::init(unsigned int nMaxParticleCount, const QVector3D &wallBoxMin, const QVector3D &wallBoxMax, const QVector3D &originalFluidBoxMin, const QVector3D &originalFluidBoxMax, const QVector3D &gravity) { m_pParticleSystem->reset(nMaxParticleCount); m_WallBoxMin = wallBoxMin; m_WallBoxMax = wallBoxMax; m_OriginalFluidBoxMin = originalFluidBoxMin; m_OriginalFluidBoxMax = originalFluidBoxMax; m_Gravity = gravity; m_fParticleRadius = pow(m_fParticleMass / m_fStaticDensity, 1.0f / 3.0f); initFluidVolume(originalFluidBoxMin, originalFluidBoxMax, m_fParticleRadius / m_fUnitScale); m_pGridContainer->init(wallBoxMin, wallBoxMax, m_fUnitScale, m_fSmoothRadius * 2.0f, m_pFieldSize); m_pFluidRenderer->init(m_pParticleSystem, this); // Marching cubes m_pMCMesh = new BBMarchingCubeMesh(); m_pDensityField = new float[(m_pFieldSize[0] + 1) * (m_pFieldSize[1] + 1) * (m_pFieldSize[2] + 1)]; m_pMCMesh->init(m_pFieldSize, 0.25f * m_pGridContainer->getGridDelta(), m_WallBoxMin, m_fDensityThreshold); m_pGridContainer->insertParticles(m_pParticleSystem); m_pParticleNeighborTable->reset(m_pParticleSystem->getSize()); // PCISPH computeGradient(); computePCISPHDensityErrorFactor(); } void BBSPHFluidSystem::render(BBCamera *pCamera) { m_pGridContainer->insertParticles(m_pParticleSystem); m_pParticleNeighborTable->reset(m_pParticleSystem->getSize()); if (m_bPredictCorrection) { computeNeighborTable(); // 1. Calculate the neighbor information of each particle and record it in the neighbor table ---- computeGradient() in init() // 2. Calculate the acceleration caused by all forces except pressure (viscosity, gravity, collision) computePCISPHAcceleration(); // 3. Correction loops predictPCISPHCorrection(); // 4. The corrected pressure is used to calculate the particle velocity and position computePCISPHPositionAndVelocity(); } else { computeDensityAndPressure(); computeAcceleration(); computePositionAndVelocity(); } if (m_bAnisotropic) computeAnisotropicKernel(); computeImplicitField(m_pFieldSize, m_WallBoxMin, 0.25f * m_pGridContainer->getGridDelta()); m_pMCMesh->createMCMesh(m_pDensityField); m_pFluidRenderer->render(pCamera); // m_pMCMesh->render(pCamera); if (m_bAnisotropic) { // restore original position for (int i = 0; i < m_OldPositions.size(); i++) { BBSPHParticle *pParticle = m_pParticleSystem->getParticle(i); pParticle->m_Position = m_OldPositions[i]; } } } void BBSPHFluidSystem::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { BBGameObject::setPosition(position, bUpdateLocalTransform); m_pFluidRenderer->setPosition(position, bUpdateLocalTransform); } void BBSPHFluidSystem::reset() { float fSpacing = m_fParticleRadius / m_fUnitScale; int nParticleIndex = 0; for (float z = m_OriginalFluidBoxMin.z(); z < m_OriginalFluidBoxMax.z(); z += fSpacing) { for (float y = m_OriginalFluidBoxMin.y(); y < m_OriginalFluidBoxMax.y(); y += fSpacing) { for (float x = m_OriginalFluidBoxMin.x(); x < m_OriginalFluidBoxMax.x(); x += fSpacing) { BBSPHParticle *pParticle = m_pParticleSystem->getParticle(nParticleIndex); pParticle->m_Position = QVector3D(x, y, z); nParticleIndex++; } } } } void BBSPHFluidSystem::initFluidVolume(const QVector3D &fluidBoxMin, const QVector3D &fluidBoxMax, float fSpacing) { for (float z = fluidBoxMin.z(); z < fluidBoxMax.z(); z += fSpacing) { for (float y = fluidBoxMin.y(); y < fluidBoxMax.y(); y += fSpacing) { for (float x = fluidBoxMin.x(); x < fluidBoxMax.x(); x += fSpacing) { m_pParticleSystem->addParticle(x, y, z); } } } } void BBSPHFluidSystem::computeNeighborTable() { // h ^ 2 float h2 = m_fSmoothRadius * m_fSmoothRadius; // Traverse all particles for (unsigned int i = 0; i < m_pParticleSystem->getSize(); i++) { BBSPHParticle *pCurrentParticle = m_pParticleSystem->getParticle(i); int pGridCell[8]; m_pGridContainer->findCells(pCurrentParticle->m_Position, m_fSmoothRadius / m_fUnitScale, pGridCell); m_pParticleNeighborTable->setCurrentParticle(i); float sum = 0.0; for (int cell = 0; cell < 8; cell++) { if (pGridCell[cell] == -1) { // edge continue; } // The head of index list of particles that are in the current grid int nNeighborParticleIndex = m_pGridContainer->getGridData(pGridCell[cell]); // Traverse the list while (nNeighborParticleIndex != -1) { BBSPHParticle *pNeighborParticle = m_pParticleSystem->getParticle(nNeighborParticleIndex); if (pCurrentParticle == pNeighborParticle) { sum += pow(h2, 3.0); } else { QVector3D pi_pj = (pCurrentParticle->m_Position - pNeighborParticle->m_Position) * m_fUnitScale; float r2 = pi_pj.lengthSquared(); if (r2 < h2) { // Insert pNeighborParticle into the NeighborTable of pCurrentParticle sum += pow(h2 - r2, 3.0); if (!m_pParticleNeighborTable->addNeighborParticle(nNeighborParticleIndex, sqrtf(r2))) { goto NEIGHBOR_FULL; } } } nNeighborParticleIndex = pNeighborParticle->m_nNextIndex; } } NEIGHBOR_FULL: m_pParticleNeighborTable->recordCurrentNeighbor(); pCurrentParticle->m_fKernel = sum * m_fKernelPoly6; } } /** * @brief BBSPHFluidSystem::computeDensityAndPressure Pressure, density, and neighbor */ void BBSPHFluidSystem::computeDensityAndPressure() { // h ^ 2 float h2 = m_fSmoothRadius * m_fSmoothRadius; // Traverse all particles for (unsigned int i = 0; i < m_pParticleSystem->getSize(); i++) { BBSPHParticle *pCurrentParticle = m_pParticleSystem->getParticle(i); int pGridCell[8]; m_pGridContainer->findCells(pCurrentParticle->m_Position, m_fSmoothRadius / m_fUnitScale, pGridCell); m_pParticleNeighborTable->setCurrentParticle(i); // According to SPH formula float fDensity = 0.001f; for (int cell = 0; cell < 8; cell++) { if (pGridCell[cell] == -1) { // edge continue; } // The head of index list of particles that are in the current grid int nNeighborParticleIndex = m_pGridContainer->getGridData(pGridCell[cell]); // Traverse the list while (nNeighborParticleIndex != -1) { BBSPHParticle *pNeighborParticle = m_pParticleSystem->getParticle(nNeighborParticleIndex); if (pCurrentParticle != pNeighborParticle) { QVector3D pi_pj = pCurrentParticle->m_Position - pNeighborParticle->m_Position; pi_pj *= m_fUnitScale; float r2 = pi_pj.lengthSquared(); if (r2 < h2) { fDensity += pow(h2 - r2, 3.0f); // Insert pNeighborParticle into the NeighborTable of pCurrentParticle if (!m_pParticleNeighborTable->addNeighborParticle(nNeighborParticleIndex, sqrtf(r2))) { goto NEIGHBOR_FULL; } } } nNeighborParticleIndex = pNeighborParticle->m_nNextIndex; } } NEIGHBOR_FULL: m_pParticleNeighborTable->recordCurrentNeighbor(); // According to SPH formula pCurrentParticle->m_fDensity = m_fKernelPoly6 * m_fParticleMass * fDensity; pCurrentParticle->m_fPressure = (pCurrentParticle->m_fDensity - m_fStaticDensity) * m_fBoundingStiffness; pCurrentParticle->m_fDensity = 1.0f / pCurrentParticle->m_fDensity; } } void BBSPHFluidSystem::computeAcceleration() { // Traverse all particles for (unsigned int i = 0; i < m_pParticleSystem->getSize(); i++) { BBSPHParticle *pCurrentParticle = m_pParticleSystem->getParticle(i); QVector3D acceleration(0, 0, 0); int nNeighborCount = m_pParticleNeighborTable->getNeighborCount(i); for (unsigned int j = 0; j < nNeighborCount; j++) { unsigned int nNeighborIndex = -1; float r = 0.0f; m_pParticleNeighborTable->getNeighborInfo(i, j, nNeighborIndex, r); BBSPHParticle *pNeighborParticle = m_pParticleSystem->getParticle(nNeighborIndex); // According to SPH formula QVector3D ri_rj = pCurrentParticle->m_Position - pNeighborParticle->m_Position; ri_rj *= m_fUnitScale; float h_r = m_fSmoothRadius - r; float P = -0.5f * h_r * m_fKernelSpiky * (pCurrentParticle->m_fPressure + pNeighborParticle->m_fPressure) / r; float D = h_r * pCurrentParticle->m_fDensity * pNeighborParticle->m_fDensity; float V = m_fKernelViscosity * m_fViscosity; acceleration += (P * ri_rj + V * (pNeighborParticle->m_EvalVelocity - pCurrentParticle->m_EvalVelocity)) * D; } acceleration += m_Gravity; pCurrentParticle->m_Acceleration = acceleration; computeBoundaryForce(pCurrentParticle); } } void BBSPHFluidSystem::computeBoundaryForce(BBSPHParticle *pParticle) { float fSpeedLimiting2 = m_fSpeedLimiting * m_fSpeedLimiting; QVector3D acceleration = pParticle->m_Acceleration; float fAcceleration2 = acceleration.lengthSquared(); // Limit speed if (fAcceleration2 > fSpeedLimiting2) acceleration *= m_fSpeedLimiting / sqrtf(fAcceleration2); // When particle is in the edge float diff; float threshold = 1.0f; diff = threshold - (pParticle->m_Position.z() - m_WallBoxMin.z()); diff *= m_fUnitScale; if (diff > 0.0f) { QVector3D normal(0, 0, 1); float coefficient = m_fBoundingStiffness * diff - m_fBoundingDamping * QVector3D::dotProduct(normal, pParticle->m_EvalVelocity); acceleration += coefficient * normal; } diff = threshold - (m_WallBoxMax.z() - pParticle->m_Position.z()); diff *= m_fUnitScale; if (diff > 0.0f) { QVector3D normal(0, 0, -1); float coefficient = m_fBoundingStiffness * diff - m_fBoundingDamping * QVector3D::dotProduct(normal, pParticle->m_EvalVelocity); acceleration += coefficient * normal; } diff = threshold - (pParticle->m_Position.x() - m_WallBoxMin.x()); diff *= m_fUnitScale; if (diff > 0.0f) { QVector3D normal(1, 0, 0); float coefficient = m_fBoundingStiffness * diff - m_fBoundingDamping * QVector3D::dotProduct(normal, pParticle->m_EvalVelocity); acceleration += coefficient * normal; } diff = threshold - (m_WallBoxMax.x() - pParticle->m_Position.x()); diff *= m_fUnitScale; if (diff > 0.0f) { QVector3D normal(-1, 0, 0); float coefficient = m_fBoundingStiffness * diff - m_fBoundingDamping * QVector3D::dotProduct(normal, pParticle->m_EvalVelocity); acceleration += coefficient * normal; } diff = threshold - (pParticle->m_Position.y() - m_WallBoxMin.y()); diff *= m_fUnitScale; if (diff > 0.0f) { QVector3D normal(0, 1, 0); float coefficient = m_fBoundingStiffness * diff - m_fBoundingDamping * QVector3D::dotProduct(normal, pParticle->m_EvalVelocity); acceleration += coefficient * normal; } diff = threshold - (m_WallBoxMax.y() - pParticle->m_Position.y()); diff *= m_fUnitScale; if (diff > 0.0f) { QVector3D normal(0, -1, 0); float coefficient = m_fBoundingStiffness * diff - m_fBoundingDamping * QVector3D::dotProduct(normal, pParticle->m_EvalVelocity); acceleration += coefficient * normal; } pParticle->m_Acceleration = acceleration; } void BBSPHFluidSystem::handleCollision(BBSPHParticle* pParticle) { static float fDamping = 0.1f; for (int i = 0; i < 3; i++) { if (pParticle->m_PredictedPosition[i] < m_WallBoxMin[i]) { pParticle->m_PredictedPosition[i] = m_WallBoxMin[i]; pParticle->m_Velocity[i] *= fDamping; } if (pParticle->m_PredictedPosition[i] > m_WallBoxMax[i]) { pParticle->m_PredictedPosition[i] = m_WallBoxMax[i]; pParticle->m_Velocity[i] *= fDamping; } } } void BBSPHFluidSystem::computePositionAndVelocity() { // Traverse all particles for (unsigned int i = 0; i < m_pParticleSystem->getSize(); i++) { BBSPHParticle *pParticle = m_pParticleSystem->getParticle(i); // v(t+1/2) = v(t-1/2) + a(t)dt QVector3D v = pParticle->m_Velocity + pParticle->m_Acceleration * m_fDeltaTime; // v(t+1) = [v(t-1/2) + v(t+1/2)] * 0.5 pParticle->m_EvalVelocity = (v + pParticle->m_Velocity) * 0.5f; pParticle->m_Velocity = v; // p(t+1) = p(t) + v(t+1/2)dt pParticle->m_Position += v * m_fDeltaTime / m_fUnitScale; } } void BBSPHFluidSystem::computePositionAndVelocityWithGravity() { for (unsigned int i = 0; i < m_pParticleSystem->getSize(); i++) { BBSPHParticle* pParticle = m_pParticleSystem->getParticle(i); pParticle->m_Acceleration += m_Gravity; pParticle->m_Velocity += pParticle->m_Acceleration * m_fDeltaTime; pParticle->m_Position += pParticle->m_Velocity * m_fDeltaTime / m_fUnitScale; } } /** * @brief BBSPHFluidSystem::computeImplicitField Calculating implicit function values from particle * @param pNum Num * @param minPos * @param unitWidth * @param pOutField Array */ void BBSPHFluidSystem::computeImplicitField(unsigned int pNum[3], const QVector3D &minPos, const QVector3D &unitWidth) { unsigned int nSlice0 = pNum[0] + 1; unsigned int nSlice1 = nSlice0 * (pNum[1] + 1); for (int k = 0; k < pNum[2]; k++) { for (int j = 0; j < pNum[1]; j++) { for (int i = 0; i < pNum[0]; i++) { QVector3D pos = minPos + QVector3D(i, j, k) * unitWidth; m_pDensityField[k * nSlice1 + j * nSlice0 + i] = computeColorField(pos); } } } } float BBSPHFluidSystem::computeColorField(const QVector3D &pos) { // Density field float c = 0.0f; if (pos.x() < m_WallBoxMin.x()) return c; if (pos.x() > m_WallBoxMax.x()) return c; if (pos.y() < m_WallBoxMin.y()) return c; if (pos.y() > m_WallBoxMax.y()) return c; if (pos.z() < m_WallBoxMin.z()) return c; if (pos.z() > m_WallBoxMax.z()) return c; float h = m_fSmoothRadius; float h2 = h * h; int pGridCell[8]; m_pGridContainer->findCells(pos, h / m_fUnitScale, pGridCell); for (int cell = 0; cell < 8; cell++) { if (pGridCell[cell] < 0) { continue; } int nNeighborParticleIndex = m_pGridContainer->getGridData(pGridCell[cell]); // Traverse the list while (nNeighborParticleIndex != -1) { BBSPHParticle *pNeighborParticle = m_pParticleSystem->getParticle(nNeighborParticleIndex); if (m_bAnisotropic) { QMatrix3x3 G = m_G[nNeighborParticleIndex]; QVector3D rij = pos - pNeighborParticle->m_Position; // Transform to ellipse for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { rij[i] += G(i, j) * rij[j]; } } float r = rij.length() * m_fUnitScale; float q = h2 - r * r; if (q > 0) { float determinant = G(0, 0) * G(1, 1) * G(2, 2) + G(0, 1) * G(1, 2) * G(2, 0) + G(0, 2) * G(1, 0) * G(2, 1) - G(0, 0) * G(1, 2) * G(2, 1) - G(0, 1) * G(1, 0) * G(2, 2) - G(0, 2) * G(1, 1) * G(2, 0); c += determinant * m_fParticleMass * m_fKernelPoly6 * q * q * q; } } else { // isotropic float r = pos.distanceToPoint(pNeighborParticle->m_Position) * m_fUnitScale; float q = h2 - r * r; if (q > 0) { c += m_fParticleMass * m_fKernelPoly6 * q * q * q; } } nNeighborParticleIndex = pNeighborParticle->m_nNextIndex; } } return c; } void BBSPHFluidSystem::computeAnisotropicKernel() { if (m_pParticleSystem->getSize() == 0) return; float h0 = m_fSmoothRadius; float h = 2.0 * h0; m_G.resize(m_pParticleSystem->getSize()); // Laplace smoothing coefficient float lambda = 0.9f; // New particle position by smoothing QVector3D positions[m_pParticleSystem->getSize()]; for (unsigned int i = 0; i < m_pParticleSystem->getSize(); i++) { QVector3D pos0 = m_pParticleSystem->getParticle(i)->m_Position; int pGridCell[64]; m_pGridContainer->findTwoCells(pos0, h / m_fUnitScale, pGridCell); QVector3D posw(0, 0, 0); float sumw = 0.0f; for (int cell = 0; cell < 64; cell++) { if (pGridCell[cell] < 0) continue; int nNeighborParticleIndex = m_pGridContainer->getGridData(pGridCell[cell]); while (nNeighborParticleIndex != -1) { BBSPHParticle *pNeighborParticle = m_pParticleSystem->getParticle(nNeighborParticleIndex); QVector3D pos1 = pNeighborParticle->m_Position; float r = pos0.distanceToPoint(pos1) * m_fUnitScale; if (r < h) { float q = 1 - r / h; float wij = q * q * q; posw += pos1 * wij; sumw += wij; } nNeighborParticleIndex = pNeighborParticle->m_nNextIndex; } } positions[i] = posw / sumw; positions[i] = (1 - lambda) * m_pParticleSystem->getParticle(i)->m_Position + lambda * positions[i]; } m_OldPositions.resize(m_pParticleSystem->getSize()); for (unsigned int i = 0; i < m_pParticleSystem->getSize(); i++) { BBSPHParticle *pParticle = m_pParticleSystem->getParticle(i); m_OldPositions[i] = pParticle->m_Position; pParticle->m_Position = positions[i]; } m_pGridContainer->insertParticles(m_pParticleSystem); // compute covariance matrix for (unsigned int i = 0; i < m_pParticleSystem->getSize(); i++) { QVector3D xi = positions[i]; QVector3D xiw(0, 0, 0); float sumw = 0.0f; int pGridCell[64]; m_pGridContainer->findTwoCells(xi, h / m_fUnitScale, pGridCell); for (int cell = 0; cell < 64; cell++) { if (pGridCell[cell] < 0) continue; int nNeighborParticleIndex = m_pGridContainer->getGridData(pGridCell[cell]); while (nNeighborParticleIndex != -1) { QVector3D xj = positions[nNeighborParticleIndex]; float r = xi.distanceToPoint(xj) * m_fUnitScale; if (r < h) { float q = 1 - r / h; float wij = q * q * q; xiw += xj * wij; sumw += wij; } nNeighborParticleIndex = m_pParticleSystem->getParticle(nNeighborParticleIndex)->m_nNextIndex; } } xiw /= sumw; QMatrix3x3 c; c.fill(0.0f); sumw = 0.0f; // The number of neighbor particles int n = 0; for (int cell = 0; cell < 64; cell++) { if (pGridCell[cell] < 0) continue; int nNeighborParticleIndex = m_pGridContainer->getGridData(pGridCell[cell]); while (nNeighborParticleIndex != -1) { QVector3D xj = positions[nNeighborParticleIndex]; float r = xi.distanceToPoint(xj) * m_fUnitScale; if (r < h) { float q = 1 - r / h; float wij = q * q * q; QVector3D dxj = xj - xiw; for (int k = 0; k < 3; k++) { c(0, k) += wij * dxj[0] * dxj[k]; c(1, k) += wij * dxj[1] * dxj[k]; c(2, k) += wij * dxj[2] * dxj[k]; } n++; sumw += wij; } nNeighborParticleIndex = m_pParticleSystem->getParticle(nNeighborParticleIndex)->m_nNextIndex; } } c /= sumw; // SVD float w[3], u[9], v[9]; for (int j = 0; j < 3; j++) { u[j * 3 + 0] = c(0, j); u[j * 3 + 1] = c(1, j); u[j * 3 + 2] = c(2, j); } BBMatrix::SVDdecomposition(w, u, v, 1.0e-10); // Eigenvalue Σ QVector3D eigenvalue(w[0], w[1], w[2]); // C = R Σ R^T // Eigenvector (rotation matrix R) QMatrix3x3 R; for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { R(j, k) = u[k * 3 + j]; } } // threshold int ne = 25; float ks = 1400; float kn = 0.5f; float kr = 4.0f; if (n > ne) { // When the maximum variance on main axis ([0]) is greater than kr times the minimum variance on the other axis // The ratio between any two eigenvalues is less than kr eigenvalue[1] = max(eigenvalue[1], eigenvalue[0] / kr); eigenvalue[2] = max(eigenvalue[2], eigenvalue[0] / kr); // The matrix norm of ksC is approximately equal to 1 // The matrix norm reflects the linear mapping of one vector to another, and the scale of the "length" of the vector // So that the volume of particles with complete neighborhoods remains constant. eigenvalue *= ks; } else { // When there are fewer particles nearby // Reset to spherical to prevent poor particle deformation for almost isolated particles eigenvalue = QVector3D(1, 1, 1) * kn; } // Kernel Matrix G = R Σ^-1 R^T QMatrix3x3 sigma; sigma(0, 0) = 1.0f / eigenvalue.x(), sigma(0, 1) = 0.0f, sigma(0, 2) = 0.0f; sigma(1, 0) = 0.0f, sigma(1, 1) = 1.0f / eigenvalue.y(), sigma(1, 2) = 0.0f; sigma(2, 0) = 0.0f, sigma(2, 1) = 0.0f, sigma(2, 2) = 1.0f / eigenvalue.z(); QMatrix3x3 G = R * sigma * R.transposed(); float limiting = -1.0e10; for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { if (G(k, j) > limiting) limiting = G(k, j); } } G /= limiting; m_G[i] = G; } } void BBSPHFluidSystem::computeGradient() { // Σ▽wij▽wij & Σ▽wij computeNeighborTable(); float h = m_fSmoothRadius; float h2 = h * h; for (int i = 0; i < m_pParticleSystem->getSize(); i++) { BBSPHParticle *pParticle = m_pParticleSystem->getParticle(i); int nNeighborCount = m_pParticleNeighborTable->getNeighborCount(i); for (unsigned int j = 0; j < nNeighborCount; j++) { unsigned int nNeighborIndex = -1; float r = 0.0f; m_pParticleNeighborTable->getNeighborInfo(i, j, nNeighborIndex, r); BBSPHParticle *pNeighborParticle = m_pParticleSystem->getParticle(nNeighborIndex); QVector3D pi_pj = (pParticle->m_Position - pNeighborParticle->m_Position) * m_fUnitScale; float r2 = pi_pj.lengthSquared(); if (r2 < h2) { float r = sqrtf(r2); QVector3D gradient = (pParticle->m_Position - pNeighborParticle->m_Position) * m_fKernelSpiky / r * (h - r) * (h - r); pParticle->m_SumGradient += gradient; pNeighborParticle->m_SumGradient -= gradient; pParticle->m_SumGradient2 += QVector3D::dotProduct(gradient, gradient); pNeighborParticle->m_SumGradient2 += QVector3D::dotProduct(-gradient, -gradient); } } } } /** * @brief BBSPHFluidSystem::computePCISPHDensityErrorFactor When the number of neighbor particles is insufficient, it will lead to calculation errors * So when initializing the fluid, that is, when the fluid particles are filled with neighbor particles, the coefficient is calculated */ void BBSPHFluidSystem::computePCISPHDensityErrorFactor() { int nMaxNeighborCount = 0; int nMaxNeighborCountCurrentParticleIndex = 0; for (int i = 0; i < m_pParticleSystem->getSize(); i++) { int nNeighborCount = m_pParticleNeighborTable->getNeighborCount(i); if (nNeighborCount > nMaxNeighborCount) { nMaxNeighborCount = nNeighborCount; nMaxNeighborCountCurrentParticleIndex = i; } } BBSPHParticle *pMaxParticle = m_pParticleSystem->getParticle(nMaxNeighborCountCurrentParticleIndex); // According to formula float volume = m_fParticleMass / m_fStaticDensity; float factor = 2.0f * volume * volume * m_fDeltaTime * m_fDeltaTime; float divisor = -QVector3D::dotProduct(pMaxParticle->m_SumGradient, pMaxParticle->m_SumGradient) - pMaxParticle->m_SumGradient2; divisor *= factor; m_fPCISPHDensityErrorFactor = -1.0f / divisor; } /** * @brief BBSPHFluidSystem::computePCISPHAcceleration not including pressure */ void BBSPHFluidSystem::computePCISPHAcceleration() { float h = m_fSmoothRadius; for (int i = 0; i < m_pParticleSystem->getSize(); i++) { BBSPHParticle *pParticle = m_pParticleSystem->getParticle(i); pParticle->m_Acceleration = QVector3D(0, 0, 0); float volume = m_fParticleMass / m_fStaticDensity; int nNeighborCount = m_pParticleNeighborTable->getNeighborCount(i); for (unsigned int j = 0; j < nNeighborCount; j++) { unsigned int nNeighborIndex = -1; float r = 0.0f; m_pParticleNeighborTable->getNeighborInfo(i, j, nNeighborIndex, r); BBSPHParticle *pNeighborParticle = m_pParticleSystem->getParticle(nNeighborIndex); float V = m_fKernelViscosity * m_fViscosity * (h - r) * volume * volume; pParticle->m_Acceleration -= (pParticle->m_Velocity - pNeighborParticle->m_Velocity) * V / m_fParticleMass; } computeBoundaryForce(pParticle); pParticle->m_Acceleration += m_Gravity; // init pParticle->m_fCorrectPressure = 0.0f; pParticle->m_CorrectPressureForce = QVector3D(0, 0, 0); } } void BBSPHFluidSystem::predictPCISPHCorrection() { static int nMinLoops = 3; static int nMaxLoops = 100; static float fAllowedMaxDensityError = 1.0f; int nIteration = 0; bool bEndLoop = false; while ((nIteration < nMinLoops) || ((nIteration < nMaxLoops) && !bEndLoop)) { for (int i = 0; i < m_pParticleSystem->getSize(); i++) { BBSPHParticle *pParticle = m_pParticleSystem->getParticle(i); predictPCISPHPositionAndVelocity(pParticle); } float fMaxError = 0.0f; for (int i = 0; i < m_pParticleSystem->getSize(); i++) { float fError = predictPCISPHDensityAndPressure(i); fMaxError = max(fMaxError, fError); } // Less than the density error threshold, break if (max(0.1f * fMaxError - 100.0f, 0.0f) < fAllowedMaxDensityError) { bEndLoop = true; } for (int i = 0; i < m_pParticleSystem->getSize(); i++) { computePCISPHCorrectivePressureForce(i); } nIteration++; } } void BBSPHFluidSystem::predictPCISPHPositionAndVelocity(BBSPHParticle *pParticle) { // v' = v + t * a // a = F / m // v' = v + t * F / m // v' = v + t * F * V / m // v' = v + t * F * 1 / density QVector3D F = m_fParticleMass * pParticle->m_Acceleration + pParticle->m_CorrectPressureForce; QVector3D predictedVelocity = pParticle->m_Velocity + m_fDeltaTime * F / m_fParticleMass; pParticle->m_PredictedPosition = pParticle->m_Position + m_fDeltaTime * predictedVelocity; // Collision handleCollision(pParticle); } float BBSPHFluidSystem::predictPCISPHDensityAndPressure(int nParticleIndex) { float h2 = m_fSmoothRadius * m_fSmoothRadius; BBSPHParticle* pParticle = m_pParticleSystem->getParticle(nParticleIndex); pParticle->m_fPredictedDensity = pParticle->m_fKernel * m_fParticleMass; int nNeighborCount = m_pParticleNeighborTable->getNeighborCount(nParticleIndex); for (unsigned int j = 0; j < nNeighborCount; j++) { unsigned int nNeighborIndex = -1; float r = 0.0f; m_pParticleNeighborTable->getNeighborInfo(nParticleIndex, j, nNeighborIndex, r); BBSPHParticle* pNeighborParticle = m_pParticleSystem->getParticle(nNeighborIndex); // Use the predicted position to recalculate the distance and kernel QVector3D pi_pj = (pParticle->m_PredictedPosition - pNeighborParticle->m_PredictedPosition) * m_fUnitScale; float r2 = pi_pj.lengthSquared(); if (r2 < h2) { pParticle->m_fPredictedDensity += m_fKernelPoly6 * pow(h2 - r2, 3.0) * m_fParticleMass; } } // Consider only positive errors pParticle->m_fDensityError = max(pParticle->m_fPredictedDensity - m_fStaticDensity, 0.0f); // Correct positive pressure pParticle->m_fCorrectPressure += max(pParticle->m_fDensityError * m_fPCISPHDensityErrorFactor, 0.0f); return pParticle->m_fPredictedDensity; } void BBSPHFluidSystem::computePCISPHCorrectivePressureForce(int nParticleIndex) { float h = m_fSmoothRadius; float h2 = m_fSmoothRadius * m_fSmoothRadius; float fStaticDensity2 = m_fStaticDensity * m_fStaticDensity; BBSPHParticle* pParticle = m_pParticleSystem->getParticle(nParticleIndex); pParticle->m_CorrectPressureForce = QVector3D(0, 0, 0); int nNeighborCount = m_pParticleNeighborTable->getNeighborCount(nParticleIndex); for (unsigned int j = 0; j < nNeighborCount; j++) { unsigned int nNeighborIndex = -1; float r = 0.0f; m_pParticleNeighborTable->getNeighborInfo(nParticleIndex, j, nNeighborIndex, r); BBSPHParticle* pNeighborParticle = m_pParticleSystem->getParticle(nNeighborIndex); QVector3D pi_pj = (pParticle->m_Position - pNeighborParticle->m_Position) * m_fUnitScale; float r2 = pi_pj.lengthSquared(); if (r2 < h2) { r = sqrtf(r2); QVector3D gradient = pi_pj * m_fKernelSpiky / r * (h - r) * (h - r); pParticle->m_CorrectPressureForce -= m_fParticleMass * m_fParticleMass * gradient * (pParticle->m_fCorrectPressure + pNeighborParticle->m_fCorrectPressure) / fStaticDensity2; } } } void BBSPHFluidSystem::computePCISPHPositionAndVelocity() { for (int i = 0; i < m_pParticleSystem->getSize(); i++) { BBSPHParticle* pParticle = m_pParticleSystem->getParticle(i); pParticle->m_Acceleration += pParticle->m_CorrectPressureForce / m_fParticleMass; // v(t+1/2) = v(t-1/2) + a(t)dt QVector3D v = pParticle->m_Velocity + pParticle->m_Acceleration * m_fDeltaTime; // v(t+1) = [v(t-1/2) + v(t+1/2)] * 0.5 pParticle->m_EvalVelocity = (v + pParticle->m_Velocity) * 0.5f; pParticle->m_Velocity = v; // p(t+1) = p(t) + v(t+1/2)dt pParticle->m_Position += v * m_fDeltaTime / m_fUnitScale; } } <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFileSystemDockWidget.cpp<|end_filename|> #include "BBFileSystemDockWidget.h" #include "ui_BBFileSystemDockWidget.h" #include "BBFileSystemManager.h" BBFileSystemDockWidget::BBFileSystemDockWidget(QWidget *pParent) : QDockWidget(pParent), m_pUi(new Ui::BBFileSystemDockWidget) { m_pUi->setupUi(this); m_pUi->dockProjectContents->updateSizeHint(QSize(1024, 400)); // Stretch the width of the file list m_pUi->splitterProject->setStretchFactor(0, 1); m_pUi->splitterProject->setStretchFactor(1, 2); setConnect(); m_pFileSystemManager = new BBFileSystemManager(m_pUi->treeFolder, m_pUi->listFile, m_pUi->barFilePath); } BBFileSystemDockWidget::~BBFileSystemDockWidget() { BB_SAFE_DELETE(m_pUi); BB_SAFE_DELETE(m_pFileSystemManager); } void BBFileSystemDockWidget::bindPreviewOpenGLWidget(BBPreviewOpenGLWidget *pPreviewOpenGLWidget) { m_pFileSystemManager->bindPreviewOpenGLWidget(pPreviewOpenGLWidget); } void BBFileSystemDockWidget::createProject() { m_pFileSystemManager->createProject(); } void BBFileSystemDockWidget::openProject() { m_pFileSystemManager->openProject(); } void BBFileSystemDockWidget::removeCurrentItem() { emit removeMaterialPreview(); m_pFileSystemManager->setCurrentItemInFileList(NULL); } void BBFileSystemDockWidget::clickItemInFolderTree(const QString &filePath, QTreeWidgetItem *pItem) { m_pFileSystemManager->clickItemInFolderTree(filePath, pItem); } void BBFileSystemDockWidget::clickItemInFileList(const QString &filePath, const BBFileType &eType) { if (eType == BBFileType::Material) { emit removeCurrentItemInHierarchyTree(); emit showMaterialInPropertyManager(filePath); } } void BBFileSystemDockWidget::pressItemInFileList(const BBFileType &eType) { } void BBFileSystemDockWidget::doubleClickItemInFileList(const QString &filePath, const BBFileType &eType) { if (eType == BBFileType::Material) { emit showMaterialPreview(filePath); } else { m_pFileSystemManager->doubleClickItemInFileList(filePath); } } void BBFileSystemDockWidget::changeCurrentItemInFileList(BBFileType eCurrentType, BBFileType ePreviousType) { // emit removeCurrentItemInHierarchyTree(); // if (ePreviousType == BBFileType::Material && eCurrentType != BBFileType::Material) // { // // remove material sphere in the preview // emit removeMaterialPreview(); // } } void BBFileSystemDockWidget::inFocusInFileList() { } void BBFileSystemDockWidget::clickItemInFolderPathBar(const QString &filePath) { m_pFileSystemManager->clickItemInFolderPathBar(filePath); } void BBFileSystemDockWidget::newFolder(const QString &parentPath, const BBSignalSender &eSender) { m_pFileSystemManager->newFolder(parentPath, eSender); } void BBFileSystemDockWidget::newFile(const QString &parentPath, int nType) { m_pFileSystemManager->newFile(parentPath, nType); } void BBFileSystemDockWidget::saveScene() { m_pFileSystemManager->saveScene(); } void BBFileSystemDockWidget::showInFolder(const QString &filePath) { m_pFileSystemManager->showInFolder(filePath); } void BBFileSystemDockWidget::renameInFolderTree(QTreeWidgetItem *pParentFolderItem, const QString &oldPath, const QString &newPath) { m_pFileSystemManager->renameInFolderTree(pParentFolderItem, oldPath, newPath); } void BBFileSystemDockWidget::renameInFileList(QListWidgetItem *pFileItem, const QString &oldPath, const QString &newPath) { m_pFileSystemManager->renameInFileList(pFileItem, oldPath, newPath); } void BBFileSystemDockWidget::deleteFolderInFolderTree(QTreeWidgetItem *pItem) { m_pFileSystemManager->deleteFolderInFolderTree(pItem); } void BBFileSystemDockWidget::deleteFilesInFileList(const QList<QListWidgetItem*> &items) { m_pFileSystemManager->deleteFilesInFileList(items); } void BBFileSystemDockWidget::importAsset(const QString &parentPath, const QList<QUrl> &urls) { m_pFileSystemManager->importAsset(parentPath, urls); } void BBFileSystemDockWidget::moveFolders(const QList<QTreeWidgetItem*> &items, QTreeWidgetItem *pNewParentItem, bool bCopy) { m_pFileSystemManager->moveFolders(items, pNewParentItem, bCopy); } void BBFileSystemDockWidget::moveFolders(const QList<QString> &oldFilePaths, const QString &newParentPath, bool bCopy) { m_pFileSystemManager->moveFolders(oldFilePaths, newParentPath, bCopy); } void BBFileSystemDockWidget::moveFiles(const QList<QString> &oldFilePaths, QTreeWidgetItem *pNewParentItem, bool bCopy) { m_pFileSystemManager->moveFiles(oldFilePaths, pNewParentItem, bCopy); } void BBFileSystemDockWidget::moveFiles(const QList<QListWidgetItem*> &items, const QString &oldParentPath, const QString &newParentPath, bool bCopy) { m_pFileSystemManager->moveFiles(items, oldParentPath, newParentPath, bCopy); } void BBFileSystemDockWidget::updateAll() { m_pFileSystemManager->updateAll(); } void BBFileSystemDockWidget::setConnect() { // update selected folder QObject::connect(m_pUi->treeFolder, SIGNAL(accessFolder(QString, QTreeWidgetItem*)), this, SLOT(clickItemInFolderTree(QString, QTreeWidgetItem*))); QObject::connect(m_pUi->listFile, SIGNAL(openFile(QString, BBFileType)), this, SLOT(doubleClickItemInFileList(QString, BBFileType))); QObject::connect(m_pUi->barFilePath, SIGNAL(accessFolder(QString)), this, SLOT(clickItemInFolderPathBar(QString))); // click file item, and show property, or remove QObject::connect(m_pUi->listFile, SIGNAL(clickItem(QString, BBFileType)), this, SLOT(clickItemInFileList(QString, BBFileType))); QObject::connect(m_pUi->listFile, SIGNAL(pressItem(BBFileType)), this, SLOT(pressItemInFileList(BBFileType))); QObject::connect(m_pUi->listFile, SIGNAL(changeCurrentItem(BBFileType, BBFileType)), this, SLOT(changeCurrentItemInFileList(BBFileType, BBFileType))); QObject::connect(m_pUi->listFile, SIGNAL(inFocus()), this, SLOT(inFocusInFileList())); // click buttons in the file system QObject::connect(m_pUi->buttonRootProject, SIGNAL(clicked()), m_pUi->treeFolder, SLOT(pressRootButton())); QObject::connect(m_pUi->buttonMoreProject, SIGNAL(clicked()), m_pUi->treeFolder, SLOT(pressSettingButton())); // scroll folder path bar QObject::connect(m_pUi->buttonMovePathLeft, SIGNAL(pressed()), m_pUi->scrollAreaFilePath, SLOT(moveToLeft())); QObject::connect(m_pUi->buttonMovePathRight, SIGNAL(pressed()), m_pUi->scrollAreaFilePath, SLOT(moveToRight())); // new folder QObject::connect(m_pUi->treeFolder, SIGNAL(newFolder(QString, BBSignalSender)), this, SLOT(newFolder(QString, BBSignalSender))); QObject::connect(m_pUi->listFile, SIGNAL(newFolder(QString, BBSignalSender)), this, SLOT(newFolder(QString, BBSignalSender))); // new Scene ... QObject::connect(m_pUi->treeFolder, SIGNAL(newFile(QString, int)), this, SLOT(newFile(QString, int))); QObject::connect(m_pUi->listFile, SIGNAL(newFile(QString, int)), this, SLOT(newFile(QString, int))); // show in folder QObject::connect(m_pUi->treeFolder, SIGNAL(showInFolder(QString)), this, SLOT(showInFolder(QString))); QObject::connect(m_pUi->listFile, SIGNAL(showInFolder(QString)), this, SLOT(showInFolder(QString))); // rename QObject::connect(m_pUi->treeFolder, SIGNAL(rename(QTreeWidgetItem*, QString, QString)), this, SLOT(renameInFolderTree(QTreeWidgetItem*, QString, QString))); QObject::connect(m_pUi->listFile, SIGNAL(rename(QListWidgetItem*, QString, QString)), this, SLOT(renameInFileList(QListWidgetItem*, QString, QString))); // delete files QObject::connect(m_pUi->treeFolder, SIGNAL(deleteFolder(QTreeWidgetItem*)), this, SLOT(deleteFolderInFolderTree(QTreeWidgetItem*))); QObject::connect(m_pUi->treeFolder, SIGNAL(finishDeleteAction()), this, SLOT(updateAll())); QObject::connect(m_pUi->listFile, SIGNAL(deleteFiles(QList<QListWidgetItem*>)), this, SLOT(deleteFilesInFileList(QList<QListWidgetItem*>))); // import external assets QObject::connect(m_pUi->listFile, SIGNAL(importAsset(QString, QList<QUrl>)), this, SLOT(importAsset(QString, QList<QUrl>))); // move items QObject::connect(m_pUi->treeFolder, SIGNAL(moveFolders(QList<QTreeWidgetItem*>, QTreeWidgetItem*, bool)), this, SLOT(moveFolders(QList<QTreeWidgetItem*>, QTreeWidgetItem*, bool))); QObject::connect(m_pUi->treeFolder, SIGNAL(moveFiles(QList<QString>, QTreeWidgetItem*, bool)), this, SLOT(moveFiles(QList<QString>, QTreeWidgetItem*, bool))); QObject::connect(m_pUi->listFile, SIGNAL(moveFolders(QList<QString>, QString, bool)), this, SLOT(moveFolders(QList<QString>, QString, bool))); QObject::connect(m_pUi->listFile, SIGNAL(moveFiles(QList<QListWidgetItem*>, QString, QString, bool)), this, SLOT(moveFiles(QList<QListWidgetItem*>, QString, QString, bool))); } <|start_filename|>Code/BBearEditor/Engine/Physics/FluidSystem/BBSPHFluidRenderer.cpp<|end_filename|> #include "BBSPHFluidRenderer.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BBMaterial.h" #include "Render/BBDrawCall.h" #include "Render/Texture/BBProcedureTexture.h" #include "Render/BBRenderPass.h" #include "BBSPHParticleSystem.h" #include "Scene/BBScene.h" #include "Scene/BBSceneManager.h" #include "2D/BBFullScreenQuad.h" #include "Physics/FluidSystem/BBSPHFluidSystem.h" BBSPHFluidRenderer::BBSPHFluidRenderer(const QVector3D &position) : BBRenderableObject(position, QVector3D(0, 0, 0), QVector3D(1, 1, 1)), m_nSSFGBufferMaterialIndex(3) { m_pScreenQuadXFilterMaterial = nullptr; m_pScreenQuadYFilterMaterial = nullptr; m_pScreenQuadNormalMaterial = nullptr; m_pScreenQuadShadingMaterial = nullptr; } BBSPHFluidRenderer::~BBSPHFluidRenderer() { BB_SAFE_DELETE(m_pScreenQuadXFilterMaterial); BB_SAFE_DELETE(m_pScreenQuadYFilterMaterial); BB_SAFE_DELETE(m_pScreenQuadNormalMaterial); BB_SAFE_DELETE(m_pScreenQuadShadingMaterial); } void BBSPHFluidRenderer::init(BBSPHParticleSystem *pParticleSystem, BBSPHFluidSystem *pFluidSystem) { m_pParticleSystem = pParticleSystem; m_pFluidSystem = pFluidSystem; m_pVBO = new BBVertexBufferObject(pParticleSystem->getSize()); for (int i = 0; i < m_pVBO->getVertexCount(); i++) { m_pVBO->setPosition(i, pParticleSystem->getParticle(i)->m_Position); m_pVBO->setColor(i, BBConstant::m_LightGreen); } m_pCurrentMaterial->init("BBSPHFluidParticle", BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/SPHFluidParticle.vert), BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/SPHFluidParticle.frag)); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setSSBO(m_pSSBO); pDrawCall->setVBO(m_pVBO, GL_POINTS, 0, m_pVBO->getVertexCount()); appendDrawCall(pDrawCall); // SSF initSSFMaterial(); } void BBSPHFluidRenderer::render(BBCamera *pCamera) { for (int i = 0; i < m_pVBO->getVertexCount(); i++) { m_pVBO->setPosition(i, m_pParticleSystem->getParticle(i)->m_Position); } m_pVBO->submitData(); BBRenderableObject::render(pCamera); } void BBSPHFluidRenderer::switchSSF(bool bEnable) { BBScene *pScene = BBSceneManager::getScene(); if (bEnable) { pScene->setRenderingFunc(&BBScene::deferredRendering1_4); setCurrentMaterial(getExtraMaterial(m_nSSFGBufferMaterialIndex)); BBFullScreenQuad *pFullScreenQuad0 = pScene->getFullScreenQuad(0); pFullScreenQuad0->setCurrentMaterial(m_pScreenQuadXFilterMaterial); BBFullScreenQuad *pFullScreenQuad1 = pScene->getFullScreenQuad(1); pFullScreenQuad1->setCurrentMaterial(m_pScreenQuadYFilterMaterial); BBFullScreenQuad *pFullScreenQuad2 = pScene->getFullScreenQuad(2); pFullScreenQuad2->setCurrentMaterial(m_pScreenQuadNormalMaterial); BBFullScreenQuad *pFullScreenQuad3 = pScene->getFullScreenQuad(3); pFullScreenQuad3->setCurrentMaterial(m_pScreenQuadShadingMaterial); } else { pScene->setRenderingFunc(&BBScene::defaultRendering); restoreMaterial(); } } void BBSPHFluidRenderer::resetFluidParticles() { m_pFluidSystem->reset(); } void BBSPHFluidRenderer::initSSFMaterial() { BBScene *pScene = BBSceneManager::getScene(); // GBuffer pass BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("SSF_1_GBuffer", BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/SSF_VS_GBuffer.vert), BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/SSF_FS_1_GBuffer.frag), BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/SSF_GS_GBuffer.shader)); pMaterial->setFloat("ParticleRadius", 0.125f); // pMaterial->setBlendState(true); // pMaterial->setBlendFunc(GL_ONE, GL_ONE); // pMaterial->setZTestState(false); setExtraMaterial(m_nSSFGBufferMaterialIndex, pMaterial); // x Filter pass m_pScreenQuadXFilterMaterial = new BBMaterial(); m_pScreenQuadXFilterMaterial->init("SSF_2_Screen_Filter", BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/FullScreenQuad.vert), BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/SSF_FS_2_Screen_Filter.frag)); m_pScreenQuadXFilterMaterial->setSampler2D("DepthMap", pScene->getColorFBO(0, 0)); m_pScreenQuadXFilterMaterial->setSampler2D("ThicknessMap", pScene->getColorFBO(0, 1)); m_pScreenQuadXFilterMaterial->setFloat("FilterRadius", 5.0f); m_pScreenQuadXFilterMaterial->setFloat("SpatialScale", 0.2f); m_pScreenQuadXFilterMaterial->setFloat("RangeScale", 0.2f); m_pScreenQuadXFilterMaterial->setVector4("BlurDir", 1.0f, 0.0f, 0.0f, 0.0f); // y Filter pass m_pScreenQuadYFilterMaterial = new BBMaterial(); m_pScreenQuadYFilterMaterial->init("SSF_2_Screen_Filter", BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/FullScreenQuad.vert), BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/SSF_FS_2_Screen_Filter.frag)); m_pScreenQuadYFilterMaterial->setSampler2D("DepthMap", pScene->getColorFBO(1, 0)); m_pScreenQuadYFilterMaterial->setSampler2D("ThicknessMap", pScene->getColorFBO(1, 1)); m_pScreenQuadYFilterMaterial->setFloat("FilterRadius", 5.0f); m_pScreenQuadYFilterMaterial->setFloat("SpatialScale", 0.2f); m_pScreenQuadYFilterMaterial->setFloat("RangeScale", 0.2f); m_pScreenQuadYFilterMaterial->setVector4("BlurDir", 0.0f, 1.0f, 0.0f, 0.0f); // Compute normals pass m_pScreenQuadNormalMaterial = new BBMaterial(); m_pScreenQuadNormalMaterial->init("SSF_3_Screen_Normal", BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/FullScreenQuad.vert), BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/SSF_FS_3_Screen_Normal.frag)); m_pScreenQuadNormalMaterial->setSampler2D("DepthMap", pScene->getColorFBO(2, 0)); // Shading pass m_pScreenQuadShadingMaterial = new BBMaterial(); m_pScreenQuadShadingMaterial->init("SSF_4_Screen_Shading", BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/FullScreenQuad.vert), BB_PATH_RESOURCE_SHADER(Physics/FluidSystem/SSF_FS_4_Screen_Shading.frag)); m_pScreenQuadShadingMaterial->setSampler2D("DepthMap", pScene->getColorFBO(2, 0)); m_pScreenQuadShadingMaterial->setSampler2D("ThicknessMap", pScene->getColorFBO(2, 1)); m_pScreenQuadShadingMaterial->setSampler2D("NormalMap", pScene->getColorFBO(3, 0)); } <|start_filename|>Code/BBearEditor/Engine/Render/OfflineRenderer/BBScatterMaterial.cpp<|end_filename|> #include "BBScatterMaterial.h" #include "Math/BBMath.h" /** * @brief BBScatterMaterial::BBScatterMaterial */ BBScatterMaterial::BBScatterMaterial() { } BBScatterMaterial::~BBScatterMaterial() { } /** * @brief BBAreaLightMaterial::BBAreaLightMaterial * @param color */ BBAreaLightMaterial::BBAreaLightMaterial(const QVector3D &color) { m_Color = color; } BBAreaLightMaterial::~BBAreaLightMaterial() { } bool BBAreaLightMaterial::scatter(const BBRay &ray, const BBHitInfo &hitInfo, BBScatterInfo &scatterInfo) { return false; } QVector3D BBAreaLightMaterial::emitted(const QVector3D &position, const QVector2D &texcoords) { return m_Color; } /** * @brief BBLambertian::BBLambertian * @param albedo */ BBLambertian::BBLambertian(const QVector3D &albedo) { m_Albedo = albedo; } BBLambertian::~BBLambertian() { } bool BBLambertian::scatter(const BBRay &ray, const BBHitInfo &hitInfo, BBScatterInfo &scatterInfo) { scatterInfo.m_bSpecular = false; scatterInfo.m_ScatteredRay.setRay(hitInfo.m_Position, hemisphericalRandom(hitInfo.m_Normal)); scatterInfo.m_Attenuation = m_Albedo; return true; } QVector3D BBLambertian::emitted(const QVector3D &position, const QVector2D &texcoords) { return QVector3D(0, 0, 0); } /** * @brief BBMetal::BBMetal * @param albedo * @param fFuzz */ BBMetal::BBMetal(const QVector3D &albedo, float fFuzz) { m_Albedo = albedo; m_fFuzz = fFuzz < 1 ? fFuzz : 1; } BBMetal::~BBMetal() { } bool BBMetal::scatter(const BBRay &ray, const BBHitInfo &hitInfo, BBScatterInfo &scatterInfo) { QVector3D reflected = reflect(ray.getDirection(), hitInfo.m_Normal); QVector3D scatteredRayDir = reflected + m_fFuzz * sphericalRandom(); if (QVector3D::dotProduct(scatteredRayDir, hitInfo.m_Normal) <= 0) { return false; } scatterInfo.m_bSpecular = true; scatterInfo.m_ScatteredRay.setRay(hitInfo.m_Position, scatteredRayDir); scatterInfo.m_Attenuation = m_Albedo; return true; } QVector3D BBMetal::emitted(const QVector3D &position, const QVector2D &texcoords) { return QVector3D(0, 0, 0); } /** * @brief BBDielectric::BBDielectric * @param fRefractivity */ BBDielectric::BBDielectric(float fRefractivity) { m_fRefractivity = fRefractivity; } BBDielectric::~BBDielectric() { } bool BBDielectric::scatter(const BBRay &ray, const BBHitInfo &hitInfo, BBScatterInfo &scatterInfo) { QVector3D outNormal; QVector3D reflected = reflect(ray.getDirection(), hitInfo.m_Normal); float reflectance = 0.0f; // Transparent objects do not absorb energy scatterInfo.m_Attenuation = QVector3D(1, 1, 1); scatterInfo.m_bSpecular = true; QVector3D refracted = QVector3D(0, 0, 0); float fRefractivity = 1.0f; float cosRN = 0.0f; // When the light is transmitted from the medium to the outside of the medium, the normal will be reversed float cosLN = QVector3D::dotProduct(ray.getDirection(), hitInfo.m_Normal); if (cosLN > 0) { outNormal = -hitInfo.m_Normal; fRefractivity = m_fRefractivity; cosRN = fRefractivity * cosLN; } else { outNormal = hitInfo.m_Normal; fRefractivity = 1.0f / m_fRefractivity; cosRN = -cosLN; } // When there is no refraction, it reflects if (refract(ray.getDirection(), outNormal, fRefractivity, refracted)) { reflectance = schlick(cosRN, m_fRefractivity); } else { // The reflectance is 100% reflectance = 1.0f; } // Use probability to decide if (frandom() <= reflectance) { scatterInfo.m_ScatteredRay.setRay(hitInfo.m_Position, reflected); } else { scatterInfo.m_ScatteredRay.setRay(hitInfo.m_Position, refracted); } return true; } QVector3D BBDielectric::emitted(const QVector3D &position, const QVector2D &texcoords) { return QVector3D(0, 0, 0); } <|start_filename|>Code/BBearEditor/Engine/Scene/CoordinateSystem/BBCoordinateComponent.cpp<|end_filename|> #include "BBCoordinateComponent.h" #include "Render/BBMaterial.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BBRenderPass.h" #include "Render/BBDrawCall.h" #include "Render/BufferObject/BBElementBufferObject.h" /** * @brief BBCoordinateComponent::BBCoordinateComponent */ BBCoordinateComponent::BBCoordinateComponent() : BBCoordinateComponent(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBCoordinateComponent::BBCoordinateComponent(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBRenderableObject(px, py, pz, rx, ry, rz, sx, sy, sz) { m_SelectedAxis = BBAxisName::AxisNULL; } void BBCoordinateComponent::init() { m_pCurrentMaterial->init("coordinate", BB_PATH_RESOURCE_SHADER(coordinate.vert), BB_PATH_RESOURCE_SHADER(coordinate.frag)); m_pCurrentMaterial->getBaseRenderPass()->setBlendState(true); m_pCurrentMaterial->getBaseRenderPass()->setZFunc(GL_ALWAYS); // m_pCurrentMaterial->getBaseRenderPass()->setLineWidth(1.5f); BBRenderableObject::init(); } void BBCoordinateComponent::setSelectedAxis(const BBAxisFlags &axis) { if (axis == m_SelectedAxis) return; // The axis that was selected last time returns to normal if (m_SelectedAxis != BBAxisName::AxisNULL) { setVertexColor(m_SelectedAxis, false); } if (axis != BBAxisName::AxisNULL) { setVertexColor(axis, true); } m_SelectedAxis = axis; } void BBCoordinateComponent::setVertexColor(const BBAxisFlags &axis, bool bSelected) { int count1 = m_pVBO->getVertexCount() / 3; int count2 = count1 * 2; int count3 = m_pVBO->getVertexCount(); if (axis & BBAxisName::AxisX) { if (bSelected) { setVertexColor(0, count1, BBConstant::m_Yellow); } else { setVertexColor(0, count1, BBConstant::m_Red); } } if (axis & BBAxisName::AxisY) { if (bSelected) { setVertexColor(count1, count2, BBConstant::m_Yellow); } else { setVertexColor(count1, count2, BBConstant::m_Green); } } if (axis & BBAxisName::AxisZ) { if (bSelected) { setVertexColor(count2, count3, BBConstant::m_Yellow); } else { setVertexColor(count2, count3, BBConstant::m_Blue); } } // update m_pVBO->submitData(); } void BBCoordinateComponent::setVertexColor(int start, int end, const QVector3D &color) { for (int i = start; i < end; i++) { m_pVBO->setColor(i, color); } } void BBCoordinateComponent::setVertexColor(int start, int end, const QVector4D &color) { for (int i = start; i < end; i++) { m_pVBO->setColor(i, color); } } /** * @brief BBCoordinateArrow::BBCoordinateArrow */ BBCoordinateArrow::BBCoordinateArrow() : BBCoordinateArrow(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBCoordinateArrow::BBCoordinateArrow(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBCoordinateComponent(px, py, pz, rx, ry, rz, sx, sy, sz) { } void BBCoordinateArrow::init() { m_pVBO = new BBVertexBufferObject(39); m_pVBO->setPosition(0, 1.2f, 0.0f, 0.0f); m_pVBO->setPosition(1, 0.85f, 0.1f, 0.0f); m_pVBO->setPosition(2, 0.85f, 0.086603f, 0.05f); m_pVBO->setPosition(3, 0.85f, 0.05f, 0.086603f); m_pVBO->setPosition(4, 0.85f, 0.0f, 0.1f); m_pVBO->setPosition(5, 0.85f, -0.05f, 0.086603f); m_pVBO->setPosition(6, 0.85f, -0.086603f, 0.05f); m_pVBO->setPosition(7, 0.85f, -0.1f, 0.0f); m_pVBO->setPosition(8, 0.85f, -0.086603f, -0.05f); m_pVBO->setPosition(9, 0.85f, -0.05f, -0.086603f); m_pVBO->setPosition(10, 0.85f, 0.0f, -0.1f); m_pVBO->setPosition(11, 0.85f, 0.05f, -0.086603f); m_pVBO->setPosition(12, 0.85f, 0.086603f, -0.05f); for (int i = 0; i < 13; i++) m_pVBO->setColor(i, BBConstant::m_Red); m_pVBO->setPosition(13, 0.0f, 1.2f, 0.0f); m_pVBO->setPosition(14, 0.1f, 0.85f, 0.0f); m_pVBO->setPosition(15, 0.086603f, 0.85f, 0.05f); m_pVBO->setPosition(16, 0.05f, 0.85f, 0.086603f); m_pVBO->setPosition(17, 0.0f, 0.85f, 0.1f); m_pVBO->setPosition(18, -0.05f, 0.85f, 0.086603f); m_pVBO->setPosition(19, -0.086603f, 0.85f, 0.05f); m_pVBO->setPosition(20, -0.1f, 0.85f, 0.0f); m_pVBO->setPosition(21, -0.086603f, 0.85f, -0.05f); m_pVBO->setPosition(22, -0.05f, 0.85f, -0.086603f); m_pVBO->setPosition(23, 0.0f, 0.85f, -0.1f); m_pVBO->setPosition(24, 0.05f, 0.85f, -0.086603f); m_pVBO->setPosition(25, 0.086603f, 0.85f, -0.05f); for (int i = 13; i < 26; i++) m_pVBO->setColor(i, BBConstant::m_Green); m_pVBO->setPosition(26, 0.0f, 0.0f, 1.2f); m_pVBO->setPosition(27, 0.1f, 0.0f, 0.85f); m_pVBO->setPosition(28, 0.086603f, 0.05f, 0.85f); m_pVBO->setPosition(29, 0.05f, 0.086603f, 0.85f); m_pVBO->setPosition(30, 0.0f, 0.1f, 0.85f); m_pVBO->setPosition(31, -0.05f, 0.086603f, 0.85f); m_pVBO->setPosition(32, -0.086603f, 0.05f, 0.85f); m_pVBO->setPosition(33, -0.1f, 0.0f, 0.85f); m_pVBO->setPosition(34, -0.086603f, -0.05f, 0.85f); m_pVBO->setPosition(35, -0.05f, -0.086603f, 0.85f); m_pVBO->setPosition(36, 0.0f, -0.1f, 0.85f); m_pVBO->setPosition(37, 0.05f, -0.086603f, 0.85f); m_pVBO->setPosition(38, 0.086603f, -0.05f, 0.85f); for (int i = 26; i < 39; i++) m_pVBO->setColor(i, BBConstant::m_Blue); m_nIndexCount = 108; unsigned short indexes[] = {0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 6, 0, 6, 7, 0, 7, 8, 0, 8, 9, 0, 9, 10, 0, 10, 11, 0, 11, 12, 0, 12, 1, 13, 14, 15, 13, 15, 16, 13, 16, 17, 13, 17, 18, 13, 18, 19, 13, 19, 20, 13, 20, 21, 13, 21, 22, 13, 22, 23, 13, 23, 24, 13, 24, 25, 13, 25, 14, 26, 27, 28, 26, 28, 29, 26, 29, 30, 26, 30, 31, 26, 31, 32, 26, 32, 33, 26, 33, 34, 26, 34, 35, 26, 35, 36, 26, 36, 37, 26, 37, 38, 26, 38, 27}; m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0; i < m_nIndexCount; i++) { m_pIndexes[i] = indexes[i]; } BBCoordinateComponent::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_TRIANGLES, m_nIndexCount, 0); appendDrawCall(pDrawCall); } /** * @brief BBCoordinateAxis::BBCoordinateAxis */ BBCoordinateAxis::BBCoordinateAxis() : BBCoordinateAxis(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBCoordinateAxis::BBCoordinateAxis(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBCoordinateComponent(px, py, pz, rx, ry, rz, sx, sy, sz) { } void BBCoordinateAxis::init() { m_pVBO = new BBVertexBufferObject(6); m_pVBO->setPosition(0, 1.0f, 0.0f, 0.0f); m_pVBO->setPosition(1, 0.0f, 0.0f, 0.0f); m_pVBO->setPosition(2, 0.0f, 1.0f, 0.0f); m_pVBO->setPosition(3, 0.0f, 0.0f, 0.0f); m_pVBO->setPosition(4, 0.0f, 0.0f, 1.0f); m_pVBO->setPosition(5, 0.0f, 0.0f, 0.0f); for (int i = 0; i < 2; i++) { m_pVBO->setColor(i, BBConstant::m_Red); } for (int i = 2; i < 4; i++) { m_pVBO->setColor(i, BBConstant::m_Green); } for (int i = 4; i < 6; i++) { m_pVBO->setColor(i, BBConstant::m_Blue); } BBCoordinateComponent::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, GL_LINES, 0, 6); appendDrawCall(pDrawCall); } /** * @brief BBCoordinateRectFace::BBCoordinateRectFace */ BBCoordinateRectFace::BBCoordinateRectFace() : BBCoordinateRectFace(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBCoordinateRectFace::BBCoordinateRectFace(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBCoordinateComponent(px, py, pz, rx, ry, rz, sx, sy, sz) { } void BBCoordinateRectFace::init() { m_pVBO = new BBVertexBufferObject(24); // face m_pVBO->setPosition(0, 0.0f, 0.3f, 0.3f); m_pVBO->setPosition(1, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(2, 0.0f, 0.0f, 0.0f); m_pVBO->setPosition(3, 0.0f, 0.3f, 0.0f); m_pVBO->setPosition(4, 0.3f, 0.0f, 0.3f); m_pVBO->setPosition(5, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(6, 0.0f, 0.0f, 0.0f); m_pVBO->setPosition(7, 0.3f, 0.0f, 0.0f); m_pVBO->setPosition(8, 0.3f, 0.3f, 0.0f); m_pVBO->setPosition(9, 0.0f, 0.3f, 0.0f); m_pVBO->setPosition(10, 0.0f, 0.0f, 0.0f); m_pVBO->setPosition(11, 0.3f, 0.0f, 0.0f); // line m_pVBO->setPosition(12, 0.0f, 0.3f, 0.3f); m_pVBO->setPosition(13, 0.0f, 0.3f, 0.0f); m_pVBO->setPosition(14, 0.0f, 0.3f, 0.3f); m_pVBO->setPosition(15, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(16, 0.3f, 0.0f, 0.3f); m_pVBO->setPosition(17, 0.3f, 0.0f, 0.0f); m_pVBO->setPosition(18, 0.3f, 0.0f, 0.3f); m_pVBO->setPosition(19, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(20, 0.3f, 0.3f, 0.0f); m_pVBO->setPosition(21, 0.3f, 0.0f, 0.0f); m_pVBO->setPosition(22, 0.3f, 0.3f, 0.0f); m_pVBO->setPosition(23, 0.0f, 0.3f, 0.0f); for (int i = 0; i < 4; i++) { m_pVBO->setColor(i, BBConstant::m_RedTransparency); } for (int i = 4; i < 8; i++) { m_pVBO->setColor(i, BBConstant::m_GreenTransparency); } for (int i = 8; i < 12; i++) { m_pVBO->setColor(i, BBConstant::m_BlueTransparency); } for (int i = 12; i < 16; i++) { m_pVBO->setColor(i, BBConstant::m_Red); } for (int i = 16; i < 20; i++) { m_pVBO->setColor(i, BBConstant::m_Green); } for (int i = 20; i < 24; i++) { m_pVBO->setColor(i, BBConstant::m_Blue); } BBCoordinateComponent::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, GL_QUADS, 0, 12); appendDrawCall(pDrawCall); BBDrawCall *pDrawCall2 = new BBDrawCall; pDrawCall2->setMaterial(m_pCurrentMaterial); pDrawCall2->setVBO(m_pVBO, GL_LINES, 12, 24); appendDrawCall(pDrawCall2); } /** * @brief BBCoordinateQuarterCircle::BBCoordinateQuarterCircle */ BBCoordinateQuarterCircle::BBCoordinateQuarterCircle() : BBCoordinateQuarterCircle(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBCoordinateQuarterCircle::BBCoordinateQuarterCircle(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBCoordinateComponent(px, py, pz, rx, ry, rz, sx, sy, sz) { } void BBCoordinateQuarterCircle::init() { m_pVBO = new BBVertexBufferObject(78); for (int i = 0; i < 13; i++) { float c1 = cosf(0.1309 * i); float s1 = sinf(0.1309 * i); float c2 = 0.8f * c1; float s2 = 0.8f * s1; m_pVBO->setPosition(i, 0.0f, c1, s1); m_pVBO->setColor(i, BBConstant::m_Red); m_pVBO->setPosition(i + 13, 0.0f, c2, s2); m_pVBO->setColor(i + 13, BBConstant::m_Red); m_pVBO->setPosition(i + 26, c1, 0.0f, s1); m_pVBO->setColor(i + 26, BBConstant::m_Green); m_pVBO->setPosition(i + 39, c2, 0.0f, s2); m_pVBO->setColor(i + 39, BBConstant::m_Green); m_pVBO->setPosition(i + 52, c1, s1, 0.0f); m_pVBO->setColor(i + 52, BBConstant::m_Blue); m_pVBO->setPosition(i + 65, c2, s2, 0.0f); m_pVBO->setColor(i + 65, BBConstant::m_Blue); } m_nIndexCount = 144; m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0; i < 12; i++) { m_pIndexes[i * 4] = i; m_pIndexes[i * 4 + 1] = i + 1; m_pIndexes[i * 4 + 2] = i + 14; m_pIndexes[i * 4 + 3] = i + 13; m_pIndexes[i * 4 + 48] = i + 26; m_pIndexes[i * 4 + 49] = i + 27; m_pIndexes[i * 4 + 50] = i + 40; m_pIndexes[i * 4 + 51] = i + 39; m_pIndexes[i * 4 + 96] = i + 52; m_pIndexes[i * 4 + 97] = i + 53; m_pIndexes[i * 4 + 98] = i + 66; m_pIndexes[i * 4 + 99] = i + 65; } BBCoordinateComponent::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_QUADS, m_nIndexCount, 0); appendDrawCall(pDrawCall); } /** * @brief BBCoordinateCircle::BBCoordinateCircle */ BBCoordinateCircle::BBCoordinateCircle() : BBCoordinateCircle(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBCoordinateCircle::BBCoordinateCircle(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBCoordinateComponent(px, py, pz, rx, ry, rz, sx, sy, sz) { } void BBCoordinateCircle::init() { m_pVBO = new BBVertexBufferObject(96); for (int i = 0; i < 48; i++) { float c1 = cosf(0.1309 * i); float s1 = sinf(0.1309 * i); float c2 = 0.8f * c1; float s2 = 0.8f * s1; // Circle m_pVBO->setPosition(2 * i, 0.0f, c1, s1); m_pVBO->setColor(2 * i, BBConstant::m_Yellow); m_pVBO->setPosition(2 * i + 1, 0.0f, c2, s2); m_pVBO->setColor(2 * i + 1, BBConstant::m_Yellow); } m_nIndexCount = 192; m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0, j = 0; i < 48; i++, j+=2) { m_pIndexes[i * 4] = j; m_pIndexes[i * 4 + 1] = j + 1; m_pIndexes[i * 4 + 2] = j + 3; m_pIndexes[i * 4 + 3] = j + 2; } m_pIndexes[190] = 1; m_pIndexes[191] = 0; BBCoordinateComponent::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_QUADS, m_nIndexCount, 0); appendDrawCall(pDrawCall); } /** * @brief BBCoordinateTickMark::BBCoordinateTickMark */ BBCoordinateTickMark::BBCoordinateTickMark() : BBCoordinateTickMark(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBCoordinateTickMark::BBCoordinateTickMark(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBCoordinateComponent(px, py, pz, rx, ry, rz, sx, sy, sz) { } void BBCoordinateTickMark::init() { // unit = 10 degree, 360/10*2 = 72 Circles m_pVBO = new BBVertexBufferObject(72); for (int i = 0; i < 36; i++) { float c1 = cosf(0.174533f * i); float s1 = sinf(0.174533f * i); float c2; float s2; //0 30 60... there is a longer tick mark if (i % 3 == 0) { c2 = 0.86f * c1; s2 = 0.86f * s1; } else { c2 = 0.93f * c1; s2 = 0.93f * s1; } // Circle m_pVBO->setPosition(2 * i, 0.0f, c1, s1); m_pVBO->setColor(2 * i, BBConstant::m_Gray); m_pVBO->setPosition(2 * i + 1, 0.0f, c2, s2); m_pVBO->setColor(2 * i + 1, BBConstant::m_Gray); } BBCoordinateComponent::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, GL_LINES, 0, 72); appendDrawCall(pDrawCall); } /** * @brief BBCoordinateSector::BBCoordinateSector */ BBCoordinateSector::BBCoordinateSector() : BBCoordinateSector(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBCoordinateSector::BBCoordinateSector(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBCoordinateComponent(px, py, pz, rx, ry, rz, sx, sy, sz) { reset(); } void BBCoordinateSector::init() { // unit = 1 2pi/360 // +1 is center of circle m_pVBO = new BBVertexBufferObject(361); m_pVBO->setPosition(360, 0.0f, 0.0f, 0.0f); m_pVBO->setColor(360, BBConstant::m_GrayTransparency); for (int i = 0; i < 360; i++) { float c = 0.8f * cosf(0.017453f * i); float s = 0.8f * sinf(0.017453f * i); // on the circle m_pVBO->setPosition(i, 0.0f, c, s); m_pVBO->setColor(i, BBConstant::m_Gray); } m_nIndexCount = 1080; m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0; i < 360; i++) { m_pIndexes[3 * i] = 360; m_pIndexes[3 * i + 1] = i; m_pIndexes[3 * i + 2] = i + 1; } m_pIndexes[1079] = 0; BBCoordinateComponent::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); appendDrawCall(pDrawCall); } void BBCoordinateSector::render(BBCamera *pCamera) { if (m_nAngle != 0) { // unit = 1 degree, 1 triangle, 3 indexes int nIndexCount = abs(m_nAngle) * 3; unsigned short *pIndexes = new unsigned short[nIndexCount]; // if the angle is positive, show sector in front semicircle if (m_nAngle > 0) { for (int i = 0; i < nIndexCount; i++) { pIndexes[i] = m_pIndexes[i]; } } // if the angle is negative, show sector in back semicircle else { for (int i = 0; i < nIndexCount; i++) { pIndexes[i] = m_pIndexes[m_nIndexCount - i - 1]; } } m_pEBO->submitData(pIndexes, nIndexCount); m_pDrawCalls->setEBO(m_pEBO, GL_TRIANGLES, abs(m_nAngle) * 3, 0); } BBCoordinateComponent::render(pCamera); } void BBCoordinateSector::setAngle(int nDeltaAngle) { m_nAngle += nDeltaAngle; // m_nAngle in [-360, 360] if (m_nAngle > 360) { m_nAngle -= 360; } else if (m_nAngle < -360) { m_nAngle += 360; } } void BBCoordinateSector::reset() { m_nAngle = 0; } /** * @brief BBCoordinateCube::BBCoordinateCube */ QVector3D BBCoordinateCube::m_Sign[8] = { QVector3D(1, 1, 1), QVector3D(1, -1, 1), QVector3D(1, -1, -1), QVector3D(1, 1, -1), QVector3D(-1, 1, 1), QVector3D(-1, -1, 1), QVector3D(-1, -1, -1), QVector3D(-1, 1, -1) }; BBCoordinateCube::BBCoordinateCube() : BBCoordinateCube(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBCoordinateCube::BBCoordinateCube(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBCoordinateComponent(px, py, pz, rx, ry, rz, sx, sy, sz) { m_fHalfLength = 0.08f; } void BBCoordinateCube::init() { m_pVBO = new BBVertexBufferObject(24); for (int i = 0; i < 8; i++) { m_pVBO->setPosition(i, 1.0f + m_Sign[i].x() * m_fHalfLength, m_Sign[i].y() * m_fHalfLength, m_Sign[i].z() * m_fHalfLength); m_pVBO->setColor(i, BBConstant::m_Red); m_pVBO->setPosition(i + 8, m_Sign[i].x() * m_fHalfLength, 1.0f + m_Sign[i].y() * m_fHalfLength, m_Sign[i].z() * m_fHalfLength); m_pVBO->setColor(i + 8, BBConstant::m_Green); m_pVBO->setPosition(i + 16, m_Sign[i].x() * m_fHalfLength, m_Sign[i].y() * m_fHalfLength, 1.0f + m_Sign[i].z() * m_fHalfLength); m_pVBO->setColor(i + 16, BBConstant::m_Blue); } m_nIndexCount = 72; m_pIndexes = new unsigned short[m_nIndexCount]; unsigned short indexes[] = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 5, 4, 3, 7, 6, 2, 0, 4, 7, 3, 1, 5, 6, 2}; for (int i = 0; i < 24; i++) { m_pIndexes[i] = indexes[i]; m_pIndexes[i + 24] = indexes[i] + 8; m_pIndexes[i + 48] = indexes[i] + 16; } BBCoordinateComponent::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_QUADS, m_nIndexCount, 0); appendDrawCall(pDrawCall); } void BBCoordinateCube::move(const QVector3D &delta) { // the size of the cube does not change // As scale, the position of cube changes for (int i = 0; i < 8; i++) { m_pVBO->setPosition(i, m_Sign[i].x() * m_fHalfLength + 1.0f + delta.x(), m_Sign[i].y() * m_fHalfLength, m_Sign[i].z() * m_fHalfLength); m_pVBO->setPosition(i + 8, m_Sign[i].x() * m_fHalfLength, m_Sign[i].y() * m_fHalfLength + 1.0f + delta.y(), m_Sign[i].z() * m_fHalfLength); m_pVBO->setPosition(i + 16, m_Sign[i].x() * m_fHalfLength, m_Sign[i].y() * m_fHalfLength, m_Sign[i].z() * m_fHalfLength + 1.0f + delta.z()); } m_pVBO->submitData(); } /** * @brief BBCoordinateTriangleFace::BBCoordinateTriangleFace */ BBCoordinateTriangleFace::BBCoordinateTriangleFace() : BBCoordinateTriangleFace(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBCoordinateTriangleFace::BBCoordinateTriangleFace(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBCoordinateComponent(px, py, pz, rx, ry, rz, sx, sy, sz) { } void BBCoordinateTriangleFace::init() { m_pVBO = new BBVertexBufferObject(36); // GL_TRIANGLES m_pVBO->setPosition(0, 0.0f, 0.0f, 0.0f); m_pVBO->setPosition(1, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(2, 0.0f, 0.3f, 0.0f); m_pVBO->setPosition(3, 0.0f, 0.3f, 0.3f); m_pVBO->setPosition(4, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(5, 0.0f, 0.3f, 0.0f); m_pVBO->setPosition(6, 0.0f, 0.0f, 0.0f); m_pVBO->setPosition(7, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(8, 0.3f, 0.0f, 0.0f); m_pVBO->setPosition(9, 0.3f, 0.0f, 0.3f); m_pVBO->setPosition(10, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(11, 0.3f, 0.0f, 0.0f); m_pVBO->setPosition(12, 0.0f, 0.0f, 0.0f); m_pVBO->setPosition(13, 0.0f, 0.3f, 0.0f); m_pVBO->setPosition(14, 0.3f, 0.0f, 0.0f); m_pVBO->setPosition(15, 0.3f, 0.3f, 0.0f); m_pVBO->setPosition(16, 0.0f, 0.3f, 0.0f); m_pVBO->setPosition(17, 0.3f, 0.0f, 0.0f); // GL_LINES m_pVBO->setPosition(18, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(19, 0.0f, 0.3f, 0.0f); m_pVBO->setPosition(20, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(21, 0.0f, 0.3f, 0.3f); m_pVBO->setPosition(22, 0.0f, 0.3f, 0.0f); m_pVBO->setPosition(23, 0.0f, 0.3f, 0.3f); m_pVBO->setPosition(24, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(25, 0.3f, 0.0f, 0.0f); m_pVBO->setPosition(26, 0.0f, 0.0f, 0.3f); m_pVBO->setPosition(27, 0.3f, 0.0f, 0.3f); m_pVBO->setPosition(28, 0.3f, 0.0f, 0.0f); m_pVBO->setPosition(29, 0.3f, 0.0f, 0.3f); m_pVBO->setPosition(30, 0.0f, 0.3f, 0.0f); m_pVBO->setPosition(31, 0.3f, 0.0f, 0.0f); m_pVBO->setPosition(32, 0.0f, 0.3f, 0.0f); m_pVBO->setPosition(33, 0.3f, 0.3f, 0.0f); m_pVBO->setPosition(34, 0.3f, 0.0f, 0.0f); m_pVBO->setPosition(35, 0.3f, 0.3f, 0.0f); for (int i = 0; i < 6; i++) { m_pVBO->setColor(i, BBConstant::m_RedTransparency); } for (int i = 6; i < 12; i++) { m_pVBO->setColor(i, BBConstant::m_GreenTransparency); } for (int i = 12; i < 18; i++) { m_pVBO->setColor(i, BBConstant::m_BlueTransparency); } for (int i = 18; i < 24; i++) { m_pVBO->setColor(i, BBConstant::m_Red); } for (int i = 24; i < 30; i++) { m_pVBO->setColor(i, BBConstant::m_Green); } for (int i = 30; i < 36; i++) { m_pVBO->setColor(i, BBConstant::m_Blue); } BBCoordinateComponent::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, GL_TRIANGLES, 0, 18); appendDrawCall(pDrawCall); BBDrawCall *pDrawCall2 = new BBDrawCall; pDrawCall2->setMaterial(m_pCurrentMaterial); pDrawCall2->setVBO(m_pVBO, GL_LINES, 18, 36); appendDrawCall(pDrawCall2); } <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBRenderManager.cpp<|end_filename|> #include "BBRenderManager.h" #include "Dialog/BBResourceDialog.h" #include "3D/BBNormalIndicator.h" #include "Scene/BBScene.h" #include "Scene/BBRendererManager.h" #include "Scene/BBSceneManager.h" #include "../BBPropertyFactory.h" #include "FileSystem/BBFileSystemDataManager.h" #include "3D/BBNormalIndicator.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BBMaterial.h" #include "Render/BBRenderPass.h" BBRenderManager::BBRenderManager(BBRenderableObject *pObject, QWidget *pParent) : BBGroupManager("Render", BB_PATH_RESOURCE_ICON(render.png), pParent) { m_pRenderableObject = pObject; QString materialPath = BBRendererManager::getMaterialPath(pObject->getMaterial()); QString materialPath2 = BBRendererManager::getMaterialPath(pObject->getExtraMaterial(EXTRA_MATERIAL_INDEX_2));; m_pAttributeColorFactory = new BBColorFactory(1.0f, 1.0f, 1.0f, 1.0f, this); addFactory("Attribute Color", m_pAttributeColorFactory, 1); QObject::connect(m_pAttributeColorFactory, SIGNAL(colorChanged(float, float, float, float)), this, SLOT(changeAttributeColor(float, float, float, float))); m_pMaterialFactory = new BBDragAcceptedFactory(BB_PATH_RESOURCE_ICON(material5.png), materialPath, this); m_pMaterialFactory->setFilter(BBFileSystemDataManager::m_MaterialSuffixs); addFactory("Material", m_pMaterialFactory, 1); QObject::connect(m_pMaterialFactory, SIGNAL(iconClicked()), this, SLOT(popupResourceDialog())); QObject::connect(m_pMaterialFactory, SIGNAL(currentFilePathChanged(QString)), this, SLOT(changeMaterial(QString))); m_pMaterialFactory2 = new BBDragAcceptedFactory(BB_PATH_RESOURCE_ICON(material5.png), materialPath2, this); m_pMaterialFactory2->setFilter(BBFileSystemDataManager::m_MaterialSuffixs); addFactory("Material2", m_pMaterialFactory2, 1); QObject::connect(m_pMaterialFactory2, SIGNAL(currentFilePathChanged(QString)), this, SLOT(changeMaterial2(QString))); QCheckBox *pNormalIndicatorTrigger = new QCheckBox(this); addFactory("Normal Indicator", pNormalIndicatorTrigger, 1, Qt::AlignRight); QObject::connect(pNormalIndicatorTrigger, SIGNAL(clicked(bool)), this, SLOT(triggerNormalIndicator(bool))); QCheckBox *pLinePolygonModeTrigger = new QCheckBox(this); addFactory("Line PolygonMode", pLinePolygonModeTrigger, 1, Qt::AlignRight); QObject::connect(pLinePolygonModeTrigger, SIGNAL(clicked(bool)), this, SLOT(triggerLinePolygonMode(bool))); } BBRenderManager::~BBRenderManager() { BB_SAFE_DELETE(m_pAttributeColorFactory); BB_SAFE_DELETE(m_pMaterialFactory); BB_SAFE_DELETE(m_pMaterialFactory2); } void BBRenderManager::changeAttributeColor(float r, float g, float b, float a) { m_pRenderableObject->getVBO()->setColor(r, g, b, a); } void BBRenderManager::changeMaterial(const QString &filePath) { m_pRenderableObject->setCurrentMaterial(BBRendererManager::loadMaterial(filePath)); } void BBRenderManager::changeMaterial2(const QString &filePath) { m_pRenderableObject->setExtraMaterial(EXTRA_MATERIAL_INDEX_2, BBRendererManager::loadMaterial(filePath)); } void BBRenderManager::popupResourceDialog() { BBResourceDialog dialog(BB_PATH_RESOURCE_MATERIAL, this); if (dialog.exec()) { m_pMaterialFactory->changeCurrentFilePath(dialog.getCurrentItemFilePath()); } } void BBRenderManager::triggerNormalIndicator(bool bEnable) { BBNormalIndicator *pNormalIndicator = BBSceneManager::getScene()->getNormalIndicator(); if (bEnable) { pNormalIndicator->init(m_pRenderableObject); pNormalIndicator->setActivity(true); } else { pNormalIndicator->setActivity(false); } } void BBRenderManager::triggerLinePolygonMode(bool bEnable) { if (bEnable) { m_pRenderableObject->getMaterial()->getBaseRenderPass()->setPolygonMode(GL_LINE); } else { m_pRenderableObject->getMaterial()->getBaseRenderPass()->setPolygonMode(GL_FILL); } } <|start_filename|>Code/BBearEditor/Engine/3D/Mesh/BBMesh.h<|end_filename|> #ifndef BBMESH_H #define BBMESH_H #include "Base/BBRenderableObject.h" enum BBMeshType { OBJ = 0x01, FBX = 0x02, TERRAIN = 0x04, AREALIGHT = 0x08, PROCEDURE_MESH = 0x16 }; class BBBoundingBox3D; class BBMesh : public BBRenderableObject { public: BBMesh(); BBMesh(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); virtual void init(const QString &path, BBBoundingBox3D *&pOutBoundingBox); void init(BBVertexBufferObject *pVBO, GLenum eDrawPrimitiveType, int nDrawStartIndex, int nDrawCount, BBBoundingBox3D *&pOutBoundingBox); void setExtraMaterial(int nMaterialIndex, BBMaterial *pMaterial) override; void setMeshType(const BBMeshType &eMeshType) { m_eMeshType = eMeshType; } BBMeshType getMeshType() { return m_eMeshType; } bool hit(const BBRay &ray, float &fDistance) override; bool hit(const BBRay &ray, float fMinDistance, float fMaxDistance, BBHitInfo &hitInfo); protected: virtual void load(const QString &path, QList<QVector4D> &outPositions) = 0; GLenum m_eDrawPrimitiveType; // Some meshes are composed of multiple primitivetypes and require multiple sets of data representation BBElementBufferObject *m_pEBO2; unsigned short *m_pIndexes2; int m_nIndexCount2; BBMeshType m_eMeshType; }; #endif // BBMESH_H <|start_filename|>Code/BBearEditor/Engine/Render/OfflineRenderer/BBOfflineRenderer.h<|end_filename|> #ifndef BBOFFLINERENDERER_H #define BBOFFLINERENDERER_H #include <QImage> #define TestModelCount 9 class BBScene; class BBMaterial; class BBModel; class BBAreaLight; class BBPhotonMap; class BBOfflineRenderer { public: BBOfflineRenderer(BBScene *pScene); virtual ~BBOfflineRenderer(); void createTestScene(); void startPhotonMapping(); private: void renderFrame(); void showFrame(); void generatePhotonMap(); void showPhotonMap(); private: BBScene *m_pScene; BBMaterial *m_pMaterial; int m_nWidth; int m_nHeight; BBModel *m_pModels[TestModelCount]; BBAreaLight *m_pAreaLight; BBPhotonMap *m_pPhotonMap; QImage m_CurrentImage; int m_nBlendFrameCount; }; #endif // BBOFFLINERENDERER_H <|start_filename|>Code/BBearEditor/Engine/Physics/FluidSystem/BBSPHParticleNeighborTable.h<|end_filename|> #ifndef BBSPHPARTICLENEIGHBORTABLE_H #define BBSPHPARTICLENEIGHBORTABLE_H #define MAX_NEIGHBOR_COUNT 20 struct BBNeighborDataBufferCode { unsigned int m_nCurrentNeighborCount; unsigned int m_nNeighborDataBufferOffset; }; class BBSPHParticleNeighborTable { public: BBSPHParticleNeighborTable(); virtual ~BBSPHParticleNeighborTable(); void reset(unsigned int nParticleCount); void setCurrentParticle(unsigned int nParticleIndex); bool addNeighborParticle(unsigned int nNeighborIndex, float fNeighborDistance); // current -> m_pNeighborDataBuffer; record code void recordCurrentNeighbor(); int getNeighborCount(unsigned int nCurrentParticleIndex); void getNeighborInfo(unsigned int nCurrentParticleIndexInBuffer, unsigned int nNeighborParticleIndexInNeighborTable, unsigned int &nNeighborParticleIndexInBuffer, float &fNeighborParticleDistance); private: void extendNeighborDataBuffer(unsigned int nNeedSize); unsigned int m_nParticleCount; unsigned int m_nParticleCapacity; unsigned char *m_pNeighborDataBuffer; unsigned int m_nNeighborDataBufferSize; unsigned int m_nNeighborDataBufferOffset; // Guide how to get data from m_pNeighborDataBuffer BBNeighborDataBufferCode *m_pNeighborDataBufferCode; // The data of current particle unsigned int m_nCurrentParticleIndex; int m_nCurrentNeighborCount; unsigned int m_CurrentNeighborIndexes[MAX_NEIGHBOR_COUNT]; float m_CurrentNeighborDistances[MAX_NEIGHBOR_COUNT]; }; #endif // BBSPHPARTICLENEIGHBORTABLE_H <|start_filename|>Code/BBearEditor/Engine/Render/BBDrawCall.h<|end_filename|> #ifndef BBDRAWCALL_H #define BBDRAWCALL_H #include "BBMaterial.h" #include "BBLinkedList.h" class BBCamera; class BBCanvas; class BBVertexBufferObject; class BBElementBufferObject; class BBGameObject; class BBDrawCall; class BBRenderableObject; class BBRenderQueue; class BBShaderStorageBufferObject; class BBAtomicCounterBufferObject; typedef void (BBDrawCall::*BBDrawFunc)(BBCamera *pCamera); typedef void (BBDrawCall::*BBUpdateOrderInRenderQueueFunc)(); typedef void (BBDrawCall::*BBBindFunc)(); typedef void (BBDrawCall::*BBUnbindFunc)(); typedef void (BBDrawCall::*BBDrawBufferObjectFunc)(GLenum eDrawPrimitiveType, int nDrawStartIndex, int nDrawCount); class BBDrawCall : public BBBaseRenderComponent, public BBLinkedList { public: BBDrawCall(); void setMaterial(BBMaterial *pMaterial); void updateMaterialBlendState(bool bEnable); void setVBO(BBVertexBufferObject *pVBO, GLenum eDrawPrimitiveType = GL_TRIANGLES, int nDrawStartIndex = 0, int nDrawCount = 3); void setSSBO(BBShaderStorageBufferObject *pSSBO, GLenum eDrawPrimitiveType = GL_TRIANGLES, int nDrawStartIndex = 0, int nDrawCount = 3); void setACBO(BBAtomicCounterBufferObject *pACBO, bool bClear); void removeACBO() { m_pACBO = nullptr; } void setEBO(BBElementBufferObject *pEBO, GLenum eDrawPrimitiveType, int nIndexCount, int nDrawStartIndex); void setVisibility(bool bVisible) { m_bVisible = bVisible; } void updateOrderInRenderQueue(const QVector3D &renderableObjectPosition); float getDistanceToCamera(BBCamera *pCamera); void draw(BBCamera *pCamera); public: inline BBMaterial* getMaterial() { return m_pMaterial; } public: static void switchRenderingSettings(int nIndex); void renderOnePass(BBCamera *pCamera); void renderOnePass(BBCamera *pCamera, QList<BBGameObject*> lights); void renderOnePassSSBO(BBCamera *pCamera); void renderForwardPass(BBCamera *pCamera); void renderUIPass(BBCanvas *pCanvas); void renderViewSpaceFBOPass(BBCamera *pCamera); void renderLightSpaceFBOPass(BBCamera *pCamera); private: void updateOrderInOpaqueRenderQueue(); void updateOrderInTransparentRenderQueue(); BBUpdateOrderInRenderQueueFunc m_UpdateOrderInRenderQueueFunc; private: void bindBufferObject(); void unbindBufferObject(); void bindVBO(); void unbindVBO(); void bindSSBO(); void unbindSSBO(); void drawBufferObject(GLenum eDrawPrimitiveType, int nDrawStartIndex, int nDrawCount); void drawVBO(GLenum eDrawPrimitiveType, int nDrawStartIndex, int nDrawCount); void drawSSBO(GLenum eDrawPrimitiveType, int nDrawStartIndex, int nDrawCount); BBBindFunc m_BindFunc; BBUnbindFunc m_UnbindFunc; BBDrawBufferObjectFunc m_DrawBufferObjectFunc; private: QList<BBGameObject*> collectLights(); static BBDrawFunc m_DrawFunc; BBMaterial *m_pMaterial; GLenum m_eDrawPrimitiveType; int m_nDrawStartIndex; BBVertexBufferObject *m_pVBO; BBShaderStorageBufferObject *m_pSSBO; bool m_bClearACBO; BBAtomicCounterBufferObject *m_pACBO; int m_nDrawCount; BBElementBufferObject *m_pEBO; int m_nIndexCount; QVector3D m_RenderableObjectPosition; bool m_bVisible; }; #endif // BBDRAWCALL_H <|start_filename|>Code/BBearEditor/Editor/Common/BBTreeWidget.h<|end_filename|> #ifndef BBTREEWIDGET_H #define BBTREEWIDGET_H #include <QLineEdit> #include <QTreeWidget> #include "Utils/BBUtils.h" #include <QTime> class BBLineEdit : public QLineEdit { Q_OBJECT public: explicit BBLineEdit(QWidget *parent = 0); signals: void finishEdit(); private: void focusOutEvent(QFocusEvent *event) override; void keyPressEvent(QKeyEvent *event) override; }; // drop target enum BBIndicatorPos { // drop in the item rect CENTER = 0x01, // drop between two items TOP = 0x02, BOTTOM = 0x04 }; class BBTreeWidget : public QTreeWidget { Q_OBJECT public: virtual QString getMimeType() { return BB_MIMETYPE_TREEWIDGET; } explicit BBTreeWidget(QWidget *parent = 0); virtual ~BBTreeWidget(); public: static QString getLevelPath(QTreeWidgetItem *pItem); protected: void startDrag(Qt::DropActions supportedActions) override; virtual bool moveItem(); virtual bool moveItemFromFileList(const QMimeData *pMimeData); virtual bool moveItemFromOthers(const QMimeData *pMimeData); void dragEnterEvent(QDragEnterEvent *event) override; void dragMoveEvent(QDragMoveEvent *event) override; void dragLeaveEvent(QDragLeaveEvent *event) override; void dropEvent(QDropEvent *event) override; void paintEvent(QPaintEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void contextMenuEvent(QContextMenuEvent *event) override; void keyPressEvent(QKeyEvent *event) override; void focusInEvent(QFocusEvent *event) override; QTreeWidgetItem *m_pIndicatorItem; BBIndicatorPos m_eIndicatorPos; QMenu *m_pMenu; QList<QTreeWidgetItem*> m_ClipBoardItems; QTreeWidgetItem *m_pLastItem; QTime m_LastTime; QTreeWidgetItem *m_pEditingItem; BBLineEdit *m_pRenameEditor; protected: virtual void setMenu() = 0; void filterSelectedItems(); QTreeWidgetItem* getParentOfMovingItem(int &nIndex); // drag, Which column of icons to use virtual int getDragIconColumnIndex() { return 0; } virtual void pasteOne(QTreeWidgetItem *pSource, QTreeWidgetItem* pTranscript); virtual void pasteEnd(); void deleteAction(QTreeWidgetItem *pItem); virtual void deleteOne(QTreeWidgetItem *pItem); protected slots: virtual void copyAction(); virtual void pasteAction(); void openRenameEditor(); virtual void finishRename(); virtual void deleteAction(); }; #endif // BBTREEWIDGET_H <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFileSystemManager.h<|end_filename|> #ifndef BBFILESYSTEMMANAGER_H #define BBFILESYSTEMMANAGER_H #include <QString> #include "Utils/BBUtils.h" using namespace BBFileSystem; class BBPreviewOpenGLWidget; class BBFolderTreeWidget; class BBFileListWidget; class BBFilePathBarWidget; class BBFileSystemDataManager; class BBFileSystemManager { public: BBFileSystemManager(BBFolderTreeWidget *pFolderTreeWidget, BBFileListWidget *pFileListWidget, BBFilePathBarWidget *pFilePathBarWidget); ~BBFileSystemManager(); BBFileListWidget* getFileListWidget() { return m_pFileListWidget; } void bindPreviewOpenGLWidget(BBPreviewOpenGLWidget *pPreviewOpenGLWidget); void createProject(); void openProject(); void clickItemInFolderTree(const QString &filePath, QTreeWidgetItem *pItem); void doubleClickItemInFileList(const QString &filePath); void clickItemInFolderPathBar(const QString &filePath); void setCurrentItemInFileList(QListWidgetItem *pItem); void newFolder(const QString &parentPath, const BBSignalSender &eSender); void newFile(const QString &parentPath, int nType); void saveScene(); void showInFolder(const QString &filePath); void renameInFolderTree(QTreeWidgetItem *pParentFolderItem, const QString &oldPath, const QString &newPath); void renameInFileList(QListWidgetItem *pFileItem, const QString &oldPath, const QString &newPath); void deleteFolderInFolderTree(QTreeWidgetItem *pItem); void deleteFilesInFileList(const QList<QListWidgetItem*> &items); void importAsset(const QString &parentPath, const QList<QUrl> &urls); void moveFolders(const QList<QTreeWidgetItem*> &items, QTreeWidgetItem *pNewParentItem, bool bCopy); void moveFolders(const QList<QString> &oldFilePaths, const QString &newParentPath, bool bCopy); void moveFiles(const QList<QString> &oldFilePaths, QTreeWidgetItem *pNewParentItem, bool bCopy); void moveFiles(const QList<QListWidgetItem*> &items, const QString &oldParentPath, const QString &newParentPath, bool bCopy); void updateAll(); private: void clearFolderTree(); void setFolderTree(); void setFolderTreeCurrentItem(const QString &filePath); void updateFileList(const QString &parentPath, QTreeWidgetItem *pParentFolderItem, QListWidgetItem *pCurrentItem); void updateFileList(const QString &parentPath, QListWidgetItem *pCurrentItem); void updateFolderPathBar(const QString &filePath); void rename(QTreeWidgetItem *pParentFolderItem, QListWidgetItem *pFileItem, const QString &oldPath, const QString &newPath); BBFolderTreeWidget *m_pFolderTreeWidget; BBFileListWidget *m_pFileListWidget; BBFilePathBarWidget *m_pFilePathBarWidget; BBFileSystemDataManager *m_pDataManager; }; #endif // BBFILESYSTEMMANAGER_H <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFileSystemManager.cpp<|end_filename|> #include "BBFileSystemManager.h" #include "Render/BBOpenGLWidget.h" #include "BBFileSystemDataManager.h" #include "BBFolderTreeWidget.h" #include "BBFileListWidget.h" #include "BBFilePathBarWidget.h" #include "Scene/BBSceneManager.h" BBFileSystemManager::BBFileSystemManager(BBFolderTreeWidget *pFolderTreeWidget, BBFileListWidget *pFileListWidget, BBFilePathBarWidget *pFilePathBarWidget) { m_pFolderTreeWidget = pFolderTreeWidget; m_pFileListWidget = pFileListWidget; m_pFilePathBarWidget = pFilePathBarWidget; m_pDataManager = new BBFileSystemDataManager(); // m_pDataManager->bindPreviewOpenGLWidget(m_pPreviewOpenGLWidget); } BBFileSystemManager::~BBFileSystemManager() { BB_SAFE_DELETE(m_pDataManager); } void BBFileSystemManager::bindPreviewOpenGLWidget(BBPreviewOpenGLWidget *pPreviewOpenGLWidget) { m_pDataManager->bindPreviewOpenGLWidget(pPreviewOpenGLWidget); } void BBFileSystemManager::createProject() { // //新项目预创建直射光 // GameObject *object = ui->openGLWidget->scene.createLight("directional light.png", 650, 300); // //结点加入层级视图 // ui->treeHierarchy->addGameObjectSlot(object); // //取消直射光的选中状态 // ui->treeHierarchy->cancelSelectedItems(); } void BBFileSystemManager::openProject() { // load file system m_pDataManager->load(); setFolderTree(); updateFileList(BBConstant::BB_PATH_PROJECT_USER, NULL, NULL); updateFolderPathBar(BBConstant::BB_PATH_PROJECT_USER); } void BBFileSystemManager::clickItemInFolderTree(const QString &filePath, QTreeWidgetItem *pItem) { m_pDataManager->setCurrentViewedItem(pItem); updateFileList(filePath, pItem, NULL); updateFolderPathBar(filePath); } void BBFileSystemManager::doubleClickItemInFileList(const QString &filePath) { QString updatedPath = filePath; if (m_pDataManager->openFile(filePath)) { updatedPath = BBFileSystemDataManager::getParentPath(filePath); } // when this is a folder, need to update and access new folder setFolderTreeCurrentItem(updatedPath); updateFileList(updatedPath, NULL); updateFolderPathBar(updatedPath); } void BBFileSystemManager::clickItemInFolderPathBar(const QString &filePath) { setFolderTreeCurrentItem(filePath); updateFileList(filePath, NULL); updateFolderPathBar(filePath); } void BBFileSystemManager::setCurrentItemInFileList(QListWidgetItem *pItem) { m_pFileListWidget->setCurrentItem(pItem); } void BBFileSystemManager::newFolder(const QString &parentPath, const BBSignalSender &eSender) { clearFolderTree(); QTreeWidgetItem *pFolderItem = NULL; QListWidgetItem *pFileItem = NULL; if (m_pDataManager->newFolder(parentPath, pFolderItem, pFileItem)) { // if list is showing parentPath if (m_pFileListWidget->getCurrentParentPath() == parentPath) { updateFileList(parentPath, pFileItem); } if (eSender == BBSignalSender::FolderTree) { m_pFolderTreeWidget->setCurrentItem(pFolderItem); } } setFolderTree(); } void BBFileSystemManager::newFile(const QString &parentPath, int nType) { QListWidgetItem *pCurrentItem = NULL; if (m_pDataManager->newFile(parentPath, nType, pCurrentItem)) { if (m_pFileListWidget->getCurrentParentPath() == parentPath) { updateFileList(parentPath, m_pDataManager->getCurrentViewedItem(), pCurrentItem); } } } void BBFileSystemManager::saveScene() { QListWidgetItem *pCurrentItem = NULL; if (m_pDataManager->saveScene(BBFileSystemDataManager::getAbsolutePath(m_pDataManager->getCurrentViewedItem()), pCurrentItem)) { updateFileList(BBFileSystemDataManager::getAbsolutePath(m_pDataManager->getCurrentViewedItem()), pCurrentItem); } } void BBFileSystemManager::showInFolder(const QString &filePath) { m_pDataManager->showInFolder(filePath); } void BBFileSystemManager::renameInFolderTree(QTreeWidgetItem *pParentFolderItem, const QString &oldPath, const QString &newPath) { QListWidgetItem *pFileItem = m_pDataManager->getFileItem(pParentFolderItem, oldPath); BB_PROCESS_ERROR_RETURN(pFileItem); rename(pParentFolderItem, pFileItem, oldPath, newPath); } void BBFileSystemManager::renameInFileList(QListWidgetItem *pFileItem, const QString &oldPath, const QString &newPath) { QTreeWidgetItem *pParentFolderItem = m_pDataManager->getParentFolderItem(oldPath); rename(pParentFolderItem, pFileItem, oldPath, newPath); } void BBFileSystemManager::deleteFolderInFolderTree(QTreeWidgetItem *pItem) { BB_PROCESS_ERROR_RETURN(m_pDataManager->deleteFolder(pItem)); // no need to update, since this is to handle single item // when delete action is over, we will update } void BBFileSystemManager::deleteFilesInFileList(const QList<QListWidgetItem*> &items) { clearFolderTree(); QTreeWidgetItem *pParentItem = m_pDataManager->getCurrentViewedItem(); QString parentPath = m_pFileListWidget->getCurrentParentPath(); if (m_pDataManager->deleteFiles(pParentItem, parentPath, items)) { updateFileList(parentPath, pParentItem, NULL); } setFolderTree(); } void BBFileSystemManager::importAsset(const QString &parentPath, const QList<QUrl> &urls) { clearFolderTree(); if (m_pDataManager->importFiles(parentPath, urls)) { updateFileList(m_pFileListWidget->getCurrentParentPath(), m_pDataManager->getCurrentViewedItem(), NULL); m_pFileListWidget->setSelectedItems(m_pDataManager->getSelectedFileItems()); } setFolderTree(); } void BBFileSystemManager::moveFolders(const QList<QTreeWidgetItem*> &items, QTreeWidgetItem *pNewParentItem, bool bCopy) { clearFolderTree(); QList<QListWidgetItem*> selectedItems; if (m_pDataManager->moveFolders(items, pNewParentItem, bCopy, selectedItems)) { QString parentPath = m_pDataManager->getAbsolutePath(m_pDataManager->getCurrentViewedItem()); updateFileList(parentPath, NULL); updateFolderPathBar(parentPath); } setFolderTree(); m_pFolderTreeWidget->setSelectedItems(items); } void BBFileSystemManager::moveFolders(const QList<QString> &oldFilePaths, const QString &newParentPath, bool bCopy) { clearFolderTree(); QList<QListWidgetItem*> selectedItems; if (m_pDataManager->moveFolders(oldFilePaths, newParentPath, bCopy, selectedItems)) { QString parentPath = m_pDataManager->getAbsolutePath(m_pDataManager->getCurrentViewedItem()); updateFileList(parentPath, NULL); m_pFileListWidget->setSelectedItems(selectedItems); } setFolderTree(); } void BBFileSystemManager::moveFiles(const QList<QString> &oldFilePaths, QTreeWidgetItem *pNewParentItem, bool bCopy) { clearFolderTree(); QList<QTreeWidgetItem*> selectedItems; if (m_pDataManager->moveFiles(oldFilePaths, pNewParentItem, bCopy, selectedItems)) { QString parentPath = m_pDataManager->getAbsolutePath(m_pDataManager->getCurrentViewedItem()); updateFileList(parentPath, NULL); updateFolderPathBar(parentPath); } setFolderTree(); m_pFolderTreeWidget->setSelectedItems(selectedItems); } void BBFileSystemManager::moveFiles(const QList<QListWidgetItem*> &items, const QString &oldParentPath, const QString &newParentPath, bool bCopy) { // otherwise, item that is in the top level cannot be moved into other items clearFolderTree(); if (m_pDataManager->moveFiles(items, oldParentPath, newParentPath, bCopy)) { updateFileList(m_pFileListWidget->getCurrentParentPath(), m_pDataManager->getCurrentViewedItem(), NULL); } setFolderTree(); } void BBFileSystemManager::updateAll() { clearFolderTree(); setFolderTree(); QString parentPath = m_pDataManager->getAbsolutePath(m_pDataManager->getCurrentViewedItem()); updateFileList(parentPath, m_pFileListWidget->currentItem()); updateFolderPathBar(m_pFileListWidget->getCurrentParentPath()); } void BBFileSystemManager::clearFolderTree() { m_pFolderTreeWidget->removeTopLevelItems(); } /** * @brief BBFileSystemManager::setFolderTree set entire tree */ void BBFileSystemManager::setFolderTree() { m_pFolderTreeWidget->loadTopLevelItems(m_pDataManager->getFolderTreeWidgetTopLevelItems()); } /** * @brief BBFileSystemManager::updateFolderTree set current item of the tree * @param filePath */ void BBFileSystemManager::setFolderTreeCurrentItem(const QString &filePath) { QTreeWidgetItem *pItem = m_pDataManager->getFolderItemByPath(filePath); m_pFolderTreeWidget->expandCurrentViewedItem(pItem); } void BBFileSystemManager::updateFileList(const QString &parentPath, QTreeWidgetItem *pParentFolderItem, QListWidgetItem *pCurrentItem) { BBFILE *pFolderContent = NULL; m_pDataManager->getFileListWidgetItems(pParentFolderItem, pFolderContent); m_pFileListWidget->loadItems(parentPath, pFolderContent, pCurrentItem); } void BBFileSystemManager::updateFileList(const QString &parentPath, QListWidgetItem *pCurrentItem) { QTreeWidgetItem *pParentFolderItem = m_pDataManager->getFolderItemByPath(parentPath); updateFileList(parentPath, pParentFolderItem, pCurrentItem); } void BBFileSystemManager::updateFolderPathBar(const QString &filePath) { m_pFilePathBarWidget->showFolderPath(filePath); } void BBFileSystemManager::rename(QTreeWidgetItem *pParentFolderItem, QListWidgetItem *pFileItem, const QString &oldPath, const QString &newPath) { clearFolderTree(); if (m_pDataManager->rename(pParentFolderItem, pFileItem, oldPath, newPath)) { // cannot use m_pFileListWidget->getCurrentParentPath(), which is an old path QString parentPath = m_pDataManager->getAbsolutePath(m_pDataManager->getCurrentViewedItem()); updateFileList(parentPath, pFileItem); updateFolderPathBar(parentPath); // //重新显示属性栏的属性 名字更新 // itemClicked(editingItem); } setFolderTree(); } <|start_filename|>Code/BBearEditor/Editor/Tools/FBX2BBear/BBFBX2BBear.cpp<|end_filename|> #include "BBFBX2BBear.h" #include <QListWidgetItem> #include "Utils/BBUtils.h" void BBFBX2BBear::loadFBXFile(QListWidgetItem *pItem) { BB_PROCESS_ERROR_RETURN(pItem); qDebug() << pItem->text(); } <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBGeometricProcessingManager.cpp<|end_filename|> #include "BBGeometricProcessingManager.h" #include "Utils/BBUtils.h" #include "Geometry/BBMeshSubdivision.h" #include <QCheckBox> #include "3D/Mesh/BBProcedureMesh.h" #include "Render/BufferObject/BBVertexBufferObject.h" BBGeometricProcessingManager::BBGeometricProcessingManager(BBProcedureMesh *pMesh, QWidget *pParent) : BBGroupManager("Geometry", BB_PATH_RESOURCE_ICON(model.png), pParent) { m_pMesh = pMesh; QCheckBox *pCatmullClarkTrigger = new QCheckBox(this); addFactory("Catmull-Clark", pCatmullClarkTrigger, 1, Qt::AlignRight); QObject::connect(pCatmullClarkTrigger, SIGNAL(clicked(bool)), this, SLOT(triggerCatmullClarkAlgorithm(bool))); } BBGeometricProcessingManager::~BBGeometricProcessingManager() { } void BBGeometricProcessingManager::triggerCatmullClarkAlgorithm(bool bEnable) { if (bEnable) { BBCatmullClarkMeshSubdivision *pSubdivision = new BBCatmullClarkMeshSubdivision(m_pMesh); } } <|start_filename|>Code/BBearEditor/Editor/Dialog/BBConfirmationDialog.cpp<|end_filename|> #include "BBConfirmationDialog.h" #include "ui_BBConfirmationDialog.h" #include "Utils/BBUtils.h" #include <QApplication> #include <QDesktopWidget> #include "Render/BBEditViewDockWidget.h" BBConfirmationDialog::BBConfirmationDialog(QWidget *pParent) : QDialog(pParent), m_pUi(new Ui::BBConfirmationDialog) { m_pUi->setupUi(this); m_bCanceled = true; // Frameles setWindowFlags(Qt::FramelessWindowHint | windowFlags()); // Show it in the center move((QApplication::desktop()->width() - width()) / 2, (QApplication::desktop()->height() - height()) / 2); // Press Enter to invoke the click event of the yes button m_pUi->buttonYes->setDefault(true); QObject::connect(m_pUi->buttonClose, SIGNAL(clicked(bool)), this, SLOT(pressCloseButton())); QObject::connect(m_pUi->buttonNo, SIGNAL(clicked(bool)), this, SLOT(pressNoButton())); } BBConfirmationDialog::~BBConfirmationDialog() { BB_SAFE_DELETE(m_pUi); } void BBConfirmationDialog::setTitle(const QString &title) { m_pUi->labelTitle->setText(title); } void BBConfirmationDialog::setMessage(const QString &message) { m_pUi->labelMessage->setText(message); } void BBConfirmationDialog::pressCloseButton() { m_bCanceled = true; } void BBConfirmationDialog::pressNoButton() { m_bCanceled = false; } <|start_filename|>Resources/shaders/ParticleSystem/Particles1.vert<|end_filename|> #version 430 struct Vertex { vec4 BBPosition; vec4 BBColor; vec4 BBTexcoord; vec4 BBNormal; vec4 BBTangent; vec4 BBBiTangent; }; layout (std140, binding = 0) buffer Bundle { Vertex vertexes[]; } bundle; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; varying vec4 v2f_color; varying vec2 v2f_texcoord; void main() { // Every four vertices form a point sprite // >> 2 : / 4 int sprite_id = gl_VertexID >> 2; vec4 sprite_pos = bundle.vertexes[sprite_id].BBPosition; // point sprite needs to face us vec4 sprite_pos_view_space = BBViewMatrix * BBModelMatrix * sprite_pos; v2f_texcoord = vec2(((gl_VertexID - 1) & 2) >> 1, (gl_VertexID & 2) >> 1); float sprite_size = 0.015; // Use one point coordinate to calculate four vertex coordinates vec3 offset = vec3((v2f_texcoord * 2.0 - 1.0) * sprite_size, 0.0); vec4 fixed_pos = vec4(sprite_pos_view_space.xyz + offset, 1.0); v2f_color = bundle.vertexes[gl_VertexID].BBColor; gl_Position = BBProjectionMatrix * fixed_pos; } <|start_filename|>Code/BBearEditor/Engine/Physics/Force/BBDirectionalForce.cpp<|end_filename|> #include "BBDirectionalForce.h" #include "../Body/BBBaseBody.h" BBDirectionalForce::BBDirectionalForce(float x, float y, float z) : BBDirectionalForce(QVector3D(x, y, z)) { } BBDirectionalForce::BBDirectionalForce(const QVector3D &direction) : BBForce() { m_Direction = direction; } void BBDirectionalForce::applyForce(BBBaseBody *pBody, float fDeltaTime) { for (int i = 0; i < pBody->getParticleCount(); i++) { QVector3D velocity = pBody->getParticleVelocity(i); velocity += m_Direction * fDeltaTime; pBody->setParticleVelocity(i, velocity); } } <|start_filename|>Code/BBearEditor/Editor/Render/BBOfflineOpenGLWidget.h<|end_filename|> #ifndef BBOFFLINEOPENGLWIDGET_H #define BBOFFLINEOPENGLWIDGET_H #include "BBOpenGLWidget.h" class BBOfflineRenderer; class BBOfflineOpenGLWidget : public BBOpenGLWidget { Q_OBJECT public: BBOfflineOpenGLWidget(QWidget *pParent = 0); ~BBOfflineOpenGLWidget(); BBOfflineRenderer* getOfflineRenderer() { return m_pOfflineRenderer; } private: void initializeGL() override; void resizeGL(int nWidth, int nHeight) override; BBOfflineRenderer *m_pOfflineRenderer; }; #endif // BBOFFLINEOPENGLWIDGET_H <|start_filename|>Code/BBearEditor/Editor/Dialog/BBResourceDialog.cpp<|end_filename|> #include "BBResourceDialog.h" #include "ui_BBResourceDialog.h" #include "Utils/BBUtils.h" #include <QDir> QSize BBResourceDialog::m_ItemSize = QSize(32, 32); BBResourceDialog::BBResourceDialog(const QString &folderPath, QWidget *pParent) : QDialog(pParent), m_pUi(new Ui::BBResourceDialog) { m_pUi->setupUi(this); setWindowFlags(Qt::FramelessWindowHint | windowFlags()); if (pParent) { move(pParent->mapToGlobal(QPoint(0, 0))); } loadListItems(folderPath); } BBResourceDialog::~BBResourceDialog() { delete m_pUi; } QString BBResourceDialog::getCurrentItemFilePath() { int nIndex = m_pUi->resourceList->currentIndex().row(); if (nIndex < 0) { return ""; } else { return m_ItemFilePaths.at(nIndex); } } bool BBResourceDialog::loadListItems(const QString &folderPath) { QDir dir(folderPath); dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); QFileInfoList fileInfoList = dir.entryInfoList(); foreach (QFileInfo fileInfo, fileInfoList) { QListWidgetItem *pItem = new QListWidgetItem; pItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled); pItem->setSizeHint(m_ItemSize); pItem->setIcon(QIcon(BB_PATH_RESOURCE_ICON(material5))); pItem->setText(fileInfo.baseName()); m_pUi->resourceList->addItem(pItem); m_ItemFilePaths.append(fileInfo.filePath()); } return true; } <|start_filename|>Code/BBearEditor/Engine/3D/BBSkyBox.cpp<|end_filename|> #include "BBSkyBox.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BBCamera.h" #include "Render/BBMaterial.h" #include "Render/BBRenderPass.h" #include "Render/Texture/BBTexture.h" #include "Render/BBDrawCall.h" #include "Utils/BBUtils.h" #include "2D/BBFullScreenQuad.h" int BBSkyBox::m_nEnvironmentMapSize = 512; // Since the irradiance map averages all the surrounding radiation values, it loses most of the high-frequency details, // so we can store it at a lower resolution (32x32) and let OpenGL's linear filtering complete most of the work. int BBSkyBox::m_nIrradianceMapSize = 32; int BBSkyBox::m_nBaseMipmapSize = 128; int BBSkyBox::m_nMaxMipLevels = 5; int BBSkyBox::m_nBRDFLUTTextureSize = 512; BBSkyBox::BBSkyBox() : BBRenderableObject() { m_pEnvironmentMapMaterial = nullptr; m_pIrradianceMapMaterial = nullptr; m_pPrefilterMapMaterial = nullptr; m_pBRDFLUTTextureMaterial = nullptr; } BBSkyBox::~BBSkyBox() { BB_SAFE_DELETE(m_pEnvironmentMapMaterial); BB_SAFE_DELETE(m_pIrradianceMapMaterial); BB_SAFE_DELETE(m_pPrefilterMapMaterial); BB_SAFE_DELETE(m_pBRDFLUTTextureMaterial); } void BBSkyBox::init(const QString &path) { m_SkyBoxFilePath = path; initIBLSettings(); m_pVBO = new BBVertexBufferObject(24); m_pVBO->setPosition(0, -0.5f, -0.5f, -0.5f); m_pVBO->setPosition(1, 0.5f, -0.5f, -0.5f); m_pVBO->setPosition(2, -0.5f, 0.5f, -0.5f); m_pVBO->setPosition(3, 0.5f, 0.5f, -0.5f); m_pVBO->setPosition(4, 0.5f, -0.5f, 0.5f); m_pVBO->setPosition(5, -0.5f, -0.5f, 0.5f); m_pVBO->setPosition(6, 0.5f, 0.5f, 0.5f); m_pVBO->setPosition(7, -0.5f, 0.5f, 0.5f); m_pVBO->setPosition(8, -0.5f, -0.5f, 0.5f); m_pVBO->setPosition(9, -0.5f, -0.5f, -0.5f); m_pVBO->setPosition(10, -0.5f, 0.5f, 0.5f); m_pVBO->setPosition(11, -0.5f, 0.5f, -0.5f); m_pVBO->setPosition(12, 0.5f, -0.5f, -0.5f); m_pVBO->setPosition(13, 0.5f, -0.5f, 0.5f); m_pVBO->setPosition(14, 0.5f, 0.5f, -0.5f); m_pVBO->setPosition(15, 0.5f, 0.5f, 0.5f); m_pVBO->setPosition(16, -0.5f, 0.5f, -0.5f); m_pVBO->setPosition(17, 0.5f, 0.5f, -0.5f); m_pVBO->setPosition(18, -0.5f, 0.5f, 0.5f); m_pVBO->setPosition(19, 0.5f, 0.5f, 0.5f); m_pVBO->setPosition(20, -0.5f, -0.5f, 0.5f); m_pVBO->setPosition(21, 0.5f, -0.5f, 0.5f); m_pVBO->setPosition(22, -0.5f, -0.5f, -0.5f); m_pVBO->setPosition(23, 0.5f, -0.5f, -0.5f); initFrom6Map(); // initFromHDREnvironmentMap(); // initFromEnvironmentCubeMap(); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, GL_TRIANGLE_STRIP, 0, 24); appendDrawCall(pDrawCall); } void BBSkyBox::render(BBCamera *pCamera) { QMatrix4x4 modelMatrix; modelMatrix.translate(pCamera->getPosition()); m_pCurrentMaterial->setMatrix4(LOCATION_MODELMATRIX, modelMatrix.data()); BBRenderableObject::render(modelMatrix, pCamera); } void BBSkyBox::writeEnvironmentMap(BBCamera *pCamera) { // Switch to a specific material and render the 6 faces of the sky box into FBO respectively setCurrentMaterial(m_pEnvironmentMapMaterial); for (int i = 0; i < 6; i++) { m_pEnvironmentMapMaterial->setMatrix4("ViewMatrix", m_IBLCubeMapViewMatrix[i].data()); BBTexture().startWritingTextureCube(m_EnvironmentMap, i); BBRenderableObject::render(pCamera); } // After setting the texture of the cube map, let OpenGL generate mipmap BBTexture().generateTextureCubeMipmap(m_EnvironmentMap); // Restore default material restoreMaterial(); } void BBSkyBox::writeIrradianceMap(BBCamera *pCamera) { setCurrentMaterial(m_pIrradianceMapMaterial); for (int i = 0; i < 6; i++) { m_pIrradianceMapMaterial->setMatrix4("ViewMatrix", m_IBLCubeMapViewMatrix[i].data()); BBTexture().startWritingTextureCube(m_IrradianceMap, i); BBRenderableObject::render(pCamera); } restoreMaterial(); } void BBSkyBox::writePrefilterMapMipmap(BBCamera *pCamera, int nMipLevel) { setCurrentMaterial(m_pPrefilterMapMaterial); m_pPrefilterMapMaterial->setFloat("Roughness", (float)nMipLevel / (float)(m_nMaxMipLevels - 1)); for (int i = 0; i < 6; i++) { m_pPrefilterMapMaterial->setMatrix4("ViewMatrix", m_IBLCubeMapViewMatrix[i].data()); BBTexture().startWritingTextureCubeMipmap(m_PrefilterMapMipmap, i, nMipLevel); BBRenderableObject::render(pCamera); } restoreMaterial(); } void BBSkyBox::writeBRDFLUTTexture(BBCamera *pCamera, BBFullScreenQuad *pFullScreenQuad) { pFullScreenQuad->setCurrentMaterial(m_pBRDFLUTTextureMaterial); BBTexture().startWritingTexture2D(m_BRDFLUTTexture); pFullScreenQuad->render(pCamera); pFullScreenQuad->restoreMaterial(); } void BBSkyBox::changeResource(const QString &path) { } void BBSkyBox::changeAlgorithm(int nIndex) { } void BBSkyBox::initFrom6Map() { QString paths[6] = {m_SkyBoxFilePath + "right", m_SkyBoxFilePath + "left", m_SkyBoxFilePath + "bottom", m_SkyBoxFilePath + "top", m_SkyBoxFilePath + "back", m_SkyBoxFilePath + "front"}; m_CommonSkyBoxCube = BBTexture().createTextureCube(paths); m_pCurrentMaterial->init("SkyBox_Common", BB_PATH_RESOURCE_SHADER(SkyBox/Common.vert), BB_PATH_RESOURCE_SHADER(SkyBox/Common.frag)); m_pCurrentMaterial->setZTestState(false); } void BBSkyBox::initFromHDREnvironmentMap() { m_pCurrentMaterial->init("SkyBox_Equirectangular", BB_PATH_RESOURCE_SHADER(SkyBox/Equirectangular.vert), BB_PATH_RESOURCE_SHADER(SkyBox/Equirectangular.frag)); GLuint hdrTexture = BBTexture().createHDRTexture2D(BB_PATH_RESOURCE_TEXTURE(HDR/Walk_Of_Fame/Mans_Outside_2k.hdr)); m_pCurrentMaterial->setSampler2D(LOCATION_SKYBOX_EQUIRECTANGULAR_MAP, hdrTexture); m_pCurrentMaterial->setZTestState(false); } void BBSkyBox::initFromEnvironmentCubeMap() { m_pCurrentMaterial->init("SkyBox_Common", BB_PATH_RESOURCE_SHADER(SkyBox/Common.vert), BB_PATH_RESOURCE_SHADER(SkyBox/Common.frag)); m_pCurrentMaterial->setSamplerCube(LOCATION_SKYBOX_MAP, m_EnvironmentMap); m_pCurrentMaterial->setZTestState(false); } /** * @brief BBSkyBox::initEnvironmentMapMaterial init the material that is used for making lighting map */ void BBSkyBox::initIBLSettings() { // We need to sample mipmap and turn on trilinear filtering on the environment map m_EnvironmentMap = BBTexture().allocateTextureCube(m_nEnvironmentMapSize, m_nEnvironmentMapSize, GL_RGB16F, GL_RGB, GL_LINEAR_MIPMAP_LINEAR); m_IrradianceMap = BBTexture().allocateTextureCube(m_nIrradianceMapSize, m_nIrradianceMapSize, GL_RGB16F, GL_RGB); m_PrefilterMapMipmap = BBTexture().allocateTextureCubeMipmap(m_nBaseMipmapSize, m_nBaseMipmapSize, GL_RGB16F, GL_RGB); m_BRDFLUTTexture = BBTexture().allocateTexture2D(m_nBRDFLUTTextureSize, m_nBRDFLUTTextureSize, GL_RG16F, GL_RG); m_IBLCubeMapProjectionMatrix.perspective(90.0f, 1.0f, 0.1f, 10.0f); m_IBLCubeMapViewMatrix[0].lookAt(QVector3D(0, 0, 0), QVector3D(1, 0, 0), QVector3D(0, 1, 0)); m_IBLCubeMapViewMatrix[1].lookAt(QVector3D(0, 0, 0), QVector3D(-1, 0, 0), QVector3D(0, 1, 0)); m_IBLCubeMapViewMatrix[2].lookAt(QVector3D(0, 0, 0), QVector3D(0, -1, 0), QVector3D(0, 0, -1)); m_IBLCubeMapViewMatrix[3].lookAt(QVector3D(0, 0, 0), QVector3D(0, 1, 0), QVector3D(0, 0, 1)); m_IBLCubeMapViewMatrix[4].lookAt(QVector3D(0, 0, 0), QVector3D(0, 0, -1), QVector3D(0, 1, 0)); m_IBLCubeMapViewMatrix[5].lookAt(QVector3D(0, 0, 0), QVector3D(0, 0, 1), QVector3D(0, 1, 0)); m_pEnvironmentMapMaterial = new BBMaterial(); m_pEnvironmentMapMaterial->init("SkyBox_Equirectangular_To_Cubemap", BB_PATH_RESOURCE_SHADER(SkyBox/Cubemap.vert), BB_PATH_RESOURCE_SHADER(SkyBox/Equirectangular2Cubemap.frag)); m_pEnvironmentMapMaterial->setZFunc(GL_LEQUAL); m_pEnvironmentMapMaterial->setMatrix4("ProjectionMatrix", m_IBLCubeMapProjectionMatrix.data()); GLuint hdrTexture = BBTexture().createHDRTexture2D(BB_PATH_RESOURCE_TEXTURE(HDR/Walk_Of_Fame/Mans_Outside_2k.hdr)); m_pEnvironmentMapMaterial->setSampler2D(LOCATION_SKYBOX_EQUIRECTANGULAR_MAP, hdrTexture); m_pIrradianceMapMaterial = new BBMaterial(); m_pIrradianceMapMaterial->init("SkyBox_Irradiance_Convolution", BB_PATH_RESOURCE_SHADER(SkyBox/Cubemap.vert), BB_PATH_RESOURCE_SHADER(SkyBox/Irradiance_Convolution.frag)); m_pIrradianceMapMaterial->setZFunc(GL_LEQUAL); m_pIrradianceMapMaterial->setMatrix4("ProjectionMatrix", m_IBLCubeMapProjectionMatrix.data()); m_pIrradianceMapMaterial->setSamplerCube("EnvironmentMap", m_EnvironmentMap); m_pPrefilterMapMaterial = new BBMaterial(); m_pPrefilterMapMaterial->init("SkyBox_PrefilterMap", BB_PATH_RESOURCE_SHADER(SkyBox/Cubemap.vert), BB_PATH_RESOURCE_SHADER(SkyBox/PrefilterMap.frag)); m_pPrefilterMapMaterial->setZFunc(GL_LEQUAL); m_pPrefilterMapMaterial->setMatrix4("ProjectionMatrix", m_IBLCubeMapProjectionMatrix.data()); m_pPrefilterMapMaterial->setSamplerCube("EnvironmentMap", m_EnvironmentMap); m_pBRDFLUTTextureMaterial = new BBMaterial(); m_pBRDFLUTTextureMaterial->init("BRDFLUT", BB_PATH_RESOURCE_SHADER(PBR/BRDFLUT.vert), BB_PATH_RESOURCE_SHADER(PBR/BRDFLUT.frag)); } <|start_filename|>Code/BBearEditor/Engine/Render/Shadow/BBShadow.cpp<|end_filename|> #include "BBShadow.h" #include "Scene/BBSceneManager.h" #include "Scene/BBScene.h" #include "Base/BBGameObject.h" #include "2D/BBFullScreenQuad.h" #include "Render/BBMaterial.h" void BBShadow::enable(int nAlgorithmIndex, bool bEnable) { BBScene *pScene = BBSceneManager::getScene(); if (bEnable) { pScene->setRenderingFunc(&BBScene::deferredRendering1_1); open(pScene); } else { pScene->setRenderingFunc(&BBScene::defaultRendering); // objects go back original materials QList<BBGameObject*> objects = pScene->getModels(); for (QList<BBGameObject*>::Iterator itr = objects.begin(); itr != objects.end(); itr++) { BBGameObject *pObject = *itr; pObject->restoreMaterial(); } } } void BBShadow::open(BBScene *pScene) { setGBufferPass(pScene); setScreenQuadPass(pScene); } void BBShadow::setGBufferPass(BBScene *pScene) { BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("Shadow_VSM_GBuffer", BB_PATH_RESOURCE_SHADER(Shadow/VSM_GBuffer.vert), BB_PATH_RESOURCE_SHADER(Shadow/VSM_GBuffer.frag)); QList<BBGameObject*> objects = pScene->getModels(); for (QList<BBGameObject*>::Iterator itr = objects.begin(); itr != objects.end(); itr++) { BBGameObject *pObject = *itr; pObject->setCurrentMaterial(pMaterial->clone()); } } void BBShadow::setScreenQuadPass(BBScene *pScene) { // depth map is saved in the FBO 2 // get d and d^2 // filter them to get E(d) and E(d^2) BBFullScreenQuad *pFullScreenQuad = pScene->getFullScreenQuad(0); BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("Shadow_VSM_ScreenQuad", BB_PATH_RESOURCE_SHADER(Shadow/VSM_ScreenQuad.vert), BB_PATH_RESOURCE_SHADER(Shadow/VSM_ScreenQuad.frag)); pMaterial->setSampler2D("AlbedoAndMetallicTex", pScene->getColorFBO(0, 0)); pMaterial->setSampler2D("NormalAndDoubleRoughnessTex", pScene->getColorFBO(0, 1)); pMaterial->setSampler2D("PositionTex", pScene->getColorFBO(0, 2)); pFullScreenQuad->setCurrentMaterial(pMaterial); } <|start_filename|>Code/BBearEditor/Editor/Dialog/BBConfirmationDialog.h<|end_filename|> #ifndef BBCONFIRMATIONDIALOG_H #define BBCONFIRMATIONDIALOG_H #include <QDialog> class BBEditViewDockWidget; namespace Ui { class BBConfirmationDialog; } class BBConfirmationDialog : public QDialog { Q_OBJECT public: explicit BBConfirmationDialog(QWidget *pParent = 0); virtual ~BBConfirmationDialog(); void setTitle(const QString &title); void setMessage(const QString &message); inline bool isCanceled() { return m_bCanceled; } private slots: void pressCloseButton(); void pressNoButton(); private: Ui::BBConfirmationDialog *m_pUi; /* true means doing nothing, false means removing the performation before */ bool m_bCanceled; }; #endif // BBCONFIRMATIONDIALOG_H <|start_filename|>Code/BBearEditor/Engine/Physics/FluidSystem/BBSPHGridContainer.cpp<|end_filename|> #include "BBSPHGridContainer.h" #include "BBSPHParticleSystem.h" #include "Utils/BBUtils.h" BBSPHGridContainer::BBSPHGridContainer() { } void BBSPHGridContainer::init(const QVector3D &min, const QVector3D &max, float fUnitScale, float fGridCellSize, unsigned int *pFieldSize) { m_GridMin = min; m_GridMax = max; m_GridSize = m_GridMax - m_GridMin; m_fGridCellSize = fGridCellSize / fUnitScale; m_GridResolution.setX(ceil(m_GridSize.x() / m_fGridCellSize)); m_GridResolution.setY(ceil(m_GridSize.y() / m_fGridCellSize)); m_GridResolution.setZ(ceil(m_GridSize.z() / m_fGridCellSize)); // Resize the grid to a multiple of the cell size m_GridSize = m_GridResolution * m_fGridCellSize; m_GridDelta = m_GridResolution / m_GridSize; m_GridData.resize((int)(m_GridResolution.x() * m_GridResolution.y() * m_GridResolution.z())); pFieldSize[0] = m_GridResolution.x() * 4; pFieldSize[1] = m_GridResolution.y() * 4; pFieldSize[2] = m_GridResolution.z() * 4; } int BBSPHGridContainer::getGridData(int nGridIndex) { if (nGridIndex < 0 | nGridIndex >= m_GridData.size()) { return -1; } else { return m_GridData[nGridIndex]; } } int BBSPHGridContainer::getGridCellIndex(const QVector3D &p) { // Rounding int gx = (int)((p.x() - m_GridMin.x()) * m_GridDelta.x()); int gy = (int)((p.y() - m_GridMin.y()) * m_GridDelta.y()); int gz = (int)((p.z() - m_GridMin.z()) * m_GridDelta.z()); return (gz * m_GridResolution.y() + gy) * m_GridResolution.x() + gx; } void BBSPHGridContainer::insertParticles(BBSPHParticleSystem *pParticleSystem) { // reset std::fill(m_GridData.begin(), m_GridData.end(), -1); BBSPHParticle *pParticle = pParticleSystem->getParticle(0); for (unsigned int n = 0; n < pParticleSystem->getSize(); n++, pParticle++) { int nGridCellIndex = getGridCellIndex(pParticle->m_Position); // Within each grid, particles form a linked list // m_GridData[nGridCellIndex] is header if (nGridCellIndex >= 0 && nGridCellIndex < m_GridData.size()) { // Insert header pParticle->m_nNextIndex = m_GridData[nGridCellIndex]; m_GridData[nGridCellIndex] = n; } else { pParticle->m_nNextIndex = -1; } } } int BBSPHGridContainer::findCell(const QVector3D &p) { int nGridCellIndex = getGridCellIndex(p); if (nGridCellIndex < 0 || nGridCellIndex >= m_GridData.size()) { return -1; } else { return nGridCellIndex; } } void BBSPHGridContainer::findCells(const QVector3D &p, float radius, int *pGridCell) { // Because smooth kernel radius * 2 == grid size, there are 8 grid around it for (int i = 0; i < 8; i++) { pGridCell[i] = -1; } // Smooth kernel min pos to which the particle belongs int minX = (p.x() - radius - m_GridMin.x()) * m_GridDelta.x(); int minY = (p.y() - radius - m_GridMin.y()) * m_GridDelta.y(); int minZ = (p.z() - radius - m_GridMin.z()) * m_GridDelta.z(); if (minX < 0) minX = 0; if (minY < 0) minY = 0; if (minZ < 0) minZ = 0; pGridCell[0] = (minZ * m_GridResolution.y() + minY) * m_GridResolution.x() + minX; pGridCell[1] = pGridCell[0] + 1; pGridCell[2] = pGridCell[0] + m_GridResolution.x(); pGridCell[3] = pGridCell[2] + 1; if (minZ + 1 < m_GridResolution.z()) { pGridCell[4] = pGridCell[0] + m_GridResolution.y() * m_GridResolution.x(); pGridCell[5] = pGridCell[4] + 1; pGridCell[6] = pGridCell[4] + m_GridResolution.x(); pGridCell[7] = pGridCell[6] + 1; } if (minX + 1 >= m_GridResolution.x()) { pGridCell[1] = -1; pGridCell[3] = -1; pGridCell[5] = -1; pGridCell[7] = -1; } if (minY + 1 >= m_GridResolution.y()) { pGridCell[2] = -1; pGridCell[3] = -1; pGridCell[6] = -1; pGridCell[7] = -1; } } void BBSPHGridContainer::findTwoCells(const QVector3D &p, float radius, int *pGridCell) { for (int i = 0; i < 64; i++) { pGridCell[i] = -1; } int minX = (p.x() - radius - m_GridMin.x()) * m_GridDelta.x(); int minY = (p.y() - radius - m_GridMin.y()) * m_GridDelta.y(); int minZ = (p.z() - radius - m_GridMin.z()) * m_GridDelta.z(); if (minX < 0) minX = 0; if (minY < 0) minY = 0; if (minZ < 0) minZ = 0; int base = (minZ * m_GridResolution.y() + minY) * m_GridResolution.x() + minX; for (int z = 0; z < 4; z++) { for (int y = 0; y < 4; y++) { for (int x = 0; x < 4; x++) { if ((minX + x >= m_GridResolution.x()) || (minY + y >= m_GridResolution.y()) || (minZ + z >= m_GridResolution.z())) pGridCell[16 * z + 4 * y + x] = -1; else pGridCell[16 * z + 4 * y + x] = base + (z * m_GridResolution.y() + y) * m_GridResolution.x() + x; } } } } <|start_filename|>Code/BBearEditor/Engine/Physics/Force/BBDirectionalForce.h<|end_filename|> #ifndef BBDIRECTIONALFORCE_H #define BBDIRECTIONALFORCE_H #include "BBForce.h" #include <QVector3D> class BBDirectionalForce : public BBForce { public: BBDirectionalForce(float x, float y, float z); BBDirectionalForce(const QVector3D &direction); void applyForce(BBBaseBody *pBody, float fDeltaTime) override; private: QVector3D m_Direction; }; #endif // BBDIRECTIONALFORCE_H <|start_filename|>Code/BBearEditor/Engine/Render/Lighting/GameObject/BBSpotLight.h<|end_filename|> #ifndef BBSPOTLIGHT_H #define BBSPOTLIGHT_H #include "BBPointLight.h" class BBSpotLight : public BBPointLight { public: BBSpotLight(BBScene *pScene); BBSpotLight(BBScene *pScene, const QVector3D &position, const QVector3D &rotation); void setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform = true) override; void setRotation(const QVector3D &rotation, bool bUpdateLocalTransform = true) override; bool cull(BBCamera *pCamera, const QRectF &displayBox) override; bool cull(BBCamera *pCamera, int nFrustumIndexX, int nFrustumIndexY) override; void setDirection(); void setAngle(float fAngle) { m_Setting0[2] = fAngle; } void setLevel(float fValue) { m_Setting0[3] = fValue; } inline float* getDirection() { return m_Setting2; } inline float getAngle() { return m_Setting0[2]; } inline float getLevel() { return m_Setting0[3]; } }; #endif // BBSPOTLIGHT_H <|start_filename|>Code/BBearEditor/Editor/Render/BBEditViewDockWidget.cpp<|end_filename|> #include "BBEditViewDockWidget.h" #include <QKeyEvent> #include "Scene/BBSceneManager.h" #include <QFileDialog> #include "FileSystem/BBFileSystemDataManager.h" #include <QVBoxLayout> #include <QLabel> BBEditViewDockWidget::BBEditViewDockWidget(QWidget *pParent) : QDockWidget(pParent) { setFeatures(QDockWidget::NoDockWidgetFeatures); setTitleBar(); } void BBEditViewDockWidget::setTitleBarText() { QString fileName = BBFileSystemDataManager::getFileNameByPath(BBSceneManager::getCurrentSceneFilePath()); QString text = "Edit View [" + BBFileSystemDataManager::getBaseName(fileName); if (BBSceneManager::isSceneChanged()) { text += "*"; } text += "]"; m_pWindowTitle->setText(text); } void BBEditViewDockWidget::setTitleBar() { QWidget *pBar = titleBarWidget(); BB_SAFE_DELETE(pBar); pBar = new QWidget(this); pBar->setStyleSheet("background-color: #191f28; padding-top: 8px; padding-bottom: 8px; padding-left: 5px;"); QVBoxLayout *pLayout = new QVBoxLayout(pBar); pLayout->setMargin(0); m_pWindowTitle = new QLabel(pBar); m_pWindowTitle->setStyleSheet("color: #d6dfeb; font: 75 9pt \"Arial\";"); pLayout->addWidget(m_pWindowTitle); setTitleBarText(); setTitleBarWidget(pBar); } void BBEditViewDockWidget::keyPressEvent(QKeyEvent *e) { keyPress(e); if (e->isAutoRepeat()) return; switch (e->key()) { case Qt::Key_W: pressMoveKey('W'); pressTransform('W'); break; case Qt::Key_A: pressMoveKey('A'); break; case Qt::Key_S: pressMoveKey('S'); break; case Qt::Key_D: pressMoveKey('D'); break; case Qt::Key_Q: pressMoveKey('Q'); break; case Qt::Key_E: pressMoveKey('E'); pressTransform('E'); break; case Qt::Key_R: pressTransform('R'); break; case Qt::Key_Escape: pressESC(); break; default: break; } if ((e->modifiers() == Qt::ControlModifier) && (e->key() == Qt::Key_S)) { emit saveCurrentScene(); } } void BBEditViewDockWidget::keyReleaseEvent(QKeyEvent *e) { switch (e->key()) { case Qt::Key_W: releaseMoveKey('W'); break; case Qt::Key_A: releaseMoveKey('A'); break; case Qt::Key_S: releaseMoveKey('S'); break; case Qt::Key_D: releaseMoveKey('D'); break; case Qt::Key_Q: releaseMoveKey('Q'); break; case Qt::Key_E: releaseMoveKey('E'); break; default: break; } } void BBEditViewDockWidget::focusInEvent(QFocusEvent *event) { Q_UNUSED(event); cancelFileListSelectedItems(); } <|start_filename|>Resources/shaders/Cartoon/CartoonFire.frag<|end_filename|> varying vec4 V_Texcoord; uniform vec4 BBTime; // Ashima vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } vec4 permute(vec4 x) { return mod289(((x * 34.0) + 1.0) * x); } vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; } float snoise(vec3 v) { const vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0) ; const vec4 D = vec4(0.0, 0.5, 1.0, 2.0); // First corner vec3 i = floor(v + dot(v, C.yyy)); vec3 x0 = v - i + dot(i, C.xxx); // Other corners vec3 g = step(x0.yzx, x0.xyz); vec3 l = 1.0 - g; vec3 i1 = min(g.xyz, l.zxy); vec3 i2 = max(g.xyz, l.zxy); // x0 = x0 - 0.0 + 0.0 * C.xxx; // x1 = x0 - i1 + 1.0 * C.xxx; // x2 = x0 - i2 + 2.0 * C.xxx; // x3 = x0 - 1.0 + 3.0 * C.xxx; vec3 x1 = x0 - i1 + C.xxx; vec3 x2 = x0 - i2 + C.yyy; // 2.0 * C.x = 1/3 = C.y vec3 x3 = x0 - D.yyy; // -1.0 + 3.0 * C.x = -0.5 = -D.y // Permutations i = mod289(i); vec4 p = permute(permute(permute(i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + i.x + vec4(0.0, i1.x, i2.x, 1.0)); // Gradients: 7x7 points over a square, mapped onto an octahedron. // The ring size 17*17 = 289 is close to a multiple of 49 (49 * 6 = 294) float n_ = 0.142857142857; // 1.0 / 7.0 vec3 ns = n_ * D.wyz - D.xzx; vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p, 7 * 7) vec4 x_ = floor(j * ns.z); vec4 y_ = floor(j - 7.0 * x_); // mod(j, N) vec4 x = x_ *ns.x + ns.yyyy; vec4 y = y_ *ns.x + ns.yyyy; vec4 h = 1.0 - abs(x) - abs(y); vec4 b0 = vec4(x.xy, y.xy); vec4 b1 = vec4(x.zw, y.zw); // vec4 s0 = vec4(lessThan(b0, 0.0)) * 2.0 - 1.0; // vec4 s1 = vec4(lessThan(b1, 0.0)) * 2.0 - 1.0; vec4 s0 = floor(b0) * 2.0 + 1.0; vec4 s1 = floor(b1) * 2.0 + 1.0; vec4 sh = -step(h, vec4(0.0)); vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww; vec3 p0 = vec3(a0.xy, h.x); vec3 p1 = vec3(a0.zw, h.y); vec3 p2 = vec3(a1.xy, h.z); vec3 p3 = vec3(a1.zw, h.w); // Normalise gradients vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3))); p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w; // Mix final noise value vec4 m = max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); m = m * m; return 42.0 * dot(m*m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3))); } // End Ashima ///////////////////////////////////////////////// int STEP = 4; float CUTOFF = 0.15; float getNoise(vec2 uv, float t) { float speed = 1.5; float scale = 2.0; float noise = snoise(vec3(uv.x * scale, uv.y * scale - t * speed, 0.0)); // superposition of noise scale = 6.0; noise += snoise(vec3(uv.x * scale + t, uv.y * scale, 0.0)) * 0.2; // map to 0~1 noise = (noise / 2.0 + 0.5); return noise; } // Separates the gradient into several color levels float getDepth(float n) { float d = (n - CUTOFF) / (1.0 - CUTOFF); d = floor(d * STEP) / STEP; return d; } vec3 hsv2rgb(vec3 c) { vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); } void main(void) { vec2 uv = V_Texcoord.xy; uv.x *= 4.0; vec3 final_color = vec3(0.0); float noise = getNoise(uv, BBTime.z / 5000.0); // General outline of fire (triangle) CUTOFF = uv.y; CUTOFF += abs(uv.x * 0.5 - 1.0); if (noise > CUTOFF) { // Show fire float d = pow(getDepth(noise), 0.7); // Coloring fire vec3 hsv = vec3(d * 0.17, 0.8 - d / 4.0, d + 0.8); final_color = hsv2rgb(hsv); } gl_FragColor = vec4(final_color, 1.0); } <|start_filename|>Code/BBearEditor/Engine/Geometry/BBMarchingCubeMesh.cpp<|end_filename|> #include "BBMarchingCubeMesh.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BufferObject/BBElementBufferObject.h" #include "Render/BBMaterial.h" #include "Render/BBDrawCall.h" #include "Render/BBRenderPass.h" /* 6--------7 *---5----* /| /| /| /| / | / | 9 | 10 | / | / | / 4 / 6 2--------3 | *----1---* | | | | | | | | | | 5----|---8 | *---7|---* | / | / 0 / 2 / | / | / | 8 | 11 |/ |/ |/ |/ 1--------4 *---3----* e.g. v1 : 0000 0001 e0 e3 e8 : 0001 0000 1001 : 0x109 * */ unsigned int BBMarchingCubeMesh::m_EdgeTable[256] = { 0x0 , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0 }; int BBMarchingCubeMesh::m_TriangleTable[256][16] = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1} }; BBMarchingCubeMesh::BBMarchingCubeMesh() { m_bValidSurface = false; } BBMarchingCubeMesh::~BBMarchingCubeMesh() { deleteSurface(); } void BBMarchingCubeMesh::init(unsigned int *pNum, const QVector3D &unitWidth, const QVector3D &min, float fThreshold) { if (m_bValidSurface) { deleteSurface(); } m_fIsoLevel = fThreshold; m_Grid.m_nNum[0] = pNum[0]; m_Grid.m_nNum[1] = pNum[1]; m_Grid.m_nNum[2] = pNum[2]; m_Grid.m_UnitWidth = unitWidth; m_Grid.m_Min = min; m_pCurrentMaterial->init("base", BB_PATH_RESOURCE_SHADER(base.vert), BB_PATH_RESOURCE_SHADER(base.frag)); m_pCurrentMaterial->setBlendState(true); m_pCurrentMaterial->getBaseRenderPass()->setPolygonMode(GL_LINE); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_TRIANGLES, m_nIndexCount, 0); appendDrawCall(pDrawCall); } bool BBMarchingCubeMesh::createMCMesh(float *pField) { if (pField == nullptr) return false; // input density field m_pScalarField = pField; generateIsoSurface(); return true; } void BBMarchingCubeMesh::generateIsoSurface() { // used for computing index unsigned int nSlice0 = m_Grid.m_nNum[0] + 1; unsigned int nSlice1 = nSlice0 * (m_Grid.m_nNum[1] + 1); // generate isosurface for (unsigned int z = 0; z < m_Grid.m_nNum[2]; z++) { for (unsigned int y = 0; y < m_Grid.m_nNum[1]; y++) { for (unsigned int x = 0; x < m_Grid.m_nNum[0]; x++) { // Traverse each point of the density field and judge whether it exceeds the density threshold unsigned int nTableIndex = 0; if (m_pScalarField[z * nSlice1 + y * nSlice0 + x] < m_fIsoLevel) nTableIndex |= 1; if (m_pScalarField[z * nSlice1 + (y + 1) * nSlice0 + x] < m_fIsoLevel) nTableIndex |= 2; if (m_pScalarField[z * nSlice1 + (y + 1) * nSlice0 + (x + 1)] < m_fIsoLevel) nTableIndex |= 4; if (m_pScalarField[z * nSlice1 + y * nSlice0 + (x + 1)] < m_fIsoLevel) nTableIndex |= 8; if (m_pScalarField[(z + 1) * nSlice1 + y * nSlice0 + x] < m_fIsoLevel) nTableIndex |= 16; if (m_pScalarField[(z + 1) * nSlice1 + (y + 1) * nSlice0 + x] < m_fIsoLevel) nTableIndex |= 32; if (m_pScalarField[(z + 1) * nSlice1 + (y + 1) * nSlice0 + (x + 1)] < m_fIsoLevel) nTableIndex |= 64; if (m_pScalarField[(z + 1) * nSlice1 + y * nSlice0 + (x + 1)] < m_fIsoLevel) nTableIndex |= 128; if (m_EdgeTable[nTableIndex] != 0) { /* 6--------7 *---5----* /| /| /| /| / | / | 9 | 10 | / | / | / 4 / 6 2--------3 | *----1---* | | | | | | | | | | 5----|---8 | *---7|---* | / | / 0 / 2 / | / | / | 8 | 11 |/ |/ |/ |/ 1--------4 *---3----* e.g. v1 : 0000 0001 e0 e3 e8 : 0001 0000 1001 : 0x109 * */ // Priority min : 3, 0, 8 // The corresponding edge number of the point is obtained // Take the edge number as the index and the point position as the value if (m_EdgeTable[nTableIndex] & 8) // 0000 0000 1000 : 8 : 3 { generateEdgeVertexMap(x, y, z, 3); } if (m_EdgeTable[nTableIndex] & 1) { generateEdgeVertexMap(x, y, z, 0); } if (m_EdgeTable[nTableIndex] & 256) { generateEdgeVertexMap(x, y, z, 8); } // Bottom & Right : 2, 11 if (x == m_Grid.m_nNum[0] - 1) { if (m_EdgeTable[nTableIndex] & 4) { generateEdgeVertexMap(x, y, z, 2); } if (m_EdgeTable[nTableIndex] & 2048) { generateEdgeVertexMap(x, y, z, 11); } } // Top & Left : 1, 9 if (y == m_Grid.m_nNum[1] - 1) { if (m_EdgeTable[nTableIndex] & 2) { generateEdgeVertexMap(x, y, z, 1); } if (m_EdgeTable[nTableIndex] & 512) { generateEdgeVertexMap(x, y, z, 9); } } // Back & Left : 4, 7 if (z == m_Grid.m_nNum[2] - 1) { if (m_EdgeTable[nTableIndex] & 16) { generateEdgeVertexMap(x, y, z, 4); } if (m_EdgeTable[nTableIndex] & 128) { generateEdgeVertexMap(x, y, z, 7); } } if ((x == m_Grid.m_nNum[0] - 1) && (y == m_Grid.m_nNum[1] - 1)) { if (m_EdgeTable[nTableIndex] & 1024) { generateEdgeVertexMap(x, y, z, 10); } } if ((x == m_Grid.m_nNum[0] - 1) && (z == m_Grid.m_nNum[2] - 1)) { if (m_EdgeTable[nTableIndex] & 64) { generateEdgeVertexMap(x, y, z, 6); } } if ((y == m_Grid.m_nNum[1] - 1) && (z == m_Grid.m_nNum[2] - 1)) { if (m_EdgeTable[nTableIndex] & 32) { generateEdgeVertexMap(x, y, z, 5); } } // generate triangle for (unsigned int i = 0; m_TriangleTable[nTableIndex][i] != -1; i += 3) { BBMCTriangle triangle; triangle.m_VertexID[0] = getEdgeID(x, y, z, m_TriangleTable[nTableIndex][i]); triangle.m_VertexID[1] = getEdgeID(x, y, z, m_TriangleTable[nTableIndex][i + 1]); triangle.m_VertexID[2] = getEdgeID(x, y, z, m_TriangleTable[nTableIndex][i + 2]); m_TriangleVector.push_back(triangle); } } } } } generateVBOAndEBO(); m_bValidSurface = true; } void BBMarchingCubeMesh::generateEdgeVertexMap(unsigned int x, unsigned int y, unsigned int z, unsigned int nEdge) { BBMCVertex v = computeIntersection(x, y, z, nEdge); unsigned int id = getEdgeID(x, y, z, nEdge); m_EVMap.insert(BBMCEVMap::value_type(id, v)); } /** * @brief BBMarchingCubeMesh::computeIntersection Calculate equivalent points by interpolation * @param x * @param y * @param z * @param nEdge edge number */ BBMCVertex BBMarchingCubeMesh::computeIntersection(unsigned int x, unsigned int y, unsigned int z, unsigned int nEdge) { // For a voxel edge with an intersection with the isosurface, // the intersection coordinates are represented by P, // P1 and P2 represent the coordinates of the two endpoints on the edge, // V1 and V2 represent the values on the two endpoints, and V represents the isosurface // P = P1 + (V - V1) * (P2 - P1) / (V2 - V1) // N is number QVector3D N1(x, y, z); QVector3D N2(x, y, z); switch (nEdge) { case 0: N2[1]++; break; case 1: N1[1]++; N2[0]++; N2[1]++; break; case 2: N1[0]++; N1[1]++; N2[0]++; break; case 3: N1[0]++; break; case 4: N1[2]++; N2[1]++; N2[2]++; break; case 5: N1[1]++; N1[2]++; N2[0]++; N2[1]++; N2[2]++; break; case 6: N1[0]++; N1[1]++; N1[2]++; N2[0]++; N2[2]++; break; case 7: N1[0]++; N1[2]++; N2[2]++; break; case 8: N2[2]++; break; case 9: N1[1]++; N2[1]++; N2[2]++; break; case 10: N1[0]++; N1[1]++; N2[0]++; N2[1]++; N2[2]++; break; case 11: N1[0]++; N2[0]++; N2[2]++; break; } QVector3D P1 = m_Grid.m_Min + N1 * m_Grid.m_UnitWidth; QVector3D P2 = m_Grid.m_Min + N2 * m_Grid.m_UnitWidth; // used for computing index unsigned int nSlice0 = m_Grid.m_nNum[0] + 1; unsigned int nSlice1 = nSlice0 * (m_Grid.m_nNum[1] + 1); float V1 = m_pScalarField[(int)(N1.z() * nSlice1 + N1.y() * nSlice0 + N1.x())]; float V2 = m_pScalarField[(int)(N2.z() * nSlice1 + N2.y() * nSlice0 + N2.x())]; float V = m_fIsoLevel; // The linear interpolation is calculated BBMCVertex intersection; intersection.m_nID = -1; intersection.m_Position = P1 + (V - V1) * (P2 - P1) / (V2 - V1); return intersection; } /** * @brief BBMarchingCubeMesh::getEdgeID * @param x * @param y * @param z * @param nEdge 0~11 * @return total */ unsigned int BBMarchingCubeMesh::getEdgeID(unsigned int x, unsigned int y, unsigned int z, unsigned int nEdge) { switch (nEdge) { case 0: return getVertexID(x, y, z) + 1; case 1: return getVertexID(x, y + 1, z); case 2: return getVertexID(x + 1, y, z) + 1; case 3: return getVertexID(x, y, z); case 4: return getVertexID(x, y, z + 1) + 1; case 5: return getVertexID(x, y + 1, z + 1); case 6: return getVertexID(x + 1, y, z + 1) + 1; case 7: return getVertexID(x, y, z + 1); case 8: return getVertexID(x, y, z) + 2; case 9: return getVertexID(x, y + 1, z) + 2; case 10: return getVertexID(x + 1, y + 1, z) + 2; case 11: return getVertexID(x + 1, y, z) + 2; default: return -1; } } unsigned int BBMarchingCubeMesh::getVertexID(unsigned int x, unsigned int y, unsigned int z) { // * 3 because of triangle return 3 * (z * (m_Grid.m_nNum[1] + 1) * (m_Grid.m_nNum[0] + 1) + y * (m_Grid.m_nNum[0] + 1) + x); } void BBMarchingCubeMesh::generateVBOAndEBO() { BBMCEVMap::iterator mapIt = m_EVMap.begin(); BBMCTriangleVector::iterator vecIt = m_TriangleVector.begin(); unsigned int nVertexID = 0; // normalize id while (mapIt != m_EVMap.end()) { (*mapIt).second.m_nID = nVertexID; nVertexID++; mapIt++; } if (nVertexID == 0) return; while (vecIt != m_TriangleVector.end()) { for (unsigned int i = 0; i < 3; i++) { unsigned int newID = m_EVMap[(*vecIt).m_VertexID[i]].m_nID; (*vecIt).m_VertexID[i] = newID; } vecIt++; } mapIt = m_EVMap.begin(); m_pVBO = new BBVertexBufferObject(nVertexID); for (unsigned int i = 0; i < nVertexID; i++, mapIt++) { m_pVBO->setPosition(i, (*mapIt).second.m_Position); m_pVBO->setColor(i, 1.0f, 1.0f, 1.0f, 0.5f); } vecIt = m_TriangleVector.begin(); m_nIndexCount = 3 * m_TriangleVector.size(); m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0; i < m_nIndexCount; i += 3, vecIt++) { m_pIndexes[i] = (*vecIt).m_VertexID[0]; m_pIndexes[i + 1] = (*vecIt).m_VertexID[1]; m_pIndexes[i + 2] = (*vecIt).m_VertexID[2]; } m_pVBO->computeNormal(m_pIndexes, m_nIndexCount); m_pVBO->submitData(); if (m_pEBO) BB_SAFE_DELETE(m_pEBO); m_pEBO = new BBElementBufferObject(m_nIndexCount); m_pEBO->submitData(m_pIndexes, m_nIndexCount); m_pDrawCalls->setVBO(m_pVBO); m_pDrawCalls->setEBO(m_pEBO, GL_TRIANGLES, m_nIndexCount, 0); m_EVMap.clear(); m_TriangleVector.clear(); } void BBMarchingCubeMesh::deleteSurface() { m_bValidSurface = false; m_pScalarField = nullptr; m_fIsoLevel = 0; m_Grid.m_nNum[0] = 0; m_Grid.m_nNum[1] = 0; m_Grid.m_nNum[2] = 0; m_Grid.m_UnitWidth = QVector3D(0, 0, 0); m_Grid.m_Min = QVector3D(0, 0, 0); m_EVMap.clear(); m_TriangleVector.clear(); } <|start_filename|>Code/BBearEditor/Engine/Render/BufferObject/BBAtomicCounterBufferObject.cpp<|end_filename|> #include "BBAtomicCounterBufferObject.h" BBAtomicCounterBufferObject::BBAtomicCounterBufferObject() : BBBufferObject() { createBufferObject(GL_ATOMIC_COUNTER_BUFFER, sizeof(GLuint), GL_DYNAMIC_DRAW); clear(); } void BBAtomicCounterBufferObject::clear() { GLuint *pContent = nullptr; glBindBuffer(m_BufferType, m_Name); pContent = (GLuint*)glMapBufferRange(m_BufferType, 0, sizeof(GLuint), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT | GL_MAP_UNSYNCHRONIZED_BIT); memset(pContent, 0, sizeof(GLuint)); glUnmapBuffer(m_BufferType); } void BBAtomicCounterBufferObject::bind() { // Parameter 2 corresponds to the binding tag in the shader glBindBufferBase(m_BufferType, 0, m_Name); } void BBAtomicCounterBufferObject::unbind() { glBindBufferBase(m_BufferType, 0, 0); } <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBGroupManager.h<|end_filename|> #ifndef BBGROUPMANAGER_H #define BBGROUPMANAGER_H #include <QWidget> class BBLineEditFactory; class QToolButton; class QPushButton; class QMenu; class BBGameObject; class BBVector3DFactory; class BBScene; class BBEnumFactory; class QCheckBox; // Manage a group of property class BBGroupManager : public QWidget { Q_OBJECT public: explicit BBGroupManager(const QString &groupName, const QString &iconPath, QWidget *pParent = nullptr); ~BBGroupManager(); QWidget* addFactory(const QString &name, QWidget *pFactory, int nStretch = 1, const Qt::Alignment &alignment = Qt::Alignment()); QWidget* addFactories(const QString &name, QWidget *pFactory1, QWidget *pFactory2, int nStretch = 1); QWidget* addFactory(QWidget *pFactory, const QString &name = "default"); BBLineEditFactory* addFactory(const QString &name, float fValue); void addMargin(int nHeight); public slots: void setContainerExpanded(bool bExpanded); protected: QToolButton *m_pMainButton; QPushButton *m_pMenuButton; QMenu *m_pMenu; QWidget *m_pContainer; }; enum BBReferenceSystem { Global = 0, Local = 1 }; class BBTransformGroupManager : public BBGroupManager { Q_OBJECT public: BBTransformGroupManager(BBGameObject *pGameObject, QWidget *pParent = 0); ~BBTransformGroupManager(); void updatePositionValue(); void updateRotationValue(); void updateScaleValue(); private slots: void changePosition(const QVector3D &value); void changeRotation(const QVector3D &value); void changeScale(const QVector3D &value); void popMenu(); void showGlobalCoordinate(); void showLocalCoordinate(); signals: void coordinateSystemUpdated(); private: BBVector3DFactory *m_pPositionFactory; BBVector3DFactory *m_pRotationFactory; BBVector3DFactory *m_pScaleFactory; BBGameObject *m_pCurrentGameObject; BBReferenceSystem m_eReferenceSystem; }; #endif // BBGROUPMANAGER_H <|start_filename|>Code/BBearEditor/Editor/SceneManager/BBHierarchyTreeWidget.cpp<|end_filename|> #include "BBHierarchyTreeWidget.h" #include <QMimeData> #include <QMenu> #include "Base/BBGameObject.h" #include "Base/BBGameObjectSet.h" #include "Scene/BBSceneManager.h" BBHierarchyTreeWidget::BBHierarchyTreeWidget(QWidget *parent) : BBTreeWidget(parent) { BBSceneManager::bindHierarchyTreeWidget(this); QStringList list; list.push_back("Label"); list.push_back("Type"); setHeaderLabels(list); // Column width of the first column setColumnWidth(0, 300); QObject::connect(this, SIGNAL(itemSelectionChanged()), this, SLOT(changeSelectedItems())); QObject::connect(this, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(doubleClickItem(QTreeWidgetItem*, int))); // QObject::connect(this, SIGNAL(itemChanged(QTreeWidgetItem*, int)), // this, SLOT(itemChangedSlot(QTreeWidgetItem*, int))); // Popup menu setMenu(); } void BBHierarchyTreeWidget::takeTopLevelItems() { while (topLevelItemCount() > 0) { takeTopLevelItem(0); } } void BBHierarchyTreeWidget::reconstruct(const QList<QTreeWidgetItem*> &topLevelItems) { addTopLevelItems(topLevelItems); } void BBHierarchyTreeWidget::setMenu() { m_pMenu = new QMenu(this); QAction *pActionUndo = new QAction(tr("Undo")); pActionUndo->setShortcut(QKeySequence(tr("Ctrl+Z"))); QAction *pActionRedo = new QAction(tr("Redo")); pActionRedo->setShortcut(QKeySequence(tr("Shift+Ctrl+Z"))); QAction *pActionCopy = new QAction(tr("Copy")); pActionCopy->setShortcut(QKeySequence(tr("Ctrl+C"))); QAction *pActionPaste = new QAction(tr("Paste")); pActionPaste->setShortcut(QKeySequence(tr("Ctrl+V"))); QAction *pActionRename = new QAction(tr("Rename")); #if defined(Q_OS_WIN32) pActionRename->setShortcut(Qt::Key_F2); #elif defined(Q_OS_MAC) pActionRename->setShortcut(Qt::Key_Return); #endif QAction *pActionDelete = new QAction(tr("Delete")); pActionDelete->setShortcut(QKeySequence(tr("Ctrl+D"))); m_pMenu->addAction(pActionUndo); m_pMenu->addAction(pActionRedo); m_pMenu->addSeparator(); m_pMenu->addAction(pActionCopy); m_pMenu->addAction(pActionPaste); m_pMenu->addSeparator(); m_pMenu->addAction(pActionRename); m_pMenu->addAction(pActionDelete); // connect the trigger event QObject::connect(pActionCopy, SIGNAL(triggered()), this, SLOT(copyAction())); QObject::connect(pActionPaste, SIGNAL(triggered()), this, SLOT(pasteAction())); QObject::connect(pActionRename, SIGNAL(triggered()), this, SLOT(openRenameEditor())); QObject::connect(pActionDelete, SIGNAL(triggered()), this, SLOT(deleteAction())); } void BBHierarchyTreeWidget::pasteOne(QTreeWidgetItem *pSource, QTreeWidgetItem* pTranscript) { // copy GameObject in the scene, and insert map copyGameObject(BBSceneManager::getGameObject(pSource), pTranscript); // handle children for (int i = 0; i < pSource->childCount(); i++) { pasteOne(pSource->child(i), pTranscript->child(i)); } } void BBHierarchyTreeWidget::deleteOne(QTreeWidgetItem *pItem) { // remove corresponding gameobject and map BBGameObject *pGameObject = BBSceneManager::getGameObject(pItem); // //如果是模型对象 其使用的材质的使用者列表 需要除去该对象 // if (object->getClassName() == ModelClassName) // { // Model *model = (Model*) object; // model->materialRemoveUser(); // } BBSceneManager::removeObjectMap(pItem); BBTreeWidget::deleteOne(pItem); // cannot delete pGameObject before deleting treeItem // because when treeitem changes, removing coordinate system will be triggered, which needs pGameObject deleteGameObject(pGameObject); } bool BBHierarchyTreeWidget::moveItem() { if (BBTreeWidget::moveItem()) { // successful drop, change local transform of all selected items QList<QTreeWidgetItem*> items = selectedItems(); for (int i = 0; i < items.count(); i++) { QTreeWidgetItem *pItem = items.at(i); BBGameObject *pParent = BBSceneManager::getGameObject(pItem->parent()); BBSceneManager::getGameObject(pItem)->setLocalTransform(pParent); } // update the property manager // otherwise, the local coordinates is the previous value that is relative to previous parent changeSelectedItems(); return true; } else { return false; } } bool BBHierarchyTreeWidget::moveItemFromFileList(const QMimeData *pMimeData) { BB_PROCESS_ERROR_RETURN_FALSE(m_pIndicatorItem); QByteArray data; QDataStream dataStream(&data, QIODevice::ReadOnly); QString filePath; dataStream >> filePath; qDebug() << filePath; } bool BBHierarchyTreeWidget::moveItemFromOthers(const QMimeData *pMimeData) { QByteArray data; if ((data = pMimeData->data(BB_MIMETYPE_BASEOBJECT)) != nullptr) { QDataStream dataStream(&data, QIODevice::ReadOnly); QString filePath; dataStream >> filePath; if (filePath == BB_PATH_TERRAIN) { // create terrain // createModel(filePath); } else { filePath = BB_PATH_RESOURCE_MESH() + filePath; createModel(filePath); } } else if ((data = pMimeData->data(BB_MIMETYPE_LIGHTOBJECT)) != nullptr) { QDataStream dataStream(&data, QIODevice::ReadOnly); QString fileName; dataStream >> fileName; createLight(fileName); } else { return false; } moveItemToIndicator(); return true; } void BBHierarchyTreeWidget::moveItemToIndicator() { // Objects dragged from the file list or prefab list // The default item created is the last one at the top level QTreeWidgetItem *pItem = topLevelItem(topLevelItemCount() - 1); // move to m_pIndicatorItem if (m_pIndicatorItem) { // pos int index = -1; QTreeWidgetItem *pParent = getParentOfMovingItem(index); // remove item that needs to move takeTopLevelItem(topLevelItemCount() - 1); // change local coordinate BBGameObject *pGameObject = BBSceneManager::getGameObject(pItem); if (!pGameObject) return; BBGameObject *pParentGameObject = BBSceneManager::getGameObject(pParent); pGameObject->setLocalTransform(pParentGameObject); // add in the new position if (pParent) { pParent->insertChild(index, pItem); } else { insertTopLevelItem(index, pItem); } // focus on setCurrentItem(pItem); // expand parent, show new item if (pParent) { setItemExpanded(pParent, true); } } // if m_pIndicatorItem is NULL, means adding to the end. No need to move } QIcon BBHierarchyTreeWidget::getClassIcon(const QString &className) { return QIcon(BB_PATH_RESOURCE_ICON() + className + ".png"); } void BBHierarchyTreeWidget::addGameObject(BBGameObject *pGameObject) { QTreeWidgetItem* pItem = new QTreeWidgetItem({pGameObject->getName(), pGameObject->getClassName()}); pItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled); // Checked means active if (pGameObject->getActivity()) pItem->setCheckState(0, Qt::Checked); else pItem->setCheckState(0, Qt::Unchecked); pItem->setIcon(1, getClassIcon(pGameObject->getIconName())); addTopLevelItem(pItem); BBSceneManager::insertObjectMap(pItem, pGameObject); // parent = NULL, since pItem is in the top level pGameObject->setLocalTransform(NULL); // setCurrentItem needs to be placed in back of insert map // otherwise, when currentItem is changed and trigger changeSelectedItems that cannot find pGameObject in map setCurrentItem(pItem); } void BBHierarchyTreeWidget::addGameObject(BBGameObject *pGameObject, QTreeWidgetItem *pItem) { BBSceneManager::insertObjectMap(pItem, pGameObject); BBGameObject *pParent = BBSceneManager::getGameObject(pItem->parent()); pGameObject->setLocalTransform(pParent); // show property in inspector setItemSelected(pItem, true); setItemExpanded(pItem, true); changeSelectedItems(); } void BBHierarchyTreeWidget::selectPickedItem(BBGameObject *pGameObject) { if (pGameObject == NULL) { setCurrentItem(NULL); } else { setCurrentItem(BBSceneManager::getSceneTreeItem(pGameObject)); } } void BBHierarchyTreeWidget::selectPickedItems(const QList<BBGameObject*> &gameObjects) { QList<QTreeWidgetItem*> items = BBSceneManager::getSceneTreeItems(gameObjects); QTreeWidgetItemIterator it(this); while (*it) { if (items.contains(*it)) { (*it)->setSelected(true); } else { (*it)->setSelected(false); } it++; } } void BBHierarchyTreeWidget::updateMultipleSelectedItems(BBGameObject *pGameObject) { // get item corresponding object QTreeWidgetItem *pItem = BBSceneManager::getSceneTreeItem(pGameObject); if (pItem->isSelected()) { // If it is already selected, uncheck it pItem->setSelected(false); // show indicator and bounding box ... // If the parent of the item is selected, the bounding box of the item still needs to be displayed QList<QTreeWidgetItem*> items = selectedItems(); QTreeWidgetItem *parent = NULL; for (parent = pItem->parent(); parent; parent = parent->parent()) { if (items.contains(parent)) { break; } } if (parent == NULL) { // all itself and its parent are not selected pGameObject->setVisibility(false); } } else { // If it is not selected, select it pItem->setSelected(true); } } void BBHierarchyTreeWidget::changeSelectedItems() { emit removeCurrentItemInFileList(); QList<QTreeWidgetItem*> items = selectedItems(); int count = items.count(); if (count == 0) { // do not select object in OpenGL view setCoordinateSystemSelectedObject(NULL); // do not show properties in inspector showGameObjectProperty(NULL); } else if (count == 1) { // single selection BBGameObject *pGameObject = BBSceneManager::getGameObject(items.first()); // select corresponding object in OpenGL view setCoordinateSystemSelectedObject(pGameObject); // show properties in inspector showGameObjectProperty(pGameObject); } else { QList<BBGameObject*> gameObjects; for (int i = 0; i < count; i++) { // Ancestors and descendants are selected at the same time, only ancestors are processed QTreeWidgetItem *parent; for (parent = items.at(i)->parent(); parent; parent = parent->parent()) { // Traverse ancestors to see if they are also selected if (items.contains(parent)) { break; } } if (parent == NULL) { gameObjects.append(BBSceneManager::getGameObject(items.at(i))); } // if there is parent, the item can be processed when its parent is processed } count = gameObjects.count(); if (count == 1) { // after filter, there is just an item that needs to be processed BBGameObject *pGameObject = gameObjects.first(); setCoordinateSystemSelectedObject(pGameObject); // show properties in inspector showGameObjectProperty(pGameObject); } else { // The center of gravity of all objects selected in the coordinate system BBGameObjectSet *pSet = new BBGameObjectSet(gameObjects); pSet->setBaseAttributes("multiple", "Set", "set"); // When all objects are invisible, pSet shows an invisible icon pSet->setActivity(false); for (int i = 0; i < count; i++) { if (gameObjects.at(i)->getActivity()) { pSet->setActivity(true); break; } } setCoordinateSystemSelectedObjects(gameObjects, pSet); // show properties of the set in inspector showGameObjectSetProperty(pSet, gameObjects); } } } void BBHierarchyTreeWidget::doubleClickItem(QTreeWidgetItem *pItem, int nColumn) { Q_UNUSED(nColumn); lookAtGameObject(BBSceneManager::getGameObject(pItem)); } void BBHierarchyTreeWidget::deleteAction() { // no need to show BBConfirmationDialog filterSelectedItems(); QList<QTreeWidgetItem*> items = selectedItems(); if (items.count() == 0) return; for (int i = 0; i < items.count(); i++) { BBTreeWidget::deleteAction(items.at(i)); } setCurrentItem(NULL); } void BBHierarchyTreeWidget::removeCurrentItem() { setCurrentItem(NULL); } //bool HierarchyTree::moveItemFromFileList(const QMimeData *mimeData) //{ // //只接受网格文件 // QByteArray data = mimeData->data(FileList::getMimeType()); // QDataStream dataStream(&data, QIODevice::ReadOnly); // QString filePath; // dataStream >> filePath; // QString suffix = filePath.mid(filePath.lastIndexOf('.') + 1); // if (FileList::meshSuffixs.contains(suffix)) // { // createModel(filePath); // } // else // { // return false; // } // //新建的树节点根据指示器位置放置 // moveItemToIndicator(); // return true; //} //void HierarchyTree::finishRename() //{ // if (editingItem == NULL) // return; // //是否对名字进行了修改 // //新名字不为空 // QString name = edit->text(); // QString preName = editingItem->text(0); // if (preName != name && !name.isEmpty()) // { // //修改对应GameObject的名字 // GameObject *gameObject = mMap.value(editingItem); // gameObject->setName(name); // //更新属性栏 // updateNameInInspector(gameObject, name); // //item重命名 // editingItem->setText(0, name); // //重命名后 如果在剪贴板中 移除掉 // if (clipBoardItems.contains(editingItem)) // { // clipBoardItems.removeOne(editingItem); // } // } // BaseTree::finishRename(); //} //void HierarchyTree::itemChangedSlot(QTreeWidgetItem *item, int column) //{ // GameObject *gameObject = mMap.value(item); // bool isActive = item->checkState(column); // gameObject->setActive(isActive); // //属性栏的可见性按钮状态刷新 // changeButtonActiveCheckStateInInspector(gameObject, isActive); // //选中当前项 只点击复选框 不会选中当前项 // setCurrentItem(item); //} //void HierarchyTree::renameItemName(GameObject *gameObject) //{ // QTreeWidgetItem *item = mMap.key(gameObject); // item->setText(0, gameObject->getName()); // //重命名后 如果在剪贴板中 移除掉 // if (clipBoardItems.contains(item)) // { // clipBoardItems.removeOne(item); // } //} //void HierarchyTree::changeGameObjectActivation(GameObject *gameObject, bool isActive) //{ // if (isActive) // mMap.key(gameObject)->setCheckState(0, Qt::Checked); // else // mMap.key(gameObject)->setCheckState(0, Qt::Unchecked); // //checkState修改会调用itemChangedSlot //} //void HierarchyTree::focusInEvent(QFocusEvent *event) //{ // Q_UNUSED(event); // cancelFileListSelectedItems(); //} <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFileListWidget.h<|end_filename|> #ifndef BBFILELISTWIDGET_H #define BBFILELISTWIDGET_H #include <QListWidget> #include <QPlainTextEdit> #include "Utils/BBUtils.h" using namespace BBFileSystem; class QWidgetAction; class BBPlainTextEdit : public QPlainTextEdit { Q_OBJECT public: BBPlainTextEdit(QWidget *pParent = 0); signals: void editFinished(); private: void focusOutEvent(QFocusEvent *event) override; void keyPressEvent(QKeyEvent *event) override; }; class BBFileListWidget : public QListWidget { Q_OBJECT public: explicit BBFileListWidget(QWidget *pParent = nullptr); ~BBFileListWidget(); inline QString getMimeType() { return BB_MIMETYPE_FILELISTWIDGET; } inline QString getCurrentParentPath() { return m_ParentPath; } void loadItems(const QString &parentPath, BBFILE *pFileData, QListWidgetItem *pCurrentItem); void setSelectedItems(const QList<QListWidgetItem*> &items); public: static QSize m_ItemSize; private slots: void clickItem(QListWidgetItem *pItem); void pressItem(QListWidgetItem *pItem); void doubleClickItem(QListWidgetItem *pItem); void changeCurrentItem(QListWidgetItem *pCurrent, QListWidgetItem *pPrevious); void changeItemSize(int factor); void newFolder(); void newSceneAction(); void newMaterialAction(); void newScript(); void showInFolder(); void copyAction(); void pasteAction(); void openRenameEditor(); void finishRename(); void deleteAction(); signals: void openFile(const QString &filePath, const BBFileType &eType); void newFolder(const QString &parentPath, const BBSignalSender &eSender); void newFile(const QString &parentPath, int nType); void showInFolder(const QString &filePath); void rename(QListWidgetItem *pFileItem, const QString &oldPath, const QString &newPath); void deleteFiles(const QList<QListWidgetItem*> &items); void importAsset(const QString &parentPath, const QList<QUrl> &urls); void moveFolders(const QList<QString> &oldFilePaths, const QString &newParentPath, bool bCopy); void moveFiles(const QList<QListWidgetItem*> &items, const QString &oldParentPath, const QString &newParentPath, bool bCopy); void clickItem(const QString &filePath, const BBFileType &eType); void pressItem(const BBFileType &eType); void changeCurrentItem(BBFileType eCurrentType, BBFileType ePreviousType); void inFocus(); private: void setMenu(); QWidgetAction* createWidgetAction(const QString &iconPath, const QString &name); void newFile(int nType); void startDrag(Qt::DropActions supportedActions) override; void dragEnterEvent(QDragEnterEvent *event) override; void dragMoveEvent(QDragMoveEvent *event) override; void dragLeaveEvent(QDragLeaveEvent *event) override; void dropEvent(QDropEvent *event) override; bool moveItem(); bool moveItemFromFolderTree(const QMimeData *pMimeData); void paintEvent(QPaintEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void contextMenuEvent(QContextMenuEvent *event) override; void keyPressEvent(QKeyEvent *event) override; void focusInEvent(QFocusEvent *event) override; QString getPathByItem(QListWidgetItem *pItem); const BBSignalSender m_eSenderTag; static QSize m_StandardIconSize; static QSize m_StandardItemSize; QMenu *m_pMenu; QString m_ParentPath; BBFILE *m_pFileData; QListWidgetItem *m_pEditingItem; BBPlainTextEdit *m_pRenameEditor; QListWidgetItem *m_pIndicatorItem; }; #endif // BBFILELISTWIDGET_H //private slots: // void pasteFileFromProjectTree(QList<QString> filePaths, QString destPath, QList<QString> pastedFolderNames); // void updateMaterialFileIcon(QString filePath); //signals: // void showMaterialProperty(QString filePath); // void showFbxProperty(QString filePath); // void clearPropertyWidget(); <|start_filename|>Code/BBearEditor/Engine/Profiler/BBProfiler.cpp<|end_filename|> #include "BBProfiler.h" #include "Utils/BBUtils.h" QMap<void*, BBMemoryLabel>* BBProfiler::m_pMemoryObjects = NULL; QMap<void*, size_t>* BBProfiler::m_pMemoryObjectsSize = NULL; QMap<BBMemoryLabel, int>* BBProfiler::m_pUsedMemorySize = NULL; int BBProfiler::m_nTotalUsedMemorySize = 0; void BBProfiler::init() { static QMap<void*, BBMemoryLabel> memoryObjects = BBStatic::var<0, QMap<void*, BBMemoryLabel>>(); static QMap<void*, size_t> memoryObjectsSize = BBStatic::var<0, QMap<void*, size_t>>(); static QMap<BBMemoryLabel, int> usedMemorySize = BBStatic::var<0, QMap<BBMemoryLabel, int>>(); m_pMemoryObjects = &memoryObjects; m_pMemoryObjectsSize = &memoryObjectsSize; m_pUsedMemorySize = &usedMemorySize; } void BBProfiler::addMemoryObject(void *ptr, const BBMemoryLabel &eLabel, size_t size) { if (!m_pMemoryObjects || !m_pMemoryObjectsSize || !m_pUsedMemorySize) { init(); } m_pMemoryObjects->insert(ptr, eLabel); m_pMemoryObjectsSize->insert(ptr, size); m_nTotalUsedMemorySize += size; if (m_pUsedMemorySize->find(eLabel) != m_pUsedMemorySize->end()) { (*m_pUsedMemorySize)[eLabel] += size; } else { m_pUsedMemorySize->insert(eLabel, size); } } bool BBProfiler::deleteMemoryObject(void *ptr) { QMap<void*, BBMemoryLabel>::Iterator iter = m_pMemoryObjects->find(ptr); if (iter != m_pMemoryObjects->end()) { auto sizeIter = m_pMemoryObjectsSize->find(ptr); int size = sizeIter.value(); (*m_pUsedMemorySize)[iter.value()] -= size; m_nTotalUsedMemorySize -= size; m_pMemoryObjectsSize->erase(sizeIter); m_pMemoryObjects->erase(iter); return true; } return false; } int BBProfiler::getTotalUsedMemorySize() { return m_nTotalUsedMemorySize; } <|start_filename|>Resources/shaders/ParticleSystem/Particles1.frag<|end_filename|> #version 430 varying vec4 v2f_color; varying vec2 v2f_texcoord; void main(void) { float d = length(v2f_texcoord * 2.0 - 1.0) * 2.5; float a = exp(-d * d); if (a < 0.01) discard; gl_FragColor = vec4(v2f_color.rgb, a); } <|start_filename|>Code/BBearEditor/Editor/Render/BBEditViewOpenGLWidget.cpp<|end_filename|> #include "BBEditViewOpenGLWidget.h" #include "Scene/BBScene.h" #include "Render/BBCamera.h" #include <QMouseEvent> #include "Utils/BBUtils.h" #include "Base/BBGameObject.h" #include <QMimeData> #include "3D/BBModel.h" #include <QDrag> #include "Geometry/BBRay.h" #include "Scene/CoordinateSystem/BBTransformCoordinateSystem.h" #include <QTreeWidgetItem> #include "Scene/BBSceneManager.h" #include "Lighting/GameObject/BBLight.h" #include "2D/BBCanvas.h" #include "2D/BBSpriteObject2D.h" #include "ParticleSystem/BBParticleSystem.h" #include "FileSystem/BBFileSystemDataManager.h" #include "Scene/BBRendererManager.h" BBEditViewOpenGLWidget::BBEditViewOpenGLWidget(QWidget *pParent) : BBOpenGLWidget(pParent) { BBSceneManager::bindEditViewOpenGLWidget(this); m_bRightPressed = false; m_pCurrentCanvas = nullptr; m_pPreviewObject = nullptr; setAcceptDrops(true); // Mouse events can be captured without pressing setMouseTracking(true); m_bRegionSelecting = false; // Single selection mode m_bMultipleSelecting = false; startRenderThread(); // //右下角的浏览视图 // QHBoxLayout *l = new QHBoxLayout(this); // l->setMargin(0); // mPreview = new BaseOpenGLWidget(this); // mPreview->setMinimumSize(150, 100); // l->addWidget(mPreview, 1, Qt::AlignBottom | Qt::AlignRight); // mPreview->hide(); } BBEditViewOpenGLWidget::~BBEditViewOpenGLWidget() { BB_SAFE_DELETE(m_pPreviewObject); stopRenderThread(); } BBGameObject* BBEditViewOpenGLWidget::createModel(const BBSerializer::BBGameObject &gameObject) { BBGameObject *pResult = m_pScene->createModel(gameObject); addGameObject(pResult); return pResult; } void BBEditViewOpenGLWidget::startRenderThread() { m_pRenderThread = new QThread(this); m_pRenderTimer = new QTimer(); m_pRenderTimer->setInterval(BB_CONSTANT_UPDATE_RATE); m_pRenderTimer->moveToThread(m_pRenderThread); QObject::connect(m_pRenderThread, SIGNAL(started()), m_pRenderTimer, SLOT(start())); QObject::connect(m_pRenderTimer, SIGNAL(timeout()), this, SLOT(update()), Qt::DirectConnection); QObject::connect(m_pRenderThread, SIGNAL(finished()), m_pRenderTimer, SLOT(deleteLater())); m_pRenderThread->start(); } void BBEditViewOpenGLWidget::stopRenderThread() { m_pRenderThread->quit(); m_pRenderThread->wait(); BB_SAFE_DELETE(m_pRenderThread); } void BBEditViewOpenGLWidget::pressESC() { setCoordinateSystemSelectedObject(nullptr); } void BBEditViewOpenGLWidget::pressMoveKey(char key) { // Handling camera movement if (!m_bRightPressed) return; // qDebug() << key << "true"; m_pScene->getCamera()->move(key, true); } void BBEditViewOpenGLWidget::releaseMoveKey(char key) { if (!m_bRightPressed) return; // qDebug() << key << "false"; m_pScene->getCamera()->move(key, false); } void BBEditViewOpenGLWidget::pressTransform(char key) { // If the camera is processed, the coordinate system transform is not processed if (m_bRightPressed) return; m_pScene->getTransformCoordinateSystem()->setCoordinateSystem(key); } void BBEditViewOpenGLWidget::setCoordinateSystemSelectedObject(BBGameObject *pGameObject) { m_pScene->getTransformCoordinateSystem()->setSelectedObject(pGameObject); } void BBEditViewOpenGLWidget::setCoordinateSystemSelectedObjects(const QList<BBGameObject*> &gameObjects, BBGameObjectSet *pSet) { m_pScene->getTransformCoordinateSystem()->setSelectedObjects(gameObjects, pSet); } void BBEditViewOpenGLWidget::pressMultipleSelectionKey(bool bPressed) { // switch single or multiple selection mode m_bMultipleSelecting = bPressed; } void BBEditViewOpenGLWidget::updateCoordinateSystem() { m_pScene->getTransformCoordinateSystem()->update(); } void BBEditViewOpenGLWidget::createModelAtOrigin(const QString &filePath) { // Send signal to treeHierarchy addGameObject(m_pScene->createModel(filePath)); } void BBEditViewOpenGLWidget::createLightAtOrigin(const QString &fileName) { addGameObject(m_pScene->createLight(fileName)); } void BBEditViewOpenGLWidget::deleteGameObject(BBGameObject *pGameObject) { m_pScene->deleteGameObject(pGameObject); } void BBEditViewOpenGLWidget::copyGameObject(BBGameObject *pSourceObject, QTreeWidgetItem *pTranscriptItem) { BBGameObject *pTranscriptObject = NULL; if (pSourceObject->getClassName() == BB_CLASSNAME_MODEL) { pTranscriptObject = m_pScene->createModel(pSourceObject->getFilePath(), pSourceObject->getPosition()); } // else if (sourceObject->getClassName() == DirectionLightClassName // || sourceObject->getClassName() == PointLightClassName // || sourceObject->getClassName() == SpotLightClassName) // { // //拷贝一个灯光对象 // transcriptObject = scene.createLight(sourceObject->getFilePath(), position); // } else { } BB_PROCESS_ERROR_RETURN(pTranscriptObject); pTranscriptObject->setName(pTranscriptItem->text(0)); pTranscriptObject->setActivity(pSourceObject->getActivity()); // then, handle in HierarchyTreeWidget addGameObject(pTranscriptObject, pTranscriptItem); } void BBEditViewOpenGLWidget::lookAtGameObject(BBGameObject *pGameObject) { m_pScene->lookAtGameObject(pGameObject); } void BBEditViewOpenGLWidget::createPreviewModel() { m_pPreviewObject = m_pScene->createModel(m_UserDataInThread, m_nXInThread, m_nYInThread); } void BBEditViewOpenGLWidget::mousePressEvent(QMouseEvent *e) { if (e->button() == Qt::RightButton) { m_bRightPressed = true; m_OriginalMousePos = e->globalPos(); setCursor(Qt::BlankCursor); } else if (e->button() == Qt::LeftButton) { // Start dragging for selection area, and record the starting point m_SelectionRegionStartingPoint = e->pos(); } } void BBEditViewOpenGLWidget::mouseMoveEvent(QMouseEvent *e) { if (e->buttons() & Qt::RightButton) { QPoint currentPos = e->globalPos(); float deltaX = currentPos.x() - m_OriginalMousePos.x(); float deltaY = currentPos.y() - m_OriginalMousePos.y(); // rotate camera // Otherwise, the farther the current moves, the larger the delta QCursor::setPos(m_OriginalMousePos); //qDebug() << "rotate camera"; float angleRotatedByUp = deltaX / 1000; float angleRotatedByRight = deltaY / 1000; m_pScene->getCamera()->yaw(-angleRotatedByUp); m_pScene->getCamera()->pitch(-angleRotatedByRight); } else if (e->buttons() & Qt::LeftButton) { if (m_bRegionSelecting) { // do not perform transform of gameobject // show selection region, and select gameobjects m_pScene->setSelectionRegionVisibility(true); pickObjects(m_pScene->getSelectedObjects(m_SelectionRegionStartingPoint, e->pos())); } else { // do not perform selection operation BBRay ray = m_pScene->getCamera()->createRayFromScreen(e->pos().x(), e->pos().y()); if (m_pScene->getTransformCoordinateSystem()->mouseMoveEvent(e->pos().x(), e->pos().y(), ray, true)) { // update value in property manager updateTransformInPropertyManager(m_pScene->getTransformCoordinateSystem()->getSelectedObject(), m_pScene->getTransformCoordinateSystem()->getTransformModeKey()); } else { // if also do not perform transform, determine whether turn on m_bRegionSelecting // If the mouse moves only a small distance, it is not considered as selection operation QPoint delta = e->pos() - m_SelectionRegionStartingPoint; static int nThreshold = 49; if ((delta.x() * delta.x() + delta.y() * delta.y()) > nThreshold) { m_bRegionSelecting = true; } } } } else { // move mouse without press mouse BBRay ray = m_pScene->getCamera()->createRayFromScreen(e->pos().x(), e->pos().y()); m_pScene->getTransformCoordinateSystem()->mouseMoveEvent(e->pos().x(), e->pos().y(), ray, false); } } void BBEditViewOpenGLWidget::mouseReleaseEvent(QMouseEvent *e) { if (e->button() == Qt::RightButton) { // end camera movement m_bRightPressed = false; QCursor::setPos(m_OriginalMousePos); setCursor(Qt::ArrowCursor); m_pScene->getCamera()->resetMove(); } else if (e->button() == Qt::LeftButton) { BBRay ray = m_pScene->getCamera()->createRayFromScreen(e->pos().x(), e->pos().y()); // if it is the release at the end of the transform and selection operation // there is no need to pick object if (!m_pScene->getTransformCoordinateSystem()->isTransforming() && !m_bRegionSelecting) { // 3D pick objects BBGameObject *pObject = m_pScene->pickObjectInAllObjects(ray); // send signals, show related imformation in Hierarchy tree and inspector if (m_bMultipleSelecting) { // If the object is not NULL // add it to the multi-selection objects (or subtract it when it is already selected) if (pObject) { updateMultipleSelectedObjects(pObject); } } else { // Single selection pickObject(pObject); } } // When the coordinate system is no longer moved, reset m_LastMousePos // stop m_bTransforming, can pick object in the next mouse release m_pScene->getTransformCoordinateSystem()->stopTransform(); // When the coordinate system is moved, the mouse leaves the coordinate system // If the ray is not updated when released, the selected coordinate axis cannot be restored to its original color m_pScene->getTransformCoordinateSystem()->mouseMoveEvent(e->pos().x(), e->pos().y(), ray, false); // Exit selection mode m_pScene->setSelectionRegionVisibility(false); m_bRegionSelecting = false; } } void BBEditViewOpenGLWidget::wheelEvent(QWheelEvent *event) { m_pScene->getCamera()->setMoveSpeed(event->delta() > 0 ? 1 : -1); } void BBEditViewOpenGLWidget::dragEnterEvent(QDragEnterEvent *event) { QByteArray data; if ((data = event->mimeData()->data(BB_MIMETYPE_BASEOBJECT)) != nullptr) { QDataStream dataStream(&data, QIODevice::ReadOnly); m_DragType.clear(); dataStream >> m_DragType; if (m_DragType == BB_CLASSNAME_CANVAS) { m_pPreviewObject = m_pScene->createCanvas(event->pos().x(), event->pos().y()); } else if (m_DragType == BB_CLASSNAME_SPRITEOBJECT2D) { } else if (m_DragType == BB_CLASSNAME_TERRAIN) { openThreadToCreatePreviewModel(m_DragType, event->pos().x(), event->pos().y()); } else if (m_DragType == BB_CLASSNAME_PARTICLE) { m_pPreviewObject = m_pScene->createParticleSystem(event->pos().x(), event->pos().y()); } else if (m_DragType == BB_CLASSNAME_SPHFLUID) { m_pPreviewObject = m_pScene->createGameObject(event->pos().x(), event->pos().y(), BB_CLASSNAME_SPHFLUID); } else if (m_DragType == BB_CLASSNAME_CLOTH) { m_pPreviewObject = m_pScene->createGameObject(event->pos().x(), event->pos().y(), BB_CLASSNAME_CLOTH); } else if (m_DragType == BB_CLASSNAME_PROCEDURE_MESH) { m_pPreviewObject = m_pScene->createModel(BB_CLASSNAME_PROCEDURE_MESH, event->pos().x(), event->pos().y()); } else { // Create a temporary object to show drag effect // no need to create the corresponding item in the hierarchical tree openThreadToCreatePreviewModel(BB_PATH_RESOURCE_MESH() + m_DragType, event->pos().x(), event->pos().y()); } // Remove the selected state of the coordinate system setCoordinateSystemSelectedObject(NULL); event->accept(); } else if ((data = event->mimeData()->data(BB_MIMETYPE_LIGHTOBJECT)) != nullptr) { event->accept(); } else if ((data = event->mimeData()->data(BB_MIMETYPE_FILELISTWIDGET)) != nullptr) { QDataStream dataStream(&data, QIODevice::ReadOnly); QString filePath; dataStream >> filePath; if (BBFileSystemDataManager::judgeFileType(filePath, BBFileType::Mesh)) { openThreadToCreatePreviewModel(filePath, event->pos().x(), event->pos().y()); event->accept(); } else if (BBFileSystemDataManager::judgeFileType(filePath, BBFileType::Material)) { event->accept(); } else { event->ignore(); } } else { event->ignore(); } } void BBEditViewOpenGLWidget::dragMoveEvent(QDragMoveEvent *event) { QByteArray data; event->accept(); if (m_pPreviewObject) { if (m_pPreviewObject->getClassName() == BB_CLASSNAME_MODEL || m_pPreviewObject->getClassName() == BB_CLASSNAME_PARTICLE || m_pPreviewObject->getClassName() == BB_CLASSNAME_SPHFLUID || m_pPreviewObject->getClassName() == BB_CLASSNAME_CLOTH || m_pPreviewObject->getClassName() == BB_CLASSNAME_PROCEDURE_MESH) { BBRay ray = m_pScene->getCamera()->createRayFromScreen(event->pos().x(), event->pos().y()); m_pPreviewObject->setPosition(ray.computeIntersectWithXOZPlane(0)); } else if (m_pPreviewObject->getClassName() == BB_CLASSNAME_CANVAS) { m_pPreviewObject->setScreenCoordinateWithSwitchingOriginalPoint(event->pos().x(), event->pos().y()); } } else if (m_DragType == BB_CLASSNAME_SPRITEOBJECT2D) { m_pCurrentCanvas = nullptr; if (!m_pScene->hitCanvas(event->pos().x(), event->pos().y(), m_pCurrentCanvas)) { event->ignore(); } } else if ((data = event->mimeData()->data(BB_MIMETYPE_FILELISTWIDGET)) != nullptr) { QDataStream dataStream(&data, QIODevice::ReadOnly); QString filePath; dataStream >> filePath; // drag material file BBRay ray = m_pScene->getCamera()->createRayFromScreen(event->pos().x(), event->pos().y()); BBModel *pModel = (BBModel*)m_pScene->pickObjectInModels(ray, false); if (pModel) { pModel->setCurrentMaterial(BBRendererManager::loadMaterial(filePath)); } else { event->ignore(); } } } void BBEditViewOpenGLWidget::dragLeaveEvent(QDragLeaveEvent *event) { if (m_pPreviewObject) { // no longer show pre-created object m_pScene->deleteGameObject(m_pPreviewObject); m_pPreviewObject = nullptr; } event->accept(); } void BBEditViewOpenGLWidget::dropEvent(QDropEvent *event) { event->accept(); setFocus(); QByteArray data; if ((data = event->mimeData()->data(BB_MIMETYPE_BASEOBJECT)) != nullptr) { if (m_pPreviewObject) { // Show item in hierarchical tree // need the item so that set local coordinate addGameObject(m_pPreviewObject); // Set to empty for the next calculation m_pPreviewObject = nullptr; } else if (m_pCurrentCanvas) { BBSpriteObject2D *pSpriteObject2D = m_pScene->createSpriteObject2D(m_pCurrentCanvas, event->pos().x(), event->pos().y()); addGameObject(pSpriteObject2D); // need to make Sprite2D be the child of canvas BBSceneManager::addSpriteObject2DForCanvas(m_pCurrentCanvas, pSpriteObject2D); // Set to empty for the next calculation m_pCurrentCanvas = nullptr; } else { event->ignore(); } } else if ((data = event->mimeData()->data(BB_MIMETYPE_LIGHTOBJECT)) != nullptr) { QDataStream dataStream(&data, QIODevice::ReadOnly); QString fileName; dataStream >> fileName; BBGameObject *pLight = m_pScene->createLight(fileName, event->pos().x(), event->pos().y()); addGameObject(pLight); } else if ((data = event->mimeData()->data(BB_MIMETYPE_FILELISTWIDGET)) != nullptr) { if (m_pPreviewObject) { addGameObject(m_pPreviewObject); m_pPreviewObject = nullptr; } else { event->ignore(); } } else { event->ignore(); } } void BBEditViewOpenGLWidget::openThreadToCreatePreviewModel(const QString &userData, int x, int y) { QThread *pThread = new QThread(this); m_UserDataInThread = userData; m_nXInThread = x; m_nYInThread = y; QObject::connect(pThread, SIGNAL(started()), this, SLOT(createPreviewModel())); pThread->start(); } <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBMaterialPropertyGroupManager.cpp<|end_filename|> #include "BBMaterialPropertyGroupManager.h" #include "Utils/BBUtils.h" #include "Render/Texture/BBTexture.h" #include "Render/BBPreviewOpenGLWidget.h" #include "Scene/BBRendererManager.h" #include "Render/BBMaterial.h" #include <QCheckBox> #include "../BBPropertyFactory.h" #include "Render/BBMaterialProperty.h" BBMaterialPropertyGroupManager::BBMaterialPropertyGroupManager(BBMaterial *pMaterial, BBPreviewOpenGLWidget *pPreviewOpenGLWidget, QWidget *pParent) : BBGroupManager("Main", BB_PATH_RESOURCE_ICON(render.png), pParent) { m_pMaterial = pMaterial; m_pPreviewOpenGLWidget = pPreviewOpenGLWidget; addBlendStateItem(); addBlendFuncItem(); addCullStateItem(); addCullFaceItem(); addMargin(10); // read BBMaterialProperty addPropertyItems(); } BBMaterialPropertyGroupManager::~BBMaterialPropertyGroupManager() { } void BBMaterialPropertyGroupManager::addBlendStateItem() { QCheckBox *pBlendState = new QCheckBox(this); addFactory("Blend State", pBlendState, 1, Qt::AlignRight); // original value bool bBlendState = m_pMaterial->getBlendState(); pBlendState->setChecked(bBlendState); QObject::connect(pBlendState, SIGNAL(clicked(bool)), this, SLOT(enableBlendState(bool))); } void BBMaterialPropertyGroupManager::addBlendFuncItem() { QStringList items = {"GL_ZERO", "GL_ONE", "GL_SRC_COLOR", "GL_ONE_MINUS_SRC_COLOR", "GL_SRC_ALPHA", "GL_ONE_MINUS_SRC_ALPHA", "GL_DST_ALPHA", "GL_ONE_MINUS_DST_ALPHA"}; BBEnumFactory *pSRCBlendFunc = new BBEnumFactory("SRC", items, BBUtils::getBlendFuncName(m_pMaterial->getSRCBlendFunc()), this); BBEnumFactory *pDSTBlendFunc = new BBEnumFactory("DST", items, BBUtils::getBlendFuncName(m_pMaterial->getDSTBlendFunc()), this); QObject::connect(pSRCBlendFunc, SIGNAL(currentItemChanged(int)), this, SLOT(switchSRCBlendFunc(int))); QObject::connect(pDSTBlendFunc, SIGNAL(currentItemChanged(int)), this, SLOT(switchDSTBlendFunc(int))); QWidget *pWidget = addFactories("Blend Func", pSRCBlendFunc, pDSTBlendFunc); pWidget->setVisible(m_pMaterial->getBlendState()); } void BBMaterialPropertyGroupManager::addCullStateItem() { QCheckBox *pCullState = new QCheckBox(this); addFactory("Cull State", pCullState, 1, Qt::AlignRight); // original value bool bCullState = m_pMaterial->getCullState(); pCullState->setChecked(bCullState); QObject::connect(pCullState, SIGNAL(clicked(bool)), this, SLOT(enableCullState(bool))); } void BBMaterialPropertyGroupManager::addCullFaceItem() { QStringList items = {"GL_FRONT", "GL_BACK"}; BBEnumFactory *pCullFace = new BBEnumFactory("Cull Face", items, BBUtils::getCullFaceName(m_pMaterial->getCullFace()), this, 1, 1); QObject::connect(pCullFace, SIGNAL(currentItemChanged(int)), this, SLOT(switchCullFace(int))); QWidget *pWidget = addFactory(pCullFace, "Cull Face"); pWidget->setVisible(m_pMaterial->getCullState()); } void BBMaterialPropertyGroupManager::enableBlendState(bool bEnable) { m_pMaterial->setBlendState(bEnable); QWidget* pWidget = findChild<QWidget*>("Blend Func"); if (pWidget) { m_pContainer->setVisible(false); pWidget->setVisible(bEnable); m_pContainer->setVisible(true); } m_pPreviewOpenGLWidget->updateMaterialSphere(m_pMaterial); BBRendererManager::changeBlendState(m_pMaterial, bEnable); } void BBMaterialPropertyGroupManager::switchSRCBlendFunc(int nIndex) { m_pMaterial->setSRCBlendFunc(BBUtils::getBlendFunc(nIndex)); m_pPreviewOpenGLWidget->updateMaterialSphere(m_pMaterial); BBRendererManager::changeSRCBlendFunc(m_pMaterial, nIndex); } void BBMaterialPropertyGroupManager::switchDSTBlendFunc(int nIndex) { m_pMaterial->setDSTBlendFunc(BBUtils::getBlendFunc(nIndex)); m_pPreviewOpenGLWidget->updateMaterialSphere(m_pMaterial); BBRendererManager::changeDSTBlendFunc(m_pMaterial, nIndex); } void BBMaterialPropertyGroupManager::enableCullState(bool bEnable) { m_pMaterial->setCullState(bEnable); QWidget* pWidget = findChild<QWidget*>("Cull Face"); if (pWidget) { m_pContainer->setVisible(false); pWidget->setVisible(bEnable); m_pContainer->setVisible(true); } m_pPreviewOpenGLWidget->updateMaterialSphere(m_pMaterial); BBRendererManager::changeCullState(m_pMaterial, bEnable); } void BBMaterialPropertyGroupManager::switchCullFace(int nIndex) { m_pMaterial->setCullFace(BBUtils::getCullFace(nIndex)); m_pPreviewOpenGLWidget->updateMaterialSphere(m_pMaterial); BBRendererManager::changeCullFace(m_pMaterial, BBUtils::getCullFace(nIndex)); } void BBMaterialPropertyGroupManager::addPropertyItems() { QList<std::string> names; QList<BBMaterialProperty*> properties; m_pMaterial->getEditableProperties(names, properties); for (int i = 0; i < properties.count(); i++) { BBMaterialUniformPropertyType eType = properties[i]->getType(); QString name = QString::fromStdString(names[i]); if (eType == BBMaterialUniformPropertyType::Vector4) { BBVector4MaterialProperty *pProperty = (BBVector4MaterialProperty*)properties[i]; BBVector4MaterialPropertyFactoryType eFactoryType = pProperty->getFactoryType(); if (eFactoryType == BBVector4MaterialPropertyFactoryType::Color) { const float *color = pProperty->getPropertyValue(); BBColorFactory *pColorFactory = new BBColorFactory(names[i], color[0], color[1], color[2], color[3], this); addFactory(pProperty->getNameInPropertyManager(), pColorFactory, 1); QObject::connect(pColorFactory, SIGNAL(colorChanged(float, float, float, float, std::string)), this, SLOT(setColor(float, float, float, float, std::string))); } else { } } else if (eType == BBMaterialUniformPropertyType::Float) { BBFloatMaterialProperty *pProperty = (BBFloatMaterialProperty*)properties[i]; BBLineEditFactory *pFloatFactory = addFactory(name, pProperty->getPropertyValue()); pFloatFactory->setSlideStep(0.005f); pFloatFactory->setRange(0, 1); QObject::connect(pFloatFactory, SIGNAL(valueChanged(QString, float)), this, SLOT(setFloat(QString, float))); } else if (eType == BBMaterialUniformPropertyType::Sampler2D) { BBSampler2DMaterialProperty *pProperty = (BBSampler2DMaterialProperty*)properties[i]; BBTextureFactory *pTextureFactory = new BBTextureFactory(name, pProperty->getResourcePath(), this); addFactory(name, pTextureFactory, 3); QObject::connect(pTextureFactory, SIGNAL(setSampler2D(QString, QString)), this, SLOT(setSampler2D(QString, QString))); // Find whether there are matching tiling and offset items QString key = LOCATION_TILINGANDOFFSET_PREFIX + name; int nIndex = names.indexOf(key.toStdString().c_str()); if (nIndex >= 0) { // whether the matching item is a TilingAndOffset, otherwise it will be invalid BBMaterialProperty *pMatchingProperty = properties[nIndex]; if (pMatchingProperty->getType() == BBMaterialUniformPropertyType::Vector4) { BBVector4MaterialProperty *pVecProperty = (BBVector4MaterialProperty*)pMatchingProperty; BBVector4MaterialPropertyFactoryType eFactoryType = pVecProperty->getFactoryType(); if (eFactoryType == BBVector4MaterialPropertyFactoryType::TilingAndOffset) { pTextureFactory->enableTilingAndOffset(true); const float *pValue = pVecProperty->getPropertyValue(); pTextureFactory->setTiling(pValue[0], pValue[1]); pTextureFactory->setOffset(pValue[2], pValue[3]); QObject::connect(pTextureFactory, SIGNAL(setTilingAndOffset(QString, float, float, float, float)), this, SLOT(setTilingAndOffset(QString, float, float, float, float))); } } } } else if (eType == BBMaterialUniformPropertyType::SamplerCube) { BBSamplerCubeMaterialProperty *pProperty = (BBSamplerCubeMaterialProperty*)properties[i]; BBCubeMapFactory *pCubeMapFactory = new BBCubeMapFactory(name, pProperty->getResourcePaths(), this); addFactory(pCubeMapFactory); QObject::connect(pCubeMapFactory, SIGNAL(setSamplerCube(QString, QString*)), this, SLOT(setSamplerCube(QString, QString*))); } } } void BBMaterialPropertyGroupManager::setSampler2D(const QString &uniformName, const QString &texturePath) { BBTexture texture; m_pMaterial->setSampler2D(uniformName.toStdString().c_str(), texture.createTexture2D(texturePath), texturePath); m_pPreviewOpenGLWidget->updateMaterialSphere(m_pMaterial); BBRendererManager::changeSampler2D(m_pMaterial, uniformName, texturePath); } void BBMaterialPropertyGroupManager::setTilingAndOffset(const QString &uniformName, float fTilingX, float fTilingY, float fOffsetX, float fOffsetY) { m_pMaterial->setVector4(uniformName.toStdString().c_str(), fTilingX, fTilingY, fOffsetX, fOffsetY); m_pPreviewOpenGLWidget->updateMaterialSphere(m_pMaterial); float *ptr = new float[4] {fTilingX, fTilingY, fOffsetX, fOffsetY}; BBRendererManager::changeVector4(m_pMaterial, uniformName.toStdString().c_str(), ptr); } void BBMaterialPropertyGroupManager::setSamplerCube(const QString &uniformName, QString *pResourcePaths) { BBTexture texture; m_pMaterial->setSamplerCube(uniformName.toStdString().c_str(), texture.createTextureCube(pResourcePaths), pResourcePaths); m_pPreviewOpenGLWidget->updateMaterialSphere(m_pMaterial); BBRendererManager::changeSamplerCube(m_pMaterial, uniformName, pResourcePaths); } void BBMaterialPropertyGroupManager::setFloat(const QString &uniformName, float fValue) { m_pMaterial->setFloat(uniformName.toStdString().c_str(), fValue); m_pPreviewOpenGLWidget->updateMaterialSphere(m_pMaterial); BBRendererManager::changeFloat(m_pMaterial, uniformName, fValue); } void BBMaterialPropertyGroupManager::setColor(float r, float g, float b, float a, const std::string &uniformName) { m_pMaterial->setVector4(uniformName, r, g, b, a); m_pPreviewOpenGLWidget->updateMaterialSphere(m_pMaterial); float *ptr = new float[4] {r, g, b, a}; BBRendererManager::changeVector4(m_pMaterial, uniformName, ptr); } <|start_filename|>Code/BBearEditor/Engine/Geometry/BBMeshSubdivision.cpp<|end_filename|> #include "BBMeshSubdivision.h" #include "Utils/BBUtils.h" #include "3D/Mesh/BBProcedureMesh.h" #include "Render/BufferObject/BBVertexBufferObject.h" /** * @brief BBMeshSubdivision::BBMeshSubdivision * @param eType */ BBMeshSubdivision::BBMeshSubdivision(const BBMeshSubdivisionMeshType &eType) { if (eType == Triangle) m_nMeshUnitPointNum = 3; else if (eType == Quadrangle) m_nMeshUnitPointNum = 4; } /** * @brief BBCatmullClarkMeshSubdivision::BBCatmullClarkMeshSubdivision * @param eType */ BBCatmullClarkMeshSubdivision::BBCatmullClarkMeshSubdivision(BBProcedureMesh *pMesh, const BBMeshSubdivisionMeshType &eType) : BBMeshSubdivision(eType) { m_InputPositions = pMesh->getVBO()->getPositions(); m_pInputVertexIndexes = pMesh->getVertexIndexes(); m_nInputIndexCount = pMesh->getIndexCount(); QList<QVector3D> facePoints = getFacePoints(); } /** * @brief BBCatmullClarkMeshSubdivision::getFacePoints a face point is the average of all the points of the face */ QList<QVector3D> BBCatmullClarkMeshSubdivision::getFacePoints() { QList<QVector3D> facePoints; // For the moment, consider that primitive consists of 4 vertices for (int i = 0; i < m_nInputIndexCount; i += m_nMeshUnitPointNum) { // each face unsigned short index0 = m_pInputVertexIndexes[i + 0]; unsigned short index1 = m_pInputVertexIndexes[i + 1]; unsigned short index2 = m_pInputVertexIndexes[i + 2]; unsigned short index3 = m_pInputVertexIndexes[i + 3]; QVector3D point0(m_InputPositions[index0]); QVector3D point1(m_InputPositions[index1]); QVector3D point2(m_InputPositions[index2]); QVector3D point3(m_InputPositions[index3]); QVector3D facePoint = (point0 + point1 + point2 + point3) / m_nMeshUnitPointNum; facePoints.append(facePoint); } return facePoints; } void BBCatmullClarkMeshSubdivision::generateEdgeFaceList() { } <|start_filename|>Code/BBearEditor/Engine/2D/BBCanvas.h<|end_filename|> #ifndef BBCANVAS_H #define BBCANVAS_H #include "Base/BBGameObject.h" class BBAABBBoundingBox2D; class BBClipArea2D; class BBSpriteObject2D; class BBCanvas : public BBGameObject { public: BBCanvas(int x = 0, int y = 0, int nWidth = 630, int nHeight = 400); ~BBCanvas(); void init() override; void render() override; void resize(float fWidth, float fHeight); void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; void setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform = true) override; void setRotation(const QVector3D &rotation, bool bUpdateLocalTransform = true) override; void setScale(const QVector3D &scale, bool bUpdateLocalTransform = true) override; void setActivity(bool bActive) override; void setVisibility(bool bVisible) override; bool hit(int x, int y) override; const float* getUniformInfo() { return m_UniformInfo; } public: void addSpriteObject2D(BBSpriteObject2D *pSpriteObject2D); private: BBAABBBoundingBox2D *m_pAABBBoundingBox2D; BBClipArea2D *m_pClipArea2D; QList<BBSpriteObject2D*> m_SpriteObject2DSet; float m_UniformInfo[4]; }; #endif // BBCANVAS_H <|start_filename|>Code/BBearEditor/Engine/3D/BBHorizontalPlane.cpp<|end_filename|> #include "BBHorizontalPlane.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BufferObject/BBElementBufferObject.h" #include "Render/BBRenderPass.h" #include "Render/BBMaterial.h" #include "Utils/BBUtils.h" #include "Render/BBCamera.h" #include "Render/BBDrawCall.h" BBHorizontalPlane::BBHorizontalPlane() : BBRenderableObject(0, 0, 0, 0, 0, 0, 1, 1, 1) { } void BBHorizontalPlane::init() { float fCoefficient = 2.0f; m_pVBO = new BBVertexBufferObject(246); for (int i = 0; i <= 40; i++) { // The most transparent point on the periphery m_pVBO->setPosition(i, -20 + i, 0.0f, -20); m_pVBO->setNormal(i, 0.0f, 1.0f, 0.0f); m_pVBO->setColor(i, 0.847059f, 0.603922f, 0.309804f, 0.01f * fCoefficient); m_pVBO->setPosition(i + 41, -20, 0.0f, -20 + i); m_pVBO->setNormal(i + 41, 0.0f, 1.0f, 0.0f); m_pVBO->setColor(i + 41, 0.847059f, 0.603922f, 0.309804f, 0.01f * fCoefficient); m_pVBO->setPosition(i + 82, -20 + i, 0.0f, 20); m_pVBO->setNormal(i + 82, 0.0f, 1.0f, 0.0f); m_pVBO->setColor(i + 82, 0.847059f, 0.603922f, 0.309804f, 0.01f * fCoefficient); m_pVBO->setPosition(i + 123, 20, 0.0f, -20 + i); m_pVBO->setNormal(i + 123, 0.0f, 1.0f, 0.0f); m_pVBO->setColor(i + 123, 0.847059f, 0.603922f, 0.309804f, 0.01f * fCoefficient); // Two midlines float alpha = 0.09f - abs(-20 + i) * 0.004f; m_pVBO->setPosition(i + 164, -20 + i, 0.0f, 0); m_pVBO->setNormal(i + 164, 0.0f, 1.0f, 0.0f); m_pVBO->setColor(i + 164, 0.847059f, 0.603922f, 0.309804f, alpha * fCoefficient); m_pVBO->setPosition(i + 205, 0, 0.0f, -20 + i); m_pVBO->setNormal(i + 205, 0.0f, 1.0f, 0.0f); m_pVBO->setColor(i + 205, 0.847059f, 0.603922f, 0.309804f, alpha * fCoefficient); } m_nIndexCount = 328; m_pIndexes = new unsigned short[m_nIndexCount]; int count = m_nIndexCount / 4; for (int i = 0; i < count; i++) { m_pIndexes[i * 4] = i; m_pIndexes[i * 4 + 1] = i + 164; m_pIndexes[i * 4 + 2] = i + 82; m_pIndexes[i * 4 + 3] = i + 164; } m_pCurrentMaterial->init("base", BB_PATH_RESOURCE_SHADER(base.vert), BB_PATH_RESOURCE_SHADER(base.frag)); m_pCurrentMaterial->getBaseRenderPass()->setBlendState(true); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_LINES, m_nIndexCount, 0); appendDrawCall(pDrawCall); } void BBHorizontalPlane::render(BBCamera *pCamera) { QMatrix4x4 modelMatrix; modelMatrix.translate(pCamera->getPosition().x(), 0, pCamera->getPosition().z()); // The higher, the lower the grid resolution // need to be enlarged, 1 10 100, determined by the digit number of height. int height = abs((int)pCamera->getPosition().y()); // compute the digit number of height int num = 1; int ratio; do { ratio = pow(10, num); num++; } while (height / ratio != 0); modelMatrix.scale(ratio / 10); m_pCurrentMaterial->setMatrix4(LOCATION_MODELMATRIX, modelMatrix.data()); BBRenderableObject::render(modelMatrix, pCamera); } <|start_filename|>Code/BBearEditor/Engine/2D/BBCanvas.cpp<|end_filename|> #include "BBCanvas.h" #include "BBSpriteObject2D.h" #include "Geometry/BBBoundingBox2D.h" #include "2D/BBClipArea2D.h" #include "Render/BBMaterial.h" #include "Scene/BBSceneManager.h" #define IterateSprite2DSet(x) \ for (QList<BBSpriteObject2D*>::Iterator itr = m_SpriteObject2DSet.begin(); itr != m_SpriteObject2DSet.end(); itr++) {x;} BBCanvas::BBCanvas(int x, int y, int nWidth, int nHeight) : BBGameObject(x, y, nWidth, nHeight) { m_pAABBBoundingBox2D = new BBAABBBoundingBox2D(x, y, nWidth / 2.0, nHeight / 2.0); m_pClipArea2D = new BBClipArea2D(x, y, nWidth / 2.0, nHeight / 2.0); resize(800.0f, 600.0f); } BBCanvas::~BBCanvas() { BB_SAFE_DELETE(m_pAABBBoundingBox2D); BB_SAFE_DELETE(m_pClipArea2D); IterateSprite2DSet(delete *itr); } void BBCanvas::init() { m_pAABBBoundingBox2D->init(); m_pClipArea2D->init(); IterateSprite2DSet(init()); } void BBCanvas::render() { m_pAABBBoundingBox2D->render(this); m_pClipArea2D->render(this); IterateSprite2DSet((*itr)->render(this)); } void BBCanvas::resize(float fWidth, float fHeight) { m_UniformInfo[0] = fWidth / 2.0f; m_UniformInfo[1] = fHeight / 2.0f; m_UniformInfo[2] = 0.0f; m_UniformInfo[3] = 0.0f; } /** * @brief BBCanvas::setPosition screen coordinate * @param position * @param bUpdateLocalTransform */ void BBCanvas::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { BBGameObject::setPosition(position, bUpdateLocalTransform); m_pAABBBoundingBox2D->setPosition(position, bUpdateLocalTransform); m_pClipArea2D->setPosition(position, bUpdateLocalTransform); IterateSprite2DSet((*itr)->setPosition(position, bUpdateLocalTransform)); } void BBCanvas::setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform) { BBGameObject::setRotation(nAngle, axis, bUpdateLocalTransform); BBGameObject::setRotation(QVector3D(0, 0, m_Rotation.z())); m_pAABBBoundingBox2D->setRotation(nAngle, axis, bUpdateLocalTransform); m_pClipArea2D->setRotation(nAngle, axis, bUpdateLocalTransform); IterateSprite2DSet((*itr)->setRotation(nAngle, axis, bUpdateLocalTransform)); } void BBCanvas::setRotation(const QVector3D &rotation, bool bUpdateLocalTransform) { BBGameObject::setRotation(rotation, bUpdateLocalTransform); m_pAABBBoundingBox2D->setRotation(rotation, bUpdateLocalTransform); m_pClipArea2D->setRotation(rotation, bUpdateLocalTransform); IterateSprite2DSet((*itr)->setRotation(rotation, bUpdateLocalTransform)); } void BBCanvas::setScale(const QVector3D &scale, bool bUpdateLocalTransform) { BBGameObject::setScale(scale, bUpdateLocalTransform); IterateSprite2DSet((*itr)->setScale(scale, bUpdateLocalTransform)); // m_pBoundingBox2D->setScale(scale, bUpdateLocalTransform); } void BBCanvas::setActivity(bool bActive) { IterateSprite2DSet((*itr)->setActivity(bActive)); // m_pBoundingBox2D->setActivity(bActive); setVisibility(bActive); } void BBCanvas::setVisibility(bool bVisible) { // m_pBoundingBox2D->setVisibility(bVisible); } bool BBCanvas::hit(int x, int y) { return m_pAABBBoundingBox2D->hit(x, y); } void BBCanvas::addSpriteObject2D(BBSpriteObject2D *pSpriteObject2D) { m_SpriteObject2DSet.append(pSpriteObject2D); } <|start_filename|>Code/BBearEditor/Editor/PropertyManager/BBPropertyFactory.cpp<|end_filename|> #include "BBPropertyFactory.h" #include <QHBoxLayout> #include "Utils/BBUtils.h" #include "BBFactoryComponent.h" #include <QLineEdit> #include <QRegExpValidator> #include <QListView> #include <QLabel> #include <QComboBox> #include "Lighting/GameObject/BBLight.h" #include "FileSystem/BBFileSystemDataManager.h" #include <QFile> #include <QFileInfo> #include "Render/BBMaterial.h" #include <QCheckBox> /** * @brief BBLineEditFactory::BBLineEditFactory * @param name * @param fValue * @param pParent * @param nNameStretch * @param nValueStretch */ BBLineEditFactory::BBLineEditFactory(const QString &name, float fValue, QWidget *pParent, int nNameStretch, int nValueStretch) : QWidget(pParent) { QHBoxLayout *pLayout = new QHBoxLayout(this); pLayout->setMargin(0); // name lable in the left side m_pSliderLabel = new BBSliderLabel(this); m_pSliderLabel->setText(name); // otherwise, using tab key can focus on it m_pSliderLabel->setFocusPolicy(Qt::NoFocus); pLayout->addWidget(m_pSliderLabel, nNameStretch, Qt::AlignLeft); // edit in the right side m_pEdit = new QLineEdit(this); // m_pEdit->setAlignment(Qt::AlignRight); // Limit the range of float as [-999999.999999, 999999.999999] setRange(-1000000, 1000000); setRegExp("^(-?[0]|-?[1-9][0-9]{0,5})(?:\\.\\d{1,6})?$|(^\\t?$)"); setSlideStep(0.2f); setValue(fValue); pLayout->addWidget(m_pEdit, nValueStretch); QObject::connect(m_pSliderLabel, SIGNAL(slide(int)), this, SLOT(changeValueBySlider(int))); QObject::connect(m_pEdit, SIGNAL(textEdited(QString)), this, SLOT(changeEditText(QString))); QObject::connect(m_pEdit, SIGNAL(editingFinished()), this, SLOT(showFromLeft())); } BBLineEditFactory::~BBLineEditFactory() { BB_SAFE_DELETE(m_pSliderLabel); BB_SAFE_DELETE(m_pEdit); } void BBLineEditFactory::setRange(float fMin, float fMax) { m_fMinValue = fMin; m_fMaxValue = fMax; } void BBLineEditFactory::setRegExp(const QString &pattern) { // limit input QRegExp re(pattern); QRegExpValidator *pValidator = new QRegExpValidator(re, m_pEdit); m_pEdit->setValidator(pValidator); } QString BBLineEditFactory::setValue(float fValue) { // do not use scientific notation, and do not show the extra 0 at the end QString text = QString("%1").arg(fValue, 0, 'f').replace(QRegExp("(\\.){0,1}0+$"), ""); m_pEdit->setText(text); showFromLeft(); return text; } void BBLineEditFactory::changeEditText(const QString &text) { valueChanged(text.toFloat()); valueChanged(m_pSliderLabel->text(), text.toFloat()); } void BBLineEditFactory::changeValueBySlider(int nDeltaX) { float fValue = m_pEdit->text().toFloat(); fValue += nDeltaX * m_fSlideStep; // Limit scope if (fValue >= m_fMaxValue) fValue = m_fMaxValue; if (fValue <= m_fMinValue) fValue = m_fMinValue; QString text = setValue(fValue); // trigger textEdited signal, change corresponding object in scene m_pEdit->textEdited(text); } void BBLineEditFactory::showFromLeft() { // Display from the first place, otherwise you won’t see the minus sign m_pEdit->setCursorPosition(0); } /** * @brief BBVector2DFactory::BBVector2DFactory * @param value * @param pParent */ BBVector2DFactory::BBVector2DFactory(const QVector2D &value, QWidget *pParent) : QWidget(pParent) { m_Value = value; QHBoxLayout *pLayout = new QHBoxLayout(this); pLayout->setMargin(0); m_pEditX = new BBLineEditFactory("X", value.x(), this); m_pEditY = new BBLineEditFactory("Y", value.y(), this); pLayout->addWidget(m_pEditX); pLayout->addWidget(m_pEditY); QObject::connect(m_pEditX, SIGNAL(valueChanged(float)), this, SLOT(setX(float))); QObject::connect(m_pEditY, SIGNAL(valueChanged(float)), this, SLOT(setY(float))); } BBVector2DFactory::~BBVector2DFactory() { BB_SAFE_DELETE(m_pEditX); BB_SAFE_DELETE(m_pEditY); } void BBVector2DFactory::setValue(const QVector2D &value) { m_Value = value; m_pEditX->setValue(value.x()); m_pEditY->setValue(value.y()); } void BBVector2DFactory::setX(float x) { m_Value.setX(x); valueChanged(m_Value); } void BBVector2DFactory::setY(float y) { m_Value.setY(y); valueChanged(m_Value); } /** * @brief BBVector3DFactory::BBVector3DFactory * @param value * @param pParent */ BBVector3DFactory::BBVector3DFactory(const QVector3D &value, QWidget *pParent) : QWidget(pParent) { m_Value = value; QHBoxLayout *pLayout = new QHBoxLayout(this); pLayout->setMargin(0); m_pEditX = new BBLineEditFactory("X", value.x(), this); m_pEditY = new BBLineEditFactory("Y", value.y(), this); m_pEditZ = new BBLineEditFactory("Z", value.z(), this); pLayout->addWidget(m_pEditX); pLayout->addWidget(m_pEditY); pLayout->addWidget(m_pEditZ); QObject::connect(m_pEditX, SIGNAL(valueChanged(float)), this, SLOT(setX(float))); QObject::connect(m_pEditY, SIGNAL(valueChanged(float)), this, SLOT(setY(float))); QObject::connect(m_pEditZ, SIGNAL(valueChanged(float)), this, SLOT(setZ(float))); } BBVector3DFactory::~BBVector3DFactory() { BB_SAFE_DELETE(m_pEditX); BB_SAFE_DELETE(m_pEditY); BB_SAFE_DELETE(m_pEditZ); } void BBVector3DFactory::setValue(const QVector3D &value) { m_Value = value; m_pEditX->setValue(value.x()); m_pEditY->setValue(value.y()); m_pEditZ->setValue(value.z()); } void BBVector3DFactory::setX(float x) { m_Value.setX(x); valueChanged(m_Value); } void BBVector3DFactory::setY(float y) { m_Value.setY(y); valueChanged(m_Value); } void BBVector3DFactory::setZ(float z) { m_Value.setZ(z); valueChanged(m_Value); } /** * @brief BBEnumFactory::BBEnumFactory * @param name * @param comboBoxItems * @param currentText * @param pParent * @param labelStretch * @param comboBoxStretch */ BBEnumFactory::BBEnumFactory(const QString &name, const QStringList &comboBoxItems, const QString &currentText, QWidget *pParent, int labelStretch, int comboBoxStretch) : QWidget(pParent) { QGridLayout *pLayout = new QGridLayout(this); pLayout->setMargin(0); m_pLabel = new QLabel(name, this); m_pLabel->setFocusPolicy(Qt::NoFocus); pLayout->addWidget(m_pLabel, 0, 0, 1, labelStretch); m_pComboBox = new QComboBox(this); m_pComboBox->addItems(comboBoxItems); // With this sentence, qss can take effect m_pComboBox->setView(new QListView()); m_pComboBox->setCurrentText(currentText); pLayout->addWidget(m_pComboBox, 0, 1, 1, comboBoxStretch); QObject::connect(m_pComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeCurrentItem(int))); QObject::connect(m_pComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(changeCurrentItem(QString))); } BBEnumFactory::~BBEnumFactory() { BB_SAFE_DELETE(m_pLabel); BB_SAFE_DELETE(m_pComboBox); } int BBEnumFactory::getCurrentItemIndex() { return m_pComboBox->currentIndex(); } void BBEnumFactory::changeCurrentItem(int nIndex) { emit currentItemChanged(nIndex); } void BBEnumFactory::changeCurrentItem(const QString &text) { emit currentItemChanged(text); } /** * @brief BBEnumExpansionFactory::BBEnumExpansionFactory * @param name * @param comboBoxItems * @param buttonText * @param currentText * @param pParent * @param labelStretch * @param comboBoxStretch */ BBEnumExpansionFactory::BBEnumExpansionFactory(const QString &name, const QStringList &comboBoxItems, const QString &buttonText, const QString &currentText, QWidget *pParent, int labelStretch, int comboBoxStretch) : BBEnumFactory(name, comboBoxItems, currentText, pParent, labelStretch, comboBoxStretch) { QWidget *pWidget = new QWidget(this); QHBoxLayout *pLayout = new QHBoxLayout(pWidget); pLayout->setMargin(0); m_pTrigger = new QCheckBox(pWidget); pLayout->addWidget(m_pTrigger); m_pButton = new QPushButton(buttonText, pWidget); m_pButton->setStyleSheet("QPushButton { border: none; border-radius: 2px; padding-left: 3px; padding-right: 3px; color: #d6dfeb; font: 9pt \"Arial\"; background: #0ebf9c; }" "QPushButton:hover { background: #8c0ebf9c; }"); pLayout->addWidget(m_pButton); QGridLayout *pFactoryLayout = (QGridLayout*)layout(); pFactoryLayout->addWidget(pWidget, 1, 1, 1, 1, Qt::AlignLeft); QObject::connect(m_pTrigger, SIGNAL(clicked(bool)), this, SLOT(clickTrigger(bool))); QObject::connect(m_pButton, SIGNAL(clicked()), this, SLOT(clickButton())); } BBEnumExpansionFactory::~BBEnumExpansionFactory() { BB_SAFE_DELETE(m_pTrigger); BB_SAFE_DELETE(m_pButton); } void BBEnumExpansionFactory::enableTrigger(bool bEnable) { m_pTrigger->setVisible(bEnable); } void BBEnumExpansionFactory::enableButton(bool bEnable) { m_pButton->setVisible(bEnable); } void BBEnumExpansionFactory::clickButton() { emit buttonClicked(); } void BBEnumExpansionFactory::clickTrigger(bool bClicked) { emit triggerClicked(bClicked); } /** * @brief BBColorFactory::BBColorFactory * @param r * @param g * @param b * @param a * @param pParent */ BBColorFactory::BBColorFactory(float r, float g, float b, float a, QWidget *pParent) : BBColorFactory(new float[4] {r, g, b, a}, pParent) { } BBColorFactory::BBColorFactory(const std::string &uniformName, float r, float g, float b, float a, QWidget *pParent) : BBColorFactory(r, g, b, a, pParent) { m_UniformName = uniformName; } BBColorFactory::BBColorFactory(float *color, QWidget *pParent) : QWidget(pParent) { QHBoxLayout *pLayout = new QHBoxLayout(this); pLayout->setMargin(0); QPushButton *pDropper = new QPushButton(this); pDropper->setStyleSheet("image: url(../../resources/icons/eyedropper.png);"); pLayout->addWidget(pDropper, 0); m_pColorButton = new BBColorButton(this); pLayout->addWidget(m_pColorButton, 1); QObject::connect(pDropper, SIGNAL(clicked()), this, SLOT(catchColor())); // default m_pColorButton->setColor(color); } BBColorFactory::~BBColorFactory() { BB_SAFE_DELETE(m_pColorButton); } void BBColorFactory::catchColor() { // Create a dialog box that is the same as the screen, select the color on it BBScreenDialog dialog; // After the selection is completed, the color button is set to the selected color QObject::connect(&dialog, SIGNAL(setColor(float, float, float)), this, SLOT(finishCatchColor(float, float, float))); dialog.exec(); } void BBColorFactory::finishCatchColor(float r, float g, float b) { m_pColorButton->setColor(r * 255, g * 255, b * 255); emit colorChanged(r, g, b, 1.0f, m_UniformName); } /** * @brief BBLightColorFactory::BBLightColorFactory * @param pLight * @param pParent */ BBLightColorFactory::BBLightColorFactory(BBLight *pLight, QWidget *pParent) : BBColorFactory(pLight->getDiffuseColor(), pParent) { m_pLight = pLight; } void BBLightColorFactory::finishCatchColor(float r, float g, float b) { BBColorFactory::finishCatchColor(r, g, b); m_pLight->setDiffuseColor(r, g, b); } /** * @brief BBIconFactory::BBIconFactory * @param pParent */ BBIconFactory::BBIconFactory(QWidget *pParent) : QWidget(pParent) { QHBoxLayout *pLayout = new QHBoxLayout(this); pLayout->setMargin(0); QWidget *pLeft = new QWidget(this); m_pLeftLayout = new QGridLayout(pLeft); m_pLeftLayout->setMargin(0); QWidget *pBottomLeft = new QWidget(pLeft); QHBoxLayout *pBottomLeftLayout = new QHBoxLayout(pBottomLeft); pBottomLeftLayout->setMargin(0); // Button m_pRemoveButton = new QPushButton(pBottomLeft); m_pRemoveButton->setStyleSheet("image: url(../../resources/icons/return.png);"); pBottomLeftLayout->addWidget(m_pRemoveButton, 0); m_pSelectButton = new QPushButton(pBottomLeft); m_pSelectButton->setStyleSheet("image: url(../../resources/icons/more2.png);"); pBottomLeftLayout->addWidget(m_pSelectButton, 0); // name m_pNameEdit = new QLineEdit(pBottomLeft); m_pNameEdit->setEnabled(false); pBottomLeftLayout->addWidget(m_pNameEdit, 1); m_pLeftLayout->addWidget(pBottomLeft, 2, 0, 1, 1, Qt::AlignBottom); pLayout->addWidget(pLeft, 1); // picture in the right QWidget *pRight = new QWidget(this); pRight->setStyleSheet("border: none; border-radius: 2px; background: rgb(60, 64, 75);"); QHBoxLayout *pFrameLayout = new QHBoxLayout(pRight); pFrameLayout->setMargin(1); m_pIconLabel = new BBIconLabel(pRight); pFrameLayout->addWidget(m_pIconLabel); pLayout->addWidget(pRight); QObject::connect(m_pIconLabel, SIGNAL(currentFilePathChanged(QString)), this, SLOT(changeCurrentFilePath(QString))); } BBIconFactory::~BBIconFactory() { BB_SAFE_DELETE(m_pLeftLayout); BB_SAFE_DELETE(m_pRemoveButton); BB_SAFE_DELETE(m_pSelectButton); BB_SAFE_DELETE(m_pIconLabel); BB_SAFE_DELETE(m_pNameEdit); } void BBIconFactory::setContent(const QString &filePath) { if (filePath.isEmpty()) { // there is nothing m_pIconLabel->setText("None"); m_pNameEdit->setText(""); } else { QFileInfo fileInfo(filePath); if (fileInfo.exists()) { m_pIconLabel->setText(""); m_pNameEdit->setText(fileInfo.fileName()); } else { m_pIconLabel->setText("Missing"); m_pNameEdit->setText(""); } } m_pIconLabel->setIcon(filePath); } /** * @brief BBTextureFactory::BBTextureFactory * @param pParent */ BBTextureFactory::BBTextureFactory(const QString &uniformName, const QString &originalIconPath, QWidget *pParent, int nIndex) : BBIconFactory(pParent) { m_UniformName = uniformName; m_nIndex = nIndex; m_pIconLabel->setFilter(BBFileSystemDataManager::m_TextureSuffixs); setContent(originalIconPath); QWidget *pWidget = new QWidget(this); pWidget->setObjectName("Tiling"); QHBoxLayout *pLayout = new QHBoxLayout(pWidget); pLayout->setMargin(0); pLayout->addWidget(new QLabel("Tiling"), 1); m_pTilingFactory = new BBVector2DFactory(QVector2D(0, 0), this); pLayout->addWidget(m_pTilingFactory, 2); m_pLeftLayout->addWidget(pWidget, 0, 0, 1, 1, Qt::AlignTop); pWidget = new QWidget(this); pWidget->setObjectName("Offset"); pLayout = new QHBoxLayout(pWidget); pLayout->setMargin(0); pLayout->addWidget(new QLabel("Offset"), 1); m_pOffsetFactory = new BBVector2DFactory(QVector2D(0, 0), this); pLayout->addWidget(m_pOffsetFactory, 2); m_pLeftLayout->addWidget(pWidget, 1, 0, 1, 1, Qt::AlignTop); enableTilingAndOffset(false); QObject::connect(m_pTilingFactory, SIGNAL(valueChanged(QVector2D)), this, SLOT(changeTiling(QVector2D))); QObject::connect(m_pOffsetFactory, SIGNAL(valueChanged(QVector2D)), this, SLOT(changeOffset(QVector2D))); } void BBTextureFactory::enableTilingAndOffset(bool bEnable) { findChild<QWidget*>("Tiling")->setVisible(bEnable); findChild<QWidget*>("Offset")->setVisible(bEnable); } void BBTextureFactory::setTiling(float fTilingX, float fTilingY) { m_pTilingFactory->setValue(QVector2D(fTilingX, fTilingY)); } void BBTextureFactory::setOffset(float fOffsetX, float fOffsetY) { m_pOffsetFactory->setValue(QVector2D(fOffsetX, fOffsetY)); } void BBTextureFactory::changeCurrentFilePath(const QString &filePath) { setContent(filePath); emit setSampler2D(m_UniformName, filePath, m_nIndex); } void BBTextureFactory::changeTiling(const QVector2D &value) { emit setTilingAndOffset(LOCATION_TILINGANDOFFSET_PREFIX + m_UniformName, value.x(), value.y(), m_pOffsetFactory->getX(), m_pOffsetFactory->getY()); } void BBTextureFactory::changeOffset(const QVector2D &value) { emit setTilingAndOffset(LOCATION_TILINGANDOFFSET_PREFIX + m_UniformName, m_pTilingFactory->getX(), m_pTilingFactory->getY(), value.x(), value.y()); } /** * @brief BBCubeMapFactory::BBCubeMapFactory * @param uniformName * @param originalIconPath * @param pParent */ BBCubeMapFactory::BBCubeMapFactory(const QString &uniformName, const QString originalIconPath[], QWidget *pParent) : QWidget(pParent) { for (int i = 0; i < 6; i++) { m_ResourcePaths[i] = originalIconPath[i]; } QVBoxLayout *pLayout = new QVBoxLayout(this); pLayout->setMargin(0); QString subName[6] = {"_Positive_X", "_Negative_X", "_Positive_Y", "_Negative_Y", "_Positive_Z", "_Negative_Z"}; for (int i = 0; i < 6; i++) { QWidget *pTextureFactoryWidget = new QWidget(this); QHBoxLayout *pTextureFactoryLayout = new QHBoxLayout(pTextureFactoryWidget); pTextureFactoryLayout->setMargin(0); pTextureFactoryLayout->addWidget(new QLabel(uniformName + subName[i]), 1, Qt::AlignTop); m_pTextureFactory[i] = new BBTextureFactory(uniformName, originalIconPath[i], this, i); pTextureFactoryLayout->addWidget(m_pTextureFactory[i], 1); pLayout->addWidget(pTextureFactoryWidget); QObject::connect(m_pTextureFactory[i], SIGNAL(setSampler2D(QString, QString, int)), this, SLOT(changeCurrentFilePath(QString, QString, int))); } } BBCubeMapFactory::~BBCubeMapFactory() { for (int i = 0; i < 6; i++) { BB_SAFE_DELETE(m_pTextureFactory[i]); } } void BBCubeMapFactory::changeCurrentFilePath(const QString &uniformName, const QString &texturePath, int nFaceIndex) { m_pTextureFactory[nFaceIndex]->setContent(texturePath); m_ResourcePaths[nFaceIndex] = texturePath; emit setSamplerCube(uniformName, m_ResourcePaths); } /** * @brief BBDragAcceptedFactory::BBDragAcceptedFactory * @param pParent */ BBDragAcceptedFactory::BBDragAcceptedFactory(const QString &iconPath, const QString &filePath, QWidget *pParent) : QWidget(pParent) { QHBoxLayout *pLayout = new QHBoxLayout(this); pLayout->setMargin(0); m_pIconLabel = new QPushButton(this); m_pIconLabel->setStyleSheet("image: url(" + iconPath + ");"); pLayout->addWidget(m_pIconLabel); m_pDragAcceptedEdit = new BBDragAcceptedEdit(this); pLayout->addWidget(m_pDragAcceptedEdit, 1); changeCurrentFilePath(filePath); QObject::connect(m_pIconLabel, SIGNAL(clicked()), this, SLOT(clickIcon())); QObject::connect(m_pDragAcceptedEdit, SIGNAL(currentFilePathChanged(QString)), this, SLOT(changeCurrentFilePath(QString))); } BBDragAcceptedFactory::~BBDragAcceptedFactory() { BB_SAFE_DELETE(m_pIconLabel); BB_SAFE_DELETE(m_pDragAcceptedEdit); } void BBDragAcceptedFactory::setFilter(const QStringList &acceptableSuffixs) { m_pDragAcceptedEdit->setFilter(acceptableSuffixs); } void BBDragAcceptedFactory::changeCurrentFilePath(const QString &filePath) { if (filePath.isEmpty()) { m_pDragAcceptedEdit->setText("None"); } else { QFileInfo fileInfo(filePath); if (fileInfo.exists()) { m_pDragAcceptedEdit->setText(fileInfo.baseName()); emit currentFilePathChanged(filePath); } else { m_pDragAcceptedEdit->setText("Missing"); } } } void BBDragAcceptedFactory::clickIcon() { emit iconClicked(); } /** * @brief BBSliderFactory::BBSliderFactory * @param nValue * @param nMin * @param nMax * @param pParent */ BBSliderFactory::BBSliderFactory(int nValue, int nMin, int nMax, QWidget *pParent) : QWidget(pParent) { QHBoxLayout *pLayout = new QHBoxLayout(this); pLayout->setMargin(0); m_pSlider = new QSlider(Qt::Horizontal, this); pLayout->addWidget(m_pSlider); m_pEditor = new QLineEdit(this); m_pEditor->setMaximumWidth(50); QRegExp re("[0-9]+$"); QValidator *pValidator = new QRegExpValidator(re, m_pEditor); m_pEditor->setValidator(pValidator); pLayout->addWidget(m_pEditor); setRange(nMin, nMax); setValue(nValue); QObject::connect(m_pSlider, SIGNAL(valueChanged(int)), this, SLOT(changeSliderValue(int))); QObject::connect(m_pEditor, SIGNAL(textChanged(QString)), this, SLOT(changeEditorValue(QString))); } BBSliderFactory::~BBSliderFactory() { BB_SAFE_DELETE(m_pSlider); BB_SAFE_DELETE(m_pEditor); } void BBSliderFactory::setRange(int nMin, int nMax) { m_nMin = nMin; m_nMax = nMax; m_pSlider->setRange(nMin, nMax); } void BBSliderFactory::setValue(int value) { m_pSlider->setValue(value); m_pEditor->setText(QString::number(value)); } void BBSliderFactory::changeSliderValue(int value) { m_pEditor->setText(QString::number(value)); valueChanged(value); } void BBSliderFactory::changeEditorValue(const QString &value) { int nValue = value.toInt(); m_pSlider->setValue(nValue); if (!value.isEmpty()) { if (nValue > m_nMax) nValue = m_nMax; if (nValue < m_nMin) nValue = m_nMin; m_pEditor->setText(QString::number(nValue)); } } <|start_filename|>Resources/shaders/test_FS.frag<|end_filename|> #version 430 core in G2F { vec4 color; vec3 normal; } g2f; out vec4 FragColor; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; // Lambert vec4 getLambertLight() { vec3 light_pos_normalized = normalize(BBLightPosition.xyz); vec3 normal_normalized = normalize(g2f.normal); vec4 light_color = dot(light_pos_normalized, normal_normalized) * BBLightColor; return light_color; } void main(void) { FragColor = vec4(1.0, 0.0, 0.0, 1.0); } <|start_filename|>Code/BBearEditor/Editor/MainInterface/BBMainWindow.h<|end_filename|> #ifndef BBUIMAINWINDOW_H #define BBUIMAINWINDOW_H #include <QMainWindow> namespace Ui { class BBMainWindow; } class BBMainWindow : public QMainWindow { Q_OBJECT public: explicit BBMainWindow(QWidget *parent = 0); virtual ~BBMainWindow(); private slots: void createProject(); void openProject(); void showGlobalSettingsProperty(); void showOfflineRendererProperty(); void switchGameObjectPage(int nIndex); void useToolFBX2BBear(); signals: void pressMultipleSelectionKey(bool); private: void setWindowLayout(); void setMenu(); void setGameObjectDockWidget(); void setPreview(); void setConnect(); void keyPressEvent(QKeyEvent *e) override; void keyReleaseEvent(QKeyEvent *e) override; Ui::BBMainWindow *m_pUi; }; #endif // BBUIMAINWINDOW_H <|start_filename|>Code/BBearEditor/Engine/Profiler/BBProfiler.h<|end_filename|> #pragma once #ifndef BBPROFILER_H #define BBPROFILER_H #include "Allocator/bbmemorylabel.h" #include <QMap> #include <cstddef> class BBProfiler { public: static void init(); static void addMemoryObject(void *ptr, const BBMemoryLabel &eLabel, size_t size); static bool deleteMemoryObject(void *ptr); static int getTotalUsedMemorySize(); static QMap<void*, BBMemoryLabel> *m_pMemoryObjects; static QMap<void*, size_t> *m_pMemoryObjectsSize; static QMap<BBMemoryLabel, int> *m_pUsedMemorySize; static int m_nTotalUsedMemorySize; }; #endif // BBPROFILER_H <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBOfflineRendererManager.h<|end_filename|> #ifndef BBOFFLINERENDERERMANAGER_H #define BBOFFLINERENDERERMANAGER_H #include "BBGroupManager.h" class BBOfflineRenderer; class BBOfflineRendererManager : public BBGroupManager { Q_OBJECT public: BBOfflineRendererManager(BBOfflineRenderer *pOfflineRenderer, QWidget *pParent = 0); ~BBOfflineRendererManager(); private slots: void startPhotonMapping(); private: BBOfflineRenderer *m_pOfflineRenderer; }; #endif // BBOFFLINERENDERERMANAGER_H <|start_filename|>Resources/shaders/fullscreenquad_texture.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBTexcoord; varying vec4 V_Texcoord; void main() { V_Texcoord = BBTexcoord; gl_Position = BBPosition; } <|start_filename|>Resources/shaders/SH_Lighting.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBNormal; varying vec3 V_normal; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { V_normal = normalize(mat3(transpose(inverse(BBViewMatrix * BBModelMatrix))) * BBNormal.xyz); V_normal.y = -V_normal.y; gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * BBPosition; } <|start_filename|>Code/BBearEditor/Engine/Physics/Constraint/BBPinConstraint.h<|end_filename|> #ifndef BBPINCONSTRAINT_H #define BBPINCONSTRAINT_H #include "BBBaseConstraint.h" class BBPinConstraint : public BBBaseConstraint { public: BBPinConstraint(BBBaseBody *pBody, int nParticleIndex, const QVector3D &fixedPosition); void doConstraint(float fDeltaTime) override; inline void setFixedPosition(float x, float y, float z) { setFixedPosition(QVector3D(x, y, z)); } inline void setFixedPosition(const QVector3D &position) { m_FixedPosition = position; } private: int m_nParticleIndex; QVector3D m_FixedPosition; }; #endif // BBPINCONSTRAINT_H <|start_filename|>Code/BBearEditor/Engine/Scene/CoordinateSystem/BBCoordinateComponent2D.h<|end_filename|> #ifndef BBCOORDINATECOMPONENT2D_H #define BBCOORDINATECOMPONENT2D_H #include "Base/BBRenderableObject2D.h" #include "BBCoordinateComponent.h" class BBCoordinateComponent2D : public BBRenderableObject2D { public: BBCoordinateComponent2D(int x, int y); void init() override; void setSelectedAxis(const BBAxisFlags &axis); protected: BBAxisFlags m_SelectedAxis; private: virtual void setVertexColor(const BBAxisFlags &axis, bool bSelected) = 0; }; class BBPositionCoordinateComponent2D : public BBCoordinateComponent2D { public: BBPositionCoordinateComponent2D(int x, int y); void init() override; void setVertexColor(const BBAxisFlags &axis, bool bSelected) override; }; class BBCoordinateCircle2D : public BBCoordinateCircle { public: BBCoordinateCircle2D(int x, int y, int nWidth, int nHeight); void init() override; }; class BBCoordinateTickMark2D : public BBCoordinateTickMark { public: BBCoordinateTickMark2D(int x, int y, int nWidth, int nHeight); void init() override; }; class BBCoordinateSector2D : public BBCoordinateSector { public: BBCoordinateSector2D(int x, int y, int nWidth, int nHeight); void init() override; }; class BBRotationCoordinateComponent2D : public BBCoordinateComponent2D { public: BBRotationCoordinateComponent2D(int x, int y); void init() override; void setVertexColor(const BBAxisFlags &axis, bool bSelected) override; }; class BBScaleCoordinateComponent2D : public BBCoordinateComponent2D { public: BBScaleCoordinateComponent2D(int x, int y); void init() override; void setVertexColor(const BBAxisFlags &axis, bool bSelected) override; void scale(int nDeltaX, int nDeltaY); void reset(); }; #endif // BBCOORDINATECOMPONENT2D_H <|start_filename|>Code/BBearEditor/Engine/Physics/Constraint/BBBaseConstraint.h<|end_filename|> #ifndef BBBASECONSTRAINT_H #define BBBASECONSTRAINT_H #include <QVector3D> class BBBaseBody; class BBBaseConstraint { public: BBBaseConstraint(BBBaseBody *pBody); virtual ~BBBaseConstraint(); virtual void doConstraint(float fDeltaTime) = 0; protected: BBBaseBody *m_pBody; }; #endif // BBBASECONSTRAINT_H <|start_filename|>Code/BBearEditor/Engine/Scene/CoordinateSystem/BBCoordinateSystem.cpp<|end_filename|> #include "BBCoordinateSystem.h" #include "Utils/BBUtils.h" #include "Render/BBCamera.h" #include "Geometry/BBBoundingBox.h" /** * @brief BBCoordinateSystem::BBCoordinateSystem */ BBCoordinateSystem::BBCoordinateSystem() : BBGameObject() { m_pSelectedObject = NULL; m_bTransforming = false; } BBCoordinateSystem::~BBCoordinateSystem() { BB_SAFE_DELETE(m_pSelectedObject); } void BBCoordinateSystem::render(BBCamera *pCamera) { // The coordinate system will not become smaller as the camera is zoomed out // need to scale according to the distance float fDistance = (pCamera->getPosition() - m_Position).length(); setScale(fDistance / 6.5f); } bool BBCoordinateSystem::hit(const BBRay &ray, BBBoundingBox *pBoundingBox1, const BBAxisFlags &axis1, BBBoundingBox *pBoundingBox2, const BBAxisFlags &axis2, BBBoundingBox *pBoundingBox3, const BBAxisFlags &axis3, float &fDistance) { // axis1 is the coordinate axis name corresponding to pBoundingBox1 // size of m_pCoordinateRectFace is 0.3 float d1, d2, d3; bool bResult1 = pBoundingBox1->hit(ray, d1); bool bResult2 = pBoundingBox2->hit(ray, d2); bool bResult3 = pBoundingBox3->hit(ray, d3); if (!bResult1 && !bResult2 && !bResult3) { setSelectedAxis(BBAxisName::AxisNULL); return false; } if (d1 < d2) { if (d1 < d3) { // yoz is nearest setSelectedAxis(axis1); fDistance = d1; } else { // xoy is nearest setSelectedAxis(axis3); fDistance = d3; } } else { if (d1 < d3) { // xoz is nearest setSelectedAxis(axis2); fDistance = d2; } else { if (d2 < d3) { // xoz is nearest setSelectedAxis(axis2); fDistance = d2; } else { // xoy is nearest setSelectedAxis(axis3); fDistance = d3; } } } return true; } void BBCoordinateSystem::setSelectedObject(BBGameObject *pObject) { m_pSelectedObject = pObject; if (pObject != nullptr) { setPosition(pObject->getPosition()); setRotation(pObject->getRotation()); } else { setPosition(QVector3D(0, 0, 0)); setRotation(QVector3D(0, 0, 0)); setSelectedAxis(BBAxisName::AxisNULL); } } void BBCoordinateSystem::stopTransform() { // When no movement, reset mouse pos QVector3D pos; m_LastMousePos = pos; m_bTransforming = false; } /** * @brief BBPositionCoordinateSystem::BBPositionCoordinateSystem */ BBPositionCoordinateSystem::BBPositionCoordinateSystem() : BBCoordinateSystem() { m_pCoordinateArrow = new BBCoordinateArrow(); m_pCoordinateAxis = new BBCoordinateAxis(); m_pCoordinateRectFace = new BBCoordinateRectFace(); m_pBoundingBoxX = new BBBoundingBox3D(0, 0, 0, 0, 0, 0, 1, 1, 1, 0.75f, 0.0f, 0.0f, 0.45f, 0.1f, 0.1f); m_pBoundingBoxY = new BBBoundingBox3D(0, 0, 0, 0, 0, 0, 1, 1, 1, 0.0f, 0.75f, 0.0f, 0.1f, 0.45f, 0.1f); m_pBoundingBoxZ = new BBBoundingBox3D(0, 0, 0, 0, 0, 0, 1, 1, 1, 0.0f, 0.0f, 0.75f, 0.1f, 0.1f, 0.45f); m_pBoundingBoxYOZ = new BBRectBoundingBox3D(0.0f, 0.15f, 0.15f, 0.0f, 0.15f, 0.15f); m_pBoundingBoxXOZ = new BBRectBoundingBox3D(0.15f, 0.0f, 0.15f, 0.15f, 0.0f, 0.15f); m_pBoundingBoxXOY = new BBRectBoundingBox3D(0.15f, 0.15f, 0.0f, 0.15f, 0.15f, 0.0f); } BBPositionCoordinateSystem::~BBPositionCoordinateSystem() { BB_SAFE_DELETE(m_pCoordinateArrow); BB_SAFE_DELETE(m_pCoordinateAxis); BB_SAFE_DELETE(m_pCoordinateRectFace); BB_SAFE_DELETE(m_pBoundingBoxX); BB_SAFE_DELETE(m_pBoundingBoxY); BB_SAFE_DELETE(m_pBoundingBoxZ); BB_SAFE_DELETE(m_pBoundingBoxYOZ); BB_SAFE_DELETE(m_pBoundingBoxXOZ); BB_SAFE_DELETE(m_pBoundingBoxXOY); } void BBPositionCoordinateSystem::init() { m_pCoordinateArrow->init(); m_pCoordinateAxis->init(); m_pCoordinateRectFace->init(); } void BBPositionCoordinateSystem::render(BBCamera *pCamera) { if (m_pSelectedObject == NULL) return; BBCoordinateSystem::render(pCamera); m_pCoordinateArrow->render(pCamera); m_pCoordinateAxis->render(pCamera); m_pCoordinateRectFace->render(pCamera); } void BBPositionCoordinateSystem::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { // Modifying m_Position directly will cause an error // The position of the bounding box needs to be updated at the same time // otherwise, will trigger incorrect mouse events BBCoordinateSystem::setPosition(position, bUpdateLocalTransform); m_pCoordinateArrow->setPosition(position, bUpdateLocalTransform); m_pCoordinateAxis->setPosition(position, bUpdateLocalTransform); m_pCoordinateRectFace->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxX->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxY->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxZ->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxYOZ->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxXOZ->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxXOY->setPosition(position, bUpdateLocalTransform); } void BBPositionCoordinateSystem::setScale(float scale, bool bUpdateLocalTransform) { BBCoordinateSystem::setScale(scale, bUpdateLocalTransform); m_pCoordinateArrow->setScale(scale, bUpdateLocalTransform); m_pCoordinateAxis->setScale(scale, bUpdateLocalTransform); m_pCoordinateRectFace->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxX->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxY->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxZ->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxYOZ->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxXOZ->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxXOY->setScale(scale, bUpdateLocalTransform); } void BBPositionCoordinateSystem::setSelectedAxis(const BBAxisFlags &axis) { // change color of indicator m_pCoordinateArrow->setSelectedAxis(axis); m_pCoordinateAxis->setSelectedAxis(axis); m_SelectedAxis = axis; } bool BBPositionCoordinateSystem::mouseMoveEvent(const BBRay &ray, bool bMousePressed) { do { // if transforming, there is no need to perform other operations BB_END(m_bTransforming); // otherwise, determine whether transform can be turned on BB_END(m_pSelectedObject == NULL); // handle collision detection, change color of related axis and get m_SelectedAxis // if hitting m_pCoordinateRectFace, no need to handle axis float fDistance; if (!hit(ray, m_pBoundingBoxYOZ, BBAxisName::AxisY | BBAxisName::AxisZ, m_pBoundingBoxXOZ, BBAxisName::AxisX | BBAxisName::AxisZ, m_pBoundingBoxXOY, BBAxisName::AxisX | BBAxisName::AxisY, fDistance)) { // handle axis BB_END(!hit(ray, m_pBoundingBoxX, BBAxisName::AxisX, m_pBoundingBoxY, BBAxisName::AxisY, m_pBoundingBoxZ, BBAxisName::AxisZ, fDistance)); } // do not handle transform when mouse is not pressed BB_END(!bMousePressed); // meet the conditions, turn on m_bTransforming m_bTransforming = true; } while(0); transform(ray); // The return value indicates whether the transform has really performed return m_bTransforming; } void BBPositionCoordinateSystem::transform(const BBRay &ray) { if (m_bTransforming) { // perform transform operation // compute now mouse pos QVector3D mousePos; if ((m_SelectedAxis == BBAxisName::AxisY) || (m_SelectedAxis == (BBAxisName::AxisX | BBAxisName::AxisY))) { mousePos = ray.computeIntersectWithXOYPlane(m_Position.z()); } else if ((m_SelectedAxis == BBAxisName::AxisX || m_SelectedAxis == BBAxisName::AxisZ) || (m_SelectedAxis == (BBAxisName::AxisX | BBAxisName::AxisZ))) { mousePos = ray.computeIntersectWithXOZPlane(m_Position.y()); } else if (m_SelectedAxis == (BBAxisName::AxisY | BBAxisName::AxisZ)) { mousePos = ray.computeIntersectWithYOZPlane(m_Position.x()); } // displacement can be computed if (!m_LastMousePos.isNull()) { QVector3D mouseDisplacement = mousePos - m_LastMousePos; if (m_SelectedAxis & BBAxisName::AxisX) { // The length of the projection of the mouse's displacement on the axis float d = mouseDisplacement.x(); setPosition(m_Position + QVector3D(d, 0, 0)); } if (m_SelectedAxis & BBAxisName::AxisY) { float d = mouseDisplacement.y(); setPosition(m_Position + QVector3D(0, d, 0)); } if (m_SelectedAxis & BBAxisName::AxisZ) { float d = mouseDisplacement.z(); setPosition(m_Position + QVector3D(0, 0, d)); } m_pSelectedObject->setPosition(m_Position); } // record and wait the next frame m_LastMousePos = mousePos; } } /** * @brief BBRotationCoordinateSystem::BBRotationCoordinateSystem */ BBRotationCoordinateSystem::BBRotationCoordinateSystem() : BBCoordinateSystem() { m_pCoordinateQuarterCircle = new BBCoordinateQuarterCircle(); m_pBoundingBoxYOZ = new BBQuarterCircleBoundingBox3D(0, 0, 0, 1, BBPlaneName::YOZ); m_pBoundingBoxXOZ = new BBQuarterCircleBoundingBox3D(0, 0, 0, 1, BBPlaneName::XOZ); m_pBoundingBoxXOY = new BBQuarterCircleBoundingBox3D(0, 0, 0, 1, BBPlaneName::XOY); m_pCoordinateCircle = new BBCoordinateCircle(); m_pCoordinateTickMark = new BBCoordinateTickMark(); m_pCoordinateSector = new BBCoordinateSector(); } BBRotationCoordinateSystem::~BBRotationCoordinateSystem() { BB_SAFE_DELETE(m_pCoordinateQuarterCircle); BB_SAFE_DELETE(m_pBoundingBoxYOZ); BB_SAFE_DELETE(m_pBoundingBoxXOZ); BB_SAFE_DELETE(m_pBoundingBoxXOY); BB_SAFE_DELETE(m_pCoordinateCircle); BB_SAFE_DELETE(m_pCoordinateTickMark); BB_SAFE_DELETE(m_pCoordinateSector); } void BBRotationCoordinateSystem::init() { m_pCoordinateQuarterCircle->init(); m_pCoordinateCircle->init(); m_pCoordinateTickMark->init(); m_pCoordinateSector->init(); } void BBRotationCoordinateSystem::render(BBCamera *pCamera) { if (m_pSelectedObject == nullptr) return; BBCoordinateSystem::render(pCamera); // When transforming, render circle. otherwise, render coordinate axis if (m_bTransforming) { m_pCoordinateCircle->render(pCamera); m_pCoordinateTickMark->render(pCamera); m_pCoordinateSector->render(pCamera); } else { // coordinate axis always faces camera QVector3D dir = pCamera->getPosition() - m_Position; dir.setX(dir.x() >= 0 ? 1 : -1); dir.setY(dir.y() >= 0 ? 1 : -1); dir.setZ(dir.z() >= 0 ? 1 : -1); m_pCoordinateQuarterCircle->setScale(m_pCoordinateQuarterCircle->getScale() * dir); m_pCoordinateQuarterCircle->render(pCamera); // bounding box also needs mirror transform m_pBoundingBoxYOZ->setQuadrantFlag(dir); m_pBoundingBoxXOZ->setQuadrantFlag(dir); m_pBoundingBoxXOY->setQuadrantFlag(dir); } } void BBRotationCoordinateSystem::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { BBCoordinateSystem::setPosition(position, bUpdateLocalTransform); m_pCoordinateQuarterCircle->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxYOZ->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxXOZ->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxXOY->setPosition(position, bUpdateLocalTransform); m_pCoordinateCircle->setPosition(position, bUpdateLocalTransform); m_pCoordinateTickMark->setPosition(position, bUpdateLocalTransform); m_pCoordinateSector->setPosition(position, bUpdateLocalTransform); } void BBRotationCoordinateSystem::setScale(const QVector3D &scale, bool bUpdateLocalTransform) { BBCoordinateSystem::setScale(scale, bUpdateLocalTransform); m_pCoordinateQuarterCircle->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxYOZ->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxXOZ->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxXOY->setScale(scale, bUpdateLocalTransform); m_pCoordinateCircle->setScale(scale, bUpdateLocalTransform); m_pCoordinateTickMark->setScale(scale, bUpdateLocalTransform); m_pCoordinateSector->setScale(scale, bUpdateLocalTransform); } void BBRotationCoordinateSystem::setSelectedAxis(const BBAxisFlags &axis) { m_pCoordinateQuarterCircle->setSelectedAxis(axis); // m_pCoordinateCircle is based on face YOZ and needs to rotate QVector3D rot; if (m_SelectedAxis == BBAxisName::AxisY) { rot = QVector3D(0, -90, 90); } else if (m_SelectedAxis == BBAxisName::AxisZ) { rot = QVector3D(0, -90, 0); } m_pCoordinateCircle->setRotation(rot); m_pCoordinateTickMark->setRotation(rot); m_pCoordinateSector->setRotation(rot); m_SelectedAxis = axis; } bool BBRotationCoordinateSystem::mouseMoveEvent(const BBRay &ray, bool bMousePressed) { do { // if transforming, there is no need to perform other operations BB_END(m_bTransforming); // otherwise, determine whether transform can be turned on BB_END(m_pSelectedObject == NULL); // handle collision detection, change color of related axis and get m_SelectedAxis // hit face YOZ, rotate around AxisX float fDistance; BB_END(!hit(ray, m_pBoundingBoxYOZ, BBAxisName::AxisX, m_pBoundingBoxXOZ, BBAxisName::AxisY, m_pBoundingBoxXOY, BBAxisName::AxisZ, fDistance)); // do not handle transform when mouse is not pressed BB_END(!bMousePressed); // meet the conditions, turn on m_bTransforming m_bTransforming = true; } while(0); transform(ray); // The return value indicates whether the transform has really performed return m_bTransforming; } void BBRotationCoordinateSystem::transform(const BBRay &ray) { if (m_bTransforming) { // perform transform operation // compute now mouse pos QVector3D mousePos; QVector3D rotAxis; if (m_SelectedAxis == BBAxisName::AxisX) { mousePos = ray.computeIntersectWithYOZPlane(m_Position.x()); rotAxis = QVector3D(1, 0, 0); } else if (m_SelectedAxis == BBAxisName::AxisY) { mousePos = ray.computeIntersectWithXOZPlane(m_Position.y()); rotAxis = QVector3D(0, 1, 0); } else if (m_SelectedAxis == BBAxisName::AxisZ) { mousePos = ray.computeIntersectWithXOYPlane(m_Position.z()); rotAxis = QVector3D(0, 0, 1); } else { return; } // whether displacement can be computed if (m_LastMousePos.isNull()) { // init m_pCoordinateSector->reset(); } else { // compute the intersection angle between two of mouse pos dir QVector3D mousePosDir = (mousePos - m_Position).normalized(); float c = QVector3D::dotProduct(m_LastMousePosDir, mousePosDir); int nDeltaAngle = round(acosf(c) / 3.141593f * 180); // compute the sign of angle QVector3D crossResult = QVector3D::crossProduct(m_LastMousePosDir, mousePosDir); float sign = crossResult.x() + crossResult.y() + crossResult.z(); sign = sign > 0 ? 1 : -1; nDeltaAngle = sign * nDeltaAngle; m_pCoordinateSector->setAngle(nDeltaAngle); m_pSelectedObject->setRotation(nDeltaAngle, rotAxis); } // record and wait the next frame m_LastMousePos = mousePos; m_LastMousePosDir = (m_LastMousePos - m_Position).normalized(); } } /** * @brief BBScaleCoordinateSystem::BBScaleCoordinateSystem */ BBScaleCoordinateSystem::BBScaleCoordinateSystem() : BBCoordinateSystem() { m_pCoordinateCube = new BBCoordinateCube(); m_pCoordinateAxis = new BBCoordinateAxis(); m_pCoordinateTriangleFace = new BBCoordinateTriangleFace(); m_pBoundingBoxX = new BBBoundingBox3D(0, 0, 0, 0, 0, 0, 1, 1, 1, 0.69f, 0.0f, 0.0f, 0.39f, 0.08f, 0.08f); m_pBoundingBoxY = new BBBoundingBox3D(0, 0, 0, 0, 0, 0, 1, 1, 1, 0.0f, 0.69f, 0.0f, 0.08f, 0.39f, 0.08f); m_pBoundingBoxZ = new BBBoundingBox3D(0, 0, 0, 0, 0, 0, 1, 1, 1, 0.0f, 0.0f, 0.69f, 0.08f, 0.08f, 0.39f); m_pBoundingBoxYOZ = new BBRectBoundingBox3D(0.0f, 0.15f, 0.15f, 0.0f, 0.15f, 0.15f); m_pBoundingBoxXOZ = new BBRectBoundingBox3D(0.15f, 0.0f, 0.15f, 0.15f, 0.0f, 0.15f); m_pBoundingBoxXOY = new BBRectBoundingBox3D(0.15f, 0.15f, 0.0f, 0.15f, 0.15f, 0.0f); m_pBoundingBoxXYZ = new BBTriangleBoundingBox3D(QVector3D(0.3f, 0.0f, 0.0f), QVector3D(0.0f, 0.3f, 0.0f), QVector3D(0.0f, 0.0f, 0.3f)); } BBScaleCoordinateSystem::~BBScaleCoordinateSystem() { BB_SAFE_DELETE(m_pCoordinateCube); BB_SAFE_DELETE(m_pCoordinateAxis); BB_SAFE_DELETE(m_pCoordinateTriangleFace); BB_SAFE_DELETE(m_pBoundingBoxX); BB_SAFE_DELETE(m_pBoundingBoxY); BB_SAFE_DELETE(m_pBoundingBoxZ); BB_SAFE_DELETE(m_pBoundingBoxYOZ); BB_SAFE_DELETE(m_pBoundingBoxXOZ); BB_SAFE_DELETE(m_pBoundingBoxXOY); BB_SAFE_DELETE(m_pBoundingBoxXYZ); } void BBScaleCoordinateSystem::init() { m_pCoordinateCube->init(); m_pCoordinateAxis->init(); m_pCoordinateTriangleFace->init(); } void BBScaleCoordinateSystem::render(BBCamera *pCamera) { if (m_pSelectedObject == NULL) return; BBCoordinateSystem::render(pCamera); m_pCoordinateCube->render(pCamera); m_pCoordinateAxis->render(pCamera); m_pCoordinateTriangleFace->render(pCamera); } void BBScaleCoordinateSystem::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { BBCoordinateSystem::setPosition(position, bUpdateLocalTransform); m_pCoordinateCube->setPosition(position, bUpdateLocalTransform); m_pCoordinateAxis->setPosition(position, bUpdateLocalTransform); m_pCoordinateTriangleFace->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxX->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxY->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxZ->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxYOZ->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxXOZ->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxXOY->setPosition(position, bUpdateLocalTransform); m_pBoundingBoxXYZ->setPosition(position, bUpdateLocalTransform); } void BBScaleCoordinateSystem::setRotation(const QVector3D &rotation, bool bUpdateLocalTransform) { BBCoordinateSystem::setRotation(rotation, bUpdateLocalTransform); m_pCoordinateCube->setRotation(rotation, bUpdateLocalTransform); m_pCoordinateAxis->setRotation(rotation, bUpdateLocalTransform); m_pCoordinateTriangleFace->setRotation(rotation, bUpdateLocalTransform); m_pBoundingBoxX->setRotation(rotation, bUpdateLocalTransform); m_pBoundingBoxY->setRotation(rotation, bUpdateLocalTransform); m_pBoundingBoxZ->setRotation(rotation, bUpdateLocalTransform); m_pBoundingBoxYOZ->setRotation(rotation, bUpdateLocalTransform); m_pBoundingBoxXOZ->setRotation(rotation, bUpdateLocalTransform); m_pBoundingBoxXOY->setRotation(rotation, bUpdateLocalTransform); m_pBoundingBoxXYZ->setRotation(rotation, bUpdateLocalTransform); } void BBScaleCoordinateSystem::setScale(const QVector3D &scale, bool bUpdateLocalTransform) { BBCoordinateSystem::setScale(scale, bUpdateLocalTransform); // when transforming, cube and axis will change as scale operation if (m_bTransforming) { QVector3D delta = m_pSelectedObject->getScale() - m_SelectedObjectOriginalScale; m_pCoordinateCube->move(delta); // the normalized scale is not 0 but 1 m_pCoordinateAxis->setScale(scale * (delta + QVector3D(1, 1, 1)), bUpdateLocalTransform); } else { // after stopTransform, go back m_pCoordinateCube->move(QVector3D(0, 0, 0)); m_pCoordinateAxis->setScale(scale, bUpdateLocalTransform); } m_pCoordinateCube->setScale(scale, bUpdateLocalTransform); m_pCoordinateTriangleFace->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxX->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxY->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxZ->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxYOZ->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxXOZ->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxXOY->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxXYZ->setScale(scale, bUpdateLocalTransform); } void BBScaleCoordinateSystem::setSelectedAxis(const BBAxisFlags &axis) { // change color of indicator m_pCoordinateCube->setSelectedAxis(axis); m_pCoordinateAxis->setSelectedAxis(axis); m_SelectedAxis = axis; } bool BBScaleCoordinateSystem::mouseMoveEvent(const BBRay &ray, bool bMousePressed) { do { // if transforming, there is no need to perform other operations BB_END(m_bTransforming); // otherwise, determine whether transform can be turned on BB_END(m_pSelectedObject == NULL); // handle collision detection, change color of related axis and get m_SelectedAxis // if hitting m_pCoordinateRectFace, no need to handle axis float fDistance; if (!hit(ray, m_pBoundingBoxYOZ, BBAxisName::AxisY | BBAxisName::AxisZ, m_pBoundingBoxXOZ, BBAxisName::AxisX | BBAxisName::AxisZ, m_pBoundingBoxXOY, BBAxisName::AxisX | BBAxisName::AxisY, fDistance)) { // handle axis BB_END(!hit(ray, m_pBoundingBoxX, BBAxisName::AxisX, m_pBoundingBoxY, BBAxisName::AxisY, m_pBoundingBoxZ, BBAxisName::AxisZ, fDistance)); } else { // Two axes are selected, determine whether the third axis is also selected // and perform collision detection on the triangle in the middle float d; if (m_pBoundingBoxXYZ->hit(ray, d)) { if (d <= fDistance) { // The middle triangle collision point is closer, select the three axes setSelectedAxis(BBAxisName::AxisX | BBAxisName::AxisY | BBAxisName::AxisZ); } } } // do not handle transform when mouse is not pressed BB_END(!bMousePressed); // meet the conditions, turn on m_bTransforming m_bTransforming = true; } while(0); transform(ray); // The return value indicates whether the transform has really performed return m_bTransforming; } void BBScaleCoordinateSystem::transform(const BBRay &ray) { if (m_bTransforming) { // perform transform operation // compute now mouse pos QVector3D mousePos; QMatrix4x4 rotMatrix; rotMatrix.rotate(m_Quaternion); if ((m_SelectedAxis == BBAxisName::AxisY) || (m_SelectedAxis == (BBAxisName::AxisX | BBAxisName::AxisY))) { ray.computeIntersectWithPlane(m_Position, rotMatrix * QVector3D(0, 0, 1), mousePos); } else if ((m_SelectedAxis == BBAxisName::AxisX || m_SelectedAxis == BBAxisName::AxisZ) || (m_SelectedAxis == (BBAxisName::AxisX | BBAxisName::AxisZ))) { ray.computeIntersectWithPlane(m_Position, rotMatrix * QVector3D(0, 1, 0), mousePos); } else if (m_SelectedAxis == (BBAxisName::AxisY | BBAxisName::AxisZ)) { ray.computeIntersectWithPlane(m_Position, rotMatrix * QVector3D(1, 0, 0), mousePos); } else if (m_SelectedAxis == (BBAxisName::AxisX | BBAxisName::AxisY | BBAxisName::AxisZ)) { ray.computeIntersectWithPlane(m_Position, rotMatrix * QVector3D(1, 1, 1), mousePos); } // whether displacement can be computed if (m_LastMousePos.isNull()) { // init for the scale of cube and axis m_SelectedObjectOriginalScale = m_pSelectedObject->getScale(); } else { QVector3D mouseDisplacement = mousePos - m_LastMousePos; QVector3D scale = m_pSelectedObject->getScale(); QVector3D dir; if (m_SelectedAxis == (BBAxisName::AxisX | BBAxisName::AxisY | BBAxisName::AxisZ)) { dir = QVector3D(1, -1, 1).normalized(); scale += QVector3D::dotProduct(rotMatrix * dir, mouseDisplacement) * QVector3D(1, 1, 1).normalized(); } else { if (m_SelectedAxis == BBAxisName::AxisX) { // The length of the projection of the mouse's displacement on the axis dir = QVector3D(1, 0, 0).normalized(); } else if (m_SelectedAxis == BBAxisName::AxisY) { dir = QVector3D(0, 1, 0).normalized(); } else if (m_SelectedAxis == BBAxisName::AxisZ) { dir = QVector3D(0, 0, 1).normalized(); } else if (m_SelectedAxis == (BBAxisName::AxisY | BBAxisName::AxisZ)) { dir = QVector3D(0, 1, 1).normalized(); } else if (m_SelectedAxis == (BBAxisName::AxisX | BBAxisName::AxisZ)) { dir = QVector3D(1, 0, 1).normalized(); } else if (m_SelectedAxis == (BBAxisName::AxisX | BBAxisName::AxisY)) { dir = QVector3D(1, 1, 0).normalized(); } scale += QVector3D::dotProduct(rotMatrix * dir, mouseDisplacement) * dir; } m_pSelectedObject->setScale(scale); } // record and wait the next frame m_LastMousePos = mousePos; } } <|start_filename|>Resources/shaders/Wave/SimpleExample.frag<|end_filename|> varying vec3 v2f_view_space_pos; varying vec2 v2f_texcoords; varying vec3 v2f_normal; uniform vec4 BBCameraPosition; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; vec3 computeTangent() { vec3 Q1 = dFdx(v2f_view_space_pos); vec3 Q2 = dFdy(v2f_view_space_pos); vec2 st1 = dFdx(v2f_texcoords); vec2 st2 = dFdy(v2f_texcoords); vec3 T = normalize(Q1 * st2.t - Q2 * st1.t); return T; } vec4 computeAnisotropicHighlights(float u, vec3 N, vec3 H, float r, vec4 hiliteColor) { // Anisotropic highlights from <NAME> // Roughness r, hiliteColor // The final result is the superposition of dispersion and anisotropic highlights. // Related to H float w = dot(N, H); float e = r * u / w; float c = exp(-e * e); vec4 specular = hiliteColor * vec4(c, c, c, 1.0); return specular; } vec3 blend3(vec3 x) { vec3 y = 1 - x * x; y = max(y, vec3(0.0)); return y; } void main(void) { vec3 N = normalize(v2f_normal); vec3 L = normalize(BBLightPosition.xyz); vec3 V = normalize(BBCameraPosition.xyz - v2f_view_space_pos); vec3 H = normalize(L + V); vec3 T = computeTangent(); float d = 0.001; float u = dot(T, H) * d; vec4 specular = computeAnisotropicHighlights(u, N, H, 0.2, vec4(0.9, 0.9, 0.9, 1.0)); if (u < 0.0) u = -u; vec4 diffuse = vec4(0.0, 0.0, 0.0, 1.0); // iteration for (int n = 1; n <= 8; n++) { // Wave length 0~1mm float y = 2 * u / n - 1; // Spectrum // R(Wave length) = bump(C * (y - 0.75)); // G(Wave length) = bump(C * (y - 0.50)); // B(Wave length) = bump(C * (y - 0.25)); // C is shape func, 4.0 is great diffuse.xyz += blend3(4.0 * vec3(y - 0.75, y - 0.5, y - 0.25)); } gl_FragColor = diffuse; } <|start_filename|>Code/BBearEditor/Engine/Allocator/BBMemoryLabel.h<|end_filename|> #pragma once #ifndef BBMEMORYLABEL_H #define BBMEMORYLABEL_H enum BBMemoryLabel { Default, VertexData, IndexData, Texture, Shader, Mesh, Transform, Material, Profiler }; #endif // BBMEMORYLABEL_H <|start_filename|>Code/BBearEditor/Editor/ObjectList/BBObjectListWidget.h<|end_filename|> #ifndef BBOBJECTLISTWIDGET_H #define BBOBJECTLISTWIDGET_H #include <QListWidget> class BBObjectListWidget : public QListWidget { Q_OBJECT public: explicit BBObjectListWidget(QWidget *parent = 0, const int pieceSize = 35); virtual ~BBObjectListWidget(); bool loadListItems(const char *xmlFilePath); void setMimeType(const QString &strMimeType) { m_strMimeType = strMimeType; } signals: void removeCurrentItemInFileList(); private: void startDrag(Qt::DropActions supportedActions) override; void focusInEvent(QFocusEvent *e) override; int m_iPieceSize; // {base, light, ...} QString m_strMimeType; }; #endif // BBOBJECTLISTWIDGET_H <|start_filename|>Code/BBearEditor/Engine/Physics/FluidSystem/BBSPHFluidSystem.h<|end_filename|> #ifndef BBSPHFLUIDSYSTEM_H #define BBSPHFLUIDSYSTEM_H #include "Base/BBGameObject.h" class BBSPHParticle; class BBSPHParticleSystem; class BBSPHGridContainer; class BBSPHParticleNeighborTable; class BBSPHFluidRenderer; class BBMarchingCubeMesh; class BBSPHFluidSystem : public BBGameObject { public: BBSPHFluidSystem(const QVector3D &position = QVector3D(0, 0, 0)); ~BBSPHFluidSystem(); void init(unsigned int nMaxParticleCount, const QVector3D &wallBoxMin, const QVector3D &wallBoxMax, const QVector3D &originalFluidBoxMin, const QVector3D &originalFluidBoxMax, const QVector3D &gravity = QVector3D(0, -9.8f, 0)); void render(BBCamera *pCamera) override; void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; void reset(); public: inline BBSPHFluidRenderer* getFluidRenderer() { return m_pFluidRenderer; } private: void initFluidVolume(const QVector3D &fluidBoxMin, const QVector3D &fluidBoxMax, float fSpacing); private: void computeNeighborTable(); void computeDensityAndPressure(); void computeAcceleration(); void computeBoundaryForce(BBSPHParticle *pParticle); void handleCollision(BBSPHParticle* pParticle); void computePositionAndVelocity(); void computePositionAndVelocityWithGravity(); private: void computeImplicitField(unsigned int pNum[3], const QVector3D &minPos, const QVector3D &unitWidth); // Density field float computeColorField(const QVector3D &pos); private: // Anisotropic surface void computeAnisotropicKernel(); std::vector<QVector3D> m_OldPositions; bool m_bAnisotropic; // Transform Matrixs std::vector<QMatrix3x3> m_G; private: // Paper: Predictive-Corrective Incompressible SPH void computeGradient(); void computePCISPHDensityErrorFactor(); void computePCISPHAcceleration(); void predictPCISPHCorrection(); void predictPCISPHPositionAndVelocity(BBSPHParticle *pParticle); float predictPCISPHDensityAndPressure(int nParticleIndex); void computePCISPHCorrectivePressureForce(int nParticleIndex); void computePCISPHPositionAndVelocity(); float m_fPCISPHDensityErrorFactor; bool m_bPredictCorrection; private: BBSPHParticleSystem *m_pParticleSystem; BBSPHGridContainer *m_pGridContainer; BBSPHParticleNeighborTable *m_pParticleNeighborTable; // SPH smooth kernel float m_fKernelPoly6; float m_fKernelSpiky; float m_fKernelViscosity; float m_fParticleRadius; float m_fParticleMass; float m_fUnitScale; float m_fViscosity; float m_fStaticDensity; float m_fSmoothRadius; float m_fGasConstantK; float m_fBoundingStiffness; float m_fBoundingDamping; float m_fSpeedLimiting; QVector3D m_Gravity; QVector3D m_Size; QVector3D m_WallBoxMin; QVector3D m_WallBoxMax; QVector3D m_OriginalFluidBoxMin; QVector3D m_OriginalFluidBoxMax; float m_fDeltaTime; BBSPHFluidRenderer *m_pFluidRenderer; unsigned int m_pFieldSize[3]; BBMarchingCubeMesh *m_pMCMesh; float *m_pDensityField; float m_fDensityThreshold; }; #endif // BBSPHFLUIDSYSTEM_H <|start_filename|>Code/BBearEditor/Engine/Physics/Force/BBForce.cpp<|end_filename|> #include "BBForce.h" BBForce::BBForce() { } BBForce::~BBForce() { } <|start_filename|>Code/BBearEditor/Engine/Geometry/BBPlane.h<|end_filename|> #ifndef BBPLANE_H #define BBPLANE_H #include <QVector3D> class BBPlane { public: BBPlane(); BBPlane(const QVector3D &point1, const QVector3D &point2, const QVector3D &point3); float distance(const QVector3D &point) const; static float distance(const QVector3D &pointOnPlane, const QVector3D &planeNormal, const QVector3D &point); static BBPlane invert(const BBPlane &plane); QVector3D getPoint1() const { return m_Point1; } QVector3D getPoint2() const { return m_Point2; } QVector3D getPoint3() const { return m_Point3; } QVector3D getNormal() const { return m_Normal; } private: QVector3D m_Point1; QVector3D m_Point2; QVector3D m_Point3; QVector3D m_Normal; }; #endif // BBPLANE_H <|start_filename|>Resources/shaders/GI/FLC_TriangleCut_FS.frag<|end_filename|> #version 430 core struct G2FTriangle { vec3 positions[3]; vec3 normal; vec2 texcoord; vec2 area_and_level; }; in G2F { G2FTriangle triangle; } g2f; layout (location = 0) out vec4 FragColor; struct TriangleCut { vec4 center; vec4 normal_and_level; vec4 color_and_area; }; layout (std140, binding = 1) buffer Triangles { TriangleCut triangles[]; }; layout (binding = 0, offset = 0) uniform atomic_uint TriangleID; void main(void) { vec3 center = (g2f.triangle.positions[0] + g2f.triangle.positions[1] + g2f.triangle.positions[2]) / 3.0; int current_id = int(atomicCounterIncrement(TriangleID)); triangles[current_id].center = vec4(center, 1.0); triangles[current_id].normal_and_level = vec4(g2f.triangle.normal, g2f.triangle.area_and_level.y); triangles[current_id].color_and_area = vec4(1.0, 1.0, 1.0, g2f.triangle.area_and_level.x); FragColor = vec4(center, 1.0); FragColor = vec4(current_id * 1.0 / 10000000, 0, 0, 1); } <|start_filename|>Resources/shaders/Diffuse_SSBO.vert<|end_filename|> #version 430 core struct Vertex { vec4 BBPosition; vec4 BBColor; vec4 BBTexcoord; vec4 BBNormal; vec4 BBTangent; vec4 BBBiTangent; }; layout (std140, binding = 0) buffer Bundle { Vertex vertexes[]; } bundle; out V2F { vec4 color; vec3 normal; } v2f; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { v2f.color = bundle.vertexes[gl_VertexID].BBColor; v2f.normal = mat3(transpose(inverse(BBModelMatrix))) * bundle.vertexes[gl_VertexID].BBNormal.xyz; gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * bundle.vertexes[gl_VertexID].BBPosition; } <|start_filename|>Code/BBearEditor/Editor/Tools/FBX2BBear/BBFBX2BBear.h<|end_filename|> #ifndef BBFBX2BBEAR_H #define BBFBX2BBEAR_H class QListWidgetItem; class BBFBX2BBear { public: static void loadFBXFile(QListWidgetItem *pItem); }; #endif // BBFBX2BBEAR_H <|start_filename|>Code/BBearEditor/Engine/Math/BBPerlinNoise.h<|end_filename|> #ifndef BBPERLINNOISE_H #define BBPERLINNOISE_H #include <QVector3D> class BBPerlinNoise { public: BBPerlinNoise(); static float getNoise(const QVector3D &p); static float getTurbulenceNoise(const QVector3D &p, int nDepth = 7); private: static QVector3D *generateRandFloat(); static int* generatePermute(); static void permute(int *p, int n); static QVector3D *m_pRandFloat; static int *m_pPermuteX; static int *m_pPermuteY; static int *m_pPermuteZ; }; #endif // BBPERLINNOISE_H <|start_filename|>Code/BBearEditor/Engine/3D/BBIcon.h<|end_filename|> #ifndef BBICON_H #define BBICON_H #include "Base/BBRenderableObject.h" class BBRectBoundingBox3D; class BBIcon : public BBRenderableObject { public: BBIcon(); BBIcon(const QVector3D &position, const QVector3D &rotation, const QVector3D &scale); ~BBIcon(); void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; void setRotation(const QQuaternion &quaternion, bool bUpdateLocalTransform = true) override; void setScale(const QVector3D &scale, bool bUpdateLocalTransform = true) override; void init(const QString &path) override; bool hit(const BBRay &ray, float &fDistance) override; bool belongToSelectionRegion(const BBFrustum &frustum) override; private: BBRectBoundingBox3D *m_pBoundingBox; }; #endif // BBICON_H <|start_filename|>Resources/shaders/ParticleSystem/Particles2-1.vert<|end_filename|> #version 430 attribute vec4 BBPosition; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; void main() { gl_Position = BBProjectionMatrix * BBViewMatrix * BBPosition; } <|start_filename|>Code/BBearEditor/Engine/Geometry/BBBoundingBox2D.cpp<|end_filename|> #include "BBBoundingBox2D.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BBDrawCall.h" /** * @brief BBBoundingBox2D::BBBoundingBox2D */ BBBoundingBox2D::BBBoundingBox2D() : BBBoundingBox2D(0, 0, -1, -1) { } BBBoundingBox2D::BBBoundingBox2D(int x, int y, int nWidth, int nHeight) : BBRenderableObject2D(x, y, nWidth, nHeight) { } void BBBoundingBox2D::init() { BBRenderableObject2D::init(); m_pCurrentMaterial->setVector4(LOCATION_TEXTURE_SETTING0, 0.0f, 0.0f, 0.0f, 0.0f); } /** * @brief BBAABBBoundingBox2D::BBAABBBoundingBox2D * @param fCenterX 3D coordinate * @param fCenterY 3D coordinate * @param fHalfLengthX 3D coordinate * @param fHalfLengthY 3D coordinate * @param nWidth screen coordinate * @param nHeight screen coordinate */ BBAABBBoundingBox2D::BBAABBBoundingBox2D(float fCenterX, float fCenterY, float fHalfLengthX, float fHalfLengthY, int nWidth, int nHeight) : BBBoundingBox2D(fCenterX * nWidth, fCenterY * nHeight, nWidth, nHeight) { m_nHalfLengthX = fHalfLengthX * nWidth; m_nHalfLengthY = fHalfLengthY * nHeight; } BBAABBBoundingBox2D::BBAABBBoundingBox2D(int x, int y, int nHalfLengthX, int nHalfLengthY) : BBBoundingBox2D(x, y, nHalfLengthX * 2, nHalfLengthY * 2) { m_nHalfLengthX = nHalfLengthX; m_nHalfLengthY = nHalfLengthY; } void BBAABBBoundingBox2D::init() { m_pVBO = new BBVertexBufferObject(8); m_pVBO->setPosition(0, 0.5f, 0.5f, 0.0f); m_pVBO->setPosition(1, -0.5f, 0.5f, 0.0f); m_pVBO->setPosition(2, -0.5f, 0.5f, 0.0f); m_pVBO->setPosition(3, -0.5f, -0.5f, 0.0f); m_pVBO->setPosition(4, -0.5f, -0.5f, 0.0f); m_pVBO->setPosition(5, 0.5f, -0.5f, 0.0f); m_pVBO->setPosition(6, 0.5f, -0.5f, 0.0f); m_pVBO->setPosition(7, 0.5f, 0.5f, 0.0f); for (int i = 0; i < 8; i++) { m_pVBO->setColor(i, BBConstant::m_OrangeRed); } BBBoundingBox2D::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, GL_LINES, 0, 8); appendDrawCall(pDrawCall); } bool BBAABBBoundingBox2D::hit(int x, int y) { if (x > m_Position.x() + m_nHalfLengthX) return false; if (x < m_Position.x() - m_nHalfLengthX) return false; if (y > m_Position.y() + m_nHalfLengthY) return false; if (y < m_Position.y() - m_nHalfLengthY) return false; return true; } /** * @brief BBQuarterCircleBoundingBox2D::BBQuarterCircleBoundingBox2D * @param x * @param y * @param nRadius */ BBQuarterCircleBoundingBox2D::BBQuarterCircleBoundingBox2D(int x, int y, int nRadius) : BBBoundingBox2D(x, y, nRadius * 2, nRadius * 2) { m_nRadius = nRadius; } bool BBQuarterCircleBoundingBox2D::hit(int x, int y) { if (x < m_Position.x()) return false; if (y < m_Position.y()) return false; if (((x - m_Position.x()) * (x - m_Position.x()) + (y - m_Position.y()) * (y - m_Position.y())) > m_nRadius * m_nRadius) return false; return true; } <|start_filename|>Resources/shaders/stencilUI.vert<|end_filename|> attribute vec4 BBPosition; uniform mat4 BBModelMatrix; uniform vec4 BBCanvas; void main() { vec4 screen_pos = BBModelMatrix * BBPosition; // Scaling to NDC coordinates // Z is any value of -1 ~ 1 gl_Position = vec4(screen_pos.x / BBCanvas.x, screen_pos.y / BBCanvas.y, 0.0, 1.0); } <|start_filename|>Resources/shaders/PBR/Lighting_Textured.frag<|end_filename|> #version 330 core out vec4 FragColor; in vec2 v2f_texcoords; in vec3 v2f_world_pos; in vec3 v2f_normal; uniform vec4 BBCameraPosition; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; uniform vec4 BBLightSettings0; uniform vec4 BBLightSettings1; uniform vec4 BBLightSettings2; uniform sampler2D Albedo_Map; uniform sampler2D Normal_Map; uniform sampler2D Metallic_Map; uniform sampler2D Roughness_Map; uniform sampler2D AO_Map; const float PI = 3.14159265359; vec3 getNormalFromMap() { vec3 normal = texture(Normal_Map, v2f_texcoords).xyz * 2.0 - 1.0; vec3 Q1 = dFdx(v2f_world_pos); vec3 Q2 = dFdy(v2f_world_pos); vec2 st1 = dFdx(v2f_texcoords); vec2 st2 = dFdy(v2f_texcoords); vec3 N = normalize(v2f_normal); vec3 T = normalize(Q1 * st2.t - Q2 * st1.t); vec3 B = -normalize(cross(N, T)); mat3 TBN = mat3(T, B, N); return normalize(TBN * normal); } float getLambertPointLightIntensity(vec3 normal, float radius, float distance, float attenuation, vec3 L) { float delta = radius - distance; float intensity = 0.0; if (delta >= 0) { intensity = max(0.0, dot(L, normal) * attenuation * delta / radius); } return intensity; } float getLambertSpotLightIntensity(vec3 normal, float radius, float distance, float attenuation, vec3 L) { float intensity = max(0.0, dot(normal, L)); if (intensity > 0.0) { vec3 spot_direction = normalize(BBLightSettings2.xyz); // Cosine of the angle between the current point and the spotlight direction float current_cos = max(0.0, dot(spot_direction, -L)); // cutoff cosine float cutoff_radian = BBLightSettings0.z / 2 * 3.14 / 180.0; float cutoff_cos = cos(cutoff_radian); if (current_cos > cutoff_cos) { // Within the cutoff range float delta = radius - distance; intensity = pow(current_cos, BBLightSettings0.w) * 2.0 * attenuation * delta / radius; } else { intensity = 0.0; } } return intensity; } // Fresnel equation returns the percentage of light reflected on the surface of an object, // that is, the parameter KS in our reflection equation vec3 calculateFresnelSchlick(float cos_theta, vec3 F0) { return F0 + (1.0 - F0) * pow(1.0 - cos_theta, 5.0); } float calculateDistributionGGX(vec3 N, vec3 H, float roughness) { float a = roughness * roughness; float a2 = a * a; float NdotH = max(dot(N, H), 0.0); float nom = a2; float denom = (NdotH * NdotH * (a2 - 1.0) + 1.0); denom = PI * denom * denom; // prevent divide by zero for roughness = 0.0 and NdotH = 1.0 return nom / max(denom, 0.0000001); } float calculateGeometrySchlickGGX(float NdotV, float roughness) { float r = (roughness + 1.0); float k = (r * r) / 8.0; float nom = NdotV; float denom = NdotV * (1.0 - k) + k; return nom / denom; } float calculateGeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) { float NdotV = max(dot(N, V), 0.0); float NdotL = max(dot(N, L), 0.0); float ggx1 = calculateGeometrySchlickGGX(NdotV, roughness); float ggx2 = calculateGeometrySchlickGGX(NdotL, roughness); return ggx1 * ggx2; } void main(void) { vec3 albedo = pow(texture(Albedo_Map, v2f_texcoords).rgb, vec3(2.2)); float metallic = texture(Metallic_Map, v2f_texcoords).r; float roughness = texture(Roughness_Map, v2f_texcoords).r; float ao = texture(AO_Map, v2f_texcoords).r; vec3 N = getNormalFromMap(); vec3 V = normalize(BBCameraPosition.xyz - v2f_world_pos); // Lambert radiance vec3 L = vec3(1.0); vec3 radiance = vec3(0.0); if (BBLightPosition.w == 0.0) { // there is a directional light L = normalize(BBLightPosition.xyz); float intensity = max(0.0, dot(N, L)); radiance = intensity * BBLightColor.rgb; } else { float radius = BBLightSettings1.x; float constant_factor = BBLightSettings1.y; float linear_factor = BBLightSettings1.z; float quadric_factor = BBLightSettings1.w; L = BBLightPosition.xyz - v2f_world_pos; float distance = length(L); float attenuation = 1.0 / (constant_factor + linear_factor * distance + quadric_factor * quadric_factor * distance); L = normalize(L); float intensity; if (BBLightSettings0.x == 2.0) { // there is a spot light intensity = getLambertSpotLightIntensity(N, radius, distance, attenuation, L); } else { // there is a point light intensity = getLambertPointLightIntensity(N, radius, distance, attenuation, L); } radiance = BBLightColor.rgb * intensity * BBLightSettings0.y; } vec3 H = normalize(V + L); // Cook-Torrance specular BRDF // calculate reflectance at normal incidence // if dia-electric (like plastic) use F0 of 0.04 and if it's a metal, use the albedo color as F0 (metallic workflow) vec3 F0 = vec3(0.04f); F0 = mix(F0, albedo, metallic); vec3 F = calculateFresnelSchlick(clamp(dot(H, V), 0.0, 1.0), F0); float NDF = calculateDistributionGGX(N, H, roughness); float G = calculateGeometrySmith(N, V, L, roughness); vec3 numerator = NDF * G * F; float denominator = 4 * max(dot(N, V), 0.0) * max(dot(N, L), 0.0); // + 0.001 prevent divide by zero vec3 specular = numerator / max(denominator, 0.001); // kS is equal to Fresnel vec3 kS = F; // for energy conservation, the diffuse and specular light can't be above 1.0 (unless the surface emits light) // to preserve, the diffuse component (kD) should equal 1.0 - kS. vec3 kD = vec3(1.0) - kS; // multiply kD by the inverse metalness such that only non-metals have diffuse lighting, // or a linear blend if partly metal (pure metals have no diffuse light). kD *= 1.0 - metallic; // scale light by NdotL float NdotL = max(dot(N, L), 0.0); // outgoing radiance Lo // note that we already multiplied the BRDF by the Fresnel (kS) so we won't multiply by kS again vec3 Lo = (kD * albedo / PI + specular) * radiance * NdotL; // ambient lighting vec3 ambient = vec3(0.03) * albedo * ao; vec3 final_color = ambient + Lo; // Lo as a result may grow rapidly (more than 1), but the value is truncated due to the default LDR input. // Therefore, before gamma correction, we use tone mapping to map Lo from the value of LDR to the value of HDR. // HDR tonemapping final_color = final_color / (final_color + vec3(1.0)); // gamma correct final_color = pow(final_color, vec3(1.0 / 2.2)); FragColor = vec4(final_color, 1.0); } <|start_filename|>Code/BBearEditor/Engine/Geometry/BBPhotonMap.h<|end_filename|> #ifndef BBPHOTONMAP_H #define BBPHOTONMAP_H #include <QVector3D> #include "Utils/BBUtils.h" #include "Geometry/BBRay.h" struct BBPhoton { QVector3D m_Position; // Incident QVector3D m_Direction; // Color QVector3D m_Power; int m_Axis; // for test bool m_bKNearestPhotons; BBPhoton() { m_bKNearestPhotons = false; } }; struct BBNearestPhotons { // Detection point position QVector3D m_DetectionPosition; // Maximum number of photons to find int m_nMaxPhotonCount; // Number of photons found int m_nCurrentCount; // Is the maximum heap full, m_nMaxPhotonCount == m_nCurrentCount bool m_bFulled; // Store the square of the distance in the photon maximum stack between photon and the detection point to avoid repeated calculation each time // [0] store the maximum float *m_pDistanceSquare; // Photons found BBPhoton **m_ppPhotons; BBNearestPhotons(const QVector3D &detectionPosition, int nMaxPhotonCount, float fDetectionDistance) { m_DetectionPosition = detectionPosition; m_nMaxPhotonCount = nMaxPhotonCount; m_nCurrentCount = 0; m_bFulled = false; m_pDistanceSquare = new float[m_nMaxPhotonCount + 1]; m_ppPhotons = new BBPhoton*[m_nMaxPhotonCount + 1]; m_pDistanceSquare[0] = fDetectionDistance * fDetectionDistance; } ~BBNearestPhotons() { BB_SAFE_DELETE_ARRAY(m_pDistanceSquare); BB_SAFE_DELETE_ARRAY(m_ppPhotons); } }; class BBPhotonMap { public: BBPhotonMap(int nMaxPhotonNum = 10000); ~BBPhotonMap(); BBPhotonMap operator=(const BBPhotonMap &photonMap); void store(const BBPhoton &photon); void balance(); void getKNearestPhotons(BBNearestPhotons *pNearestPhotons, int nParentIndex); QVector3D getIrradiance(const QVector3D &detectionPosition, const QVector3D &detectionNormal, float fDetectionDistance, int nMaxPhotonCount); // Test func void debug(); void debug(BBNearestPhotons *pNearestPhotons); void markKNearestPhotons(BBNearestPhotons *pNearestPhotons); bool isMarkedKNearestPhotons(int nIndex); QVector3D* getPhotonPositions(); int getPhotonNum() const { return m_nPhotonNum; } int getMaxPhotonNum() const { return m_nMaxPhotonNum; } BBPhoton* getPhoton() const { return m_pPhoton; } QVector3D getBoxMin() const { return m_BoxMin; } QVector3D getBoxMax() const { return m_BoxMax; } public: static void tracePhoton(const BBRay &ray, BBModel *pSceneModels[], int nModelCount, int depth, const QVector3D &power, BBPhotonMap *pPhotonMap, bool bOnlyStoreCausticsPhoton); static QVector3D traceRay(const BBRay &ray, BBModel *pSceneModels[], int nModelCount, int depth, BBPhotonMap *pPhotonMap); private: static int m_nMaxTraceDepth; private: void splitMedian(BBPhoton pPhoton[], int start, int end, int median, int axis); void balanceSegment(BBPhoton pPhoton[], int index, int start, int end); int m_nPhotonNum; int m_nMaxPhotonNum; BBPhoton *m_pPhoton; QVector3D m_BoxMin; QVector3D m_BoxMax; }; #endif // BBPHOTONMAP_H <|start_filename|>Code/BBearEditor/Engine/Render/BBMaterialProperty.cpp<|end_filename|> #include "BBMaterialProperty.h" #include "Utils/BBUtils.h" /** * @brief BBMaterialProperty::BBMaterialProperty * @param eType */ BBMaterialProperty::BBMaterialProperty(const BBMaterialUniformPropertyType &eType, const char *name) { m_eType = eType; memset(m_Name, 0, 64); strcpy(m_Name, name); } BBMaterialProperty::~BBMaterialProperty() { } /** * @brief BBFloatMaterialProperty::BBFloatMaterialProperty * @param name */ BBFloatMaterialProperty::BBFloatMaterialProperty(const char *name) : BBMaterialProperty(Float, name) { m_fPropertyValue = 0.0f; } BBFloatMaterialProperty::~BBFloatMaterialProperty() { } BBMaterialProperty* BBFloatMaterialProperty::clone() { BBFloatMaterialProperty *pRet = new BBFloatMaterialProperty(m_Name); pRet->setPropertyValue(m_fPropertyValue); return pRet; } /** * @brief BBFloatArrayMaterialProperty::BBFloatArrayMaterialProperty * @param name * @param nArrayCount */ BBFloatArrayMaterialProperty::BBFloatArrayMaterialProperty(const char *name, int nArrayCount) : BBMaterialProperty(FloatArray, name) { m_pPropertyValue = nullptr; m_nArrayCount = nArrayCount; } BBFloatArrayMaterialProperty::~BBFloatArrayMaterialProperty() { BB_SAFE_DELETE(m_pPropertyValue); } BBMaterialProperty* BBFloatArrayMaterialProperty::clone() { BBFloatArrayMaterialProperty *pRet = new BBFloatArrayMaterialProperty(m_Name, m_nArrayCount); pRet->setPropertyValue(m_pPropertyValue); return pRet; } /** * @brief BBMatrix4MaterialProperty::BBMatrix4MaterialProperty */ BBMatrix4MaterialProperty::BBMatrix4MaterialProperty(const char *name) : BBMaterialProperty(Matrix4, name) { m_pPropertyValue = nullptr; } BBMatrix4MaterialProperty::~BBMatrix4MaterialProperty() { BB_SAFE_DELETE(m_pPropertyValue); } BBMaterialProperty* BBMatrix4MaterialProperty::clone() { BBMatrix4MaterialProperty *pRet = new BBMatrix4MaterialProperty(m_Name); pRet->setPropertyValue(m_pPropertyValue); return pRet; } /** * @brief BBVector4MaterialProperty::BBVector4MaterialProperty * @param eType */ BBVector4MaterialProperty::BBVector4MaterialProperty(const char *name) : BBMaterialProperty(Vector4, name) { m_pPropertyValue = new float[4] {0, 0, 0, 1}; if (strncmp(name, LOCATION_COLOR_PREFIX, LOCATION_COLOR_PREFIX_CHAR_COUNT) == 0) { m_eFactoryType = Color; m_NameInPropertyManager = QString(name).mid(LOCATION_COLOR_PREFIX_CHAR_COUNT); } else if (strncmp(name, LOCATION_TILINGANDOFFSET_PREFIX, LOCATION_TILINGANDOFFSET_PREFIX_CHAR_COUNT) == 0) { m_eFactoryType = TilingAndOffset; m_NameInPropertyManager = QString(name).mid(LOCATION_TILINGANDOFFSET_PREFIX_CHAR_COUNT); } else { m_eFactoryType = Default; } } BBVector4MaterialProperty::~BBVector4MaterialProperty() { BB_SAFE_DELETE(m_pPropertyValue); } BBMaterialProperty* BBVector4MaterialProperty::clone() { BBVector4MaterialProperty *pRet = new BBVector4MaterialProperty(m_Name); pRet->setPropertyValue(m_pPropertyValue); return pRet; } /** * @brief BBVector4ArrayMaterialProperty::BBVector4ArrayMaterialProperty * @param name * @param nArrayCount */ BBVector4ArrayMaterialProperty::BBVector4ArrayMaterialProperty(const char *name, int nArrayCount) : BBMaterialProperty(Vector4Array, name) { m_pPropertyValue = nullptr; m_nArrayCount = nArrayCount; } BBVector4ArrayMaterialProperty::~BBVector4ArrayMaterialProperty() { BB_SAFE_DELETE(m_pPropertyValue); } BBMaterialProperty* BBVector4ArrayMaterialProperty::clone() { BBVector4ArrayMaterialProperty *pRet = new BBVector4ArrayMaterialProperty(m_Name, m_nArrayCount); pRet->setPropertyValue(m_pPropertyValue); return pRet; } /** * @brief BBSampler2DMaterialProperty::BBSampler2DMaterialProperty * @param name * @param nSlotIndex */ BBSampler2DMaterialProperty::BBSampler2DMaterialProperty(const char *name, int nSlotIndex) : BBMaterialProperty(Sampler2D, name) { m_TextureName = 0; m_nSlotIndex = nSlotIndex; } BBSampler2DMaterialProperty::~BBSampler2DMaterialProperty() { } BBMaterialProperty* BBSampler2DMaterialProperty::clone() { BBSampler2DMaterialProperty *pRet = new BBSampler2DMaterialProperty(m_Name, m_nSlotIndex); pRet->setTextureName(m_TextureName, m_ResourcePath); return pRet; } void BBSampler2DMaterialProperty::setTextureName(GLuint textureName, const QString &resourcePath) { m_TextureName = textureName; m_ResourcePath = resourcePath; } /** * @brief BBSampler3DMaterialProperty::BBSampler3DMaterialProperty * @param name * @param nSlotIndex */ BBSampler3DMaterialProperty::BBSampler3DMaterialProperty(const char *name, int nSlotIndex) : BBMaterialProperty(Sampler3D, name) { m_TextureName = 0; m_nSlotIndex = nSlotIndex; } BBSampler3DMaterialProperty::~BBSampler3DMaterialProperty() { } BBMaterialProperty* BBSampler3DMaterialProperty::clone() { BBSampler3DMaterialProperty *pRet = new BBSampler3DMaterialProperty(m_Name, m_nSlotIndex); pRet->setTextureName(m_TextureName, m_ResourcePath); return pRet; } void BBSampler3DMaterialProperty::setTextureName(GLuint textureName, const QString &resourcePath) { m_TextureName = textureName; m_ResourcePath = resourcePath; } /** * @brief BBSamplerCubeMaterialProperty::BBSamplerCubeMaterialProperty * @param name * @param nSlotIndex */ BBSamplerCubeMaterialProperty::BBSamplerCubeMaterialProperty(const char *name, int nSlotIndex) : BBMaterialProperty(SamplerCube, name) { m_TextureName = 0; m_nSlotIndex = nSlotIndex; } BBSamplerCubeMaterialProperty::~BBSamplerCubeMaterialProperty() { } BBMaterialProperty* BBSamplerCubeMaterialProperty::clone() { BBSamplerCubeMaterialProperty *pRet = new BBSamplerCubeMaterialProperty(m_Name, m_nSlotIndex); pRet->setTextureName(m_TextureName, m_ResourcePath); return pRet; } void BBSamplerCubeMaterialProperty::setTextureName(GLuint textureName) { m_TextureName = textureName; } void BBSamplerCubeMaterialProperty::setTextureName(GLuint textureName, const QString resourcePath[]) { m_TextureName = textureName; for (int i = 0; i < 6; i++) { m_ResourcePath[i] = resourcePath[i]; } } <|start_filename|>Code/BBearEditor/Engine/Render/BufferObject/BBAtomicCounterBufferObject.h<|end_filename|> #ifndef BBATOMICCOUNTERBUFFEROBJECT_H #define BBATOMICCOUNTERBUFFEROBJECT_H #include "BBBufferObject.h" class BBAtomicCounterBufferObject : public BBBufferObject { public: BBAtomicCounterBufferObject(); void clear(); void bind() override; void unbind() override; }; #endif // BBATOMICCOUNTERBUFFEROBJECT_H <|start_filename|>Code/BBearEditor/Engine/Render/Lighting/BBSphericalHarmonicLighting.h<|end_filename|> #ifndef BBSPHERICALHARMONICLIGHTING_H #define BBSPHERICALHARMONICLIGHTING_H #include <QVector3D> #include <QList> class BBSphericalHarmonicLighting { public: static void computeLightingData(int nAlgorithmIndex); static const float* getCoefficientL(); static int getCoefficientLCount(); static void bakeLightingMap(); static void computeCoefficientL(); private: static QImage* loadSkyBox(); static float computeSphereSurfaceArea(double x, double y); static QVector3D cubeUV2XYZ(int nSkyBoxSideIndex, double u, double v); static QList<float> getYBasis(const QVector3D &normal); private: static int m_nDegree; static int m_nWidth; static int m_nHeight; static QList<QVector3D> m_CoefficientL; }; #endif // BBSPHERICALHARMONICLIGHTING_H <|start_filename|>Code/BBearEditor/Engine/Base/BBGameObject.cpp<|end_filename|> #include "BBGameObject.h" #include "Render/BBCamera.h" #include "Scene/BBSceneManager.h" #include "BBGameObjectSet.h" #include <QTreeWidgetItem> BBGameObject::BBGameObject() : BBGameObject(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBGameObject::BBGameObject(const QVector3D &position, const QVector3D &rotation, const QVector3D &scale) : BBGameObject(position.x(), position.y(), position.z(), rotation.x(), rotation.y(), rotation.z(), scale.x(), scale.y(), scale.z()) { } BBGameObject::BBGameObject(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) { m_Position = QVector3D(px, py, pz); m_Rotation = QVector3D(rx, ry, rz); m_Scale = QVector3D(sx, sy, sz); m_Quaternion = QQuaternion::fromEulerAngles(m_Rotation); m_LocalPosition = m_Position; m_LocalRotation = m_Rotation; m_LocalScale = m_Scale; m_LocalQuaternion = m_Quaternion; setModelMatrix(px, py, pz, m_Quaternion, sx, sy, sz); m_bActive = true; m_strName = "name"; m_strClassName = "class name"; m_strIconName = "model"; } /** * @brief BBGameObject::BBGameObject 2D * @param x * @param y * @param nWidth * @param nHeight */ BBGameObject::BBGameObject(int x, int y, int nWidth, int nHeight) { setSize(nWidth, nHeight); setScreenCoordinate(x, y); } void BBGameObject::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { QVector3D displacement = position - m_Position; m_Position = position; setModelMatrix(m_Position.x(), m_Position.y(), m_Position.z(), m_Quaternion, m_Scale.x(), m_Scale.y(), m_Scale.z()); QTreeWidgetItem *pItem = BBSceneManager::getSceneTreeItem(this); // Some objects are not managed by BBHierarchyTreeWidget if (pItem) { // handle children for (int i = 0; i < pItem->childCount(); i++) { BBGameObject *pGameObject = BBSceneManager::getGameObject(pItem->child(i)); // the localTransform of child is not changed, bUpdateLocalTransform = false pGameObject->setPosition(pGameObject->getPosition() + displacement, false); } // set local if (bUpdateLocalTransform) { m_LocalPosition = m_LocalPosition + displacement; } } BBSceneManager::changeScene(this); } void BBGameObject::setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform) { // Rotate the current quaternion QQuaternion rot = QQuaternion::fromAxisAndAngle(axis, nAngle); // Multiply to the original quaternion m_Quaternion = rot * m_Quaternion; // Turn to Euler Angle m_Rotation = m_Quaternion.toEulerAngles(); setModelMatrix(m_Position.x(), m_Position.y(), m_Position.z(), m_Quaternion, m_Scale.x(), m_Scale.y(), m_Scale.z()); QTreeWidgetItem *pItem = BBSceneManager::getSceneTreeItem(this); // Some objects are not managed by BBHierarchyTreeWidget if (pItem) { // handle children // push all children into set QList<BBGameObject*> gameObjects; for (int i = 0; i < pItem->childCount(); i++) { BBGameObject *pGameObject = BBSceneManager::getGameObject(pItem->child(i)); gameObjects.append(pGameObject); } // The center point is not the center of all objects, but the position of the parent BBGameObjectSet *pSet = new BBGameObjectSet(gameObjects, m_Position); // the localTransform of child is not changed, bUpdateLocalTransform = false pSet->setRotation(nAngle, axis, false); if (bUpdateLocalTransform) { m_LocalQuaternion = rot * m_LocalQuaternion; m_LocalRotation = m_LocalQuaternion.toEulerAngles(); } } BBSceneManager::changeScene(this); } void BBGameObject::setRotation(const QVector3D &rotation, bool bUpdateLocalTransform) { // handle itself m_Rotation = rotation; m_Quaternion = QQuaternion::fromEulerAngles(m_Rotation); setModelMatrix(m_Position.x(), m_Position.y(), m_Position.z(), m_Quaternion, m_Scale.x(), m_Scale.y(), m_Scale.z()); QTreeWidgetItem *pItem = BBSceneManager::getSceneTreeItem(this); // Some objects are not managed by BBHierarchyTreeWidget if (pItem) { for (int i = 0; i < pItem->childCount(); i++) { BBGameObject *pGameObject = BBSceneManager::getGameObject(pItem->child(i)); // The transform matrix of the child object relative to the parent object QMatrix4x4 localMatrix; localMatrix.translate(pGameObject->getLocalPosition()); localMatrix.rotate(pGameObject->getLocalQuaternion()); localMatrix.scale(pGameObject->getLocalScale()); QMatrix4x4 globalMatrix = m_ModelMatrix * localMatrix; pGameObject->setPosition(globalMatrix * QVector3D(0, 0, 0), false); pGameObject->setRotation((m_Quaternion * pGameObject->getLocalQuaternion()).toEulerAngles(), false); } if (bUpdateLocalTransform) { QTreeWidgetItem *pParent = pItem->parent(); BBGameObject *pGameObject = BBSceneManager::getGameObject(pParent); setLocalTransform(pGameObject); } } BBSceneManager::changeScene(this); } void BBGameObject::setRotation(const QQuaternion &quaternion, bool bUpdateLocalTransform) { m_Quaternion = quaternion; m_Rotation = m_Quaternion.toEulerAngles(); setModelMatrix(m_Position.x(), m_Position.y(), m_Position.z(), m_Quaternion, m_Scale.x(), m_Scale.y(), m_Scale.z()); QTreeWidgetItem *pItem = BBSceneManager::getSceneTreeItem(this); // Some objects are not managed by BBHierarchyTreeWidget if (pItem) { for (int i = 0; i < pItem->childCount(); i++) { BBGameObject *pGameObject = BBSceneManager::getGameObject(pItem->child(i)); // The transform matrix of the child object relative to the parent object QMatrix4x4 localMatrix; localMatrix.translate(pGameObject->getLocalPosition()); localMatrix.rotate(pGameObject->getLocalQuaternion()); localMatrix.scale(pGameObject->getLocalScale()); QMatrix4x4 globalMatrix = m_ModelMatrix * localMatrix; pGameObject->setPosition(globalMatrix * QVector3D(0, 0, 0), false); pGameObject->setRotation((m_Quaternion * pGameObject->getLocalQuaternion()).toEulerAngles(), false); } if (bUpdateLocalTransform) { QTreeWidgetItem *pParent = pItem->parent(); BBGameObject *pGameObject = BBSceneManager::getGameObject(pParent); setLocalTransform(pGameObject); } } BBSceneManager::changeScene(this); } void BBGameObject::setScale(float scale, bool bUpdateLocalTransform) { setScale(QVector3D(scale, scale, scale), bUpdateLocalTransform); } void BBGameObject::setScale(const QVector3D &scale, bool bUpdateLocalTransform) { // handle itself m_Scale = scale; setModelMatrix(m_Position.x(), m_Position.y(), m_Position.z(), m_Quaternion, m_Scale.x(), m_Scale.y(), m_Scale.z()); QTreeWidgetItem *pItem = BBSceneManager::getSceneTreeItem(this); // Some objects are not managed by BBHierarchyTreeWidget if (pItem) { for (int i = 0; i < pItem->childCount(); i++) { BBGameObject *pGameObject = BBSceneManager::getGameObject(pItem->child(i)); // The transform matrix of the child object relative to the parent object QMatrix4x4 localMatrix; localMatrix.translate(pGameObject->getLocalPosition()); localMatrix.rotate(pGameObject->getLocalQuaternion()); localMatrix.scale(pGameObject->getLocalScale()); QMatrix4x4 globalMatrix = m_ModelMatrix * localMatrix; pGameObject->setPosition(globalMatrix * QVector3D(0, 0, 0), false); pGameObject->setScale(m_Scale * pGameObject->getLocalScale(), false); } if (bUpdateLocalTransform) { QTreeWidgetItem *pParent = pItem->parent(); if (pParent) { BBGameObject *pGameObject = BBSceneManager::getGameObject(pParent); m_LocalScale = m_Scale / pGameObject->getScale(); } else { // at the top level m_LocalScale = m_Scale; } } } BBSceneManager::changeScene(this); } void BBGameObject::setLocalTransform(BBGameObject *pParent) { if (pParent) { m_LocalPosition = m_Position - pParent->getPosition(); m_LocalScale = m_Scale / pParent->getScale(); QMatrix4x4 localMatrix = pParent->getModelMatrix().inverted() * m_ModelMatrix; // remove scale from the matrix that includes rotation and scale localMatrix.scale(QVector3D(1, 1, 1) / m_LocalScale); // 3x3 in the top-left is rotation matrix QMatrix3x3 rotMatrix; rotMatrix(0, 0) = localMatrix.data()[0]; rotMatrix(1, 0) = localMatrix.data()[1]; rotMatrix(2, 0) = localMatrix.data()[2]; rotMatrix(0, 1) = localMatrix.data()[4]; rotMatrix(1, 1) = localMatrix.data()[5]; rotMatrix(2, 1) = localMatrix.data()[6]; rotMatrix(0, 2) = localMatrix.data()[8]; rotMatrix(1, 2) = localMatrix.data()[9]; rotMatrix(2, 2) = localMatrix.data()[10]; m_LocalQuaternion = QQuaternion::fromRotationMatrix(rotMatrix); m_LocalRotation = m_LocalQuaternion.toEulerAngles(); } else { //at the top level, local = global m_LocalPosition = m_Position; m_LocalRotation = m_Rotation; m_LocalQuaternion = m_Quaternion; m_LocalScale = m_Scale; } BBSceneManager::changeScene(this); } void BBGameObject::setVisibility(bool bVisible) { m_bVisible = bVisible; // handle children QTreeWidgetItem *pItem = BBSceneManager::getSceneTreeItem(this); // Some objects are not managed by BBHierarchyTreeWidget if (pItem) { for (int i = 0; i < pItem->childCount(); i++) { BBGameObject *pGameObject = BBSceneManager::getGameObject(pItem->child(i)); if (pGameObject) pGameObject->setVisibility(bVisible); } } BBSceneManager::changeScene(this); } void BBGameObject::setBaseAttributes(const QString &name, const QString &className, const QString &iconName, bool bActive) { m_strName = name; m_strClassName = className; m_strIconName = iconName; m_bActive = bActive; } void BBGameObject::init() { } void BBGameObject::init(const QString &path) { m_strFilePath = path; } void BBGameObject::render() { } void BBGameObject::render(BBCamera *pCamera) { Q_UNUSED(pCamera); } void BBGameObject::render(BBCanvas *pCanvas) { Q_UNUSED(pCanvas); } void BBGameObject::render(const QMatrix4x4 &modelMatrix, BBCamera *pCamera) { Q_UNUSED(modelMatrix); Q_UNUSED(pCamera); } void BBGameObject::resize(float fWidth, float fHeight) { Q_UNUSED(fWidth); Q_UNUSED(fHeight); } void BBGameObject::insertInRenderQueue(BBRenderQueue *pQueue) { Q_UNUSED(pQueue); } void BBGameObject::removeFromRenderQueue(BBRenderQueue *pQueue) { Q_UNUSED(pQueue); } void BBGameObject::setCurrentMaterial(BBMaterial *pMaterial) { Q_UNUSED(pMaterial); } void BBGameObject::setCurrentMaterial(int nExtraMaterialIndex) { Q_UNUSED(nExtraMaterialIndex); } void BBGameObject::setExtraMaterial(int nMaterialIndex, BBMaterial *pMaterial) { Q_UNUSED(nMaterialIndex); Q_UNUSED(pMaterial); } void BBGameObject::rollbackMaterial() { } void BBGameObject::restoreMaterial() { } void BBGameObject::setMatrix4(const std::string &uniformName, const float *pMatrix4) { Q_UNUSED(uniformName); Q_UNUSED(pMatrix4); } void BBGameObject::setVector4(const std::string &uniformName, float x, float y, float z, float w) { Q_UNUSED(uniformName); Q_UNUSED(x); Q_UNUSED(y); Q_UNUSED(z); Q_UNUSED(w); } void BBGameObject::setTexture(const std::string &uniformName, GLuint textureName) { Q_UNUSED(uniformName); Q_UNUSED(textureName); } void BBGameObject::openLight() { } void BBGameObject::closeLight() { } bool BBGameObject::hit(const BBRay &ray, float &fDistance) { Q_UNUSED(ray); Q_UNUSED(fDistance); return m_bActive; } bool BBGameObject::hit(int x, int y) { Q_UNUSED(x); Q_UNUSED(y); return m_bActive; } bool BBGameObject::belongToSelectionRegion(const BBFrustum &frustum) { Q_UNUSED(frustum); // 4 planes, object in the middle of top bottom left right planes is selected // Whether the bounding box of object is placed in the middle of 4 planes // Eliminate objects whose the center point of the bounding box is on the outside // If the center point of the bounding box is inside, // further calculate whether each vertex of the bounding box is inside return true; } void BBGameObject::showCloseUp(QVector3D &outPosition, QVector3D &outViewCenter, float fDistFactor) { Q_UNUSED(fDistFactor); outViewCenter = m_Position + QVector3D(0, 0.5, 0); outPosition = outViewCenter + QVector3D(0, 0.5, 4); } void BBGameObject::setScreenCoordinateWithSwitchingOriginalPoint(int x, int y) { BBSceneManager::getCamera()->switchCoordinate(x, y); setScreenCoordinate(x, y); } void BBGameObject::setScreenCoordinate(int x, int y) { setPosition(QVector3D(x, y, 0.0f)); } void BBGameObject::setSize(int nWidth, int nHeight) { m_nWidth = nWidth; m_nHeight = nHeight; setScale(QVector3D(m_nWidth, m_nHeight, 0)); } void BBGameObject::translate(int nDeltaX, int nDeltaY) { setScreenCoordinate(m_Position.x() + nDeltaX, m_Position.y() + nDeltaY); } void BBGameObject::setModelMatrix(float px, float py, float pz, const QQuaternion &r, float sx, float sy, float sz) { m_ModelMatrix.setToIdentity(); m_ModelMatrix.translate(px, py, pz); m_ModelMatrix.rotate(r); m_ModelMatrix.scale(sx, sy, sz); m_ViewModelMatrix_IT = (BBSceneManager::getCamera()->getViewMatrix() * m_ModelMatrix).inverted().transposed(); } <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFilePathBarWidget.cpp<|end_filename|> #include "BBFilePathBarWidget.h" #include "Utils/BBUtils.h" #include <QHBoxLayout> #include <QButtonGroup> #include <QPushButton> #include <QLabel> #include <QScrollBar> //--------------------------------------------------------------------------------------------------- // BBFilePathBarScrollArea //--------------------------------------------------------------------------------------------------- BBFilePathBarScrollArea::BBFilePathBarScrollArea(QWidget *pParent) : QScrollArea(pParent) { QObject::connect(horizontalScrollBar(), SIGNAL(rangeChanged(int, int)), this, SLOT(moveToEnd())); } void BBFilePathBarScrollArea::moveToEnd() { horizontalScrollBar()->setValue(horizontalScrollBar()->maximumWidth()); } void BBFilePathBarScrollArea::moveToLeft() { scroll(-30); } void BBFilePathBarScrollArea::moveToRight() { scroll(30); } void BBFilePathBarScrollArea::scroll(int nStep) { horizontalScrollBar()->setSliderPosition(horizontalScrollBar()->sliderPosition() + nStep); } //--------------------------------------------------------------------------------------------------- // BBFilePathBarWidget //--------------------------------------------------------------------------------------------------- BBFilePathBarWidget::BBFilePathBarWidget(QWidget *pParent) : QWidget(pParent) { QHBoxLayout *pLayout = new QHBoxLayout(this); pLayout->setMargin(0); pLayout->setSpacing(3); setStyleSheet("QWidget {border: none; color: #d6dfeb; font: 9pt \"Arial\";}" "QPushButton {background: none; border-radius: 2px; padding: 1px 3px;}" "QPushButton:hover {background: #0ebf9c;}" "QLabel {color: rgb(60, 64, 75);}"); } void BBFilePathBarWidget::showFolderPath(const QString &path) { m_CurrentPath = path; // Clear the last showed path while (QLayoutItem *pChild = layout()->takeAt(0)) { delete pChild->widget(); } // The relative path that is relative to project directory QString relativePath = path.mid(BBConstant::BB_PATH_PROJECT.length()); m_HierarchyDirs = relativePath.split('/'); QButtonGroup *pGroup = new QButtonGroup; // do not need label separator before the first item QPushButton *pButton = new QPushButton(m_HierarchyDirs.at(0)); pGroup->addButton(pButton, 0); layout()->addWidget(pButton); // add items after the first item for (int i = 1; i < m_HierarchyDirs.count(); i++) { QLabel *pLabel = new QLabel("»"); layout()->addWidget(pLabel); pButton = new QPushButton(m_HierarchyDirs.at(i)); pGroup->addButton(pButton, i); layout()->addWidget(pButton); } QObject::connect(pGroup, SIGNAL(buttonClicked(int)), this, SLOT(accessFolder(int))); } void BBFilePathBarWidget::accessFolder(int id) { QString path = BBConstant::BB_PATH_PROJECT; for (int i = 0; i < id; i++) { path += m_HierarchyDirs.at(i) + "/"; } path += m_HierarchyDirs.at(id); accessFolder(path); } <|start_filename|>Code/BBearEditor/Engine/Physics/Solver/BBPBDSolver.cpp<|end_filename|> #include "BBPBDSolver.h" #include <algorithm> #include "../Force/BBForce.h" #include "../Body/BBBaseBody.h" BBPBDSolver::BBPBDSolver(int nSolverIteration, int nCollisionIteration) { m_nSolverIteration = nSolverIteration; m_nCollisionIteration = nCollisionIteration; m_fStopThreshold = 0.01f; } BBPBDSolver::~BBPBDSolver() { } void BBPBDSolver::addForce(BBForce *pForce) { m_Forces.push_back(pForce); } void BBPBDSolver::removeForce(BBForce *pForce) { m_Forces.erase(std::remove(std::begin(m_Forces), std::end(m_Forces), pForce), std::end(m_Forces)); } void BBPBDSolver::addBody(BBBaseBody *pBody) { m_PhysicsBodies.push_back(pBody); } void BBPBDSolver::removeBody(BBBaseBody *pBody) { m_PhysicsBodies.erase(std::remove(std::begin(m_PhysicsBodies), std::end(m_PhysicsBodies), pBody), std::end(m_PhysicsBodies)); } void BBPBDSolver::solve(float fDeltaTime) { if (fDeltaTime <= 0.0f) return; float dt = fDeltaTime / m_nSolverIteration; for (int i = 0; i < m_nSolverIteration; i++) { applyForce(fDeltaTime); predictPositions(fDeltaTime); projectConstraints(); updateVelocities(fDeltaTime); updatePositions(); } } void BBPBDSolver::applyForce(float fDeltaTime) { for (int i = 0; i < m_PhysicsBodies.size(); i++) { BBBaseBody *pBody = m_PhysicsBodies[i]; pBody->dampenVelocities(fDeltaTime); for (int j = 0; j < m_Forces.size(); j++) { m_Forces[j]->applyForce(pBody, fDeltaTime); } } } void BBPBDSolver::predictPositions(float fDeltaTime) { for (int i = 0; i < m_PhysicsBodies.size(); i++) { m_PhysicsBodies[i]->predictPositions(fDeltaTime); } } void BBPBDSolver::projectConstraints() { float fDeltaTime = 1.0f / m_nSolverIteration; for (int i = 0; i < m_nSolverIteration; i++) { for (int j = 0; j < m_PhysicsBodies.size(); j++) { m_PhysicsBodies[j]->projectConstraints(fDeltaTime); } } } void BBPBDSolver::updateVelocities(float fDeltaTime) { float fThreshold2 = m_fStopThreshold * fDeltaTime; fThreshold2 = fThreshold2 * fThreshold2; for (int i = 0; i < m_PhysicsBodies.size(); i++) { m_PhysicsBodies[i]->updateVelocities(fDeltaTime, fThreshold2); } } void BBPBDSolver::updatePositions() { for (int i = 0; i < m_PhysicsBodies.size(); i++) { m_PhysicsBodies[i]->updatePositions(); } } <|start_filename|>Resources/shaders/SkyBox/Equirectangular.vert<|end_filename|> #version 330 core in vec4 BBPosition; out vec3 v2f_local_pos; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { v2f_local_pos = BBPosition.xyz; gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * BBPosition; } <|start_filename|>Code/BBearEditor/Editor/MainInterface/BBTitleBar.h<|end_filename|> #ifndef BBUITITLEBAR_H #define BBUITITLEBAR_H #include <QWidget> #include <QMouseEvent> namespace Ui { class BBTitleBar; } class BBTitleBar : public QWidget { Q_OBJECT public: explicit BBTitleBar(QWidget *parent = 0); virtual ~BBTitleBar(); signals: void run(bool trigger); private slots: void closeWindow(); void minimizeWindow(); void maximizeWindow(); void buttonRunClicked(bool trigger); void mouseDoubleClickEvent(QMouseEvent *event) override; private: Ui::BBTitleBar *m_pUi; QWidget *m_pParent; }; #endif // BBUITITLEBAR_H <|start_filename|>Code/BBearEditor/Editor/Tools/FBX2BBear/BBFBXSkeletonGPU.h<|end_filename|> #ifndef BBFBXSKELETONGPU_H #define BBFBXSKELETONGPU_H //#include "fbxsdk.h" class BBFBXSkeletonGPU { public: BBFBXSkeletonGPU(); void init(const char *path); private: // FbxScene *m_pScene; }; #endif // BBFBXSKELETONGPU_H <|start_filename|>Code/BBearEditor/Engine/2D/BBClipArea2D.h<|end_filename|> #ifndef BBCLIPAREA2D_H #define BBCLIPAREA2D_H #include "Base/BBRenderableObject2D.h" class BBClipArea2D : public BBRenderableObject2D { public: BBClipArea2D(int x = 0, int y = 0, int nWidth = 630, int nHeight = 400); void init() override; }; #endif // BBCLIPAREA2D_H <|start_filename|>Code/BBearEditor/Engine/Base/BBRenderableObject2D.h<|end_filename|> #ifndef BBRENDERABLEOBJECT2D_H #define BBRENDERABLEOBJECT2D_H #include "Base/BBRenderableObject.h" class BBCanvas; class BBRenderableObject2D : public BBRenderableObject { public: BBRenderableObject2D(); BBRenderableObject2D(int x, int y, int nWidth = 500, int nHeight = 500); ~BBRenderableObject2D(); void init() override; void render(BBCamera *pCamera) override; void render(BBCanvas *pCanvas) override; protected: }; #endif // BBRENDERABLEOBJECT2D_H <|start_filename|>Code/BBearEditor/Engine/Physics/Constraint/BBDistanceConstraint.h<|end_filename|> #ifndef BBDISTANCECONSTRAINT_H #define BBDISTANCECONSTRAINT_H #include "BBBaseConstraint.h" class BBDistanceConstraint : public BBBaseConstraint { public: BBDistanceConstraint(BBBaseBody *pBody, int nParticleIndex1, int nParticleIndex2, float fElasticModulus); void doConstraint(float fDeltaTime) override; private: int m_nParticleIndex1; int m_nParticleIndex2; float m_fElasticModulus; float m_fOriginLength; }; #endif // BBDISTANCECONSTRAINT_H <|start_filename|>Code/BBearEditor/Engine/Render/Shadow/BBShadow.h<|end_filename|> #ifndef BBSHADOW_H #define BBSHADOW_H class BBScene; class BBShadow { public: static void enable(int nAlgorithmIndex, bool bEnable); static void open(BBScene *pScene); static void setGBufferPass(BBScene *pScene); static void setScreenQuadPass(BBScene *pScene); }; #endif // BBSHADOW_H <|start_filename|>Code/BBearEditor/Editor/Common/BBTreeWidget.cpp<|end_filename|> #include "BBTreeWidget.h" #include <QKeyEvent> #include <QMimeData> #include <QPainter> #include <QDrag> #include <QMenu> #include <QApplication> #include <QDesktopWidget> #include "Dialog/BBConfirmationDialog.h" //--------------BBLineEdit BBLineEdit::BBLineEdit(QWidget *parent) : QLineEdit(parent) { } void BBLineEdit::focusOutEvent(QFocusEvent *event) { Q_UNUSED(event); finishEdit(); } void BBLineEdit::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Return) { finishEdit(); } else { QLineEdit::keyPressEvent(event); } } //--------------BBTreeWidget BBTreeWidget::BBTreeWidget(QWidget *parent) : QTreeWidget(parent) { m_pIndicatorItem = NULL; m_pLastItem = NULL; m_eIndicatorPos = BBIndicatorPos::CENTER; m_pEditingItem = NULL; m_pRenameEditor = NULL; setDragEnabled(true); setAcceptDrops(true); // move, not copy setDefaultDropAction(Qt::MoveAction); // Internal drag, you cannot move to other trees, and you cannot move from other trees. // setDragDropMode(QAbstractItemView::InternalMove); // You can press shift and cmd to select multiple setSelectionMode(QAbstractItemView::ExtendedSelection); setDropIndicatorShown(false); } BBTreeWidget::~BBTreeWidget() { BB_SAFE_DELETE(m_pMenu); } QString BBTreeWidget::getLevelPath(QTreeWidgetItem *pItem) { if (pItem == NULL) { return ""; } else { // Hierarchical path of item QString location; for (QTreeWidgetItem *pParent = pItem; pParent; pParent = pParent->parent()) { location = pParent->text(0) + "/" + location; } // remove "/" at the end location = location.mid(0, location.length() - 1); return location; } } void BBTreeWidget::startDrag(Qt::DropActions supportedActions) { Q_UNUSED(supportedActions); // When selecting ancestors and descendants at the same time, filter out descendants filterSelectedItems(); // The path of each item is stored in mimeData QByteArray itemData; QDataStream dataStream(&itemData, QIODevice::WriteOnly); struct Info { int y; QPixmap icon; QString text; }; QList<Info> infos; // Used to calculate the size of the final drag icon QFontMetrics fm = fontMetrics(); int pixmapWidth = 0; int pixmapHeight = 0; QList<QTreeWidgetItem*> items = selectedItems(); for (int i = 0; i < items.count(); i++) { // Relative path of each item QString levelPath = getLevelPath(items.at(i)); dataStream << levelPath; Info info; QRect rect = visualItemRect(items.at(i)); info.y = rect.top(); // Final icon height, Accumulate pixmapHeight += rect.height(); info.text = items.at(i)->text(0); int textWidth = fm.width(info.text); if (textWidth > pixmapWidth) pixmapWidth = textWidth; // The icon of the item info.icon = items.at(i)->icon(getDragIconColumnIndex()).pixmap(rect.height() * devicePixelRatio()); info.icon.setDevicePixelRatio(devicePixelRatio()); info.icon = info.icon.scaled(rect.height() * devicePixelRatio(), rect.height() * devicePixelRatio(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); // infos, inserting sort according to the upper and lower position relationship int j; for (j = 0; j < infos.count(); j++) { if (infos.at(j).y > info.y) { break; } } infos.insert(j, info); } QMimeData *pMimeData = new QMimeData; // Give this data a unique identifying tag pMimeData->setData(getMimeType(), itemData); int itemHeight = pixmapHeight / infos.count(); // width, add icon and margin pixels QPixmap pixmap((pixmapWidth + itemHeight + 6) * devicePixelRatio(), pixmapHeight * devicePixelRatio()); pixmap.setDevicePixelRatio(devicePixelRatio()); pixmap.fill(Qt::transparent); QPainter painter(&pixmap); painter.setPen(QColor("#d6dfeb")); painter.setFont(QFont("Arial", 9)); // Draw the icon and text of each item onto the final icon for (int i = 0; i < infos.count(); i++) { int y = itemHeight * i; painter.drawPixmap(0, y, infos.at(i).icon); painter.drawText(QRect(itemHeight + 6, y, pixmapWidth, itemHeight), Qt::AlignLeft | Qt::AlignVCenter, infos.at(i).text); } painter.end(); QDrag drag(this); drag.setMimeData(pMimeData); drag.setPixmap(pixmap); drag.setHotSpot(QPoint(0, 0)); drag.exec(Qt::MoveAction); } bool BBTreeWidget::moveItem() { // drop target if (m_pIndicatorItem) { // drop position of moving item int index = -1; QTreeWidgetItem *pParent = getParentOfMovingItem(index); // The movable item has been filtered in startDrag QList<QTreeWidgetItem*> items = selectedItems(); // Cannot move to an item that are moving and its descendants // parent and its ancestors cannot be included in items for (QTreeWidgetItem *pForeParent = pParent; pForeParent; pForeParent = pForeParent->parent()) { BB_PROCESS_ERROR_RETURN_FALSE(!items.contains(pForeParent)); } for (int i = 0; i < items.count(); i++) { QTreeWidgetItem *pItem = items.at(i); // remove item from tree int removeIndex = -1; QTreeWidgetItem *pRemoveItemParent = pItem->parent(); QTreeWidgetItem *pIndicatorItemParent = m_pIndicatorItem->parent(); if (pRemoveItemParent) { // the item is not in the top level removeIndex = pRemoveItemParent->indexOfChild(pItem); pRemoveItemParent->removeChild(pItem); } else { removeIndex = indexOfTopLevelItem(pItem); takeTopLevelItem(removeIndex); } // If the two are at the same level and the removed item is in front of the m_pIndicatorItem, index minus 1 // pItem has been removed, so pItem->parent() cannot be used, so just use pRemoveItemParent if ((pRemoveItemParent == pIndicatorItemParent) && (removeIndex < index)) { index--; } // add item in the drop position if (pParent) { pParent->insertChild(index, pItem); } else { // at the top level insertTopLevelItem(index, pItem); } // select a new item setItemSelected(pItem, true); // Insert the next item below // Otherwise 1 2 3 becomes 3 2 1 after inserting index++; } // expand parent to make new item visible if (pParent) { setItemExpanded(pParent, true); } return true; } return false; } bool BBTreeWidget::moveItemFromFileList(const QMimeData *pMimeData) { Q_UNUSED(pMimeData); return true; } bool BBTreeWidget::moveItemFromOthers(const QMimeData *pMimeData) { Q_UNUSED(pMimeData); return false; } void BBTreeWidget::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat(getMimeType())) { // Receive internal drag event->accept(); } else if (event->mimeData()->hasFormat(BB_MIMETYPE_FILELISTWIDGET)) { // Receive items dragged from the file list event->accept(); } else if (event->mimeData()->hasFormat(BB_MIMETYPE_BASEOBJECT)) { // Receive prefab event->accept(); } else if (event->mimeData()->hasFormat(BB_MIMETYPE_LIGHTOBJECT)) { // Receive light event->accept(); } else { event->ignore(); } } void BBTreeWidget::dragMoveEvent(QDragMoveEvent *event) { // Scroll up or down when the mouse is at the top or bottom QTreeWidget::dragMoveEvent(event); QTreeWidgetItem *pItem = itemAt(event->pos()); m_pIndicatorItem = pItem; if (pItem) { if (pItem != m_pLastItem) { // The item corresponding to the position pointed has changed // Re-record the new item m_pLastItem = pItem; // Re-record the current time m_LastTime = QTime::currentTime(); } else { // When moving, the pointed item is not changed if (m_LastTime.elapsed() > 1000) { // Time exceeds a certain amount, expand the item setItemExpanded(pItem, true); } } int mouseY = event->pos().y(); int itemTop = visualItemRect(m_pIndicatorItem).top(); int itemBottom = visualItemRect(m_pIndicatorItem).bottom(); if (mouseY < itemTop + 2) { m_eIndicatorPos = BBIndicatorPos::TOP; } else if (mouseY <= itemBottom - 2) { // The mouse drops on the non-edge of the item // become the child of the item m_eIndicatorPos = BBIndicatorPos::CENTER; } else { m_eIndicatorPos = BBIndicatorPos::BOTTOM; } } else { // No item pointed, reset m_pLastItem = NULL; } // Draw the place where it will be placed repaint(); // do this in order to execute dropEvent event->accept(); } void BBTreeWidget::dragLeaveEvent(QDragLeaveEvent *event) { Q_UNUSED(event); // No need for indicator box when dragLeave m_pIndicatorItem = NULL; repaint(); } void BBTreeWidget::dropEvent(QDropEvent *event) { if (event->mimeData()->hasFormat(getMimeType())) { // Internal move item if (moveItem()) { event->accept(); } else { event->ignore(); } } else if (event->mimeData()->hasFormat(BB_MIMETYPE_FILELISTWIDGET)) { // Receive items dropped from the file list if (moveItemFromFileList(event->mimeData())) { event->accept(); } else { event->ignore(); } } else { // Receive items dropped from others if (moveItemFromOthers(event->mimeData())) { event->accept(); } else { event->ignore(); } } // The indicator item is no longer needed after dragging m_pIndicatorItem = NULL; // Reset the currently suspended item after processing m_pLastItem = NULL; repaint(); } void BBTreeWidget::paintEvent(QPaintEvent *event) { QTreeWidget::paintEvent(event); // The pointed item is not itself if (m_pIndicatorItem /*&& m_pIndicatorItem != currentItem()*/) { //using "this" is wrong QPainter painter(viewport()); QPen pen(QColor("#d6dfeb")); painter.setPen(pen); QRect rect = visualItemRect(m_pIndicatorItem); if (m_eIndicatorPos == BBIndicatorPos::CENTER) { painter.drawRect(QRect(rect.topLeft(), rect.bottomRight() - QPoint(1, 1))); } else if (m_eIndicatorPos == BBIndicatorPos::TOP) { painter.drawLine(rect.topLeft(), rect.topRight()); } else { painter.drawLine(rect.bottomLeft(), rect.bottomRight()); } painter.end(); } } void BBTreeWidget::mousePressEvent(QMouseEvent *event) { QTreeWidget::mousePressEvent(event); if (event->buttons() & Qt::LeftButton || event->buttons() & Qt::RightButton) { // There is no item at the mouse click position, remove the selection QTreeWidgetItem *pItem = itemAt(event->pos()); if (!pItem) { setCurrentItem(NULL); } } } void BBTreeWidget::contextMenuEvent(QContextMenuEvent *event) { Q_UNUSED(event); m_pMenu->exec(cursor().pos()); } void BBTreeWidget::keyPressEvent(QKeyEvent *event) { // Handling menu shortcut events int key; #if defined(Q_OS_WIN32) key = Qt::Key_F2; #elif defined(Q_OS_MAC) key = Qt::Key_Return; #endif if (event->key() == key) { openRenameEditor(); } } void BBTreeWidget::focusInEvent(QFocusEvent *event) { // parent class, when the focus is obtained, the first item will show a blue box, which is ugly Q_UNUSED(event); } void BBTreeWidget::filterSelectedItems() { QList<QTreeWidgetItem*> items = selectedItems(); if (items.count() > 1) { // Select multiple for (int i = 0; i < items.count(); i++) { for (QTreeWidgetItem *parent = items.at(i)->parent(); parent; parent = parent->parent()) { // Traverse ancestors to see if they are also selected if (items.contains(parent)) { // Ancestors and descendants are selected at the same time, only ancestors are processed setItemSelected(items.at(i), false); break; } } } } } QTreeWidgetItem* BBTreeWidget::getParentOfMovingItem(int &nIndex) { QTreeWidgetItem *pParent = NULL; //nIndex is the position inserted if (m_eIndicatorPos == BBIndicatorPos::CENTER) { // become the child of m_pIndicatorItem pParent = m_pIndicatorItem; // If add to the end, use parent->childCount() // But when item is dragged to its parent, deleting itself makes parent->childCount() decrease // add itself at the end is wrong // Add to the first nIndex = 0; } else if (m_eIndicatorPos == BBIndicatorPos::TOP) { // become the front sibling of m_pIndicatorItem pParent = m_pIndicatorItem->parent(); if (pParent) nIndex = pParent->indexOfChild(m_pIndicatorItem); else nIndex = indexOfTopLevelItem(m_pIndicatorItem); } else//m_eIndicatorPos == BBIndicatorPos::BOTTOM { // become the back sibling of m_pIndicatorItem pParent = m_pIndicatorItem->parent(); if (pParent) nIndex = pParent->indexOfChild(m_pIndicatorItem) + 1; else nIndex = indexOfTopLevelItem(m_pIndicatorItem) + 1; } return pParent; } void BBTreeWidget::pasteOne(QTreeWidgetItem *pSource, QTreeWidgetItem* pTranscript) { Q_UNUSED(pSource); Q_UNUSED(pTranscript); // Invoked only when the paste is legal // copy source, paste transcript } void BBTreeWidget::pasteEnd() { // After the paste operation is over, invoke, the subclass to perform different operations // Invoked only when the paste is legal } void BBTreeWidget::deleteAction(QTreeWidgetItem *pItem) { // After the child is deleted, childCount() will decrease. Error with for loop while (pItem->childCount() > 0) { QTreeWidgetItem* pChild = pItem->child(0); deleteAction(pChild); } deleteOne(pItem); } void BBTreeWidget::deleteOne(QTreeWidgetItem *pItem) { // If the item is in the clipboard, delete it if (m_ClipBoardItems.contains(pItem)) { m_ClipBoardItems.removeOne(pItem); } BB_SAFE_DELETE(pItem); } void BBTreeWidget::copyAction() { // copy items // Clear the last copied content saved in the clipboard m_ClipBoardItems.clear(); // Save the filtered selection to the clipboard filterSelectedItems(); m_ClipBoardItems = selectedItems(); } void BBTreeWidget::pasteAction() { int count = m_ClipBoardItems.count(); if (count == 0) { // Clipboard has no content QApplication::beep(); return; } // Copy into the pointed item, when there is no pointed item, add into the top level QTreeWidgetItem *pDestItem = currentItem(); QString destLevelPath = getLevelPath(pDestItem); for (int i = 0; i < count; i++) { QString itemLevelPath = getLevelPath(m_ClipBoardItems.at(i)); // Can’t be copied into oneself and one's descendants if (destLevelPath.mid(0, itemLevelPath.length()) == itemLevelPath) { QApplication::beep(); return; } } // legal paste // Remove the highlight of the selected item QList<QTreeWidgetItem*> selected = selectedItems(); for (int i = 0; i < selected.count(); i++) { setItemSelected(selected.at(i), false); } for (int i = 0; i < m_ClipBoardItems.count(); i++) { QTreeWidgetItem *pTranscript = m_ClipBoardItems.at(i)->clone(); QString name = pTranscript->text(0); if (pDestItem) { int childCount = pDestItem->childCount(); // Rename, the same level cannot include the same name int index = 2; while (1) { int j; for (j = 0; j < childCount; j++) { if (pDestItem->child(j)->text(0) == name) { break; } } if (j < childCount) { // If the same name, add (2) (3), continue to check whether there is the same name name = pTranscript->text(0) + "(" + QString::number(index) + ")"; index++; } else { // No the same name pTranscript->setText(0, name); break; } } // add into pDestItem pDestItem->addChild(pTranscript); } else { int childCount = topLevelItemCount(); int index = 2; while (1) { int j; for (j = 0; j < childCount; j++) { if (topLevelItem(j)->text(0) == name) { break; } } if (j < childCount) { // If the same name, add (2) (3), continue to check whether there is the same name name = pTranscript->text(0) + "(" + QString::number(index) + ")"; index++; } else { // No the same name pTranscript->setText(0, name); break; } } addTopLevelItem(pTranscript); } // highlight pasted items setItemSelected(pTranscript, true); // Subclass to perform specific operations of paste pasteOne(m_ClipBoardItems.at(i), pTranscript); } if (pDestItem) setItemExpanded(pDestItem, true); // Invoked at the end of the paste operation pasteEnd(); } void BBTreeWidget::openRenameEditor() { QList<QTreeWidgetItem*> selected = selectedItems(); if (selected.count() == 1) { // Multi-select or unselect will not perform the rename operation m_pEditingItem = selected.first(); m_pRenameEditor = new BBLineEdit(this); m_pRenameEditor->setStyleSheet("height: 16px; border: none; background: #d6dfeb; color: #191f28;" "selection-color: #d6dfeb; selection-background-color: #8193bc;" "font: 9pt \"Arial\"; padding: 0px 5px;"); // margin-left: 22px; m_pRenameEditor->setText(m_pEditingItem->text(0)); m_pRenameEditor->selectAll(); QObject::connect(m_pRenameEditor, SIGNAL(finishEdit()), this, SLOT(finishRename())); setItemWidget(m_pEditingItem, 0, m_pRenameEditor); // make effective m_pRenameEditor->setFocus(); } } void BBTreeWidget::finishRename() { removeItemWidget(m_pEditingItem, 0); BB_SAFE_DELETE(m_pRenameEditor); m_pEditingItem = NULL; // Otherwise, the list has no focus and no longer responds to key events setFocus(); } void BBTreeWidget::deleteAction() { // When selecting ancestors and descendants at the same time, filter out descendants filterSelectedItems(); QList<QTreeWidgetItem*> items = selectedItems(); if (items.count() == 0) return; // pop dialog BBConfirmationDialog dialog; dialog.setTitle("Delete selected?"); if (items.count() == 1) { dialog.setMessage("You cannot undo this action.\n\nAre you sure to delete this?"); } else { dialog.setMessage("You cannot undo this action.\n\nAre you sure to delete these " + QString::number(items.count()) + " items?"); } if (dialog.exec()) { // start delete operation for (int i = 0; i < items.count(); i++) { deleteAction(items.at(i)); } setCurrentItem(NULL); } } <|start_filename|>Code/BBearEditor/Editor/Dialog/BBProjectDialog.h<|end_filename|> #ifndef BBPROJECTDIALOG_H #define BBPROJECTDIALOG_H #include <QDialog> class QAbstractButton; class QListWidgetItem; namespace Ui { class BBProjectDialog; } class BBProjectDialog : public QDialog { Q_OBJECT public: explicit BBProjectDialog(QWidget *pParent = 0); ~BBProjectDialog(); private slots: void switchDiskAndCloud(QAbstractButton *pButton); void switchFolderAndNew(QAbstractButton *pButton); void selectFolder(); void createNewProject(); void closeDialog(); void openSelectedProject(QListWidgetItem *pItem); signals: void createProject(); void openProject(); private: void setButtonTabBar(); void loadExistingProject(); void setListWidget(); void setLineEdit(); Ui::BBProjectDialog *m_pUi; static QString m_ProjectDirArrayKey; static QString m_ProjectDirKey; static QString m_WorkSpaceDirKey; int m_nProjectCount; QList<QString> m_ProjectDirs; }; #endif // BBPROJECTDIALOG_H <|start_filename|>Resources/shaders/color.frag<|end_filename|> varying vec4 V_Color; uniform vec4 BBColor_Base_Color; void main(void) { gl_FragColor = V_Color * BBColor_Base_Color; } <|start_filename|>Resources/shaders/GI/FLC_TriangleCut_VS.vert<|end_filename|> #version 430 core struct Vertex { vec4 BBPosition; vec4 BBColor; vec4 BBTexcoord; vec4 BBNormal; vec4 BBTangent; vec4 BBBiTangent; }; layout (std140, binding = 0) buffer Bundle { Vertex vertexes[]; } bundle; out V2G { vec3 position; vec3 normal; vec2 texcoord; } v2g; uniform mat4 BBModelMatrix; void main() { v2g.position = (BBModelMatrix * bundle.vertexes[gl_VertexID].BBPosition).xyz; v2g.normal = bundle.vertexes[gl_VertexID].BBNormal.xyz; v2g.texcoord = bundle.vertexes[gl_VertexID].BBTexcoord.xy; gl_Position = vec4(0.0, 0.0, 0.0, 1.0); } <|start_filename|>Code/BBearEditor/Engine/Render/BBAttribute.h<|end_filename|> #ifndef BBATTRIBUTE_H #define BBATTRIBUTE_H #include "BBBaseRenderComponent.h" #include "BBLinkedList.h" class BBAttribute : public BBBaseRenderComponent, public BBLinkedList { public: BBAttribute(GLint location, int nComponentCount, unsigned int nBasicDataType, bool bNormalized, int nDataStride, int nDataOffset); void active(); private: GLint m_Location; int m_nComponentCount; unsigned int m_nBasicDataType; bool m_bNormalized; int m_nDataStride; int m_nDataOffset; }; #endif // BBATTRIBUTE_H <|start_filename|>Resources/shaders/diffuse.frag<|end_filename|> varying vec4 V_Color; varying vec4 V_Normal; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; // Lambert vec4 getLambertLight() { vec3 light_pos_normalized = normalize(BBLightPosition.xyz); vec3 normal_normalized = normalize(V_Normal.xyz); vec4 light_color = dot(light_pos_normalized, normal_normalized) * BBLightColor; // Ambient light_color.xyz += vec3(0.1); return light_color; } void main(void) { gl_FragColor = V_Color * getLambertLight(); } <|start_filename|>Resources/shaders/Physics/FluidSystem/SSF_FS_4_Screen_Shading.frag<|end_filename|> #version 430 core #extension GL_NV_shadow_samplers_cube : enable in vec2 v2f_texcoords; layout (location = 0) out vec4 FragColor; uniform vec4 BBCameraParameters; uniform vec4 BBCameraParameters1; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; uniform mat4 BBViewMatrix; uniform samplerCube BBSkyBox; uniform sampler2D BBSkyBoxBackground; uniform sampler2D DepthMap; uniform sampler2D ThicknessMap; uniform sampler2D NormalMap; const vec3 WaterRefractedColor = vec3(0.05f, 0.5f, 0.8f); const vec3 WaterF0 = vec3(0.15f); const float WaterK = 0.05f; const float RefractedScale = 2.0f; const float epo = 1e-2; float near; float far; float aspect; float near_height; // Clip space to view space vec3 clip2view(vec2 texcoords, float depth) { vec2 uv = (2.0 * texcoords - vec2(1.0, 1.0)) * vec2(aspect, 1.0); // near vec2 pos = 0.5 * near_height * uv * depth / near; return vec3(pos, -depth); } vec3 computeFresnel(vec3 F0, float cos_theta) { return F0 + (1.0 - F0) * pow(1.0 - cos_theta, 5.0); } void main() { near = BBCameraParameters.z; far = BBCameraParameters.w; aspect = BBCameraParameters1.y; near_height = BBCameraParameters1.z; vec3 L = normalize(mat3(BBViewMatrix) * BBLightPosition.xyz); float depth = texture(DepthMap, v2f_texcoords).r; if (depth >= far - epo) discard; vec2 tex_size = vec2(1.0 / textureSize(NormalMap, 0).s, 1.0 / textureSize(NormalMap, 0).t); vec3 N = texture(NormalMap, v2f_texcoords).xyz; float thickness = texture(ThicknessMap, v2f_texcoords).r; // phong vec3 ambient = BBLightColor.rgb * 0.1; vec3 diffuse = ambient + BBLightColor.rgb * max(dot(N, L), 0.0); // blinn-phong vec3 view_pos = clip2view(v2f_texcoords, depth); vec3 V = normalize(-view_pos); vec3 H = normalize(V + L); vec3 specular = BBLightColor.rgb * pow(max(dot(N, H), 0.0), 30.0); // fresnel vec3 fresnel = computeFresnel(WaterF0, max(dot(N, V), 0.0)); // world space vec3 reflected = normalize(mat3(inverse(BBViewMatrix)) * reflect(-V, N)); vec3 reflected_sky = textureCube(BBSkyBox, reflected).rgb; // refraction vec3 refracted = texture(BBSkyBoxBackground, v2f_texcoords - N.xy * thickness / far * RefractedScale).xyz; // transparency float transparency = exp(-thickness * WaterK); reflected = mix(WaterRefractedColor, refracted, transparency); FragColor = vec4(mix(refracted, reflected_sky, fresnel), 1.0); } <|start_filename|>Resources/scripts/new script.lua<|end_filename|> print("hello BigBear"); <|start_filename|>Code/BBearEditor/Engine/Font/BBDynamicFont.cpp<|end_filename|> #include "BBDynamicFont.h" #define INIT_CHAR_ID(size, style, outlineSize, shadowX, shadowY, charCode) \ uint64 charID; \ do { \ char *pStyle = (char*)&charID; \ *(pStyle++) = size + style; \ *(pStyle++) = outlineSize; \ *(pStyle++) = shadowX; \ *(pStyle++) = shadowY; \ *((unsigned int*)pStyle) = charCode; \ } while(0) BBDynamicFont::BBDynamicFont() { } <|start_filename|>Code/BBearEditor/Engine/Physics/FluidSystem/BBSPHGridContainer.h<|end_filename|> #ifndef BBSPHGRIDCONTAINER_H #define BBSPHGRIDCONTAINER_H #include <QVector3D> #include <vector> class BBSPHParticleSystem; class BBSPHGridContainer { public: BBSPHGridContainer(); void init(const QVector3D &min, const QVector3D &max, float fUnitScale, float fGridCellSize, unsigned int *pFieldSize); int getGridData(int nGridIndex); int getGridCellIndex(const QVector3D &p); void insertParticles(BBSPHParticleSystem *pParticleSystem); int findCell(const QVector3D &p); void findCells(const QVector3D &p, float radius, int *pGridCell); void findTwoCells(const QVector3D &p, float radius, int *pGridCell); QVector3D getGridDelta() { return m_GridDelta; } private: // Stores particles in the grid std::vector<int> m_GridData; QVector3D m_GridMin; QVector3D m_GridMax; // n * m * l QVector3D m_GridResolution; QVector3D m_GridSize; QVector3D m_GridDelta; // The size of one cell of the grid (usually twice the smooth kernel radius) float m_fGridCellSize; }; #endif // BBSPHGRIDCONTAINER_H <|start_filename|>Code/BBearEditor/Engine/Render/BBDrawCall.cpp<|end_filename|> #include "BBDrawCall.h" #include "BufferObject/BBVertexBufferObject.h" #include "BufferObject/BBShaderStorageBufferObject.h" #include "BufferObject/BBElementBufferObject.h" #include "BufferObject/BBFrameBufferObject.h" #include "BufferObject/BBAtomicCounterBufferObject.h" #include "BBCamera.h" #include "BBRenderPass.h" #include "Scene/BBSceneManager.h" #include "Scene/BBScene.h" #include "Lighting/GameObject/BBLight.h" #include "Lighting/GameObject/BBDirectionalLight.h" #include "Base/BBRenderableObject.h" #include "Render/BBRenderQueue.h" #include "Shader/BBShader.h" /** * @brief BBDrawCall::BBDrawCall */ BBDrawFunc BBDrawCall::m_DrawFunc = &BBDrawCall::renderForwardPass; BBDrawCall::BBDrawCall() : BBBaseRenderComponent() { m_pMaterial = nullptr; m_eDrawPrimitiveType = GL_TRIANGLES; m_nDrawStartIndex = 0; m_pVBO = nullptr; m_pSSBO = nullptr; m_pACBO = nullptr; m_bClearACBO = true; m_nDrawCount = 3; m_pEBO = nullptr; m_nIndexCount = 0; m_bVisible = true; m_UpdateOrderInRenderQueueFunc = &BBDrawCall::updateOrderInOpaqueRenderQueue; m_BindFunc = &BBDrawCall::bindVBO; m_UnbindFunc = &BBDrawCall::unbindVBO; m_DrawBufferObjectFunc = &BBDrawCall::drawVBO; } void BBDrawCall::setMaterial(BBMaterial *pMaterial) { if (m_pMaterial) { BBRenderQueue *pRenderQueue = BBSceneManager::getRenderQueue(); pRenderQueue->switchQueue(m_pMaterial, pMaterial, this); if (pMaterial->getBlendState()) { m_UpdateOrderInRenderQueueFunc = &BBDrawCall::updateOrderInTransparentRenderQueue; } else { m_UpdateOrderInRenderQueueFunc = &BBDrawCall::updateOrderInOpaqueRenderQueue; } } m_pMaterial = pMaterial; m_pMaterial->bindDrawCallInstance(this); // The bind function is determined according to whether VBO or ssbo is used in the shader BBVertexBufferType eType = m_pMaterial->getShader()->getVertexBufferType(); if (eType == BBVertexBufferType::VBO) { m_BindFunc = &BBDrawCall::bindVBO; m_UnbindFunc = &BBDrawCall::unbindVBO; m_DrawBufferObjectFunc = &BBDrawCall::drawVBO; } else if (eType == BBVertexBufferType::SSBO) { m_BindFunc = &BBDrawCall::bindSSBO; m_UnbindFunc = &BBDrawCall::unbindSSBO; m_DrawBufferObjectFunc = &BBDrawCall::drawSSBO; } } void BBDrawCall::updateMaterialBlendState(bool bEnable) { BBRenderQueue *pRenderQueue = BBSceneManager::getRenderQueue(); pRenderQueue->switchQueue(bEnable, this); if (bEnable) { m_UpdateOrderInRenderQueueFunc = &BBDrawCall::updateOrderInTransparentRenderQueue; } else { m_UpdateOrderInRenderQueueFunc = &BBDrawCall::updateOrderInOpaqueRenderQueue; } } void BBDrawCall::setVBO(BBVertexBufferObject *pVBO, GLenum eDrawPrimitiveType, int nDrawStartIndex, int nDrawCount) { m_pVBO = pVBO; m_eDrawPrimitiveType = eDrawPrimitiveType; m_nDrawStartIndex = nDrawStartIndex; m_nDrawCount = nDrawCount; } void BBDrawCall::setSSBO(BBShaderStorageBufferObject *pSSBO, GLenum eDrawPrimitiveType, int nDrawStartIndex, int nDrawCount) { m_pSSBO = pSSBO; m_eDrawPrimitiveType = eDrawPrimitiveType; m_nDrawStartIndex = nDrawStartIndex; m_nDrawCount = nDrawCount; } /** * @brief BBDrawCall::setACBO * @param pACBO * @param bClear Whether reset data on every refresh */ void BBDrawCall::setACBO(BBAtomicCounterBufferObject *pACBO, bool bClear) { m_pACBO = pACBO; m_bClearACBO = bClear; } void BBDrawCall::setEBO(BBElementBufferObject *pEBO, GLenum eDrawPrimitiveType, int nIndexCount, int nDrawStartIndex) { m_pEBO = pEBO; m_eDrawPrimitiveType = eDrawPrimitiveType; m_nIndexCount = nIndexCount; m_nDrawStartIndex = nDrawStartIndex; } void BBDrawCall::updateOrderInRenderQueue(const QVector3D &renderableObjectPosition) { m_RenderableObjectPosition = renderableObjectPosition; (this->*m_UpdateOrderInRenderQueueFunc)(); } float BBDrawCall::getDistanceToCamera(BBCamera *pCamera) { return m_RenderableObjectPosition.distanceToPoint(pCamera->getPosition()); } void BBDrawCall::draw(BBCamera *pCamera) { (this->*m_DrawFunc)(pCamera); } void BBDrawCall::switchRenderingSettings(int nIndex) { switch (nIndex) { case 0: m_DrawFunc = &BBDrawCall::renderForwardPass; break; case 1: m_DrawFunc = &BBDrawCall::renderViewSpaceFBOPass; break; case 2: m_DrawFunc = &BBDrawCall::renderLightSpaceFBOPass; break; default: break; } } void BBDrawCall::renderOnePass(BBCamera *pCamera) { QList<BBGameObject*> lights = collectLights(); renderOnePass(pCamera, lights); } void BBDrawCall::renderOnePass(BBCamera *pCamera, QList<BBGameObject*> lights) { m_pVBO->bind(); BBRenderPass *pBaseRenderPass = m_pMaterial->getBaseRenderPass(); for (int i = 0; i < lights.count(); i++) { BBLight *pLight = (BBLight*)lights[i]; pLight->setRenderPass(pBaseRenderPass); pBaseRenderPass->bind(pCamera); if (m_pEBO == nullptr) { m_pVBO->draw(m_eDrawPrimitiveType, m_nDrawStartIndex, m_nDrawCount); } else { m_pEBO->bind(); m_pEBO->draw(m_eDrawPrimitiveType, m_nIndexCount, m_nDrawStartIndex); m_pEBO->unbind(); } } pBaseRenderPass->unbind(); m_pVBO->unbind(); } void BBDrawCall::renderOnePassSSBO(BBCamera *pCamera) { m_pSSBO->bind(); BBRenderPass *pBaseRenderPass = m_pMaterial->getBaseRenderPass(); pBaseRenderPass->bind(pCamera); m_pEBO->bind(); m_pEBO->draw(m_eDrawPrimitiveType, m_nIndexCount, m_nDrawStartIndex); m_pEBO->unbind(); pBaseRenderPass->unbind(); m_pSSBO->unbind(); } void BBDrawCall::renderForwardPass(BBCamera *pCamera) { if (m_bVisible) { QList<BBGameObject*> lights = collectLights(); bindBufferObject(); // base if (lights.count() > 0) { // render the first light BBLight *pLight = (BBLight*)lights[0]; pLight->setRenderPass(m_pMaterial->getBaseRenderPass()); } m_pMaterial->getBaseRenderPass()->bind(pCamera); if (m_pEBO == nullptr) { drawBufferObject(m_eDrawPrimitiveType, m_nDrawStartIndex, m_nDrawCount); } else { m_pEBO->bind(); m_pEBO->draw(m_eDrawPrimitiveType, m_nIndexCount, m_nDrawStartIndex); m_pEBO->unbind(); } m_pMaterial->getBaseRenderPass()->unbind(); // additive BBRenderPass *pAdditiveRenderPass = m_pMaterial->getAdditiveRenderPass(); if (lights.count() > 1 && pAdditiveRenderPass) { for (int i = 1; i < lights.count(); i++) { BBLight *pLight = (BBLight*)lights[i]; pLight->setRenderPass(pAdditiveRenderPass); pAdditiveRenderPass->bind(pCamera); if (m_pEBO == nullptr) { drawBufferObject(m_eDrawPrimitiveType, m_nDrawStartIndex, m_nDrawCount); } else { m_pEBO->bind(); m_pEBO->draw(m_eDrawPrimitiveType, m_nIndexCount, m_nDrawStartIndex); m_pEBO->unbind(); } } pAdditiveRenderPass->unbind(); } unbindBufferObject(); } if (m_pNext != nullptr) { next<BBDrawCall>()->draw(pCamera); } } void BBDrawCall::renderUIPass(BBCanvas *pCanvas) { m_pVBO->bind(); BBRenderPass *pRenderPass = m_pMaterial->getBaseRenderPass(); pRenderPass->bind(pCanvas); pRenderPass->setupStencilBuffer(); if (m_pEBO == nullptr) { m_pVBO->draw(m_eDrawPrimitiveType, m_nDrawStartIndex, m_nDrawCount); } else { m_pEBO->bind(); m_pEBO->draw(m_eDrawPrimitiveType, m_nIndexCount, m_nDrawStartIndex); m_pEBO->unbind(); } pRenderPass->restoreStencilBuffer(); pRenderPass->unbind(); m_pVBO->unbind(); } void BBDrawCall::renderViewSpaceFBOPass(BBCamera *pCamera) { BB_PROCESS_ERROR_RETURN(m_pMaterial->isWriteFBO()); renderForwardPass(pCamera); } void BBDrawCall::renderLightSpaceFBOPass(BBCamera *pCamera) { QList<BBGameObject*> lights = collectLights(); BB_PROCESS_ERROR_RETURN(lights.count() > 0); m_pVBO->bind(); BBRenderPass *pBaseRenderPass = m_pMaterial->getBaseRenderPass(); pBaseRenderPass->setCullState(true); pBaseRenderPass->setCullFace(GL_FRONT); // Only directional light is considered for the time BBDirectionalLight *pLight = (BBDirectionalLight*)lights[0]; pLight->setRenderPass(pBaseRenderPass); BBCamera *pLightSpaceCamera = pLight->getLightSpaceCamera(); pBaseRenderPass->bind(pLightSpaceCamera); if (m_pEBO == nullptr) { m_pVBO->draw(m_eDrawPrimitiveType, m_nDrawStartIndex, m_nDrawCount); } else { m_pEBO->bind(); m_pEBO->draw(m_eDrawPrimitiveType, m_nIndexCount, m_nDrawStartIndex); m_pEBO->unbind(); } pBaseRenderPass->setCullState(false); pBaseRenderPass->setCullFace(GL_BACK); pBaseRenderPass->unbind(); BB_SAFE_DELETE(pLightSpaceCamera); m_pVBO->unbind(); } void BBDrawCall::updateOrderInOpaqueRenderQueue() { BBRenderQueue *pRenderQueue = BBSceneManager::getRenderQueue(); pRenderQueue->updateOpaqueDrawCallOrder(this); } void BBDrawCall::updateOrderInTransparentRenderQueue() { BBRenderQueue *pRenderQueue = BBSceneManager::getRenderQueue(); pRenderQueue->updateTransparentDrawCallOrder(this); } void BBDrawCall::bindBufferObject() { (this->*m_BindFunc)(); if (m_pACBO) { m_pACBO->bind(); if (m_bClearACBO) { m_pACBO->clear(); } } } void BBDrawCall::unbindBufferObject() { if (m_pACBO) { m_pACBO->unbind(); } (this->*m_UnbindFunc)(); } void BBDrawCall::bindVBO() { m_pVBO->bind(); } void BBDrawCall::unbindVBO() { m_pVBO->unbind(); } void BBDrawCall::bindSSBO() { m_pSSBO->bind(); } void BBDrawCall::unbindSSBO() { m_pSSBO->unbind(); } void BBDrawCall::drawBufferObject(GLenum eDrawPrimitiveType, int nDrawStartIndex, int nDrawCount) { (this->*m_DrawBufferObjectFunc)(eDrawPrimitiveType, nDrawStartIndex, nDrawCount); } void BBDrawCall::drawVBO(GLenum eDrawPrimitiveType, int nDrawStartIndex, int nDrawCount) { m_pVBO->draw(m_eDrawPrimitiveType, m_nDrawStartIndex, m_nDrawCount); } void BBDrawCall::drawSSBO(GLenum eDrawPrimitiveType, int nDrawStartIndex, int nDrawCount) { m_pSSBO->draw(m_eDrawPrimitiveType, m_nDrawStartIndex, m_nDrawCount); } QList<BBGameObject*> BBDrawCall::collectLights() { return BBSceneManager::getScene()->getLights(); } <|start_filename|>Code/BBearEditor/Engine/Render/Shader/BBBaseShader.cpp<|end_filename|> #include "BBBaseShader.h" #include "Render/BBAttribute.h" #include "Render/BBUniformUpdater.h" #include "Render/BufferObject/BBVertexBufferObject.h" BBBaseShader::BBBaseShader() { m_pAttributes = nullptr; m_eVertexBufferType = VBO; m_pUniforms = nullptr; m_Program = 0; } void BBBaseShader::activeAttributes() { if (m_pAttributes != nullptr) { m_pAttributes->active(); } } void BBBaseShader::initAttributes() { GLint count = 0; glGetProgramiv(m_Program, GL_ACTIVE_ATTRIBUTES, &count); for (int i = 0; i < count; i++) { GLsizei length = 0; GLenum type = 0; GLint size = 0; char attribName[256] = {0}; glGetActiveAttrib(m_Program, i, 256, &length, &size, &type, attribName); GLint location = glGetAttribLocation(m_Program, attribName); int nComponentCount = 0; int nBasicDataType = 0; if (type == GL_FLOAT_VEC4) { nComponentCount = 4; nBasicDataType = GL_FLOAT; } int nDataOffset = 0; if (strcmp(attribName, LOCATION_POSITION) == 0) { nDataOffset = 0; } else if (strcmp(attribName, LOCATION_COLOR) == 0) { nDataOffset = sizeof(float) * 4; } else if (strcmp(attribName, LOCATION_TEXCOORD) == 0) { nDataOffset = sizeof(float) * 8; } else if (strcmp(attribName, LOCATION_NORMAL) == 0) { nDataOffset = sizeof(float) * 12; } else if (strcmp(attribName, LOCATION_TANGENT) == 0) { nDataOffset = sizeof(float) * 16; } else if (strcmp(attribName, LOCATION_BITANGENT) == 0) { nDataOffset = sizeof(float) * 20; } else if (strcmp(attribName, LOCATION_SMOOTHNORMAL) == 0) { nDataOffset = sizeof(float) * 24; } else { // If the attribname of VBO is not satisfied, ssbo is used m_eVertexBufferType = SSBO; } BBAttribute *pAttribute = new BBAttribute(location, nComponentCount, nBasicDataType, GL_FALSE, sizeof(BBVertex), nDataOffset); if (m_pAttributes == nullptr) { m_pAttributes = pAttribute; } else { m_pAttributes->pushBack(pAttribute); } } } void BBBaseShader::initUniforms() { GLint count = 0; glGetProgramiv(m_Program, GL_ACTIVE_UNIFORMS, &count); // Reserved for FBO // 0 : View Space Color FBO // 1 : View Space Depth FBO // 2 : Shadow Map // 3 : Irradiance Map // 4 : Prefilter Map Mipmap // 5 : BRDF LUT Texture // 6 : SkyBox Cube // 7 : SkyBox Background int nSlotIndex = 8; for (int i = 0; i < count; i++) { GLsizei length = 0; GLenum type = 0; GLint size = 0; char uniformName[256] = {0}; glGetActiveUniform(m_Program, i, 256, &length, &size, &type, uniformName); GLint location = glGetUniformLocation(m_Program, uniformName); BBUniformUpdater *pUniformUpdater = NULL; if (type == GL_FLOAT) { if (size == 1) { pUniformUpdater = initUniformFloat(location, uniformName); } else { pUniformUpdater = initUniformFloatArray(location, uniformName, size); } } else if (type == GL_FLOAT_MAT4) { pUniformUpdater = initUniformMatrix4(location, uniformName); } else if (type == GL_FLOAT_VEC4) { if (size == 1) { pUniformUpdater = initUniformVector4(location, uniformName); } else { pUniformUpdater = initUniformVector4Array(location, uniformName, size); } } else if (type == GL_SAMPLER_2D) { pUniformUpdater = initUniformSampler2D(location, uniformName, nSlotIndex); } else if (type == GL_SAMPLER_3D) { pUniformUpdater = initUniformSampler3D(location, uniformName, nSlotIndex); } else if (type == GL_SAMPLER_CUBE) { pUniformUpdater = initUniformSamplerCube(location, uniformName, nSlotIndex); } appendUniformUpdater(pUniformUpdater); } } BBUniformUpdater* BBBaseShader::initUniformFloat(GLint location, const char *pUniformName) { BBFloatMaterialProperty *pProperty = new BBFloatMaterialProperty(pUniformName); m_Properties.insert(pUniformName, pProperty); return new BBUniformUpdater(location, &BBUniformUpdater::updateFloat, pProperty); } BBUniformUpdater* BBBaseShader::initUniformFloatArray(GLint location, const char *pUniformName, int nArrayCount) { BBFloatArrayMaterialProperty *pProperty = new BBFloatArrayMaterialProperty(pUniformName, nArrayCount); m_Properties.insert(pUniformName, pProperty); return new BBUniformUpdater(location, &BBUniformUpdater::updateFloatArray, pProperty); } BBUniformUpdater* BBBaseShader::initUniformMatrix4(GLint location, const char *pUniformName) { BBUpdateUniformFunc updateUniformFunc = &BBUniformUpdater::updateMatrix4; BBMatrix4MaterialProperty *pProperty = nullptr; BBMaterialUniformPropertyType uniformType = BBMaterialUniformPropertyType::Matrix4; if (strcmp(pUniformName, LOCATION_PROJECTIONMATRIX) == 0) { updateUniformFunc = &BBUniformUpdater::updateCameraProjectionMatrix; uniformType = BBMaterialUniformPropertyType::CameraProjectionMatrix; } else if (strcmp(pUniformName, LOCATION_PROJECTIONMATRIX_I) == 0) { updateUniformFunc = &BBUniformUpdater::updateCameraInverseProjectionMatrix; uniformType = BBMaterialUniformPropertyType::CameraInverseProjectionMatrix; } else if (strcmp(pUniformName, LOCATION_VIEWMATRIX) == 0) { updateUniformFunc = &BBUniformUpdater::updateCameraViewMatrix; uniformType = BBMaterialUniformPropertyType::CameraViewMatrix; } else if (strcmp(pUniformName, LOCATION_VIEWMATRIX_I) == 0) { updateUniformFunc = &BBUniformUpdater::updateCameraInverseViewMatrix; uniformType = BBMaterialUniformPropertyType::CameraInverseViewMatrix; } else if (strcmp(pUniformName, LOCATION_LIGHT_PROJECTIONMATRIX) == 0) { updateUniformFunc = &BBUniformUpdater::updateLightProjectionMatrix; uniformType = BBMaterialUniformPropertyType::LightProjectionMatrix; } else if (strcmp(pUniformName, LOCATION_LIGHT_VIEWMATRIX) == 0) { updateUniformFunc = &BBUniformUpdater::updateLightViewMatrix; uniformType = BBMaterialUniformPropertyType::LightViewMatrix; } else { pProperty = new BBMatrix4MaterialProperty(pUniformName); m_Properties.insert(pUniformName, pProperty); } return new BBUniformUpdater(location, updateUniformFunc, pProperty); } BBUniformUpdater* BBBaseShader::initUniformVector4(GLint location, const char *pUniformName) { BBUpdateUniformFunc updateUniformFunc = &BBUniformUpdater::updateVector4; BBVector4MaterialProperty *pProperty = nullptr; if (strcmp(pUniformName, LOCATION_CANVAS) == 0) { updateUniformFunc = &BBUniformUpdater::updateCanvas; } else if (strcmp(pUniformName, LOCATION_CAMERA_PARAMETERS0) == 0) { updateUniformFunc = &BBUniformUpdater::updateCameraParameters0; } else if (strcmp(pUniformName, LOCATION_CAMERA_PARAMETERS1) == 0) { updateUniformFunc = &BBUniformUpdater::updateCameraParameters1; } else if (strcmp(pUniformName, LOCATION_CAMERA_POSITION) == 0) { updateUniformFunc = &BBUniformUpdater::updateCameraPosition; } else if (strcmp(pUniformName, LOCATION_TIME) == 0) { updateUniformFunc = &BBUniformUpdater::updateTime; } else { pProperty = new BBVector4MaterialProperty(pUniformName); m_Properties.insert(pUniformName, pProperty); } return new BBUniformUpdater(location, updateUniformFunc, pProperty); } BBUniformUpdater* BBBaseShader::initUniformVector4Array(GLint location, const char *pUniformName, int nArrayCount) { BBUpdateUniformFunc updateUniformFunc = &BBUniformUpdater::updateVector4Array; BBVector4ArrayMaterialProperty *pProperty = nullptr; if (strcmp(pUniformName, LOCATION_SPHERICAL_HARMONIC_LIGHTING) == 0) { updateUniformFunc = &BBUniformUpdater::updateSphericalHarmonicLightingCoefficients; } else { pProperty = new BBVector4ArrayMaterialProperty(pUniformName, nArrayCount); m_Properties.insert(pUniformName, pProperty); } return new BBUniformUpdater(location, updateUniformFunc, pProperty); } BBUniformUpdater* BBBaseShader::initUniformSampler2D(GLint location, const char *pUniformName, int &nSlotIndex) { BBUpdateUniformFunc updateUniformFunc = &BBUniformUpdater::updateSampler2D; BBSampler2DMaterialProperty *pProperty = nullptr; if (strcmp(pUniformName, LOCATION_CAMERA_COLOR_TEXTURE) == 0) { updateUniformFunc = &BBUniformUpdater::updateColorFBO; m_bWriteFBO = false; } else if (strcmp(pUniformName, LOCATION_CAMERA_DEPTH_TEXTURE) == 0) { updateUniformFunc = &BBUniformUpdater::updateDepthFBO; m_bWriteFBO = false; } else if (strcmp(pUniformName, LOCATION_SHADOWMAP) == 0) { updateUniformFunc = &BBUniformUpdater::updateShadowMap; } else if (strcmp(pUniformName, LOCATION_BRDF_LUT_TEXTURE) == 0) { updateUniformFunc = &BBUniformUpdater::updateBRDFLUTTexture; } else if (strcmp(pUniformName, LOCATION_SKYBOX_BACKGROUND) == 0) { updateUniformFunc = &BBUniformUpdater::updateSkyBoxBackground; } else { pProperty = new BBSampler2DMaterialProperty(pUniformName, nSlotIndex); m_Properties.insert(pUniformName, pProperty); nSlotIndex++; } return new BBUniformUpdater(location, updateUniformFunc, pProperty); } BBUniformUpdater* BBBaseShader::initUniformSampler3D(GLint location, const char *pUniformName, int &nSlotIndex) { BBUpdateUniformFunc updateUniformFunc = &BBUniformUpdater::updateSampler3D; BBSampler3DMaterialProperty *pProperty = new BBSampler3DMaterialProperty(pUniformName, nSlotIndex); m_Properties.insert(pUniformName, pProperty); nSlotIndex++; return new BBUniformUpdater(location, updateUniformFunc, pProperty); } BBUniformUpdater* BBBaseShader::initUniformSamplerCube(GLint location, const char *pUniformName, int &nSlotIndex) { BBUpdateUniformFunc updateUniformFunc = &BBUniformUpdater::updateSamplerCube; BBSamplerCubeMaterialProperty *pProperty = nullptr; if (strcmp(pUniformName, LOCATION_SKYBOX_MAP) == 0) { updateUniformFunc = &BBUniformUpdater::updateSkyBoxCube; } else if (strcmp(pUniformName, LOCATION_IRRADIANCE_MAP) == 0) { updateUniformFunc = &BBUniformUpdater::updateIrradianceMap; } else if (strcmp(pUniformName, LOCATION_PREFILTER_MAP_MIPMAP) == 0) { updateUniformFunc = &BBUniformUpdater::updatePrefilterMapMipmap; } else { pProperty = new BBSamplerCubeMaterialProperty(pUniformName, nSlotIndex); m_Properties.insert(pUniformName, pProperty); nSlotIndex++; } return new BBUniformUpdater(location, updateUniformFunc, pProperty); } void BBBaseShader::appendUniformUpdater(BBUniformUpdater *pUniformUpdater) { if (m_pUniforms == nullptr) { m_pUniforms = pUniformUpdater; } else { m_pUniforms->pushBack(pUniformUpdater); } } GLuint BBBaseShader::compileShader(GLenum shaderType, const char *shaderCode) { GLuint shader = glCreateShader(shaderType); glShaderSource(shader, 1, &shaderCode, nullptr); glCompileShader(shader); GLint compileResult = GL_TRUE; glGetShaderiv(shader, GL_COMPILE_STATUS, &compileResult); if (compileResult == GL_FALSE) { char szLog[1024] = {0}; GLsizei logLength = 0; glGetShaderInfoLog(shader, 1024, &logLength, szLog); qDebug() << "compileShader fail, log:" << szLog; glDeleteShader(shader); shader = 0; } return shader; } <|start_filename|>Resources/shaders/Volumetric/Cloud.frag<|end_filename|> #version 330 core in vec2 v2f_texcoord; in mat4 v2f_inverse_projection_matrix; in mat4 v2f_inverse_view_matrix; out vec4 FragColor; uniform sampler2D AlbedoTex; uniform sampler2D NormalTex; uniform sampler2D PositionTex; uniform sampler2D WeatherTex; uniform sampler2D PerlinNoiseTex2D; uniform sampler3D PerlinNoiseTex3D; uniform sampler2D DistortTex; uniform vec4 BBCameraPosition; uniform sampler2D BBCameraDepthTexture; uniform vec4 BBLightColor; uniform vec4 BBLightPosition; uniform vec4 BBTime; const vec3 BoundingBoxMin = vec3(-8, 0, -8); const vec3 BoundingBoxMax = vec3(8, 2, 8); const int RayMarchingNum = 256; const int TransmitNum = 8; const vec3 Color0 = vec3(0.94, 0.97, 1.0); const vec3 Color1 = vec3(0.94, 0.97, 1.0); const float ColorOffset0 = 0.6; const float ColorOffset1 = 1.0; const float DarknessThreshold = 0.05; const vec4 PhaseParams = vec4(0.72, 1.0, 0.5, 1.58); const vec4 NoiseWeights = vec4(-0.1, 30.0, -0.3, 1.0); const float ContainerEdgeFadeDst = 5.0; vec3 g_box_size; vec3 g_box_center; // compute the world pos of per pixel vec3 computePixelWorldPos(vec2 uv, float depth) { vec4 ndc_pos = vec4(uv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0); // -> view space vec4 view_space_pos = v2f_inverse_projection_matrix * ndc_pos; // -> world space vec4 world_pos = v2f_inverse_view_matrix * view_space_pos; world_pos /= world_pos.w; return world_pos.xyz; } // A Ray-Box Intersection Algorithm and Efficient Dynamic Voxel Rendering // http://jcgt.org/published/0007/03/04/ // ray_origin_pos : camera pos // inv_ray_dir : inverse ray direction // case 1: 0 <= enter <= leave // case 2: enter < 0 < leave // case 3: enter > leave vec2 rayToContainer(vec3 box_min, vec3 box_max, vec3 ray_origin_pos, vec3 inv_ray_dir) { vec3 t0 = (box_min - ray_origin_pos) * inv_ray_dir; vec3 t1 = (box_max - ray_origin_pos) * inv_ray_dir; vec3 tmin = min(t0, t1); vec3 tmax = max(t0, t1); // Entering point float enter = max(max(tmin.x, tmin.y), tmin.z); // Leaving point float leave = min(tmax.x, min(tmax.y, tmax.z)); // The distance between camera and container float camera_to_container = max(0, enter); // The distance the light travels within the bounding box float travel_distance = max(0, leave - camera_to_container); return vec2(camera_to_container, travel_distance); } float remap(float origin_val, float origin_min, float origin_max, float new_min, float new_max) { return new_min + (origin_val - origin_min) / (origin_max - origin_min) * (new_max - new_min); } float sampleDensity(vec3 ray_pos) { vec3 offset = vec3(0.001, 0.0002, 0.0) * BBTime.z; vec3 noise_tex_uvw = ray_pos * 0.4 + offset; // The disturbances in different directions are different float noise_val = dot(texture(PerlinNoiseTex3D, noise_tex_uvw), normalize(NoiseWeights)); vec2 weather_tex_uv = (ray_pos.xz - g_box_center.xz + g_box_size.xz * 0.5f) / max(g_box_size.x, g_box_size.z) + offset.xy * vec2(0.2, 0.2); // uv distortion vec4 distort = texture(DistortTex, v2f_texcoord); weather_tex_uv = mix(weather_tex_uv, distort.xy, 0.1); // Upper narrow and lower wide float weather_val = texture(WeatherTex, weather_tex_uv).r; float h_percent = (ray_pos.y - BoundingBoxMin.y) / g_box_size.y; // As the height rises, the gradient gradually flattens from 1 float h_gradient = clamp(remap(h_percent, 0.0, weather_val, 1.0, 0.0), 0.0, 1.0); // Bottom fade float bottom = remap(weather_val, 0, 1, 0.1, 0.6); h_gradient *= clamp(remap(h_percent, 0.0, bottom, 0.0, 1.0), 0.0, 1.0); // Edge fade float dst_to_edge_x = min(ContainerEdgeFadeDst, min(ray_pos.x - BoundingBoxMin.x, BoundingBoxMax.x - ray_pos.x)); float dst_to_edge_z = min(ContainerEdgeFadeDst, min(ray_pos.z - BoundingBoxMin.z, BoundingBoxMax.z - ray_pos.z)); float edge_weight = min(dst_to_edge_x, dst_to_edge_z) / ContainerEdgeFadeDst; h_gradient *= edge_weight; return noise_val * h_gradient; } vec3 transmit(vec3 ray_pos, vec3 L, float displacement) { float travel_distance = rayToContainer(BoundingBoxMin, BoundingBoxMax, ray_pos, vec3(1.0) / L).y; float step = travel_distance / TransmitNum; float sum_density = 0.0; for (int i = 0; i < TransmitNum; i++) { ray_pos += L * step; sum_density += max(0, sampleDensity(ray_pos)); } float transmittance = exp(-sum_density * step); // color level : light color / color0 / color1 vec3 cloud_color = mix(Color0, BBLightColor.rgb, clamp(transmittance * ColorOffset0, 0.0, 1.0)); cloud_color = mix(Color1, cloud_color, clamp(pow(transmittance * ColorOffset1, 1), 0.0, 1.0)); return DarknessThreshold + transmittance * (1 - DarknessThreshold) * cloud_color; } // HG phase function float hg(float a, float g) { float g2 = g * g; return (1 - g2) / (4 * 3.1415 * pow(1 + g2 - 2 * g * (a), 1.5)); } float phase(float a) { float blend = 0.5; float hg_blend = hg(a, PhaseParams.x) * (1 - blend) + hg(a, -PhaseParams.y) * blend; return PhaseParams.z + hg_blend * PhaseParams.w; } vec4 rayMarching(vec3 enter, vec3 V, float distance_limit, vec3 L) { vec3 ray_pos = enter; vec3 light_energy = vec3(0.0); float sum_density = 1.0; // The distance that ray travels float displacement = 0.0; float step = 0.05; // The scattering towards the light is stronger // The edges of the cloud appear black float cos_angle = dot(V, L); vec3 phase_val = vec3(phase(cos_angle)); // Cloud shape g_box_size = BoundingBoxMax - BoundingBoxMin; g_box_center = (BoundingBoxMax + BoundingBoxMin) * 0.5; for (int i = 0; i < RayMarchingNum; i++) { if (displacement < distance_limit) { ray_pos = enter + V * displacement; float density = sampleDensity(ray_pos); if (density > 0.0) { vec3 transmittance = transmit(ray_pos, L, displacement); light_energy += density * step * sum_density * transmittance * phase_val; // Beer-Lambert Law // The transmission intensity decreases exponentially with the increase of the propagation distance in the medium sum_density *= exp(-density * step); if (sum_density < 0.01) { break; } } } displacement += step; } return vec4(light_energy, sum_density); } void main(void) { vec3 albedo = texture(AlbedoTex, v2f_texcoord).rgb; float depth = texture(BBCameraDepthTexture, v2f_texcoord).r; vec3 pixel_world_pos = computePixelWorldPos(v2f_texcoord, depth); vec3 ray_pos = BBCameraPosition.xyz; vec3 camera_to_object = pixel_world_pos - ray_pos; vec3 V = normalize(camera_to_object); vec3 L = normalize(BBLightPosition.xyz); // Compute ray to the container surrounding the cloud // Raymarching is started at the intersection with the cloud container float camera_to_object_distance = length(camera_to_object); vec2 ray_to_container_result = rayToContainer(BoundingBoxMin, BoundingBoxMax, ray_pos, vec3(1.0) / V); float camera_to_container = ray_to_container_result.x; float travel_distance = ray_to_container_result.y; // When distance_limit < 0, we do not need to compute float distance_limit = min(camera_to_object_distance - camera_to_container, travel_distance); // The intersection with the cloud container vec3 enter = ray_pos + V * camera_to_container; vec4 ray_marching_result = rayMarching(enter, V, distance_limit, L); FragColor = 1 - vec4(0.06, 0.03, 0.0, ray_marching_result.a - 0.2); } <|start_filename|>Code/BBearEditor/Engine/Scene/CoordinateSystem/BBCoordinateSystem2D.cpp<|end_filename|> #include "BBCoordinateSystem2D.h" #include "BBCoordinateComponent2D.h" #include "Geometry/BBBoundingBox2D.h" /** * @brief BBCoordinateSystem2D::BBCoordinateSystem2D */ BBCoordinateSystem2D::BBCoordinateSystem2D() : BBGameObject() { m_pBoundingBoxX = new BBAABBBoundingBox2D(90, 0, 53, 12); m_pBoundingBoxY = new BBAABBBoundingBox2D(0, 90, 12, 53); m_pBoundingBoxXOY = new BBAABBBoundingBox2D(18, 18, 18, 18); m_SelectedAxis = AxisNULL; m_pSelectedObject = nullptr; m_bTransforming = false; } BBCoordinateSystem2D::~BBCoordinateSystem2D() { BB_SAFE_DELETE(m_pCoordinateComponent); BB_SAFE_DELETE(m_pBoundingBoxX); BB_SAFE_DELETE(m_pBoundingBoxY); BB_SAFE_DELETE(m_pBoundingBoxXOY); } void BBCoordinateSystem2D::init() { m_pCoordinateComponent->init(); } void BBCoordinateSystem2D::render(BBCamera *pCamera) { if (m_pSelectedObject == nullptr) return; m_pCoordinateComponent->render(pCamera); } void BBCoordinateSystem2D::setScreenCoordinate(int x, int y) { BBGameObject::setScreenCoordinate(x, y); m_pCoordinateComponent->setScreenCoordinate(x, y); m_pBoundingBoxX->setScreenCoordinate(x + 90, y); m_pBoundingBoxY->setScreenCoordinate(x, y + 90); m_pBoundingBoxXOY->setScreenCoordinate(x + 18, y + 18); } void BBCoordinateSystem2D::translate(int nDeltaX, int nDeltaY) { m_pCoordinateComponent->translate(nDeltaX, nDeltaY); m_pBoundingBoxX->translate(nDeltaX, nDeltaY); m_pBoundingBoxY->translate(nDeltaX, nDeltaY); m_pBoundingBoxXOY->translate(nDeltaX, nDeltaY); } void BBCoordinateSystem2D::setScale(float scale, bool bUpdateLocalTransform) { m_pBoundingBoxX->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxY->setScale(scale, bUpdateLocalTransform); m_pBoundingBoxXOY->setScale(scale, bUpdateLocalTransform); } bool BBCoordinateSystem2D::hitAxis(int x, int y) { BBAxisFlags axis = AxisNULL; bool bRet = false; if (m_pBoundingBoxX->hit(x, y)) { axis |= AxisX; bRet = true; } if (m_pBoundingBoxY->hit(x, y)) { axis |= AxisY; bRet = true; } setSelectedAxis(axis); return bRet; } bool BBCoordinateSystem2D::hitFace(int x, int y) { bool bRet = m_pBoundingBoxXOY->hit(x, y); if (bRet) { setSelectedAxis(AxisX | AxisY); } return bRet; } void BBCoordinateSystem2D::setSelectedObject(BBGameObject *pObject) { m_pSelectedObject = pObject; if (pObject != nullptr) { setScreenCoordinate(pObject->getScreenX(), pObject->getScreenY()); setRotation(pObject->getRotation()); } else { setScreenCoordinate(0, 0); setRotation(QVector3D(0, 0, 0)); setSelectedAxis(BBAxisName::AxisNULL); } } void BBCoordinateSystem2D::setSelectedAxis(const BBAxisFlags &axis) { m_SelectedAxis = axis; m_pCoordinateComponent->setSelectedAxis(axis); } bool BBCoordinateSystem2D::mouseMoveEvent(int x, int y, bool bMousePressed) { do { // if transforming, there is no need to perform other operations BB_END(m_bTransforming); // otherwise, determine whether transform can be turned on BB_END(m_pSelectedObject == NULL); // handle collision detection, change color of related axis and get m_SelectedAxis // if hitting m_pCoordinateRectFace, no need to handle axis if (!hitFace(x, y)) { // handle axis BB_END(!hitAxis(x, y)); } // do not handle transform when mouse is not pressed BB_END(!bMousePressed); // meet the conditions, turn on m_bTransforming m_bTransforming = true; } while(0); transform(x, y); // The return value indicates whether the transform has really performed return m_bTransforming; } void BBCoordinateSystem2D::stopTransform() { // When no movement, reset mouse pos QPoint pos; m_LastMousePos = pos; m_bTransforming = false; } /** * @brief BBPositionCoordinateSystem2D::BBPositionCoordinateSystem2D */ BBPositionCoordinateSystem2D::BBPositionCoordinateSystem2D() : BBCoordinateSystem2D() { m_pCoordinateComponent = new BBPositionCoordinateComponent2D(0, 0); } void BBPositionCoordinateSystem2D::transform(int x, int y) { BB_PROCESS_ERROR_RETURN(m_bTransforming); // displacement can be computed if (!m_LastMousePos.isNull()) { if (m_SelectedAxis & BBAxisName::AxisX) { translate(x - m_LastMousePos.x(), 0); } if (m_SelectedAxis & BBAxisName::AxisY) { translate(0, y - m_LastMousePos.y()); } m_pSelectedObject->setScreenCoordinate(m_pCoordinateComponent->getScreenX(), m_pCoordinateComponent->getScreenY()); } // record and wait the next frame m_LastMousePos = QPoint(x, y); } /** * @brief BBRotationCoordinateSystem2D::BBRotationCoordinateSystem2D */ BBRotationCoordinateSystem2D::BBRotationCoordinateSystem2D() : BBCoordinateSystem2D() { m_pCoordinateComponent = new BBRotationCoordinateComponent2D(0, 0); m_pBoundingBoxXOY = new BBQuarterCircleBoundingBox2D(0, 0, 135); m_pCoordinateCircle = new BBCoordinateCircle2D(0, 0, 120, 120); m_pCoordinateTickMark = new BBCoordinateTickMark2D(0, 0, 120, 120); m_pCoordinateSector = new BBCoordinateSector2D(0, 0, 120, 120); } BBRotationCoordinateSystem2D::~BBRotationCoordinateSystem2D() { BB_SAFE_DELETE(m_pCoordinateCircle); BB_SAFE_DELETE(m_pCoordinateTickMark); BB_SAFE_DELETE(m_pCoordinateSector); } void BBRotationCoordinateSystem2D::init() { m_pCoordinateComponent->init(); m_pCoordinateCircle->init(); m_pCoordinateTickMark->init(); m_pCoordinateSector->init(); } void BBRotationCoordinateSystem2D::render(BBCamera *pCamera) { if (m_pSelectedObject == nullptr) return; m_pCoordinateComponent->render(pCamera); if (m_bTransforming) { m_pCoordinateCircle->render(pCamera); m_pCoordinateTickMark->render(pCamera); m_pCoordinateSector->render(pCamera); } } void BBRotationCoordinateSystem2D::setScreenCoordinate(int x, int y) { BBGameObject::setScreenCoordinate(x, y); m_pCoordinateComponent->setScreenCoordinate(x, y); m_pCoordinateCircle->setScreenCoordinate(x, y); m_pCoordinateTickMark->setScreenCoordinate(x, y); m_pCoordinateSector->setScreenCoordinate(x, y); m_pBoundingBoxX->setScreenCoordinate(x + 90, y); m_pBoundingBoxY->setScreenCoordinate(x, y + 90); m_pBoundingBoxXOY->setScreenCoordinate(x, y); } void BBRotationCoordinateSystem2D::stopTransform() { BBCoordinateSystem2D::stopTransform(); m_pCoordinateSector->reset(); } void BBRotationCoordinateSystem2D::transform(int x, int y) { BB_PROCESS_ERROR_RETURN(m_bTransforming); // displacement can be computed if (!m_LastMousePos.isNull()) { if (m_SelectedAxis & (BBAxisName::AxisX | BBAxisName::AxisY)) { // compute the intersection angle between two of mouse pos dir QVector3D mousePos(x, y, 0); QVector3D mousePosDir = (mousePos - m_Position).normalized(); QVector3D lastMousePos(m_LastMousePos.x(), m_LastMousePos.y(), 0); QVector3D lastMousePosDir = (lastMousePos - m_Position).normalized(); float c = QVector3D::dotProduct(lastMousePosDir, mousePosDir); int nDeltaAngle = round(acosf(c) / 3.141593f * 180); // compute the sign of angle QVector3D crossResult = QVector3D::crossProduct(lastMousePosDir, mousePosDir); float sign = crossResult.x() + crossResult.y() + crossResult.z(); sign = sign > 0 ? 1 : -1; nDeltaAngle = sign * nDeltaAngle; m_pCoordinateSector->setAngle(nDeltaAngle); m_pSelectedObject->setRotation(nDeltaAngle, QVector3D(0, 0, 1)); } } // record and wait the next frame m_LastMousePos = QPoint(x, y); } /** * @brief BBScaleCoordinateSystem2D::BBScaleCoordinateSystem2D */ BBScaleCoordinateSystem2D::BBScaleCoordinateSystem2D() : BBCoordinateSystem2D() { m_pCoordinateComponent = new BBScaleCoordinateComponent2D(0, 0); m_nDeltaX = 0; m_nDeltaY = 0; } void BBScaleCoordinateSystem2D::setRotation(const QVector3D &rotation, bool bUpdateLocalTransform) { BBCoordinateSystem2D::setRotation(rotation, bUpdateLocalTransform); m_pCoordinateComponent->setRotation(rotation, bUpdateLocalTransform); } bool BBScaleCoordinateSystem2D::mouseMoveEvent(int x, int y, bool bMousePressed) { QVector3D point(x, y, 0); point -= m_Position; point = m_Quaternion.inverted() * point; point += m_Position; BBCoordinateSystem2D::mouseMoveEvent(point.x(), point.y(), bMousePressed); } void BBScaleCoordinateSystem2D::stopTransform() { BBCoordinateSystem2D::stopTransform(); m_nDeltaX = 0; m_nDeltaY = 0; ((BBScaleCoordinateComponent2D*)m_pCoordinateComponent)->reset(); } void BBScaleCoordinateSystem2D::transform(int x, int y) { BB_PROCESS_ERROR_RETURN(m_bTransforming); // displacement can be computed if (!m_LastMousePos.isNull()) { if (m_SelectedAxis & BBAxisName::AxisX) { m_nDeltaX += x - m_LastMousePos.x(); } if (m_SelectedAxis & BBAxisName::AxisY) { m_nDeltaY += y - m_LastMousePos.y(); } ((BBScaleCoordinateComponent2D*)m_pCoordinateComponent)->scale(m_nDeltaX, m_nDeltaY); } // record and wait the next frame m_LastMousePos = QPoint(x, y); } <|start_filename|>Code/BBearEditor/Engine/Physics/Body/BBBaseBody.h<|end_filename|> #ifndef BBBASEBODY_H #define BBBASEBODY_H #include <QVector3D> class BBBaseConstraint; class BBBaseBody { public: BBBaseBody(int nParticleCount, float fMass); virtual ~BBBaseBody(); void dampenVelocities(float fDeltaTime); void predictPositions(float fDeltaTime); void projectConstraints(float fDeltaTime); void updateVelocities(float fDeltaTime, float fStopThreshold2); void updatePositions(); inline void setParticlePosition(int nIndex, const QVector3D &position) { m_pPositions[nIndex] = position; } inline void setParticlePredictedPosition(int nIndex, const QVector3D &position) { m_pPredictedPositions[nIndex] = position; } inline void setParticleVelocity(int nIndex, const QVector3D &velocity) { m_pVelocities[nIndex] = velocity; } inline int getParticleCount() { return m_nParticleCount; } inline float getParticleMass() { return m_fParticleMass; } inline QVector3D getParticlePosition(int nIndex) { return m_pPositions[nIndex]; } inline QVector3D getParticlePredictedPosition(int nIndex) { return m_pPredictedPositions[nIndex]; } inline QVector3D getParticleVelocity(int nIndex) { return m_pVelocities[nIndex]; } protected: int m_nParticleCount; float m_fParticleMass; float m_fDamping; QVector3D *m_pPositions; QVector3D *m_pPredictedPositions; QVector3D *m_pVelocities; std::vector<BBBaseConstraint*> m_Constraints; }; #endif // BBBASEBODY_H <|start_filename|>Resources/shaders/GI/FullScreenQuad.vert<|end_filename|> #version 430 core in vec4 BBPosition; in vec4 BBTexcoord; out vec2 v2f_texcoord; void main() { v2f_texcoord = BBTexcoord.xy; gl_Position = BBPosition; } <|start_filename|>Resources/shaders/RayTracing/0_GBuffer.frag<|end_filename|> #version 430 core out vec2 v2f_texcoord; out vec3 v2f_view_space_pos; layout (location = 0) out vec4 Albedo_Metallic; uniform sampler2D DiffuseTex; void main(void) { float gamma = 2.2; vec3 diffuse_color = pow(texture(DiffuseTex, v2f_texcoord).rgb, vec3(gamma)); vec3 mapped = vec3(1.0) - exp(-diffuse_color); mapped = pow(mapped, vec3(1.0 / gamma)); Albedo_Metallic = vec4(mapped, 1.0); float alpha = textureLod(DiffuseTex, v2f_texcoord, 0).a; if (alpha != 1.0) discard; } <|start_filename|>Code/BBearEditor/Engine/Physics/Constraint/BBBendingConstraint.h<|end_filename|> #ifndef BBBENDINGCONSTRAINT_H #define BBBENDINGCONSTRAINT_H #include "BBBaseConstraint.h" class BBBendingConstraint : public BBBaseConstraint { public: BBBendingConstraint(BBBaseBody *pBody, int nParticleIndex1, int nParticleIndex2, int nParticleIndex3, float fElasticModulus); void doConstraint(float fDeltaTime) override; private: int m_nParticleIndex1; int m_nParticleIndex2; int m_nParticleIndex3; float m_fElasticModulus; float m_fOriginLength; }; #endif // BBBENDINGCONSTRAINT_H <|start_filename|>Code/BBearEditor/Engine/Render/BBLinkedList.h<|end_filename|> #pragma once #ifndef BBLINKEDLIST_H #define BBLINKEDLIST_H class BBLinkedList { public: BBLinkedList(); int getCount(); template<typename T> T* next() { return (T*)m_pNext; } void pushBack(BBLinkedList *pNode); void insertAfter(BBLinkedList *pNode); template<typename T> T* removeSelf() { T *ptr = (T*)m_pNext; m_pNext = nullptr; return ptr; } void remove(BBLinkedList *pNode); bool isEnd(); void clear(); BBLinkedList *m_pNext; }; #endif // BBLINKEDLIST_H <|start_filename|>Resources/shaders/ParticleSystem/Particles2-0.frag<|end_filename|> #version 430 void main(void) { } <|start_filename|>Code/BBearEditor/Engine/Geometry/BBBoundingBox2D.h<|end_filename|> #ifndef BBBOUNDINGBOX2D_H #define BBBOUNDINGBOX2D_H #include "Base/BBRenderableObject2D.h" class BBBoundingBox2D : public BBRenderableObject2D { public: BBBoundingBox2D(); BBBoundingBox2D(int x, int y, int nWidth, int nHeight); void init() override; }; class BBAABBBoundingBox2D : public BBBoundingBox2D { public: BBAABBBoundingBox2D(float fCenterX, float fCenterY, float fHalfLengthX, float fHalfLengthY, int nWidth, int nHeight); BBAABBBoundingBox2D(int x, int y, int nHalfLengthX, int nHalfLengthY); void init() override; bool hit(int x, int y) override; int getHalfLengthX() { return m_nHalfLengthX; } int getHalfLengthY() { return m_nHalfLengthY; } private: int m_nHalfLengthX; int m_nHalfLengthY; }; class BBQuarterCircleBoundingBox2D : public BBBoundingBox2D { public: BBQuarterCircleBoundingBox2D(int x, int y, int nRadius); bool hit(int x, int y) override; private: int m_nRadius; }; #endif // BBBOUNDINGBOX2D_H <|start_filename|>Resources/shaders/special_effect.frag<|end_filename|> varying vec4 V_Color; varying vec4 V_Texcoord; uniform sampler2D Texture0; uniform vec4 Color_Base_Color; uniform vec4 BBTime; void main(void) { vec4 final_color = V_Color; final_color *= texture2D(Texture0, V_Texcoord.xy + vec2(0.0001, 0.0001) * BBTime.z); final_color *= Color_Base_Color; gl_FragColor = final_color; } <|start_filename|>Code/BBearEditor/Engine/Render/BBCamera.cpp<|end_filename|> #include "BBCamera.h" #include "math.h" #include "Geometry/BBRay.h" #include "Base/BBGameObject.h" #include "Scene/BBSceneManager.h" #include "BBDrawCall.h" #include "BBRenderQueue.h" #include "Math/BBMath.h" BBCamera::BBCamera(QVector3D position, QVector3D viewCenter, QVector3D up) : m_Position(position), m_ViewCenter(viewCenter), m_Up(up) { m_fMoveSpeed = 30.0f; resetMove(); for (int i = 0; i < 16; i++) { m_pModelView[i] = 0; m_pProjection[i] = 0; } m_fVerticalAngle = 50.0f; m_fAspect = 800.0f / 600.0f; m_fNearPlane = 0.1f; m_fFarPlane = 1000.0f; m_fDepth = 1000.0f - 0.1f; m_ProjectionMatrix.perspective(m_fVerticalAngle, m_fAspect, m_fNearPlane, m_fFarPlane); m_fDisplacement = 0.0f; m_pFrustumCluster = nullptr; m_CameraParameters0[0] = 0.0f; m_CameraParameters0[1] = 0.0f; m_CameraParameters0[2] = m_fNearPlane; m_CameraParameters0[3] = m_fFarPlane; m_CameraParameters1[0] = m_fVerticalAngle; m_CameraParameters1[1] = m_fAspect; m_CameraParameters1[2] = 2 * m_fNearPlane * tan(radians(m_fVerticalAngle) / 2.0); // Near plane height m_CameraParameters1[3] = 0.0f; } BBCamera::~BBCamera() { BB_SAFE_DELETE(m_pFrustumCluster); } void BBCamera::resetMove() { m_bMoveLeft = false; m_bMoveRight = false; m_bMoveForward = false; m_bMoveBack = false; m_bMoveUp = false; m_bMoveDown = false; } void BBCamera::update(float fDeltaTime) { QVector3D forwardDirection = m_ViewCenter - m_Position; forwardDirection.normalize(); QVector3D rightDirection = QVector3D::crossProduct(forwardDirection, m_Up); rightDirection.normalize(); float d = m_fMoveSpeed * fDeltaTime; if (m_bMoveLeft) { m_Position = m_Position - d * rightDirection; m_ViewCenter = m_ViewCenter - d * rightDirection; m_fDisplacement += d; } else if (m_bMoveRight) { m_Position = m_Position + d * rightDirection; m_ViewCenter = m_ViewCenter + d * rightDirection; m_fDisplacement += d; } if (m_bMoveForward) { m_Position = m_Position + d * forwardDirection; m_ViewCenter = m_ViewCenter + d * forwardDirection; m_fDisplacement += d; } else if (m_bMoveBack) { m_Position = m_Position - d * forwardDirection; m_ViewCenter = m_ViewCenter - d * forwardDirection; m_fDisplacement += d; } if (m_bMoveUp) { m_Position = m_Position + d * m_Up; m_ViewCenter = m_ViewCenter + d * m_Up; m_fDisplacement += d; } else if (m_bMoveDown) { m_Position = m_Position - d * m_Up; m_ViewCenter = m_ViewCenter - d * m_Up; m_fDisplacement += d; } // When the camera position changes, update render queue if (m_fDisplacement >= 10.0f) { BBSceneManager::getRenderQueue()->updateAllDrawCallOrder(); m_fDisplacement = 0.0f; } // Reset, eliminate the influence of the previous frame on the current matrix glLoadIdentity(); gluLookAt(m_Position.x(), m_Position.y(), m_Position.z(), m_ViewCenter.x(), m_ViewCenter.y(), m_ViewCenter.z(), m_Up.x(), m_Up.y(), m_Up.z()); glGetDoublev(GL_MODELVIEW_MATRIX, m_pModelView); glGetDoublev(GL_PROJECTION_MATRIX, m_pProjection); m_ViewMatrix = QMatrix4x4(m_pModelView[0], m_pModelView[4], m_pModelView[8], m_pModelView[12], m_pModelView[1], m_pModelView[5], m_pModelView[9], m_pModelView[13], m_pModelView[2], m_pModelView[6], m_pModelView[10], m_pModelView[14], m_pModelView[3], m_pModelView[7], m_pModelView[11], m_pModelView[15]); } void BBCamera::update(QVector3D position, QVector3D viewCenter) { m_Position = position; m_ViewCenter = viewCenter; glLoadIdentity(); gluLookAt(m_Position.x(), m_Position.y(), m_Position.z(), m_ViewCenter.x(), m_ViewCenter.y(), m_ViewCenter.z(), m_Up.x(), m_Up.y(), m_Up.z()); glGetDoublev(GL_MODELVIEW_MATRIX, m_pModelView); glGetDoublev(GL_PROJECTION_MATRIX, m_pProjection); m_ViewMatrix = QMatrix4x4(m_pModelView[0], m_pModelView[4], m_pModelView[8], m_pModelView[12], m_pModelView[1], m_pModelView[5], m_pModelView[9], m_pModelView[13], m_pModelView[2], m_pModelView[6], m_pModelView[10], m_pModelView[14], m_pModelView[3], m_pModelView[7], m_pModelView[11], m_pModelView[15]); } void BBCamera::resetViewportSize() { glViewport(m_pViewport[0], m_pViewport[1], m_pViewport[2], m_pViewport[3]); } void BBCamera::setViewportSize(int nWidth, int nHeight) { m_nViewportWidth = nWidth; m_nViewportHeight = nHeight; m_pViewport[0] = 0; m_pViewport[1] = 0; m_pViewport[2] = m_nViewportWidth; m_pViewport[3] = m_nViewportHeight; m_CameraParameters0[0] = m_nViewportWidth; m_CameraParameters0[1] = m_nViewportHeight; m_CameraParameters1[1] = m_fAspect = (float) nWidth / nHeight; m_ProjectionMatrix.setToIdentity(); m_ProjectionMatrix.perspective(m_fVerticalAngle, m_fAspect, m_fNearPlane, m_fFarPlane); if (m_pFrustumCluster) { BB_SAFE_DELETE(m_pFrustumCluster); } m_pFrustumCluster = new BBFrustumCluster(this, 0, 0, m_nViewportWidth, m_nViewportHeight, 2, 2, 1); } void BBCamera::switchTo3D() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(m_fVerticalAngle, m_fAspect, m_fNearPlane, m_fFarPlane); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void BBCamera::switchTo2D() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); // left, right, bottom, top edge of 2D window gluOrtho2D(-m_nViewportWidth / 2, m_nViewportWidth / 2, -m_nViewportHeight / 2, m_nViewportHeight / 2); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void BBCamera::move(char dir, bool bMove) { switch (dir) { case 'A': m_bMoveLeft = bMove; break; case 'D': m_bMoveRight = bMove; break; case 'W': m_bMoveForward = bMove; break; case 'S': m_bMoveBack = bMove; break; case 'Q': m_bMoveDown = bMove; break; case 'E': m_bMoveUp = bMove; break; default: break; } } void BBCamera::pitch(float fAngle) { // up down QVector3D forwardDirection = m_ViewCenter - m_Position; forwardDirection.normalize(); QVector3D rightDirection = QVector3D::crossProduct(forwardDirection, m_Up); rightDirection.normalize(); rotateView(fAngle, rightDirection.x(), rightDirection.y(), rightDirection.z()); } void BBCamera::yaw(float fAngle) { // left-right Rotate around the Y axis rotateView(fAngle, m_Up.x(), m_Up.y(), m_Up.z()); } void BBCamera::setMoveSpeed(int dir) { m_fMoveSpeed += 2 * dir; if (m_fMoveSpeed < 1) m_fMoveSpeed = 1; else if (m_fMoveSpeed > 100) m_fMoveSpeed = 100; } void BBCamera::lookAt(BBGameObject *pGameObject) { pGameObject->showCloseUp(m_Position, m_ViewCenter); } BBRay BBCamera::createRayFromScreen(float x, float y) { float winX = x; float winY = m_nViewportHeight - y; // Get the 3D point coordinates corresponding to the 2D point in the front clipping plane GLdouble nearPosX, nearPosY, nearPosZ; gluUnProject(winX, winY, 0.0f, m_pModelView, m_pProjection, m_pViewport, &nearPosX, &nearPosY, &nearPosZ); GLdouble farPosX, farPosY, farPosZ; gluUnProject(winX, winY, 1.0f, m_pModelView, m_pProjection, m_pViewport, &farPosX, &farPosY, &farPosZ); BBRay ray(nearPosX, nearPosY, nearPosZ, farPosX, farPosY, farPosZ); return ray; } void BBCamera::switchCoordinate(int &x, int &y) { // The coordinates of the origin in the upper left corner are converted // into the coordinates of the origin in the middle of the screen x -= m_nViewportWidth / 2.0f; y -= m_nViewportHeight / 2.0f; y = -y; } QVector3D BBCamera::projectPointToScreenSpace(const QVector3D &point) { QVector3D posOnNdcSpace = m_ProjectionMatrix * point; return QVector3D(posOnNdcSpace.x() * m_nViewportWidth / 2.0f, posOnNdcSpace.y() * m_nViewportHeight / 2.0f, 0.0f); } QVector4D BBCamera::projectPointToScreenSpace(const QVector4D &point) { QVector4D posOnClipSpace = m_ProjectionMatrix * point; QVector4D posOnNdcSpace = QVector4D(posOnClipSpace.x() / posOnClipSpace.w(), posOnClipSpace.y() / posOnClipSpace.w(), posOnClipSpace.z() / posOnClipSpace.w(), posOnClipSpace.w()); return QVector4D(posOnNdcSpace.x() * m_nViewportWidth / 2.0f, posOnNdcSpace.y() * m_nViewportHeight / 2.0f, 0.0f, 1.0f); } bool BBCamera::isFrustumContainPoint(int nFrustumIndexX, int nFrustumIndexY, int nFrustumIndexZ, const QVector3D &point) { return m_pFrustumCluster->contain(nFrustumIndexX, nFrustumIndexY, nFrustumIndexZ, point); } bool BBCamera::isSphereContainFrustum(int nFrustumIndexX, int nFrustumIndexY, int nFrustumIndexZ, const QVector3D &center, float fRadius) { return m_pFrustumCluster->containedInSphere(nFrustumIndexX, nFrustumIndexY, nFrustumIndexZ, center, fRadius); } bool BBCamera::isFrustumIntersectWithAABB(int nFrustumIndexX, int nFrustumIndexY, int nFrustumIndexZ, BBAABBBoundingBox3D *pAABB) { return m_pFrustumCluster->computeIntersectWithAABB(nFrustumIndexX, nFrustumIndexY, nFrustumIndexZ, pAABB); } void BBCamera::rotateView(float fAngle, float x, float y, float z) { // Rotate an angle around an axis, the change of view QVector3D viewDirection = m_ViewCenter - m_Position; QVector3D newDirection; float c = cosf(fAngle); float s = sinf(fAngle); QVector3D tempX(c + x * x * (1 - c), x * y * (1 - c) - z * s, x * z * (1 - c) + y * s); newDirection.setX(QVector3D::dotProduct(tempX, viewDirection)); QVector3D tempY(x * y * (1 - c) + z * s, c + y * y * (1 - c), y * z * (1 - c) - x * s); newDirection.setY(QVector3D::dotProduct(tempY, viewDirection)); QVector3D tempZ(x * z * (1 - c) - y * s, y * z * (1 - c) + x * s, c + z * z * (1 - c)); newDirection.setZ(QVector3D::dotProduct(tempZ, viewDirection)); m_ViewCenter = m_Position + newDirection; } <|start_filename|>Resources/shaders/fullscreenquad.frag<|end_filename|> varying vec4 V_Texcoord; uniform sampler2D BBTexture0; uniform sampler2D BBTexture1; uniform sampler2D BBTexture2; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; uniform vec4 BBLightSettings0; uniform vec4 BBLightSettings1; void main(void) { vec4 pos_data = texture2D(BBTexture0, V_Texcoord.xy); // vec3 world_pos = (pos_data.xyz * 2.0 - vec3(1.0)) * 1.0; vec3 world_pos = pos_data.xyz; vec4 normal_data = texture2D(BBTexture1, V_Texcoord.xy); // vec3 normal = normal_data.xyz * 2.0 - vec3(1.0); vec3 normal = normal_data.xyz; vec4 color_data = texture2D(BBTexture2, V_Texcoord.xy); vec3 color = color_data.rgb; float intensity = 0.0; vec3 final_color = vec3(0.0); if (BBLightSettings0.x != 0.0) { // there is a light if (BBLightPosition.w == 0.0) { // directional light vec3 object_to_light_source = normalize(BBLightPosition.xyz); intensity = dot(object_to_light_source, normal); final_color = color * BBLightColor.xyz * intensity; } else { // point light float radius = BBLightSettings1.x; float constant_factor = BBLightSettings1.y; float linear_factor = BBLightSettings1.z; float quadric_factor = BBLightSettings1.w; vec3 L = BBLightPosition.xyz - world_pos.xyz; float distance = length(L); float attenuation = 1.0 / (constant_factor + linear_factor * distance + quadric_factor * quadric_factor * distance); L = normalize(L); float delta = radius - distance; float intensity = 0.0; if (delta >= 0) { intensity = max(0.0, dot(L, normal) * attenuation * delta / radius); } final_color = color * BBLightColor.xyz * intensity; } } else { final_color = color; } gl_FragColor = vec4(final_color, 1.0); } <|start_filename|>Resources/shaders/diffuse.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBColor; attribute vec4 BBNormal; varying vec4 V_Color; varying vec4 V_Normal; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { V_Color = BBColor; V_Normal.xyz = mat3(transpose(inverse(BBModelMatrix))) * BBNormal.xyz; gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * BBPosition; } <|start_filename|>Code/BBearEditor/Engine/Base/BBRenderableObject2D.cpp<|end_filename|> #include "BBRenderableObject2D.h" #include "Geometry/BBBoundingBox.h" #include "Render/BBMaterial.h" #include "Scene/BBRendererManager.h" #include "Render/BBDrawCall.h" BBRenderableObject2D::BBRenderableObject2D() : BBRenderableObject2D(0, 0, 100, 100) { } BBRenderableObject2D::BBRenderableObject2D(int x, int y, int nWidth, int nHeight) : BBRenderableObject(x, y, nWidth, nHeight) { } BBRenderableObject2D::~BBRenderableObject2D() { } void BBRenderableObject2D::init() { m_pCurrentMaterial = BBRendererManager::createUIMaterial(); BBRenderableObject::init(); } void BBRenderableObject2D::render(BBCamera *pCamera) { BBRenderableObject::render(pCamera); } void BBRenderableObject2D::render(BBCanvas *pCanvas) { if (m_bActive && m_bVisible) { m_pDrawCalls->renderUIPass(pCanvas); } } <|start_filename|>Resources/shaders/UI.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBTexcoord; attribute vec4 BBColor; varying vec4 V_Color; varying vec4 V_Texcoord; varying vec4 V_Light; varying vec4 V_Dark; uniform mat4 BBModelMatrix; uniform vec4 BBCanvas; void main() { V_Color = BBColor; V_Texcoord = BBTexcoord; V_Light = vec4(1.0); // tangent V_Dark = vec4(1.0); // texcoord1 vec4 screen_pos = BBModelMatrix * BBPosition; // Scaling to NDC coordinates // Z is any value of -1 ~ 1 gl_Position = vec4(screen_pos.x / BBCanvas.x, screen_pos.y / BBCanvas.y, 0.0, 1.0); } <|start_filename|>Resources/shaders/GI.frag<|end_filename|> varying vec4 V_World_pos; varying vec4 V_Texcoord; varying vec4 V_Normal; uniform sampler2D Albedo_Map; // main light uniform vec4 BBLightSettings0; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; uniform vec4 BBCameraPosition; struct Light { vec3 color; vec3 dir; }; struct IndirectLight { vec3 diffuse; vec3 specular; }; struct GIInput { Light light; vec3 world_pos; vec3 world_view_dir; float attenuation; float ambient; }; struct GI { Light light; IndirectLight indirect_light; }; struct Surface { vec3 albedo; vec3 normal; float alpha; }; GI lightingLambertGI(GIInput data, float occlusion, vec3 world_normal) { GI gi; gi.light = data.light; // attenuation depends on shadow mask, to do ... gi.light.color *= data.attenuation; gi.indirect_light.diffuse *= occlusion; return gi; } vec4 lightingLambert(Surface s, GI gi) { vec4 c = vec4(1.0); float diff = max(0.0, dot(s.normal, gi.light.dir)); c.rgb = s.albedo * gi.light.color * diff; c.a = s.alpha; // add indirect light c.rgb += s.albedo * gi.indirect_light.diffuse; return c; } void main(void) { Surface s; s.albedo = texture2D(Albedo_Map, V_Texcoord.xy); s.normal = V_Normal; s.alpha = 1.0; GI gi; gi.light.color = BBLightColor.rgb; gi.light.dir = normalize(BBLightPosition.xyz); gi.indirect_light.diffuse = vec3(0.0); gi.indirect_light.specular = vec3(0.0); GIInput gi_input; gi_input.light = gi.light; gi_input.world_pos = V_World_pos.xyz; gi_input.world_view_dir = normalize(BBCameraPosition.xyz - V_World_pos.xyz); gi_input.attenuation = 1.0; gi_input.ambient = 0.0; gi = lightingLambertGI(gi_input, 1.0, s.normal); gl_FragColor = lightingLambert(s, gi); } <|start_filename|>Resources/shaders/Wave/SimpleExample.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBTexcoord; attribute vec4 BBNormal; varying vec3 v2f_view_space_pos; varying vec2 v2f_texcoords; varying vec3 v2f_normal; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { vec4 view_space_pos = BBViewMatrix * BBModelMatrix * BBPosition; gl_Position = BBProjectionMatrix * view_space_pos; v2f_view_space_pos = view_space_pos.xyz; v2f_texcoords = BBTexcoord.xy; v2f_normal = mat3(BBModelMatrix) * BBNormal.xyz; } <|start_filename|>Code/BBearEditor/Engine/Serializer/BBHierarchyTreeWidgetItem.pb.h<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBHierarchyTreeWidgetItem.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_BBHierarchyTreeWidgetItem_2eproto #define GOOGLE_PROTOBUF_INCLUDED_BBHierarchyTreeWidgetItem_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3016000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3016000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_BBHierarchyTreeWidgetItem_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_BBHierarchyTreeWidgetItem_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBHierarchyTreeWidgetItem_2eproto; namespace BBSerializer { class BBHierarchyTreeWidgetItem; struct BBHierarchyTreeWidgetItemDefaultTypeInternal; extern BBHierarchyTreeWidgetItemDefaultTypeInternal _BBHierarchyTreeWidgetItem_default_instance_; } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> ::BBSerializer::BBHierarchyTreeWidgetItem* Arena::CreateMaybeMessage<::BBSerializer::BBHierarchyTreeWidgetItem>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace BBSerializer { // =================================================================== class BBHierarchyTreeWidgetItem PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBHierarchyTreeWidgetItem) */ { public: inline BBHierarchyTreeWidgetItem() : BBHierarchyTreeWidgetItem(nullptr) {} ~BBHierarchyTreeWidgetItem() override; explicit constexpr BBHierarchyTreeWidgetItem(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBHierarchyTreeWidgetItem(const BBHierarchyTreeWidgetItem& from); BBHierarchyTreeWidgetItem(BBHierarchyTreeWidgetItem&& from) noexcept : BBHierarchyTreeWidgetItem() { *this = ::std::move(from); } inline BBHierarchyTreeWidgetItem& operator=(const BBHierarchyTreeWidgetItem& from) { CopyFrom(from); return *this; } inline BBHierarchyTreeWidgetItem& operator=(BBHierarchyTreeWidgetItem&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBHierarchyTreeWidgetItem& default_instance() { return *internal_default_instance(); } static inline const BBHierarchyTreeWidgetItem* internal_default_instance() { return reinterpret_cast<const BBHierarchyTreeWidgetItem*>( &_BBHierarchyTreeWidgetItem_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(BBHierarchyTreeWidgetItem& a, BBHierarchyTreeWidgetItem& b) { a.Swap(&b); } inline void Swap(BBHierarchyTreeWidgetItem* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBHierarchyTreeWidgetItem* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBHierarchyTreeWidgetItem* New() const final { return CreateMaybeMessage<BBHierarchyTreeWidgetItem>(nullptr); } BBHierarchyTreeWidgetItem* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBHierarchyTreeWidgetItem>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBHierarchyTreeWidgetItem& from); void MergeFrom(const BBHierarchyTreeWidgetItem& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBHierarchyTreeWidgetItem* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBHierarchyTreeWidgetItem"; } protected: explicit BBHierarchyTreeWidgetItem(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kParentIndexFieldNumber = 1, }; // int32 parentIndex = 1; bool has_parentindex() const; private: bool _internal_has_parentindex() const; public: void clear_parentindex(); ::PROTOBUF_NAMESPACE_ID::int32 parentindex() const; void set_parentindex(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_parentindex() const; void _internal_set_parentindex(::PROTOBUF_NAMESPACE_ID::int32 value); public: // @@protoc_insertion_point(class_scope:BBSerializer.BBHierarchyTreeWidgetItem) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::int32 parentindex_; friend struct ::TableStruct_BBHierarchyTreeWidgetItem_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // BBHierarchyTreeWidgetItem // int32 parentIndex = 1; inline bool BBHierarchyTreeWidgetItem::_internal_has_parentindex() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool BBHierarchyTreeWidgetItem::has_parentindex() const { return _internal_has_parentindex(); } inline void BBHierarchyTreeWidgetItem::clear_parentindex() { parentindex_ = 0; _has_bits_[0] &= ~0x00000001u; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBHierarchyTreeWidgetItem::_internal_parentindex() const { return parentindex_; } inline ::PROTOBUF_NAMESPACE_ID::int32 BBHierarchyTreeWidgetItem::parentindex() const { // @@protoc_insertion_point(field_get:BBSerializer.BBHierarchyTreeWidgetItem.parentIndex) return _internal_parentindex(); } inline void BBHierarchyTreeWidgetItem::_internal_set_parentindex(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000001u; parentindex_ = value; } inline void BBHierarchyTreeWidgetItem::set_parentindex(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_parentindex(value); // @@protoc_insertion_point(field_set:BBSerializer.BBHierarchyTreeWidgetItem.parentIndex) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_BBHierarchyTreeWidgetItem_2eproto <|start_filename|>Code/BBearEditor/Editor/PropertyManager/BBPropertyFactory.h<|end_filename|> #ifndef BBPROPERTYFACTORY_H #define BBPROPERTYFACTORY_H #include <QWidget> #include <QVector2D> #include <QVector3D> class BBSliderLabel; class QLineEdit; class QLabel; class QComboBox; class BBColorButton; class BBLight; class QPushButton; class BBIconLabel; class BBDragAcceptedEdit; class BBRenderableObject; class QSlider; class QGridLayout; class QVBoxLayout; class QCheckBox; /** * @brief The BBLineEditFactory class QLineEdit with the BBSliderLabel of name on the left */ class BBLineEditFactory : public QWidget { Q_OBJECT public: explicit BBLineEditFactory(const QString &name, float fValue, QWidget *pParent = nullptr, int nNameStretch = 0, int nValueStretch = 0); ~BBLineEditFactory(); void setRange(float fMin, float fMax); void setRegExp(const QString &pattern); void setSlideStep(float fStep) { m_fSlideStep = fStep; } QString setValue(float fValue); private slots: void changeEditText(const QString &text); void changeValueBySlider(int nDeltaX); void showFromLeft(); signals: void valueChanged(float fValue); void valueChanged(const QString &name, float fValue); private: BBSliderLabel *m_pSliderLabel; QLineEdit *m_pEdit; float m_fMaxValue; float m_fMinValue; float m_fSlideStep; }; class BBVector2DFactory : public QWidget { Q_OBJECT public: BBVector2DFactory(const QVector2D &value = QVector2D(0, 0), QWidget *pParent = nullptr); ~BBVector2DFactory(); void setValue(const QVector2D &value); float getX() { return m_Value.x(); } float getY() { return m_Value.y(); } public slots: void setX(float x); void setY(float y); signals: void valueChanged(const QVector2D &value); private: BBLineEditFactory *m_pEditX; BBLineEditFactory *m_pEditY; QVector2D m_Value; }; /** * @brief The BBVector3DFactory class Composed of three BBLineEditFactory */ class BBVector3DFactory : public QWidget { Q_OBJECT public: BBVector3DFactory(const QVector3D &value = QVector3D(0, 0, 0), QWidget *pParent = nullptr); ~BBVector3DFactory(); void setValue(const QVector3D &value); public slots: void setX(float x); void setY(float y); void setZ(float z); signals: void valueChanged(const QVector3D &value); private: BBLineEditFactory *m_pEditX; BBLineEditFactory *m_pEditY; BBLineEditFactory *m_pEditZ; QVector3D m_Value; }; /** * @brief The BBEnumFactory class name showed in the left side and enum box showed in the right side */ class BBEnumFactory : public QWidget { Q_OBJECT public: BBEnumFactory(const QString &name, const QStringList &comboBoxItems, const QString &currentText = "", QWidget *pParent = 0, int labelStretch = 1, int comboBoxStretch = 3); ~BBEnumFactory(); int getCurrentItemIndex(); private slots: void changeCurrentItem(int nIndex); void changeCurrentItem(const QString &text); signals: void currentItemChanged(int nIndex); void currentItemChanged(const QString &text); private: QLabel *m_pLabel; QComboBox *m_pComboBox; }; /** * @brief The BBEnumExpansionFactory class BBEnumFactory and button ... */ class BBEnumExpansionFactory : public BBEnumFactory { Q_OBJECT public: BBEnumExpansionFactory(const QString &name, const QStringList &comboBoxItems, const QString &buttonText, const QString &currentText = "", QWidget *pParent = 0, int labelStretch = 0, int comboBoxStretch = 1); ~BBEnumExpansionFactory(); void enableTrigger(bool bEnable); void enableButton(bool bEnable); private slots: void clickButton(); void clickTrigger(bool bClicked); signals: void buttonClicked(); void triggerClicked(bool bClicked); private: QCheckBox *m_pTrigger; QPushButton *m_pButton; }; /** * @brief The BBColorFactory class dropper and color box */ class BBColorFactory : public QWidget { Q_OBJECT public: BBColorFactory(float r, float g, float b, float a, QWidget *pParent = 0); BBColorFactory(const std::string &uniformName, float r, float g, float b, float a, QWidget *pParent = 0); BBColorFactory(float *color, QWidget *pParent = 0); ~BBColorFactory(); protected slots: void catchColor(); virtual void finishCatchColor(float r, float g, float b); signals: void colorChanged(float r, float g, float b, float a = 1.0f, const std::string &uniformName = ""); protected: BBColorButton *m_pColorButton; std::string m_UniformName; }; class BBLightColorFactory : public BBColorFactory { Q_OBJECT public: BBLightColorFactory(BBLight *pLight, QWidget *pParent = 0); private slots: void finishCatchColor(float r, float g, float b) override; private: BBLight *m_pLight; }; class BBIconFactory : public QWidget { Q_OBJECT public: BBIconFactory(QWidget *pParent = 0); ~BBIconFactory(); void setContent(const QString &filePath); public slots: virtual void changeCurrentFilePath(const QString &filePath) = 0; protected: // Widget except icon QGridLayout *m_pLeftLayout; QPushButton *m_pRemoveButton; QPushButton *m_pSelectButton; BBIconLabel *m_pIconLabel; QLineEdit *m_pNameEdit; }; class BBTextureFactory : public BBIconFactory { Q_OBJECT public: BBTextureFactory(const QString &uniformName, const QString &originalIconPath = "", QWidget *pParent = 0, int nIndex = 0); void enableTilingAndOffset(bool bEnable); void setTiling(float fTilingX, float fTilingY); void setOffset(float fOffsetX, float fOffsetY); public slots: void changeCurrentFilePath(const QString &filePath) override; void changeTiling(const QVector2D &value); void changeOffset(const QVector2D &value); signals: void setSampler2D(const QString &uniformName, const QString &texturePath, int nIndex = 0); void setTilingAndOffset(const QString &uniformName, float fTilingX, float fTilingY, float fOffsetX, float fOffsetY); private: BBVector2DFactory *m_pTilingFactory; BBVector2DFactory *m_pOffsetFactory; QString m_UniformName; // if it is in a group int m_nIndex; }; class BBCubeMapFactory : public QWidget { Q_OBJECT public: BBCubeMapFactory(const QString &uniformName, const QString originalIconPath[] = {}, QWidget *pParent = 0); ~BBCubeMapFactory(); public slots: void changeCurrentFilePath(const QString &uniformName, const QString &texturePath, int nFaceIndex); signals: void setSamplerCube(const QString &uniformName, QString *pResourcePaths); private: BBTextureFactory *m_pTextureFactory[6]; QString m_ResourcePaths[6]; }; class BBDragAcceptedFactory : public QWidget { Q_OBJECT public: BBDragAcceptedFactory(const QString &iconPath, const QString &filePath = "", QWidget *pParent = 0); ~BBDragAcceptedFactory(); void setFilter(const QStringList &acceptableSuffixs); public slots: void changeCurrentFilePath(const QString &filePath); void clickIcon(); signals: void currentFilePathChanged(const QString &filePath); void iconClicked(); private: QPushButton *m_pIconLabel; BBDragAcceptedEdit *m_pDragAcceptedEdit; }; /** * @brief The BBSliderFactory class slider in the left and editor in the right */ class BBSliderFactory : public QWidget { Q_OBJECT public: BBSliderFactory(int nValue = 50, int nMin = 0, int nMax = 100, QWidget *pParent = 0); ~BBSliderFactory(); void setRange(int nMin, int nMax); void setValue(int value); private slots: void changeSliderValue(int value); void changeEditorValue(const QString &value); signals: void valueChanged(int value); private: int m_nMin; int m_nMax; QSlider *m_pSlider; QLineEdit *m_pEditor; }; //class BBSliderFFactory : public QWidget //{ // Q_OBJECT //public: // BBSliderFFactory(float fValue = 0.5f, float fMin = 0.0f, float fMax = 1.0f, QWidget *pParent = 0); // ~BBSliderFFactory(); // void setRange(float fMin, float fMax); // void setValue(float value); //private slots: // void changeSliderValue(float value); // void changeEditorValue(const QString &value); //signals: // void valueChanged(float value); //private: // float m_fMin; // float m_fMax; // QSlider *m_pSlider; // QLineEdit *m_pEditor; //}; #endif // BBPROPERTYFACTORY_H <|start_filename|>Code/BBearEditor/Engine/Geometry/BBBoundingBox.cpp<|end_filename|> #include "BBBoundingBox.h" #include "Utils/BBUtils.h" #include <cfloat> #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BBMaterial.h" #include "Render/BBDrawCall.h" #include <Eigen/Eigen> #include "Render/BBCamera.h" using namespace Eigen; /** * @brief BBBoundingBox::BBBoundingBox */ BBBoundingBox::BBBoundingBox() : BBBoundingBox(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBBoundingBox::BBBoundingBox(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBRenderableObject(px, py, pz, rx, ry, rz, sx, sy, sz) { m_nBoxVertexCount = 0; m_pOriginalBoxVertexes = NULL; m_pTransformedBoxVertexes = NULL; m_DefaultColor = QVector3D(0.909804f, 0.337255f, 0.333333f); } BBBoundingBox::~BBBoundingBox() { BB_SAFE_DELETE_ARRAY(m_pOriginalBoxVertexes); BB_SAFE_DELETE_ARRAY(m_pTransformedBoxVertexes); } bool BBBoundingBox::hit(const BBRay &ray, float &fDistance) { Q_UNUSED(ray); Q_UNUSED(fDistance); return m_bActive; } QVector3D BBBoundingBox::getCenter() { return QVector3D(m_Center[0], m_Center[1], m_Center[2]); } void BBBoundingBox::setModelMatrix(float px, float py, float pz, const QQuaternion &r, float sx, float sy, float sz) { // When the corresponding model is transformed, invoke BBGameObject::setModelMatrix(px, py, pz, r, sx, sy, sz); for (int i = 0; i < m_nBoxVertexCount; i++) { m_pTransformedBoxVertexes[i] = m_ModelMatrix * m_pOriginalBoxVertexes[i]; } } /** * @brief BBRectBoundingBox3D::BBRectBoundingBox3D * @param fCenterX * @param fCenterY * @param fCenterZ * @param fHalfLengthX * @param fHalfLengthY * @param fHalfLengthZ */ BBRectBoundingBox3D::BBRectBoundingBox3D(float fCenterX, float fCenterY, float fCenterZ, float fHalfLengthX, float fHalfLengthY, float fHalfLengthZ) : BBBoundingBox() { m_nBoxVertexCount = 4; m_pOriginalBoxVertexes = new QVector3D[m_nBoxVertexCount]; m_pTransformedBoxVertexes = new QVector3D[m_nBoxVertexCount]; m_Center[0] = fCenterX; m_Center[1] = fCenterY; m_Center[2] = fCenterZ; if (fHalfLengthX == 0) { m_pOriginalBoxVertexes[0] = QVector3D(fCenterX, fCenterY + fHalfLengthY, fCenterZ + fHalfLengthZ); m_pOriginalBoxVertexes[1] = QVector3D(fCenterX, fCenterY - fHalfLengthY, fCenterZ + fHalfLengthZ); m_pOriginalBoxVertexes[2] = QVector3D(fCenterX, fCenterY - fHalfLengthY, fCenterZ - fHalfLengthZ); m_pOriginalBoxVertexes[3] = QVector3D(fCenterX, fCenterY + fHalfLengthY, fCenterZ - fHalfLengthZ); } else if (fHalfLengthY == 0) { m_pOriginalBoxVertexes[0] = QVector3D(fCenterX + fHalfLengthX, fCenterY, fCenterZ + fHalfLengthZ); m_pOriginalBoxVertexes[1] = QVector3D(fCenterX - fHalfLengthX, fCenterY, fCenterZ + fHalfLengthZ); m_pOriginalBoxVertexes[2] = QVector3D(fCenterX - fHalfLengthX, fCenterY, fCenterZ - fHalfLengthZ); m_pOriginalBoxVertexes[3] = QVector3D(fCenterX + fHalfLengthX, fCenterY, fCenterZ - fHalfLengthZ); } else if (fHalfLengthZ == 0) { m_pOriginalBoxVertexes[0] = QVector3D(fCenterX + fHalfLengthX, fCenterY + fHalfLengthY, fCenterZ); m_pOriginalBoxVertexes[1] = QVector3D(fCenterX - fHalfLengthX, fCenterY + fHalfLengthY, fCenterZ); m_pOriginalBoxVertexes[2] = QVector3D(fCenterX - fHalfLengthX, fCenterY - fHalfLengthY, fCenterZ); m_pOriginalBoxVertexes[3] = QVector3D(fCenterX + fHalfLengthX, fCenterY - fHalfLengthY, fCenterZ); } m_pTransformedBoxVertexes[0] = m_pOriginalBoxVertexes[0]; m_pTransformedBoxVertexes[1] = m_pOriginalBoxVertexes[1]; m_pTransformedBoxVertexes[2] = m_pOriginalBoxVertexes[2]; m_pTransformedBoxVertexes[3] = m_pOriginalBoxVertexes[3]; } BBRectBoundingBox3D::~BBRectBoundingBox3D() { } void BBRectBoundingBox3D::init() { m_pVBO = new BBVertexBufferObject(m_nBoxVertexCount); for (int i = 0; i < m_nBoxVertexCount; i++) { m_pVBO->setPosition(i, m_pOriginalBoxVertexes[i].x(), m_pOriginalBoxVertexes[i].y(), m_pOriginalBoxVertexes[i].z()); m_pVBO->setColor(i, m_DefaultColor); } m_nIndexCount = 8; unsigned short indexes[] = {0, 1, 1, 2, 2, 3, 3, 0}; m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0; i < m_nIndexCount; i++) { m_pIndexes[i] = indexes[i]; } m_pCurrentMaterial->init("UI", BB_PATH_RESOURCE_SHADER(UI.vert), BB_PATH_RESOURCE_SHADER(UI.frag)); m_pCurrentMaterial->setVector4(LOCATION_TEXTURE_SETTING0, 0.0f, 0.0f, 0.0f, 0.0f); m_pCurrentMaterial->setVector4(LOCATION_CAMERA_PARAMETERS0, 800.0f, 600.0f, 0.0f, 0.0f); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_LINES, m_nIndexCount, 0); appendDrawCall(pDrawCall); } bool BBRectBoundingBox3D::hit(const BBRay &ray, float &fDistance) { // If it is not activated, no collision occurs if (!BBBoundingBox::hit(ray, fDistance)) return false; QVector3D intersection; bool result = false; fDistance = FLT_MAX; if (ray.computeIntersectWithRectangle(m_pTransformedBoxVertexes[0], m_pTransformedBoxVertexes[1], m_pTransformedBoxVertexes[2], m_pTransformedBoxVertexes[3], intersection)) { float tmp = ray.computeIntersectDistance(intersection); if (tmp >= 0.0f) { result = true; fDistance = tmp; } } return result; } /** * @brief BBTriangleBoundingBox3D::BBTriangleBoundingBox3D * @param point1 * @param point2 * @param point3 */ BBTriangleBoundingBox3D::BBTriangleBoundingBox3D(const QVector3D &point1, const QVector3D &point2, const QVector3D &point3) : BBBoundingBox() { m_nBoxVertexCount = 3; m_pOriginalBoxVertexes = new QVector3D[m_nBoxVertexCount]; m_pTransformedBoxVertexes = new QVector3D[m_nBoxVertexCount]; m_pOriginalBoxVertexes[0] = point1; m_pOriginalBoxVertexes[1] = point2; m_pOriginalBoxVertexes[2] = point3; } bool BBTriangleBoundingBox3D::hit(const BBRay &ray, float &fDistance) { // If it is not activated, no collision occurs if (!BBBoundingBox::hit(ray, fDistance)) return false; QVector3D intersection; bool result = false; fDistance = FLT_MAX; if (ray.computeIntersectWithTriangle(m_pTransformedBoxVertexes[0], m_pTransformedBoxVertexes[1], m_pTransformedBoxVertexes[2], intersection)) { float tmp = ray.computeIntersectDistance(intersection); if (tmp >= 0.0f) { result = true; fDistance = tmp; } } return result; } /** * @brief BBQuarterCircleBoundingBox3D::BBQuarterCircleBoundingBox3D * @param fCenterX * @param fCenterY * @param fCenterZ * @param fRadius * @param ePlaneName */ BBQuarterCircleBoundingBox3D::BBQuarterCircleBoundingBox3D(float fCenterX, float fCenterY, float fCenterZ, float fRadius, const BBPlaneName &ePlaneName) : BBBoundingBox() { m_nBoxVertexCount = 1; m_pOriginalBoxVertexes = new QVector3D[m_nBoxVertexCount]; m_pTransformedBoxVertexes = new QVector3D[m_nBoxVertexCount]; m_Center[0] = fCenterX; m_Center[1] = fCenterY; m_Center[2] = fCenterZ; m_eSelectedPlaneName = ePlaneName; m_QuadrantFlag = QVector3D(0, 0, 0); if (ePlaneName == BBPlaneName::YOZ) { m_pOriginalBoxVertexes[0] = QVector3D(m_Center[0], m_Center[1], m_Center[2]) + QVector3D(0, fRadius, 0); } else // XOZ or XOY { m_pOriginalBoxVertexes[0] = QVector3D(m_Center[0], m_Center[1], m_Center[2]) + QVector3D(fRadius, 0, 0); } } bool BBQuarterCircleBoundingBox3D::hit(const BBRay &ray, float &fDistance) { // If it is not activated, no collision occurs if (!BBBoundingBox::hit(ray, fDistance)) return false; QVector3D intersection; bool result = false; fDistance = FLT_MAX; if (ray.computeIntersectWithQuarterCircle(m_Position, (m_pTransformedBoxVertexes[0] - m_Position).length(), m_eSelectedPlaneName, intersection, m_QuadrantFlag)) { float tmp = ray.computeIntersectDistance(intersection); if (tmp >= 0.0f) { result = true; fDistance = tmp; } } return result; } /** * @brief BBBoundingBox3D::BBBoundingBox3D * @param vertexes */ BBBoundingBox3D::BBBoundingBox3D(const QList<QVector4D> &vertexes) : BBBoundingBox3D(0, 0, 0, 0, 0, 0, 1, 1, 1, vertexes) { } BBBoundingBox3D::BBBoundingBox3D(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz, const QList<QVector4D> &vertexes) : BBBoundingBox(px, py, pz, rx, ry, rz, sx, sy, sz) { m_nBoxVertexCount = 8; m_pOriginalBoxVertexes = new QVector3D[m_nBoxVertexCount]; m_pTransformedBoxVertexes = new QVector3D[m_nBoxVertexCount]; m_DefaultColor = QVector3D(0.909804f, 0.337255f, 0.333333f); m_Center[0] = 0; m_Center[1] = 0; m_Center[2] = 0; m_HalfLength[0] = 0.5f; m_HalfLength[1] = 0.5f; m_HalfLength[2] = 0.5f; m_Axis[0][0] = 1; m_Axis[0][1] = 0; m_Axis[0][2] = 0; m_Axis[1][0] = 0; m_Axis[1][1] = 1; m_Axis[1][2] = 0; m_Axis[2][0] = 0; m_Axis[2][1] = 0; m_Axis[2][2] = 1; computeBoxVertexes(vertexes); } BBBoundingBox3D::BBBoundingBox3D(const QVector3D &position, const QVector3D &rotation, const QVector3D &scale, const QVector3D &center, const QVector3D &halfLength) : BBBoundingBox3D(position.x(), position.y(), position.z(), rotation.x(), rotation.y(), rotation.z(), scale.x(), scale.y(), scale.z(), center.x(), center.y(), center.z(), halfLength.x(), halfLength.y(), halfLength.z()) { } BBBoundingBox3D::BBBoundingBox3D(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz, float fCenterX, float fCenterY, float fCenterZ, float fHalfLengthX, float fHalfLengthY, float fHalfLengthZ) : BBBoundingBox(px, py, pz, rx, ry, rz, sx, sy, sz) { m_nBoxVertexCount = 8; m_pOriginalBoxVertexes = new QVector3D[m_nBoxVertexCount]; m_pTransformedBoxVertexes = new QVector3D[m_nBoxVertexCount]; m_Center[0] = fCenterX; m_Center[1] = fCenterY; m_Center[2] = fCenterZ; m_HalfLength[0] = fHalfLengthX; m_HalfLength[1] = fHalfLengthY; m_HalfLength[2] = fHalfLengthZ; m_Axis[0][0] = 1; m_Axis[0][1] = 0; m_Axis[0][2] = 0; m_Axis[1][0] = 0; m_Axis[1][1] = 1; m_Axis[1][2] = 0; m_Axis[2][0] = 0; m_Axis[2][1] = 0; m_Axis[2][2] = 1; QList<QVector4D> vertexes; computeBoxVertexes(vertexes); } BBBoundingBox3D::~BBBoundingBox3D() { } void BBBoundingBox3D::init() { m_pVBO = new BBVertexBufferObject(8); for (int i = 0; i < 8; i++) { m_pVBO->setPosition(i, m_pOriginalBoxVertexes[i].x(), m_pOriginalBoxVertexes[i].y(), m_pOriginalBoxVertexes[i].z()); m_pVBO->setColor(i, m_DefaultColor); } m_nIndexCount = 24; unsigned short indexes[] = {0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7}; m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0; i < m_nIndexCount; i++) { m_pIndexes[i] = indexes[i]; } m_pCurrentMaterial->init("base", BB_PATH_RESOURCE_SHADER(base.vert), BB_PATH_RESOURCE_SHADER(base.frag)); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_LINES, m_nIndexCount, 0); appendDrawCall(pDrawCall); } bool BBBoundingBox3D::hit(const BBRay &ray, float &fDistance) { // If it is not activated, no collision occurs if (!BBBoundingBox::hit(ray, fDistance)) return false; QVector3D intersection; bool result = false; fDistance = FLT_MAX; // Calculate whether to hit the 6 faces of the bounding box static unsigned int indexes[] = {0, 1, 2, 3, 4, 5, 6, 7, 1, 2, 6, 5, 0, 3, 7, 4, 0, 1, 5, 4, 3, 2, 6, 7}; for (int i = 0; i < 24; i += 4) { if (ray.computeIntersectWithRectangle(m_pTransformedBoxVertexes[indexes[i]], m_pTransformedBoxVertexes[indexes[i + 1]], m_pTransformedBoxVertexes[indexes[i + 2]], m_pTransformedBoxVertexes[indexes[i + 3]], intersection)) { float temp = ray.computeIntersectDistance(intersection); if (temp >= 0.0f) { if (temp < fDistance) fDistance = temp; result = true; } } } return result; } bool BBBoundingBox3D::belongToSelectionRegion(const BBFrustum &frustum) { for (int i = 0; i < m_nBoxVertexCount; i++) { BB_PROCESS_ERROR_RETURN_FALSE(frustum.contain(m_pTransformedBoxVertexes[i])); } return true; } QVector3D BBBoundingBox3D::getHalfLength() { return QVector3D(m_HalfLength[0], m_HalfLength[1], m_HalfLength[2]); } void BBBoundingBox3D::computeBoxVertexes(const QList<QVector4D> &vertexes) { Q_UNUSED(vertexes); FloatData temp[8]; int sign[8][3] = {{1, 1, 1}, {-1, 1, 1}, {-1, -1, 1}, {1, -1, 1}, {1, 1, -1}, {-1, 1, -1}, {-1, -1, -1}, {1, -1, -1}}; for (int index = 0; index < 8; index++) { for (int i = 0; i < 3; i++) { temp[index].v[i] = m_Center[i]; for (int j = 0; j < 3; j++) { temp[index].v[i] += m_Axis[j][i] * m_HalfLength[j] * sign[index][j]; } } m_pOriginalBoxVertexes[index] = QVector3D(temp[index].v[0], temp[index].v[1], temp[index].v[2]); m_pTransformedBoxVertexes[index] = m_ModelMatrix * m_pOriginalBoxVertexes[index]; } } /** * @brief BBAABBBoundingBox3D::BBAABBBoundingBox3D * @param vertexes */ BBAABBBoundingBox3D::BBAABBBoundingBox3D(const QList<QVector4D> &vertexes) : BBAABBBoundingBox3D(0, 0, 0, 0, 0, 0, 1, 1, 1, vertexes) { } BBAABBBoundingBox3D::BBAABBBoundingBox3D(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz, const QList<QVector4D> &vertexes) : BBBoundingBox3D(px, py, pz, rx, ry, rz, sx, sy, sz, vertexes) { m_HalfLength[0] = 0; m_HalfLength[1] = 0; m_HalfLength[2] = 0; computeBoxVertexes(vertexes); } BBAABBBoundingBox3D::BBAABBBoundingBox3D(const QVector3D &position, const QVector3D &rotation, const QVector3D &scale, const QVector3D &center, const QVector3D &halfLength) : BBBoundingBox3D(position, rotation, scale, center, halfLength) { } bool BBAABBBoundingBox3D::computeIntersectWithPlane(const QVector3D &point, const QVector3D &normal) { // The vertex closest to the plane QVector3D p = getMin(); if (normal.x() >= 0) p.setX(getMax().x()); if (normal.y() >= 0) p.setY(getMax().y()); if (normal.z() >= 0) p.setZ(getMax().z()); // The vertex of the farthest diagonal QVector3D n = getMax(); if (normal.x() >= 0) n.setX(getMin().x()); if (normal.y() >= 0) n.setY(getMin().y()); if (normal.z() >= 0) n.setZ(getMin().z()); if (p.distanceToPlane(point, normal) < 0) return false; if (n.distanceToPlane(point, normal) < 0) return true; return false; } void BBAABBBoundingBox3D::computeBoxVertexes(const QList<QVector4D> &vertexes) { int nVertexCount = vertexes.count(); // init matrix MatrixXf m(3, nVertexCount); for (int i = 0; i < nVertexCount; i++) { m(0, i) = vertexes.at(i).x(); m(1, i) = vertexes.at(i).y(); m(2, i) = vertexes.at(i).z(); } // Find the mean value of x y z, center VectorXf avg = m.rowwise().mean(); // compute the distance from each point to the center m.colwise() -= avg; for (int i = 0; i < 3; i++) { m_Center[i] = avg[i]; for (int j = 0; j < nVertexCount; j++) { m_HalfLength[i] = std::max(m_HalfLength[i], std::fabs(m(i, j))); } } BBBoundingBox3D::computeBoxVertexes(vertexes); } QVector3D BBAABBBoundingBox3D::getMax() { return m_pTransformedBoxVertexes[0]; } QVector3D BBAABBBoundingBox3D::getMin() { return m_pTransformedBoxVertexes[6]; } //void OBBBoundingBox3D::computeBoundingBox() //{ // int vertexCount = mVertexes.count(); // //初始化矩阵 // MatrixXf input(3, vertexCount); // MatrixXf m(3, vertexCount); // for (int i = 0; i < vertexCount; i++) // { // m(0, i) = mVertexes.at(i).x(); // m(1, i) = mVertexes.at(i).y(); // m(2, i) = mVertexes.at(i).z(); // } // input = m; // //cout << input << endl << endl; // //求取x y z均值 // VectorXf avg = m.rowwise().mean(); // m.colwise() -= avg; // //计算协方差矩阵 adjoint转置 // MatrixXf covMat = (m * m.adjoint()) / float(vertexCount - 1); // //cout << covMat << endl << endl; // //求特征向量和特征值 // SelfAdjointEigenSolver<MatrixXf> eigen(covMat); // MatrixXf eigenvectors = eigen.eigenvectors(); // //cout << eigenvectors << endl << endl; // //将各点的(X,Y,Z)坐标投影到计算出的坐标轴上 avg由累加所有点再求均值得到 求出center和半长度 // VectorXf minExtents(3); // VectorXf maxExtents(3); // minExtents << FLT_MAX, FLT_MAX, FLT_MAX; // maxExtents << -FLT_MAX, -FLT_MAX, -FLT_MAX; // for (int i = 0; i < vertexCount; i++) // { // VectorXf vertex = input.col(i); // VectorXf displacement = vertex - avg; // for (int j = 0; j < 3; j++) // { // minExtents[j] = min(minExtents[j], displacement.dot(eigenvectors.col(j))); // maxExtents[j] = max(maxExtents[j], displacement.dot(eigenvectors.col(j))); // } // } // VectorXf offset = (maxExtents - minExtents) / 2.0f + minExtents; // for (int i = 0; i < 3; i++) // { // avg += eigenvectors.col(i) * offset[i]; // } // for (int i = 0; i < 3; i++) // { // center[i] = avg[i]; // radius[i] = (maxExtents[i] - minExtents[i]) / 2.0f; // for (int j = 0; j < 3; j++) // axis[i][j] = eigenvectors.col(i)[j]; // } // /*qDebug() << center[0] << center[1] << center[2]; // qDebug() << radius[0] << radius[1] << radius[2]; // qDebug() << axis[0][0] << axis[0][1] << axis[0][2]; // qDebug() << axis[1][0] << axis[1][1] << axis[1][2]; // qDebug() << axis[2][0] << axis[2][1] << axis[2][2]; // qDebug() << endl;*/ // getBoundingBoxVertexes(); //} <|start_filename|>Resources/shaders/Physics/FluidSystem/SSF_GS_GBuffer.shader<|end_filename|> #version 430 core layout (points) in; layout (triangle_strip, max_vertices = 4) out; in float v2g_view_space_particle_radius[]; out float g2f_view_space_particle_radius; out vec3 g2f_view_space_center_pos; out vec3 g2f_frag_pos; uniform mat4 BBProjectionMatrix; void main() { g2f_view_space_particle_radius = v2g_view_space_particle_radius[0]; g2f_view_space_center_pos = gl_in[0].gl_Position.xyz; g2f_frag_pos = g2f_view_space_center_pos + vec3(-g2f_view_space_particle_radius, -g2f_view_space_particle_radius, 0.0); gl_Position = BBProjectionMatrix * vec4(g2f_frag_pos, 1.0); EmitVertex(); g2f_frag_pos = g2f_view_space_center_pos + vec3(g2f_view_space_particle_radius, -g2f_view_space_particle_radius, 0.0); gl_Position = BBProjectionMatrix * vec4(g2f_frag_pos, 1.0); EmitVertex(); g2f_frag_pos = g2f_view_space_center_pos + vec3(-g2f_view_space_particle_radius, g2f_view_space_particle_radius, 0.0); gl_Position = BBProjectionMatrix * vec4(g2f_frag_pos, 1.0); EmitVertex(); g2f_frag_pos = g2f_view_space_center_pos + vec3(g2f_view_space_particle_radius, g2f_view_space_particle_radius, 0.0); gl_Position = BBProjectionMatrix * vec4(g2f_frag_pos, 1.0); EmitVertex(); EndPrimitive(); } <|start_filename|>Code/BBearEditor/Engine/Physics/FluidSystem/BBSPHFluidRenderer.h<|end_filename|> #ifndef BBSPHFLUIDRENDERER_H #define BBSPHFLUIDRENDERER_H #include "Base/BBRenderableObject.h" class BBSPHParticleSystem; class BBSPHFluidSystem; class BBSPHFluidRenderer : public BBRenderableObject { public: BBSPHFluidRenderer(const QVector3D &position = QVector3D(0, 0, 0)); ~BBSPHFluidRenderer(); void init(BBSPHParticleSystem *pParticleSystem, BBSPHFluidSystem *pFluidSystem); void render(BBCamera *pCamera) override; public: void switchSSF(bool bEnable); void resetFluidParticles(); private: void initSSFMaterial(); BBMaterial *m_pScreenQuadXFilterMaterial; BBMaterial *m_pScreenQuadYFilterMaterial; BBMaterial *m_pScreenQuadNormalMaterial; BBMaterial *m_pScreenQuadShadingMaterial; private: BBSPHParticleSystem *m_pParticleSystem; BBSPHFluidSystem *m_pFluidSystem; const int m_nSSFGBufferMaterialIndex; }; #endif // BBSPHFLUIDRENDERER_H <|start_filename|>Code/BBearEditor/Editor/Render/BBPreviewOpenGLWidget.cpp<|end_filename|> #include "BBPreviewOpenGLWidget.h" #include "Scene/BBScene.h" #include "Utils/BBUtils.h" #include "3D/BBModel.h" #include "Scene/BBRendererManager.h" #include "Render/BBMaterial.h" BBPreviewOpenGLWidget::BBPreviewOpenGLWidget(QWidget *pParent) : BBOpenGLWidget(pParent) { BBRendererManager::bindPreviewOpenGLWidget(this); // sphere for preview m_pSphere = NULL; } void BBPreviewOpenGLWidget::updateMaterialSphere(BBMaterial *pMaterial) { BB_PROCESS_ERROR_RETURN(m_pSphere); BB_PROCESS_ERROR_RETURN(pMaterial); m_pSphere->setCurrentMaterial(pMaterial); update(); } void BBPreviewOpenGLWidget::showMaterialPreview(const QString &filePath) { if (!m_pSphere) { createSphere(); m_pSphere->setCurrentMaterial(BBRendererManager::loadMaterial(filePath)); } else { m_pSphere->setActivity(true); m_pSphere->setVisibility(false); } update(); } void BBPreviewOpenGLWidget::removeMaterialPreview() { BB_PROCESS_ERROR_RETURN(m_pSphere); m_pSphere->setActivity(false); update(); } void BBPreviewOpenGLWidget::initializeGL() { BBOpenGLWidget::initializeGL(); m_pScene->enableSkyBox(false); m_pScene->enableHorizontalPlane(false); } void BBPreviewOpenGLWidget::createSphere() { m_pSphere = m_pScene->createModelForPreview(BB_PATH_RESOURCE_MESH(sphere.obj)); } <|start_filename|>Code/BBearEditor/Engine/Scene/CoordinateSystem/BBTransformCoordinateSystem.h<|end_filename|> #ifndef BBTRANSFORMCOORDINATESYSTEM_H #define BBTRANSFORMCOORDINATESYSTEM_H #include "Base/BBGameObject.h" class BBGameObjectSet; class BBPositionCoordinateSystem; class BBRotationCoordinateSystem; class BBScaleCoordinateSystem; class BBPositionCoordinateSystem2D; class BBRotationCoordinateSystem2D; class BBScaleCoordinateSystem2D; // Class that manages the three Coordinate system class BBTransformCoordinateSystem : public BBGameObject { public: BBTransformCoordinateSystem(); virtual ~BBTransformCoordinateSystem(); void init() override; void render(BBCamera *pCamera) override; void setSelectedObject(BBGameObject *pObject); void setSelectedObjects(QList<BBGameObject*> gameObjects, BBGameObjectSet *pSet); bool mouseMoveEvent(int x, int y, const BBRay &ray, bool bMousePressed); void setCoordinateSystem(char modeKey); bool isTransforming() { return m_bTransforming; } void stopTransform(); void update(); inline BBGameObject* getSelectedObject() { return m_pSelectedObject; } inline char getTransformModeKey() { return m_ModeKey; } private: void switchSpaceMode(const BBCoordinateSystemSpaceMode &eMode); BBCoordinateSystemSpaceMode m_eSpaceMode; BBPositionCoordinateSystem *m_pPositionCoordinateSystem; BBRotationCoordinateSystem *m_pRotationCoordinateSystem; BBScaleCoordinateSystem *m_pScaleCoordinateSystem; BBPositionCoordinateSystem2D *m_pPositionCoordinateSystem2D; BBRotationCoordinateSystem2D *m_pRotationCoordinateSystem2D; BBScaleCoordinateSystem2D *m_pScaleCoordinateSystem2D; char m_PositionCoordinateSystemModeKey = 'W'; char m_RotationCoordinateSystemModeKey = 'E'; char m_ScaleCoordinateSystemModeKey = 'R'; char m_ModeKey; BBGameObject *m_pSelectedObject; QList<BBGameObject*> m_SelectedObjects; bool m_bTransforming; }; #endif // BBTRANSFORMCOORDINATESYSTEM_H <|start_filename|>Resources/shaders/PBR/FromUnity.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBTexcoord; attribute vec4 BBNormal; attribute vec4 BBTangent; attribute vec4 BBBiTangent; varying vec4 V_Texcoord; varying vec4 V_World_pos; varying mat3 V_TBN; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { V_Texcoord = BBTexcoord; V_World_pos = BBModelMatrix * BBPosition; vec3 T = normalize(vec3(BBModelMatrix * BBTangent)); vec3 B = normalize(vec3(BBModelMatrix * BBBiTangent)); vec3 N = normalize(vec3(BBModelMatrix * BBTangent)); V_TBN = mat3(T, B, N); gl_Position = BBProjectionMatrix * BBViewMatrix * V_World_pos; } <|start_filename|>Code/BBearEditor/Editor/MainInterface/BBTitleBar.cpp<|end_filename|> #include "BBTitleBar.h" #include "ui_BBTitleBar.h" #include "Utils/BBUtils.h" BBTitleBar::BBTitleBar(QWidget *parent) : QWidget(parent), m_pUi(new Ui::BBTitleBar) { m_pUi->setupUi(this); this->m_pParent = parent; m_pUi->buttonMaximize->setCheckable(true); m_pUi->buttonMaximize->setChecked(false); m_pUi->buttonRun->setCheckable(true); m_pUi->buttonRun->setChecked(false); QObject::connect(m_pUi->buttonRun, SIGNAL(clicked(bool)), this, SLOT(buttonRunClicked(bool))); } BBTitleBar::~BBTitleBar() { BB_SAFE_DELETE(m_pUi); } void BBTitleBar::closeWindow() { m_pParent->close(); } void BBTitleBar::minimizeWindow() { m_pParent->showMinimized(); } void BBTitleBar::maximizeWindow() { if (m_pUi->buttonMaximize->isChecked()) m_pParent->showFullScreen(); else m_pParent->showMaximized(); } void BBTitleBar::buttonRunClicked(bool trigger) { run(trigger); } void BBTitleBar::mouseDoubleClickEvent(QMouseEvent *event) { QWidget::mouseDoubleClickEvent(event); m_pParent->move(0, 0); } <|start_filename|>Code/BBearEditor/Engine/Scene/BBSceneManager.cpp<|end_filename|> #include "BBSceneManager.h" #include "Serializer/BBScene.pb.h" #include <QTreeWidgetItem> #include "Utils/BBUtils.h" #include "Render/BBEditViewOpenGLWidget.h" #include "BBScene.h" #include "Base/BBGameObject.h" #include "SceneManager/BBHierarchyTreeWidget.h" #include "2D/BBCanvas.h" #include "2D/BBSpriteObject2D.h" #include "Lighting/GI/BBGlobalIllumination.h" #include "RayTracing/BBRayTracker.h" #include "Shadow/BBShadow.h" #include "Volumetric/BBVolumetricCloud.h" QMap<QTreeWidgetItem*, BBGameObject*> BBSceneManager::m_ObjectMap; QString BBSceneManager::m_CurrentSceneFilePath; BBEditViewOpenGLWidget* BBSceneManager::m_pEditViewOpenGLWidget = nullptr; BBScene* BBSceneManager::m_pScene = nullptr; BBHierarchyTreeWidget* BBSceneManager::m_pHierarchyTreeWidget = nullptr; bool BBSceneManager::m_bSceneChanged = true; BBRenderQueue* BBSceneManager::getRenderQueue() { return m_pScene->getRenderQueue(); } BBCamera* BBSceneManager::getCamera() { return m_pScene->getCamera(); } void BBSceneManager::bindEditViewOpenGLWidget(BBEditViewOpenGLWidget *pWidget) { m_pEditViewOpenGLWidget = pWidget; m_pScene = m_pEditViewOpenGLWidget->getScene(); } void BBSceneManager::insertObjectMap(QTreeWidgetItem *pItem, BBGameObject *pGameObject) { m_ObjectMap.insert(pItem, pGameObject); changeScene(); } void BBSceneManager::removeObjectMap(QTreeWidgetItem *pItem) { m_ObjectMap.remove(pItem); changeScene(); } QTreeWidgetItem* BBSceneManager::getSceneTreeItem(BBGameObject *pGameObject) { return m_ObjectMap.key(pGameObject); } QList<QTreeWidgetItem*> BBSceneManager::getSceneTreeItems(const QList<BBGameObject*> &gameObjects) { QList<QTreeWidgetItem*> items; QMap<QTreeWidgetItem*, BBGameObject*>::Iterator it; for (it = m_ObjectMap.begin(); it != m_ObjectMap.end(); it++) { QTreeWidgetItem *pItem = it.key(); BBGameObject *pGameObject = it.value(); if (gameObjects.contains(pGameObject)) { items.append(pItem); } } return items; } BBGameObject* BBSceneManager::getGameObject(QTreeWidgetItem *pItem) { return m_ObjectMap.value(pItem); } bool BBSceneManager::isSceneSwitched(const QString &filePath) { if (m_CurrentSceneFilePath == filePath) { return false; } else { return true; } } void BBSceneManager::changeScene(BBGameObject *pGameObject) { if (!pGameObject || pGameObject->getClassName() == BB_CLASSNAME_MODEL || pGameObject->getClassName() == BB_CLASSNAME_DIRECTIONAL_LIGHT || pGameObject->getClassName() == BB_CLASSNAME_POINT_LIGHT || pGameObject->getClassName() == BB_CLASSNAME_SPOT_LIGHT) { BB_PROCESS_ERROR_RETURN(!m_bSceneChanged); m_bSceneChanged = true; m_pEditViewOpenGLWidget->updateEditViewTitle(); } } void BBSceneManager::openScene(const QString &filePath) { // clear the last opened scene removeScene(); int nLength = -1; char *pData = BBUtils::loadFileContent(filePath.toStdString().c_str(), nLength); BB_PROCESS_ERROR_RETURN(pData); BBSerializer::BBScene scene; scene.ParseFromArray(pData, nLength); QList<QTreeWidgetItem*> items; // load scene + tree int count = scene.gameobject_size(); for (int i = 0; i < count; i++) { BBSerializer::BBGameObject gameObject = scene.gameobject(i); QString className = QString::fromStdString(gameObject.classname()); BBGameObject *pGameObject = NULL; if (className == BB_CLASSNAME_MODEL) { pGameObject = m_pEditViewOpenGLWidget->createModel(gameObject); } items.append(m_ObjectMap.key(pGameObject)); } // reconstruct the parent connect of the tree m_pHierarchyTreeWidget->takeTopLevelItems(); QList<QTreeWidgetItem*> topLevelItems; for (int i = 0; i < count; i++) { QTreeWidgetItem *pItem = items.at(i); int parentIndex = scene.item(i).parentindex(); if (parentIndex < 0) { topLevelItems.append(pItem); } else { QTreeWidgetItem *pParent = items.at(parentIndex); pParent->addChild(pItem); } } m_pHierarchyTreeWidget->reconstruct(topLevelItems); BB_SAFE_DELETE(pData); m_CurrentSceneFilePath = filePath; m_pEditViewOpenGLWidget->updateEditViewTitle(); } void BBSceneManager::saveScene(const QString &filePath) { BBSerializer::BBScene scene; // for finding index of items QList<QTreeWidgetItem*> items; for (QMap<QTreeWidgetItem*, BBGameObject*>::Iterator it = m_ObjectMap.begin(); it != m_ObjectMap.end(); it++) { items.append(it.key()); } for (QMap<QTreeWidgetItem*, BBGameObject*>::Iterator it = m_ObjectMap.begin(); it != m_ObjectMap.end(); it++) { QTreeWidgetItem *pKey = it.key(); BBGameObject *pValue = it.value(); BBSerializer::BBHierarchyTreeWidgetItem *pItem = scene.add_item(); if (pKey->parent()) { pItem->set_parentindex(items.indexOf(pKey->parent())); } else { pItem->set_parentindex(-1); } BBSerializer::BBGameObject *pGameObject = scene.add_gameobject(); pGameObject->set_name(pValue->getName().toStdString().c_str()); pGameObject->set_classname(pValue->getClassName().toStdString().c_str()); pGameObject->set_filepath(pValue->getFilePath().toStdString().c_str()); BBSerializer::BBVector3f *pPosition = pGameObject->mutable_position(); setVector3f(pValue->getPosition(), pPosition); BBSerializer::BBVector3f *pLocalPosition = pGameObject->mutable_localposition(); setVector3f(pValue->getLocalPosition(), pLocalPosition); BBSerializer::BBVector3f *pRotation = pGameObject->mutable_rotation(); setVector3f(pValue->getRotation(), pRotation); BBSerializer::BBVector3f *pLocalRotation = pGameObject->mutable_localrotation(); setVector3f(pValue->getLocalRotation(), pLocalRotation); BBSerializer::BBVector3f *pScale = pGameObject->mutable_scale(); setVector3f(pValue->getScale(), pScale); BBSerializer::BBVector3f *pLocalScale = pGameObject->mutable_localscale(); setVector3f(pValue->getLocalScale(), pLocalScale); } int nLength = scene.ByteSizeLong() + 1; char szBuffer[nLength] = {0}; scene.SerializeToArray(szBuffer, nLength); BBUtils::saveToFile(filePath.toStdString().c_str(), szBuffer, nLength); m_bSceneChanged = false; m_CurrentSceneFilePath = filePath; m_pEditViewOpenGLWidget->updateEditViewTitle(); } void BBSceneManager::removeScene() { BB_PROCESS_ERROR_RETURN(m_pEditViewOpenGLWidget); m_pScene->clear(); for (QMap<QTreeWidgetItem*, BBGameObject*>::Iterator it = m_ObjectMap.begin(); it != m_ObjectMap.end(); it++) { delete it.key(); } m_ObjectMap.clear(); m_bSceneChanged = false; m_CurrentSceneFilePath.clear(); } void BBSceneManager::enableDeferredRendering(int nAlgorithmIndex, int nSubAlgorithmIndex, bool bEnable) { // 1 : GI switch (nAlgorithmIndex) { case 0: BBRayTracker::enable(nSubAlgorithmIndex, bEnable); break; case 1: BBGlobalIllumination::enable(nSubAlgorithmIndex, bEnable); break; case 2: BBShadow::enable(nSubAlgorithmIndex, bEnable); break; case 3: BBVolumetricCloud::enable(nSubAlgorithmIndex, bEnable); break; default: break; } } void BBSceneManager::addSpriteObject2DForCanvas(BBCanvas *pCanvas, BBSpriteObject2D *pSpriteObject2D) { QTreeWidgetItem *pCanvasItem = getSceneTreeItem(pCanvas); QTreeWidgetItem *pSpriteObjectItem = getSceneTreeItem(pSpriteObject2D); m_pHierarchyTreeWidget->takeTopLevelItem(m_pHierarchyTreeWidget->indexOfTopLevelItem(pSpriteObjectItem)); pCanvasItem->addChild(pSpriteObjectItem); m_pHierarchyTreeWidget->setItemExpanded(pCanvasItem, true); m_pHierarchyTreeWidget->setCurrentItem(pSpriteObjectItem); } void BBSceneManager::setVector3f(const QVector3D &value, BBSerializer::BBVector3f *&pOutVector3f) { pOutVector3f->set_x(value.x()); pOutVector3f->set_y(value.y()); pOutVector3f->set_z(value.z()); } <|start_filename|>Code/BBearEditor/Editor/Common/BBResizableWidget.h<|end_filename|> #ifndef BBRESIZABLEWIDGET_H #define BBRESIZABLEWIDGET_H #include <QWidget> class BBResizableWidget : public QWidget { Q_OBJECT public: explicit BBResizableWidget(QWidget *parent = nullptr); QSize sizeHint() const; void updateSizeHint(const QSize &size); private: QSize m_Size; }; #endif // BBRESIZABLEWIDGET_H <|start_filename|>Resources/shaders/GI/SSAO_Blur.frag<|end_filename|> #version 430 core in vec2 v2f_texcoord; layout (location = 0) out vec4 FragColor; uniform sampler2D SSAOTex; uniform sampler2D AlbedoTex; void main(void) { vec2 texel_size = 1.0 / vec2(textureSize(SSAOTex, 0)); float result = 0.0; for (int x = -2; x < 2; x++) { for (int y = -2; y < 2; y++) { vec2 offset = vec2(float(x), float(y)) * texel_size; result += texture(SSAOTex, v2f_texcoord + offset).r; } } result = result / (4.0 * 4.0); vec3 albedo = texture(AlbedoTex, v2f_texcoord).xyz; FragColor = vec4(albedo * result, 1.0); } <|start_filename|>Code/BBearEditor/Editor/SceneManager/BBHierarchyTreeWidget.h<|end_filename|> #ifndef BBHIERARCHYTREEWIDGET_H #define BBHIERARCHYTREEWIDGET_H #include "BBTreeWidget.h" class BBGameObject; class BBGameObjectSet; class BBHierarchyTreeWidget : public BBTreeWidget { Q_OBJECT public: explicit BBHierarchyTreeWidget(QWidget *parent = 0); QString getMimeType() { return BB_MIMETYPE_HIERARCHYTREEWIDGET; } void takeTopLevelItems(); void reconstruct(const QList<QTreeWidgetItem*> &topLevelItems); private: void setMenu() override; void pasteOne(QTreeWidgetItem *pSource, QTreeWidgetItem* pTranscript) override; void deleteOne(QTreeWidgetItem *pItem) override; bool moveItem() override; bool moveItemFromFileList(const QMimeData *pMimeData) override; bool moveItemFromOthers(const QMimeData *pMimeData) override; void moveItemToIndicator(); QIcon getClassIcon(const QString &className); int getDragIconColumnIndex() override { return 1; } signals: void createModel(const QString &filePath); void createLight(const QString &fileName); void setCoordinateSystemSelectedObject(BBGameObject *pGameObject); void setCoordinateSystemSelectedObjects(const QList<BBGameObject*> &gameObjects, BBGameObjectSet *pSet); void showGameObjectProperty(BBGameObject *pGameObject); void showGameObjectSetProperty(BBGameObject *pCenterGameObject, const QList<BBGameObject*> &gameObjectSet); void deleteGameObject(BBGameObject *pGameObject); void copyGameObject(BBGameObject *pSourceObject, QTreeWidgetItem *pTranscriptItem); void lookAtGameObject(BBGameObject *pGameObject); void removeCurrentItemInFileList(); private slots: void addGameObject(BBGameObject *pGameObject); void addGameObject(BBGameObject *pGameObject, QTreeWidgetItem *pItem); void selectPickedItem(BBGameObject *pGameObject); void selectPickedItems(const QList<BBGameObject*> &gameObjects); void updateMultipleSelectedItems(BBGameObject *pGameObject); void changeSelectedItems(); void doubleClickItem(QTreeWidgetItem *pItem, int nColumn); void deleteAction() override; void removeCurrentItem(); //private slots: // void changeGameObjectActivation(GameObject *gameObject, bool isActive); //signals: // void updateNameInInspector(GameObject *gameObject, QString newName); // void changeButtonActiveCheckStateInInspector(GameObject *gameObject, bool isActive); //private: // bool moveItemFromFileList(const QMimeData *mimeData) override; // void focusInEvent(QFocusEvent *event) override; }; #endif // BBHIERARCHYTREEWIDGET_H <|start_filename|>Resources/shaders/SkyBox/Common.frag<|end_filename|> #version 430 core #extension GL_NV_shadow_samplers_cube : enable in vec4 v2f_local_pos; layout (location = 0) out vec4 FragColor; uniform samplerCube BBSkyBox; void main(void) { FragColor = textureCube(BBSkyBox, v2f_local_pos.xyz); } <|start_filename|>Resources/shaders/NormalMap.frag<|end_filename|> varying mat3 V_TBN; varying vec4 V_Texcoord; uniform sampler2D Normal_Map; uniform sampler2D Base_Map; uniform vec4 BBLightSettings0; uniform vec4 BBLightPosition; void main(void) { vec3 normal = vec3(texture2D(Normal_Map, V_Texcoord.xy)); // 0~1 -> -1~1 normal = normal * 2.0 - vec3(1.0); normal = normalize(normal); normal = V_TBN * normal; normal = normalize(normal); float intensity = 0.0; if (BBLightSettings0.x == 1.0) { // Lambert vec3 L = normalize(BBLightPosition.xyz); intensity = max(0.0, dot(normal, L)); } vec4 final_color = texture2D(Base_Map, V_Texcoord.xy); final_color.xyz *= intensity; gl_FragColor = final_color; } <|start_filename|>Code/BBearEditor/Engine/ParticleSystem/BBParticle.cpp<|end_filename|> #include "BBParticle.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BufferObject/BBShaderStorageBufferObject.h" #include "Render/BufferObject/BBTranslateFeedbackObject.h" #include "Render/BBMaterial.h" #include "Render/Texture/BBProcedureTexture.h" #include "Render/BBRenderPass.h" #include "Render/BBDrawCall.h" #include "Math/BBMath.h" #include "Shader/BBComputeShader.h" #include "Scene/BBSceneManager.h" BBParticle::BBParticle(const QVector3D &position) : BBRenderableObject(position, QVector3D(0, 0, 0), QVector3D(1, 1, 1)) { m_pSSBO = nullptr; m_nVertexCount = 1 << 16; m_pUpdateCShader = nullptr; m_pTFO = nullptr; } BBParticle::~BBParticle() { BB_SAFE_DELETE(m_pSSBO); BB_SAFE_DELETE(m_pUpdateCShader); BB_SAFE_DELETE(m_pTFO); } void BBParticle::init() { create1(); m_pCurrentMaterial->getBaseRenderPass()->setBlendState(true); m_pCurrentMaterial->getBaseRenderPass()->setBlendFunc(GL_SRC_ALPHA, GL_ONE); m_pCurrentMaterial->getBaseRenderPass()->setZTestState(false); m_pCurrentMaterial->getBaseRenderPass()->setPointSpriteState(true); m_pCurrentMaterial->getBaseRenderPass()->setProgramPointSizeState(true); m_pCurrentMaterial->getBaseRenderPass()->setCullState(false); } void BBParticle::render(BBCamera *pCamera) { update1(pCamera); } void BBParticle::create0() { m_pVBO = new BBVertexBufferObject(180); for (int i = 0; i < 180; i++) { m_pVBO->setPosition(i, 2 * cosf(0.139626f * i), 0.0f, 2 * sinf(0.139626f * i)); m_pVBO->setColor(i, 0.1f, 0.4f, 0.6f); } m_pCurrentMaterial->init("Particles0", BB_PATH_RESOURCE_SHADER(ParticleSystem/Particles0.vert), BB_PATH_RESOURCE_SHADER(ParticleSystem/Particles0.frag)); BBProcedureTexture texture; m_pCurrentMaterial->getBaseRenderPass()->setSampler2D(LOCATION_TEXTURE(0), texture.create0(128)); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setSSBO(m_pSSBO); pDrawCall->setVBO(m_pVBO, GL_POINTS, 0, m_pVBO->getVertexCount()); appendDrawCall(pDrawCall); } void BBParticle::update0(BBCamera *pCamera) { setRotation(10, QVector3D(0, 1, 0)); for (int i = 0; i < m_pVBO->getVertexCount(); i++) { m_pVBO->setNormal(i, 0, 0.1f * i, 0); if (i > 90) break; } for (int i = 0; i < m_pVBO->getVertexCount(); i++) { float r = 0.02f * i; if (r > 1.0f) r -= 1.0f; m_pVBO->setColor(i, r, 0.4f, 0.6f); } m_pVBO->submitData(); BBRenderableObject::render(pCamera); } void BBParticle::create1() { m_pSSBO = new BBShaderStorageBufferObject(m_nVertexCount); m_nIndexCount = 6 * m_nVertexCount; m_pIndexes = new unsigned short[m_nIndexCount]; unsigned short *pCurrent = m_pIndexes; for (int i = 0; i < m_nVertexCount; i++) { m_pSSBO->setPosition(i, sfrandom(), sfrandom(), sfrandom()); m_pSSBO->setColor(i, 0.1f, 0.4f, 0.6f); // used as the speed of update m_pSSBO->setNormal(i, 0.0f, 0.0f, 0.0f); unsigned short index(i << 2); *(pCurrent++) = index; *(pCurrent++) = index + 1; *(pCurrent++) = index + 2; *(pCurrent++) = index; *(pCurrent++) = index + 2; *(pCurrent++) = index + 3; } m_pCurrentMaterial->init("PointSpriteSSBO", BB_PATH_RESOURCE_SHADER(ParticleSystem/Particles1.vert), BB_PATH_RESOURCE_SHADER(ParticleSystem/Particles1.frag)); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setSSBO(m_pSSBO); pDrawCall->setEBO(m_pEBO, GL_TRIANGLES, m_nIndexCount, 0); appendDrawCall(pDrawCall); // compute shader of update m_pUpdateCShader = new BBComputeShader(); m_pUpdateCShader->init(BB_PATH_RESOURCE_SHADER(ParticleSystem/UpdateParticles1.shader)); } void BBParticle::update1(BBCamera *pCamera) { m_pSSBO->bind(); // Corresponding to "layout (local_size_x = 256, local_size_y = 1, local_size_z = 1) in;" in the compute shader m_pUpdateCShader->bind(m_nVertexCount / 256, 1, 1); m_pDrawCalls->renderOnePassSSBO(pCamera); } void BBParticle::create2() { m_pVBO = new BBVertexBufferObject(3); m_pVBO->setPosition(0, 0.0f, 0.0f, 0.0f); m_pVBO->setPosition(1, 1.0f, 0.0f, 0.0f); m_pVBO->setPosition(2, 0.0f, 1.0f, 0.0f); // Parameter 3 corresponds to VBO DrawPrimitiveType m_pTFO = new BBTranslateFeedbackObject(m_pVBO->getVertexCount(), GL_STATIC_DRAW, GL_TRIANGLES); m_pCurrentMaterial->init("Particles2-0", BB_PATH_RESOURCE_SHADER(ParticleSystem/Particles2-0.vert), BB_PATH_RESOURCE_SHADER(ParticleSystem/Particles2-0.frag)); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, GL_TRIANGLES, 0, m_pVBO->getVertexCount()); appendDrawCall(pDrawCall); m_pTFO->bind(); m_pVBO->bind(); m_pCurrentMaterial->getBaseRenderPass()->bind(BBSceneManager::getCamera()); m_pVBO->draw(GL_TRIANGLES, 0, m_pVBO->getVertexCount()); m_pVBO->unbind(); m_pTFO->unbind(); m_pCurrentMaterial->getBaseRenderPass()->unbind(); m_pTFO->debug(); } void BBParticle::update2(BBCamera *pCamera) { BBRenderableObject::render(pCamera); } <|start_filename|>Resources/shaders/dissolve.frag<|end_filename|> #version 450 core in vec4 V_Texcoord; uniform sampler2D Texture0; uniform sampler2D Texture1; uniform sampler2D DissolveTex_R; uniform sampler2D RampTex_RGB; uniform float clip; out vec4 frag_color; void main(void) { vec4 dissolve_color = texture(DissolveTex_R, V_Texcoord.xy); vec2 dissolve_value = clamp((dissolve_color.rr - clip) / 0.1, 0.0, 1.0); vec4 ramp_color = texture(RampTex_RGB, dissolve_value); if (dissolve_color.r < clip) { discard; } frag_color = texture(Texture0, V_Texcoord.xy) + texture(Texture1, V_Texcoord.xy) + ramp_color; } <|start_filename|>Code/BBearEditor/Engine/Physics/Constraint/BBBendingConstraint.cpp<|end_filename|> #include "BBBendingConstraint.h" #include "../Body/BBBaseBody.h" BBBendingConstraint::BBBendingConstraint(BBBaseBody *pBody, int nParticleIndex1, int nParticleIndex2, int nParticleIndex3, float fElasticModulus) : BBBaseConstraint(pBody) { m_nParticleIndex1 = nParticleIndex1; m_nParticleIndex2 = nParticleIndex2; m_nParticleIndex3 = nParticleIndex3; m_fElasticModulus = fElasticModulus; QVector3D center = (pBody->getParticlePosition(nParticleIndex1) + pBody->getParticlePosition(nParticleIndex2) + pBody->getParticlePosition(nParticleIndex3)) / 3.0f; m_fOriginLength = pBody->getParticlePosition(nParticleIndex3).distanceToPoint(center); } void BBBendingConstraint::doConstraint(float fDeltaTime) { QVector3D position1 = m_pBody->getParticlePredictedPosition(m_nParticleIndex1); QVector3D position2 = m_pBody->getParticlePredictedPosition(m_nParticleIndex2); QVector3D position3 = m_pBody->getParticlePredictedPosition(m_nParticleIndex3); QVector3D center = (position1 + position2 + position3) / 3.0f; QVector3D dir = position3 - center; float d = dir.length(); float diff = 1.0f - m_fOriginLength / d; QVector3D force = diff * dir; QVector3D f = m_fElasticModulus / 2.0f * force * fDeltaTime; m_pBody->setParticlePredictedPosition(m_nParticleIndex1, position1 + f); m_pBody->setParticlePredictedPosition(m_nParticleIndex2, position2 + f); f = -2.0f * f; m_pBody->setParticlePredictedPosition(m_nParticleIndex3, position3 + f); } <|start_filename|>Resources/shaders/translucent.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBTexcoord; attribute vec4 BBNormal; varying vec3 V_view_dir; varying vec4 V_texcoord; varying vec4 V_normal; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; uniform vec4 BBCameraPosition; void main() { vec4 world_space_pos = BBModelMatrix * BBPosition; V_view_dir = normalize(BBCameraPosition.xyz - world_space_pos.xyz); V_texcoord = BBTexcoord; V_normal.xyz = mat3(transpose(inverse(BBModelMatrix))) * BBNormal.xyz; gl_Position = BBProjectionMatrix * BBViewMatrix * world_space_pos; } <|start_filename|>Code/BBearEditor/Engine/2D/BBSpriteObject2D.h<|end_filename|> #ifndef BBSPRITEOBJECT2D_H #define BBSPRITEOBJECT2D_H #include "Base/BBGameObject.h" class BBSprite2D; class BBAABBBoundingBox2D; class BBSpriteObject2D : public BBGameObject { public: BBSpriteObject2D(int x = 0, int y = 0, int nWidth = 50, int nHeight = 50); ~BBSpriteObject2D(); void init() override; void render(BBCanvas *pCanvas) override; void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; void setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform = true) override; void setRotation(const QVector3D &rotation, bool bUpdateLocalTransform = true) override; void setScale(const QVector3D &scale, bool bUpdateLocalTransform = true) override; private: BBSprite2D *m_pSprite2D; BBAABBBoundingBox2D *m_pAABBBoundingBox2D; }; #endif // BBSPRITEOBJECT2D_H <|start_filename|>Code/BBearEditor/Engine/Render/Lighting/GI/BBSSAOGlobalIllumination.h<|end_filename|> #ifndef BBSSAOGLOBALILLUMINATION_H #define BBSSAOGLOBALILLUMINATION_H #include <vector> #include <QVector3D> class BBScene; class BBSSAOGlobalIllumination { public: static void open(BBScene *pScene); static void setSSAOPass(BBScene *pScene); static void setSSAOBlurPass(BBScene *pScene); static float* generateKernel(); static float* generateNoise(); }; #endif // BBSSAOGLOBALILLUMINATION_H <|start_filename|>Resources/shaders/HeatDistort.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBTexcoord; varying vec4 V_Texcoord; varying vec4 V_ScreenUV; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; uniform vec4 BBScreenParameters; uniform vec4 BBTime; void main() { V_Texcoord.xy = BBTexcoord.xy + vec2(0.0001, 0.0001) * BBTime.z; vec4 pos = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * BBPosition; V_ScreenUV.xyz = pos.xyz / pos.w * 0.5 + 0.5; // (-1, 1) ~ (0, 1) gl_Position = pos; } <|start_filename|>Resources/shaders/ParticleSystem/UpdateParticles1.shader<|end_filename|> #version 430 struct Vertex { vec4 BBPosition; vec4 BBColor; vec4 BBTexcoord; vec4 BBNormal; vec4 BBTangent; vec4 BBBiTangent; }; layout (std140, binding = 0) buffer Bundle { Vertex vertexes[]; } bundle; layout (local_size_x = 256, local_size_y = 1, local_size_z = 1) in; uniform sampler2D NoiseTex; vec3 computeV(vec3 pos) { vec3 v = vec3(0.0); float gain = 1.0; float expend = 1.0; for (int i = 0; i < 4; i++) { v += texture(NoiseTex, vec2((pos * expend) / 30.0)).xyz * gain; expend *= 2.0; gain *= 0.5; } // return v; return vec3(0.05); } void main() { // An effective three-dimensional index of the location of the current execution unit in the global workgroup // linear uint particle_id = gl_GlobalInvocationID.x; // 2 ^ 16 if (particle_id > 65536) return; vec3 pos = bundle.vertexes[particle_id].BBPosition.xyz; vec3 v = bundle.vertexes[particle_id].BBNormal.xyz; v += computeV(pos * 10.0) * 0.001; pos += v; // Slow down v *= 0.95; bundle.vertexes[particle_id].BBPosition = vec4(pos, 1.0); bundle.vertexes[particle_id].BBNormal = vec4(v, 1.0); } <|start_filename|>Code/BBearEditor/Engine/Math/BBPerlinNoise.cpp<|end_filename|> #include "BBPerlinNoise.h" #include "BBMath.h" #include <QDebug> // http://www.realtimerendering.com/raytracing/Ray%20Tracing_%20The%20Next%20Week.pdf QVector3D *BBPerlinNoise::m_pRandFloat = BBPerlinNoise::generateRandFloat(); int *BBPerlinNoise::m_pPermuteX = BBPerlinNoise::generatePermute(); int *BBPerlinNoise::m_pPermuteY = BBPerlinNoise::generatePermute(); int *BBPerlinNoise::m_pPermuteZ = BBPerlinNoise::generatePermute(); BBPerlinNoise::BBPerlinNoise() { } float BBPerlinNoise::getNoise(const QVector3D &p) { // Version 1: Chessboard // int i = int(16 * p.x()) & 255; // int j = int(16 * p.y()) & 255; // int k = int(16 * p.z()) & 255; // return m_pRandFloat[m_pPermuteX[i] ^ m_pPermuteY[j] ^ m_pPermuteZ[k]]; // Version 2: smoothing // float u = p.x() - floor(p.x()); // float v = p.y() - floor(p.y()); // float w = p.z() - floor(p.z()); // int i = floor(p.x()); // int j = floor(p.y()); // int k = floor(p.z()); // float c[2][2][2]; // for (int di = 0; di < 2; di++) // { // for (int dj = 0; dj < 2; dj++) // { // for (int dk = 0; dk < 2; dk++) // { // c[di][dj][dk] = m_pRandFloat[m_pPermuteX[(i + di) & 255] ^ m_pPermuteY[(j + dj) & 255] ^ m_pPermuteZ[(k + dk) & 255]]; // } // } // } // return trilinearInterpolate(c, u, v, w); // Version 3: obvious grid features, use a hermite cubic to round off the interpolation float u = p.x() - floor(p.x()); float v = p.y() - floor(p.y()); float w = p.z() - floor(p.z()); int i = floor(p.x()); int j = floor(p.y()); int k = floor(p.z()); QVector3D c[2][2][2]; for (int di = 0; di < 2; di++) { for (int dj = 0; dj < 2; dj++) { for (int dk = 0; dk < 2; dk++) { c[di][dj][dk] = m_pRandFloat[m_pPermuteX[(i + di) & 255] ^ m_pPermuteY[(j + dj) & 255] ^ m_pPermuteZ[(k + dk) & 255]]; } } } return trilinearInterpolate(c, u, v, w) * 0.5f + 0.5f; } /** * @brief BBPerlinNoise::generateTurbulence Used directly, turbulence gives a sort of camouflage netting appearance * @param p * @param nDepth * @return */ float BBPerlinNoise::getTurbulenceNoise(const QVector3D &p, int nDepth) { float sum = 0.0f; QVector3D tmp = p; float w = 1.0f; for (int i = 0; i < nDepth; i++) { sum += w * getNoise(tmp); w *= 0.5f; tmp *= 2.0f; } return fabs(sum); } QVector3D* BBPerlinNoise::generateRandFloat() { QVector3D *p = new QVector3D[256]; for (int i = 0; i < 256; i++) { // irregular directions p[i] = QVector3D(sfrandom(), sfrandom(), sfrandom()).normalized(); } return p; } int* BBPerlinNoise::generatePermute() { int *p = new int[256]; for (int i = 0; i < 256; i++) { p[i] = i; } permute(p, 256); return p; } void BBPerlinNoise::permute(int *p, int n) { for (int i = n - 1; i > 0; i--) { int target = int(frandom() * (i + 1)); int tmp = p[i]; p[i] = p[target]; p[target] = tmp; } } <|start_filename|>Code/BBearEditor/Engine/Math/BBMatrix.h<|end_filename|> #ifndef BBMATRIX_H #define BBMATRIX_H class BBMatrix { public: static void SVDdecomposition(float w[3], float u[9], float v[9], float eps); private: static inline float pythag(const float a, const float b); template<class T> static inline T sign(const T &a, const T &b) { return b >= 0 ? (a >= 0 ? a : -a) : (a >= 0 ? -a : a); } }; #endif // BBMATRIX_H <|start_filename|>Code/BBearEditor/Editor/Render/BBOfflineOpenGLWidget.cpp<|end_filename|> #include "BBOfflineOpenGLWidget.h" #include "Scene/BBScene.h" #include "OfflineRenderer/BBOfflineRenderer.h" BBOfflineOpenGLWidget::BBOfflineOpenGLWidget(QWidget *pParent) : BBOpenGLWidget(pParent) { m_pOfflineRenderer = nullptr; } BBOfflineOpenGLWidget::~BBOfflineOpenGLWidget() { BB_SAFE_DELETE(m_pOfflineRenderer); } void BBOfflineOpenGLWidget::initializeGL() { BBOpenGLWidget::initializeGL(); m_pScene->enableHorizontalPlane(false); m_pOfflineRenderer = new BBOfflineRenderer(m_pScene); m_pOfflineRenderer->createTestScene(); } void BBOfflineOpenGLWidget::resizeGL(int nWidth, int nHeight) { BBOpenGLWidget::resizeGL(nWidth, nHeight); } <|start_filename|>Code/BBearEditor/Engine/Render/BufferObject/BBElementBufferObject.cpp<|end_filename|> #include "BBElementBufferObject.h" #include "Utils/BBUtils.h" #include <QOpenGLBuffer> BBElementBufferObject::BBElementBufferObject(int nIndexCount) : BBBufferObject() { setSize(nIndexCount); } void BBElementBufferObject::setSize(int nIndexCount, GLenum hint) { m_Name = createBufferObject(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short) * nIndexCount, hint, nullptr); } void BBElementBufferObject::submitData(const unsigned short *pIndexes, int nIndexCount) { updateData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short) * nIndexCount, pIndexes); } void BBElementBufferObject::draw(GLenum eDrawPrimitiveType, int nIndexCount, int nDrawStartIndex) { glDrawElements(eDrawPrimitiveType, nIndexCount, GL_UNSIGNED_SHORT, (void*) (sizeof(unsigned short) * nDrawStartIndex)); } <|start_filename|>Resources/shaders/GI/Template.frag<|end_filename|> #version 430 core in vec2 v2f_texcoord; layout (location = 0) out vec4 FragColor; uniform sampler2D AlbedoTex; void main(void) { FragColor = texture(AlbedoTex, v2f_texcoord); } <|start_filename|>Resources/shaders/Physics/FluidSystem/SSF_FS_1_GBuffer.frag<|end_filename|> #version 430 core in float g2f_view_space_particle_radius; in vec3 g2f_view_space_center_pos; in vec3 g2f_frag_pos; layout (location = 0) out float Depth; layout (location = 1) out float Thickness; uniform mat4 BBProjectionMatrix; void main() { // Cull to circle float r = distance(g2f_view_space_center_pos, g2f_frag_pos); if (r > g2f_view_space_particle_radius) { discard; } float depth = sqrt(g2f_view_space_particle_radius * g2f_view_space_particle_radius - r * r); float view_space_depth = depth + g2f_frag_pos.z; vec4 clip_space_pos = BBProjectionMatrix * vec4(view_space_depth, view_space_depth, view_space_depth, 1.0); gl_FragDepth = clip_space_pos.z / clip_space_pos.w * 0.5 + 0.5; Depth = -view_space_depth; Thickness = 2.0 * depth; } <|start_filename|>Code/BBearEditor/Engine/Render/RayTracing/BBRayTracker.h<|end_filename|> #ifndef BBRAYTRACKER_H #define BBRAYTRACKER_H class BBRayTracker { public: static void enable(int nAlgorithmIndex, bool bEnable); // void open(); // void close(); // void onWindowResize(int nWidth, int nHeight); //private slots: // void render(); //private: // void updateWindow(); // QColor getPixelColor(int x, int y); //private: // BBScene *m_pScene; // QThread *m_pRenderThread; // int m_nPixelCount; // int m_nCurrentPixel; // int m_nViewportWidth; // int m_nViewportHeight; // QImage m_Image; }; #endif // BBRAYTRACKER_H <|start_filename|>Code/BBearEditor/Editor/Render/BBOpenGLWidget.h<|end_filename|> #ifndef BBOPENGLWIDGET_H #define BBOPENGLWIDGET_H #include "Render/BBBaseRenderComponent.h" #include <QOpenGLWidget> class BBScene; class BBRenderThread; class BBOpenGLWidget : public QOpenGLWidget, protected QOpenGLFunctions { Q_OBJECT public: explicit BBOpenGLWidget(QWidget *parent = 0); virtual ~BBOpenGLWidget(); inline BBScene* getScene() { return m_pScene; } protected: void initializeGL() override; void resizeGL(int width, int height) override; void paintGL() override; BBScene *m_pScene; }; #endif // BBOPENGLWIDGET_H <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBFluidRendererManager.h<|end_filename|> #ifndef BBFLUIDRENDERERMANAGER_H #define BBFLUIDRENDERERMANAGER_H #include "BBGroupManager.h" class BBSPHFluidRenderer; class BBFluidRendererManager : public BBGroupManager { Q_OBJECT public: BBFluidRendererManager(BBSPHFluidRenderer *pFluidRenderer, QWidget *pParent = 0); ~BBFluidRendererManager(); private slots: void switchSSF(bool bEnable); void resetFluidParticles(); private: BBSPHFluidRenderer *m_pFluidRenderer; }; #endif // BBFLUIDRENDERERMANAGER_H <|start_filename|>Resources/shaders/SkyBox/Equirectangular.frag<|end_filename|> #version 330 core in vec3 v2f_local_pos; layout (location = 0) out vec4 FragColor; uniform sampler2D BBSkyBoxEquirectangularMap; const vec2 invAtan = vec2(0.1591, 0.3183); vec2 calculateSampleSphericalMap(vec3 v) { vec2 uv = vec2(atan(v.z, v.x), asin(v.y)); uv *= invAtan; uv += 0.5; return uv; } void main(void) { vec2 uv = calculateSampleSphericalMap(normalize(v2f_local_pos)); FragColor = texture(BBSkyBoxEquirectangularMap, uv); } <|start_filename|>Code/BBearEditor/Engine/3D/BBLightIndicator.h<|end_filename|> #ifndef BBLIGHTINDICATOR_H #define BBLIGHTINDICATOR_H #include "Base/BBRenderableObject.h" class BBLightIndicator : public BBRenderableObject { public: BBLightIndicator(); BBLightIndicator(const QVector3D &position, const QVector3D &rotation); void init() override; }; class BBDirectionalLightIndicator : public BBLightIndicator { public: BBDirectionalLightIndicator(); BBDirectionalLightIndicator(const QVector3D &position, const QVector3D &rotation); void init() override; void render(BBCamera *pCamera) override; }; class BBPointLightIndicator : public BBLightIndicator { public: BBPointLightIndicator(); BBPointLightIndicator(const QVector3D &position); void init() override; void render(BBCamera *pCamera) override; }; class BBSpotLightIndicator : public BBLightIndicator { public: BBSpotLightIndicator(); BBSpotLightIndicator(const QVector3D &position, const QVector3D &rotation); void init() override; void render(BBCamera *pCamera) override; }; #endif // BBLIGHTINDICATOR_H <|start_filename|>Code/BBearEditor/Engine/2D/BBSprite2D.h<|end_filename|> #ifndef BBSPRITE2D_H #define BBSPRITE2D_H #include "Base/BBRenderableObject2D.h" class BBSprite2D : public BBRenderableObject2D { public: BBSprite2D(int x = 0, int y = 0, int nWidth = 50, int nHeight = 50); ~BBSprite2D(); void init() override; }; #endif // BBSPRITE2D_H <|start_filename|>Resources/shaders/RayTracing.vert<|end_filename|> #version 430 core in vec4 BBPosition; in vec4 BBTexcoord; in vec4 BBNormal; out vec4 v2f_world_space_pos; out vec2 v2f_texcoord; out vec4 v2f_normal; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { v2f_texcoord = BBTexcoord.xy; v2f_normal = transpose(inverse(BBModelMatrix)) * BBNormal; v2f_normal = normalize(v2f_normal); v2f_world_space_pos = BBModelMatrix * BBPosition; gl_Position = BBProjectionMatrix * BBViewMatrix * v2f_world_space_pos; } <|start_filename|>Code/BBearEditor/Engine/Geometry/BBFrustum.h<|end_filename|> #ifndef BBFRUSTUM_H #define BBFRUSTUM_H #include <QVector3D> class BBCamera; class BBPlane; class BBGameObject; class BBAABBBoundingBox3D; class BBFrustum { public: BBFrustum(BBCamera *pCamera, int nTopLeftX, int nTopLeftY, int nWidth, int nHeight); ~BBFrustum(); bool contain(const QVector3D &point) const; public: static bool contain(const BBPlane &left, const BBPlane &right, const BBPlane &top, const BBPlane &bottom, const BBPlane &front, const BBPlane &back, const QVector3D &point); bool containWithInvertedRightAndTop(const BBPlane &left, const BBPlane &right, const BBPlane &top, const BBPlane &bottom, const QVector3D &pointOnFront, const QVector3D &pointOnBack, const QVector3D &point); protected: int m_nTopLeftX; int m_nTopLeftY; int m_nWidth; int m_nHeight; BBPlane *m_pLeft; BBPlane *m_pRight; BBPlane *m_pTop; BBPlane *m_pBottom; BBPlane *m_pFront; BBPlane *m_pBack; }; class BBFrustumCluster : public BBFrustum { public: BBFrustumCluster(BBCamera *pCamera, int x, int y, int nWidth, int nHeight, int nCountX, int nCountY, int nCountZ); ~BBFrustumCluster(); void collectPlanes(int nFrustumIndexX, int nFrustumIndexY, int nFrustumIndexZ, BBPlane &left, BBPlane &right, BBPlane &top, BBPlane &bottom, QVector3D &pointOnFront, QVector3D &pointOnBack); bool contain(int nFrustumIndexX, int nFrustumIndexY, int nFrustumIndexZ, const QVector3D &point); bool containedInSphere(int nFrustumIndexX, int nFrustumIndexY, int nFrustumIndexZ, const QVector3D &sphereCenter, float fSphereRadius); bool computeIntersectWithAABB(int nFrustumIndexX, int nFrustumIndexY, int nFrustumIndexZ, BBAABBBoundingBox3D *pAABB); private: void calculateXCrossSections(BBCamera *pCamera, int nCount); void calculateYCrossSections(BBCamera *pCamera, int nCount); void calculateZCrossSectionPoints(BBCamera *pCamera, int nCount); BBPlane *m_pXCrossSections; BBPlane *m_pYCrossSections; QVector3D *m_pZCrossSectionPoints; }; #endif // BBFRUSTUM_H <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFolderTreeWidget.h<|end_filename|> #ifndef BBFOLDERTREEWIDGET_H #define BBFOLDERTREEWIDGET_H #include "BBTreeWidget.h" #include "Utils/BBUtils.h" using namespace BBFileSystem; class QWidgetAction; class BBFolderTreeWidget : public BBTreeWidget { Q_OBJECT public: explicit BBFolderTreeWidget(QWidget *pParent = nullptr); QString getMimeType() { return BB_MIMETYPE_FOLDERTREEWIDGET; } void removeTopLevelItems(); void loadTopLevelItems(const QList<QTreeWidgetItem*> &items); void expandCurrentViewedItem(QTreeWidgetItem *pItem); void setSelectedItems(const QList<QTreeWidgetItem*> &items); private slots: void pressRootButton(); void pressSettingButton(); void clickItem(QTreeWidgetItem *pItem, int nColumn); void newFolder(); void newSceneAction(); void newMaterialAction(); void showInFolder(); void copyAction() override; void pasteAction() override; void finishRename() override; void deleteAction() override; signals: void accessFolder(const QString &filePath, QTreeWidgetItem *pItem); void newFolder(const QString &parentPath, const BBSignalSender &eSender); void newFile(const QString &parentPath, int nType); void showInFolder(const QString &filePath); void rename(QTreeWidgetItem *pParentFolderItem, const QString &oldPath, const QString &newPath); void deleteFolder(QTreeWidgetItem *pItem); void finishDeleteAction(); void moveFolders(const QList<QTreeWidgetItem*> &items, QTreeWidgetItem *pNewParentItem, bool bCopy); void moveFiles(const QList<QString> &oldFilePaths, QTreeWidgetItem *pNewParentItem, bool bCopy); private: void setMenu() override; QWidgetAction* createWidgetAction(QMenu *pParent, const QString &iconPath, const QString &name); void newFile(int nType); void deleteOne(QTreeWidgetItem *pItem) override; void dragMoveEvent(QDragMoveEvent *event) override; bool moveItem() override; bool moveItemFromFileList(const QMimeData *pMimeData) override; void updateCorrespondingWidget(QTreeWidgetItem *pItem); void recordItemExpansionState(); void resumeItemExpansionState(); const BBSignalSender m_eSenderTag; QList<QTreeWidgetItem*> m_ExpandedItems; }; #endif // BBFOLDERTREEWIDGET_H <|start_filename|>Code/BBearEditor/Editor/Render/BBEditViewDockWidget.h<|end_filename|> #ifndef BBEDITVIEWDOCKWIDGET_H #define BBEDITVIEWDOCKWIDGET_H #include <QDockWidget> class QKeyEvent; class QLabel; class BBEditViewDockWidget : public QDockWidget { Q_OBJECT public: explicit BBEditViewDockWidget(QWidget *pParent = 0); signals: void pressMoveKey(char key); void releaseMoveKey(char key); void pressTransform(char key); void pressESC(); void cancelFileListSelectedItems(); void keyPress(QKeyEvent *e); void saveCurrentScene(); private slots: void setTitleBarText(); private: void setTitleBar(); void keyPressEvent(QKeyEvent *e) override; void keyReleaseEvent(QKeyEvent *e) override; void focusInEvent(QFocusEvent *event) override; QLabel *m_pWindowTitle; }; #endif // BBEDITVIEWDOCKWIDGET_H <|start_filename|>Code/BBearEditor/Engine/Render/BBUniformUpdater.h<|end_filename|> #ifndef BBUNIFORMUPDATER_H #define BBUNIFORMUPDATER_H #include "BBBaseRenderComponent.h" #include "BBLinkedList.h" #include "BBMaterialProperty.h" /* must declare the class in advance */ class BBUniformUpdater; typedef void (BBUniformUpdater::*BBUpdateUniformFunc)(GLint location, void *pUserData, void *pPropertyValue); class BBUniformUpdater : public BBBaseRenderComponent, public BBLinkedList { public: BBUniformUpdater(GLint location, const BBUpdateUniformFunc &updateFunc, BBMaterialProperty *pTargetProperty); ~BBUniformUpdater(); inline GLint getLocation() { return m_Location; } inline BBUpdateUniformFunc getUpdateUniformFunc() { return m_UpdateUniformFunc; } inline BBMaterialProperty* getTargetProperty() { return m_pTargetProperty; } BBUniformUpdater* clone(); void updateUniform(GLint location, void *pUserData, void *pPropertyValue); void updateCameraProjectionMatrix(GLint location, void *pCamera, void *pPropertyValue); void updateCameraInverseProjectionMatrix(GLint location, void *pCamera, void *pPropertyValue); void updateCameraViewMatrix(GLint location, void *pCamera, void *pPropertyValue); void updateCameraInverseViewMatrix(GLint location, void *pCamera, void *pPropertyValue); void updateCameraPosition(GLint location, void *pCamera, void *pPropertyValue); void updateCanvas(GLint location, void *pCanvas, void *pPropertyValue); void updateCameraParameters0(GLint location, void *pCamera, void *pPropertyValue); void updateCameraParameters1(GLint location, void *pCamera, void *pPropertyValue); void updateTime(GLint location, void *pUserData, void *pPropertyValue); void updateColorFBO(GLint location, void *pCamera, void *pPropertyValue); void updateDepthFBO(GLint location, void *pCamera, void *pPropertyValue); void updateShadowMap(GLint location, void *pCamera, void *pPropertyValue); void updateLightProjectionMatrix(GLint location, void *pCamera, void *pPropertyValue); void updateLightViewMatrix(GLint location, void *pCamera, void *pPropertyValue); void updateSphericalHarmonicLightingCoefficients(GLint location, void *pCamera, void *pPropertyValue); void updateIrradianceMap(GLint location, void *pCamera, void *pPropertyValue); void updatePrefilterMapMipmap(GLint location, void *pCamera, void *pPropertyValue); void updateBRDFLUTTexture(GLint location, void *pCamera, void *pPropertyValue); void updateSkyBoxCube(GLint location, void *pCamera, void *pPropertyValue); void updateSkyBoxBackground(GLint location, void *pCamera, void *pPropertyValue); void updateFloat(GLint location, void *pCamera, void *pPropertyValue); void updateFloatArray(GLint location, void *pCamera, void *pPropertyValue); void updateMatrix4(GLint location, void *pCamera, void *pPropertyValue); void updateVector4(GLint location, void *pCamera, void *pPropertyValue); void updateVector4Array(GLint location, void *pCamera, void *pPropertyValue); void updateSampler2D(GLint location, void *pCamera, void *pPropertyValue); void updateSampler3D(GLint location, void *pCamera, void *pPropertyValue); void updateSamplerCube(GLint location, void *pCamera, void *pPropertyValue); private: GLint m_Location; BBUpdateUniformFunc m_UpdateUniformFunc; BBMaterialProperty *m_pTargetProperty; qint64 m_LastTime; }; #endif // BBUNIFORMUPDATER_H <|start_filename|>Resources/shaders/GI/FLC_TriangleCut_GS.shader<|end_filename|> #version 430 core layout (triangles) in; layout (triangle_strip, max_vertices = 51) out; in V2G { vec3 position; vec3 normal; vec2 texcoord; } v2g[]; struct G2FTriangle { vec3 positions[3]; vec3 normal; vec2 texcoord; vec2 area_and_level; }; out G2F { G2FTriangle triangle; } g2f; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; uniform vec4 BBCameraParameters; uniform int NoiseNum; uniform float Noise[64]; uniform float Sp[64]; // Divided into N stacks according to the size of the triangle uniform int SNum; const int TriangleVerticesNum = 51; float getArea(vec3 positions[3]) { // Calculate the area according to the three points of the triangle vec3 V1 = positions[1] - positions[0]; vec3 V2 = positions[2] - positions[0]; vec3 c = cross(V1, V2); return 0.5 * sqrt(dot(c, c)); } int getMaxEdge(vec3 edge[3]) { float e0 = dot(edge[0], edge[0]); float e1 = dot(edge[1], edge[1]); float e2 = dot(edge[2], edge[2]); if (e0 > e1 && e0 > e2) return 0; if (e1 > e0 && e1 > e2) return 1; if (e2 > e0 && e2 > e1) return 2; } void splitTriangle(vec3 triangle[3], inout vec3 sub_triangle0[3], inout vec3 sub_triangle1[3]) { vec3 V[3]; V[0] = triangle[1] - triangle[0]; V[1] = triangle[2] - triangle[1]; V[2] = triangle[2] - triangle[0]; int max_edge = getMaxEdge(V); if (max_edge == 0) { vec3 mid = 0.5 * (triangle[0] + triangle[1]); sub_triangle0[0] = triangle[0]; sub_triangle0[1] = triangle[2]; sub_triangle0[2] = mid; sub_triangle1[0] = triangle[2]; sub_triangle1[1] = triangle[1]; sub_triangle1[2] = mid; } else if (max_edge == 1) { vec3 mid = 0.5 * (triangle[2] + triangle[1]); sub_triangle0[0] = triangle[1]; sub_triangle0[1] = triangle[0]; sub_triangle0[2] = mid; sub_triangle1[0] = triangle[0]; sub_triangle1[1] = triangle[2]; sub_triangle1[2] = mid; } else { vec3 mid = 0.5 * (triangle[2] + triangle[0]); sub_triangle0[0] = triangle[1]; sub_triangle0[1] = triangle[0]; sub_triangle0[2] = mid; sub_triangle1[0] = triangle[2]; sub_triangle1[1] = triangle[1]; sub_triangle1[2] = mid; } } int getLevel(float area, float u) { // A/Sp_k-1 < u < A/Sp_k int level = 0; for (int i = 1; i < SNum; i++) { float AS = area / Sp[i]; if (u < AS) { level = i - 1; break; } } return level; } vec3 getNormal(vec3 triangle[3]) { vec3 V1 = triangle[1] - triangle[0]; vec3 V2 = triangle[2] - triangle[0]; return normalize(cross(V1, V2)); } vec2 getTexcoord(vec3 triangle[3]) { // Center vec3 P = (triangle[0] + triangle[1] + triangle[2]) / 3.0; vec3 P0 = v2g[0].position; vec3 P1 = v2g[1].position; vec3 P2 = v2g[2].position; float b = ((P0.x - P2.x) * (P1.y - P2.y) - (P0.y - P2.y) * (P1.x - P2.x)); float u = (P.x * (P1.y - P2.y) - P.y * (P1.x - P2.x)) / b; float v = (P.x * (P0.y - P2.y) - P.y * (P0.x - P2.x)) / (-b); vec2 T0 = v2g[0].texcoord - v2g[2].texcoord; vec2 T1 = v2g[1].texcoord - v2g[2].texcoord; return T0 * u + T1 * v; } void emitTriangle(vec3 triangle[3], float area, float level, int index) { G2FTriangle g2f_triangle; g2f_triangle.positions[0] = triangle[0]; g2f_triangle.positions[1] = triangle[1]; g2f_triangle.positions[2] = triangle[2]; g2f_triangle.normal = getNormal(triangle); g2f_triangle.texcoord = getTexcoord(triangle); g2f_triangle.area_and_level = vec2(area, level); for (int i = 0; i < 3; i++) { g2f.triangle = g2f_triangle; // gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * vec4(triangle[i], 1.0); gl_Position = vec4(g2f_triangle.positions[i], 1); EmitVertex(); } } void main() { // 1. To avoid uneven triangle segmentation, get the length of three sides of triangle // 2. Take the midpoint of the longest edge and divide it into two triangles // 3. Continue with the new two triangles // The triangle inputted from VS push into stack vec3 stack[TriangleVerticesNum]; // The index of top of stack int top = -1; stack[++top] = v2g[0].position; stack[++top] = v2g[1].position; stack[++top] = v2g[2].position; // Random number: used for random culling, and get random number according to triangle ID float u = Noise[gl_PrimitiveIDIn % NoiseNum]; float Sp_1 = Sp[0]; float Sp_N = Sp[SNum - 1]; int index = 0; // Pop triangle from the stack and subdivide triangle while (top > 0 && top < TriangleVerticesNum) { // 3 vertices of triangle vec3 triangle[3]; triangle[0] = stack[top--]; triangle[1] = stack[top--]; triangle[2] = stack[top--]; // The area of the triangle float area = getArea(triangle); if (area <= u * Sp_1) continue; if (area < u * Sp_N) { // The triangle needs to be subdivided if (top >= TriangleVerticesNum) continue; vec3 sub_triangle0[3]; vec3 sub_triangle1[3]; splitTriangle(triangle, sub_triangle0, sub_triangle1); // new sub triangles are pushed into the stack, and will be calculated if (top < TriangleVerticesNum) { stack[++top] = sub_triangle0[0]; stack[++top] = sub_triangle0[1]; stack[++top] = sub_triangle0[2]; } if (top < TriangleVerticesNum) { stack[++top] = sub_triangle1[0]; stack[++top] = sub_triangle1[1]; stack[++top] = sub_triangle1[2]; } } else { // Calculate the level of the triangle // G2F int level = getLevel(area, u); emitTriangle(triangle, area, level, index); index++; } } gl_Position = vec4(0, 0, 0, 1); EmitVertex(); EndPrimitive(); } <|start_filename|>Code/BBearEditor/Engine/Render/Shader/BBComputeShader.h<|end_filename|> #ifndef BBCOMPUTESHADER_H #define BBCOMPUTESHADER_H #include "BBShader.h" class BBComputeShader : public BBShader { public: BBComputeShader(); void init(const QString &shaderPath); void bind(GLuint numGroupsX, GLuint numGroupsY, GLuint numGroupsZ); void unbind(); }; #endif // BBCOMPUTESHADER_H <|start_filename|>Resources/shaders/ParticleSystem/Particles0.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBColor; attribute vec4 BBNormal; varying vec4 V_color; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { V_color = BBColor; gl_PointSize = 64.0; vec4 pos = vec4(BBPosition.xyz + BBNormal.xyz, 1.0); gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * pos; } <|start_filename|>Code/BBearEditor/Engine/Physics/FluidSystem/BBSPHParticleNeighborTable.cpp<|end_filename|> #include "BBSPHParticleNeighborTable.h" #include <string.h> #include "Utils/BBUtils.h" BBSPHParticleNeighborTable::BBSPHParticleNeighborTable() { m_nParticleCount = 0; m_nParticleCapacity = 0; m_pNeighborDataBuffer = nullptr; m_nNeighborDataBufferSize = 0; m_nNeighborDataBufferOffset = 0; m_pNeighborDataBufferCode = nullptr; m_nCurrentParticleIndex = 0; m_nCurrentNeighborCount = 0; } BBSPHParticleNeighborTable::~BBSPHParticleNeighborTable() { BB_SAFE_DELETE_ARRAY(m_pNeighborDataBuffer); BB_SAFE_DELETE_ARRAY(m_pNeighborDataBufferCode); } void BBSPHParticleNeighborTable::reset(unsigned int nParticleCount) { int nSize = sizeof(BBNeighborDataBufferCode); if (nParticleCount > m_nParticleCapacity) { // extend space if (m_pNeighborDataBufferCode) { BB_SAFE_DELETE_ARRAY(m_pNeighborDataBufferCode); } m_pNeighborDataBufferCode = new BBNeighborDataBufferCode[nSize * nParticleCount]; m_nParticleCapacity = nParticleCount; } m_nParticleCount = nParticleCount; memset(m_pNeighborDataBufferCode, 0, nSize * m_nParticleCapacity); m_nNeighborDataBufferOffset = 0; } void BBSPHParticleNeighborTable::setCurrentParticle(unsigned int nParticleIndex) { m_nCurrentParticleIndex = nParticleIndex; m_nCurrentNeighborCount = 0; } bool BBSPHParticleNeighborTable::addNeighborParticle(unsigned int nNeighborIndex, float fNeighborDistance) { if (m_nCurrentNeighborCount >= MAX_NEIGHBOR_COUNT) { return false; } m_CurrentNeighborIndexes[m_nCurrentNeighborCount] = nNeighborIndex; m_CurrentNeighborDistances[m_nCurrentNeighborCount] = fNeighborDistance; m_nCurrentNeighborCount++; return true; } void BBSPHParticleNeighborTable::recordCurrentNeighbor() { if (m_nCurrentNeighborCount == 0) return; unsigned int nNeighborIndexSize = m_nCurrentNeighborCount * sizeof(unsigned int); unsigned int nNeighborDistanceSize = m_nCurrentNeighborCount * sizeof(float); if (m_nNeighborDataBufferOffset + nNeighborIndexSize + nNeighborDistanceSize > m_nNeighborDataBufferSize) { extendNeighborDataBuffer(m_nNeighborDataBufferOffset + nNeighborIndexSize + nNeighborDistanceSize); } // record code m_pNeighborDataBufferCode[m_nCurrentParticleIndex].m_nCurrentNeighborCount = m_nCurrentNeighborCount; m_pNeighborDataBufferCode[m_nCurrentParticleIndex].m_nNeighborDataBufferOffset = m_nNeighborDataBufferOffset; // Copy the information of the current to the data buffer memcpy(m_pNeighborDataBuffer + m_nNeighborDataBufferOffset, m_CurrentNeighborIndexes, nNeighborIndexSize); m_nNeighborDataBufferOffset += nNeighborIndexSize; memcpy(m_pNeighborDataBuffer + m_nNeighborDataBufferOffset, m_CurrentNeighborDistances, nNeighborDistanceSize); m_nNeighborDataBufferOffset += nNeighborDistanceSize; } int BBSPHParticleNeighborTable::getNeighborCount(unsigned int nCurrentParticleIndex) { return m_pNeighborDataBufferCode[nCurrentParticleIndex].m_nCurrentNeighborCount; } void BBSPHParticleNeighborTable::getNeighborInfo(unsigned int nCurrentParticleIndexInBuffer, unsigned int nNeighborParticleIndexInNeighborTable, unsigned int &nNeighborParticleIndexInBuffer, float &fNeighborParticleDistance) { BBNeighborDataBufferCode code = m_pNeighborDataBufferCode[nCurrentParticleIndexInBuffer]; unsigned int *pNeighborIndex = (unsigned int*)(m_pNeighborDataBuffer + code.m_nNeighborDataBufferOffset); float *pNeighborDistance = (float*)(m_pNeighborDataBuffer + code.m_nNeighborDataBufferOffset + sizeof(unsigned int) * code.m_nCurrentNeighborCount); nNeighborParticleIndexInBuffer = pNeighborIndex[nNeighborParticleIndexInNeighborTable]; fNeighborParticleDistance = pNeighborDistance[nNeighborParticleIndexInNeighborTable]; } void BBSPHParticleNeighborTable::extendNeighborDataBuffer(unsigned int nNeedSize) { unsigned int nNewSize = m_nNeighborDataBufferSize > 0 ? m_nNeighborDataBufferSize : 1; while (nNewSize < nNeedSize) { nNewSize *= 2; } unsigned char *pNewBuffer = new unsigned char[nNewSize]; if (m_pNeighborDataBuffer) { memcpy(pNewBuffer, m_pNeighborDataBuffer, m_nNeighborDataBufferSize); BB_SAFE_DELETE_ARRAY(m_pNeighborDataBuffer); } m_pNeighborDataBuffer = pNewBuffer; m_nNeighborDataBufferSize = nNewSize; } <|start_filename|>Code/BBearEditor/Engine/Render/BBMaterial.h<|end_filename|> #ifndef BBMATERIAL_H #define BBMATERIAL_H #include "BBBaseRenderComponent.h" #include "BBRenderState.h" #include <QPixmap> #include "Geometry/BBRay.h" class BBCamera; class BBAttribute; class BBUniformUpdater; class BBMaterialProperty; class BBRenderPass; class BBShader; class BBDrawCall; class BBMaterial { public: BBMaterial(); ~BBMaterial(); void init(const char *shaderName, const QString &vShaderPath, const QString &fShaderPath, const QString &gShaderPath = ""); void initMultiPass(const char *shaderName, const QString &vShaderPath, const QString &fShaderPath, const QString &gShaderPath = ""); void initMultiPass(const char *shaderName1, const QString &vShaderPath1, const QString &fShaderPath1, const char *shaderName2, const QString &vShaderPath2, const QString &fShaderPath2, const QString &gShaderPath1 = "", const QString &gShaderPath2 = ""); void bindDrawCallInstance(BBDrawCall *pDrawCall) { m_pDrawCallInstance = pDrawCall; } public: void setBlendState(bool bEnable); void setSRCBlendFunc(unsigned int src); void setDSTBlendFunc(unsigned int dst); void setBlendFunc(unsigned int src, unsigned int dst); void setZTestState(bool bEnable); void setZFunc(unsigned int func); void setZMask(bool bEnable); void setStencilMask(bool bEnable); void setCullState(bool bEnable); void setCullFace(int face); bool getBlendState(); unsigned int getSRCBlendFunc(); unsigned int getDSTBlendFunc(); bool getCullState(); int getCullFace(); public: void setFloat(const std::string &uniformName, const float fValue); void setFloatArray(const std::string &uniformName, const float *pFloatArray, int nArrayCount); void setMatrix4(const std::string &uniformName, const float *pMatrix4); void setVector4(const std::string &uniformName, float x, float y, float z, float w); void setVector4(const std::string &uniformName, const float *pVector4); void setVector4Array(const std::string &uniformName, const float *pVector4Array, int nArrayCount); void setSampler2D(const std::string &uniformName, GLuint textureName, const QString &resourcePath = ""); void setSampler3D(const std::string &uniformName, GLuint textureName, const QString &resourcePath = ""); void setSamplerCube(const std::string &uniformName, GLuint textureName); void setSamplerCube(const std::string &uniformName, GLuint textureName, const QString resourcePaths[]); BBMaterial* clone(); void getEditableProperties(QList<std::string> &outNames, QList<BBMaterialProperty*> &outProperties); void setBaseRenderPass(BBRenderPass *pRenderPass) { m_pBaseRenderPass = pRenderPass; } inline BBRenderPass* getBaseRenderPass() const { return m_pBaseRenderPass; } void setAdditiveRenderPass(BBRenderPass *pRenderPass) { m_pAdditiveRenderPass = pRenderPass; } inline BBRenderPass* getAdditiveRenderPass() const { return m_pAdditiveRenderPass; } BBShader* getShader(); bool isWriteFBO(); private: BBRenderPass *m_pBaseRenderPass; BBRenderPass *m_pAdditiveRenderPass; BBDrawCall *m_pDrawCallInstance; }; #endif // BBMATERIAL_H <|start_filename|>Code/BBearEditor/Engine/Serializer/BBGameObject.pb.cc<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBGameObject.proto #include "BBGameObject.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace BBSerializer { constexpr BBGameObject::BBGameObject( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : name_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , classname_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , filepath_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , position_(nullptr) , localposition_(nullptr) , rotation_(nullptr) , localrotation_(nullptr) , scale_(nullptr) , localscale_(nullptr){} struct BBGameObjectDefaultTypeInternal { constexpr BBGameObjectDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBGameObjectDefaultTypeInternal() {} union { BBGameObject _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBGameObjectDefaultTypeInternal _BBGameObject_default_instance_; } // namespace BBSerializer static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_BBGameObject_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_BBGameObject_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_BBGameObject_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_BBGameObject_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::BBSerializer::BBGameObject, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBGameObject, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBGameObject, name_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBGameObject, classname_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBGameObject, filepath_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBGameObject, position_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBGameObject, localposition_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBGameObject, rotation_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBGameObject, localrotation_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBGameObject, scale_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBGameObject, localscale_), 0, 1, 2, 3, 4, 5, 6, 7, 8, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 14, sizeof(::BBSerializer::BBGameObject)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBGameObject_default_instance_), }; const char descriptor_table_protodef_BBGameObject_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\022BBGameObject.proto\022\014BBSerializer\032\016BBVe" "ctor.proto\"\372\003\n\014BBGameObject\022\021\n\004name\030\001 \001(" "\tH\000\210\001\001\022\026\n\tclassName\030\002 \001(\tH\001\210\001\001\022\025\n\010filePa" "th\030\003 \001(\tH\002\210\001\001\022/\n\010position\030\004 \001(\0132\030.BBSeri" "alizer.BBVector3fH\003\210\001\001\0224\n\rlocalPosition\030" "\005 \001(\0132\030.BBSerializer.BBVector3fH\004\210\001\001\022/\n\010" "rotation\030\006 \001(\0132\030.BBSerializer.BBVector3f" "H\005\210\001\001\0224\n\rlocalRotation\030\007 \001(\0132\030.BBSeriali" "zer.BBVector3fH\006\210\001\001\022,\n\005scale\030\010 \001(\0132\030.BBS" "erializer.BBVector3fH\007\210\001\001\0221\n\nlocalScale\030" "\t \001(\0132\030.BBSerializer.BBVector3fH\010\210\001\001B\007\n\005" "_nameB\014\n\n_classNameB\013\n\t_filePathB\013\n\t_pos" "itionB\020\n\016_localPositionB\013\n\t_rotationB\020\n\016" "_localRotationB\010\n\006_scaleB\r\n\013_localScaleb" "\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_BBGameObject_2eproto_deps[1] = { &::descriptor_table_BBVector_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_BBGameObject_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBGameObject_2eproto = { false, false, 567, descriptor_table_protodef_BBGameObject_2eproto, "BBGameObject.proto", &descriptor_table_BBGameObject_2eproto_once, descriptor_table_BBGameObject_2eproto_deps, 1, 1, schemas, file_default_instances, TableStruct_BBGameObject_2eproto::offsets, file_level_metadata_BBGameObject_2eproto, file_level_enum_descriptors_BBGameObject_2eproto, file_level_service_descriptors_BBGameObject_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_BBGameObject_2eproto_getter() { return &descriptor_table_BBGameObject_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_BBGameObject_2eproto(&descriptor_table_BBGameObject_2eproto); namespace BBSerializer { // =================================================================== class BBGameObject::_Internal { public: using HasBits = decltype(std::declval<BBGameObject>()._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_classname(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_filepath(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static const ::BBSerializer::BBVector3f& position(const BBGameObject* msg); static void set_has_position(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static const ::BBSerializer::BBVector3f& localposition(const BBGameObject* msg); static void set_has_localposition(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static const ::BBSerializer::BBVector3f& rotation(const BBGameObject* msg); static void set_has_rotation(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static const ::BBSerializer::BBVector3f& localrotation(const BBGameObject* msg); static void set_has_localrotation(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static const ::BBSerializer::BBVector3f& scale(const BBGameObject* msg); static void set_has_scale(HasBits* has_bits) { (*has_bits)[0] |= 128u; } static const ::BBSerializer::BBVector3f& localscale(const BBGameObject* msg); static void set_has_localscale(HasBits* has_bits) { (*has_bits)[0] |= 256u; } }; const ::BBSerializer::BBVector3f& BBGameObject::_Internal::position(const BBGameObject* msg) { return *msg->position_; } const ::BBSerializer::BBVector3f& BBGameObject::_Internal::localposition(const BBGameObject* msg) { return *msg->localposition_; } const ::BBSerializer::BBVector3f& BBGameObject::_Internal::rotation(const BBGameObject* msg) { return *msg->rotation_; } const ::BBSerializer::BBVector3f& BBGameObject::_Internal::localrotation(const BBGameObject* msg) { return *msg->localrotation_; } const ::BBSerializer::BBVector3f& BBGameObject::_Internal::scale(const BBGameObject* msg) { return *msg->scale_; } const ::BBSerializer::BBVector3f& BBGameObject::_Internal::localscale(const BBGameObject* msg) { return *msg->localscale_; } void BBGameObject::clear_position() { if (GetArena() == nullptr && position_ != nullptr) { delete position_; } position_ = nullptr; _has_bits_[0] &= ~0x00000008u; } void BBGameObject::clear_localposition() { if (GetArena() == nullptr && localposition_ != nullptr) { delete localposition_; } localposition_ = nullptr; _has_bits_[0] &= ~0x00000010u; } void BBGameObject::clear_rotation() { if (GetArena() == nullptr && rotation_ != nullptr) { delete rotation_; } rotation_ = nullptr; _has_bits_[0] &= ~0x00000020u; } void BBGameObject::clear_localrotation() { if (GetArena() == nullptr && localrotation_ != nullptr) { delete localrotation_; } localrotation_ = nullptr; _has_bits_[0] &= ~0x00000040u; } void BBGameObject::clear_scale() { if (GetArena() == nullptr && scale_ != nullptr) { delete scale_; } scale_ = nullptr; _has_bits_[0] &= ~0x00000080u; } void BBGameObject::clear_localscale() { if (GetArena() == nullptr && localscale_ != nullptr) { delete localscale_; } localscale_ = nullptr; _has_bits_[0] &= ~0x00000100u; } BBGameObject::BBGameObject(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBGameObject) } BBGameObject::BBGameObject(const BBGameObject& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_name()) { name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_name(), GetArena()); } classname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_classname()) { classname_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_classname(), GetArena()); } filepath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_filepath()) { filepath_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_filepath(), GetArena()); } if (from._internal_has_position()) { position_ = new ::BBSerializer::BBVector3f(*from.position_); } else { position_ = nullptr; } if (from._internal_has_localposition()) { localposition_ = new ::BBSerializer::BBVector3f(*from.localposition_); } else { localposition_ = nullptr; } if (from._internal_has_rotation()) { rotation_ = new ::BBSerializer::BBVector3f(*from.rotation_); } else { rotation_ = nullptr; } if (from._internal_has_localrotation()) { localrotation_ = new ::BBSerializer::BBVector3f(*from.localrotation_); } else { localrotation_ = nullptr; } if (from._internal_has_scale()) { scale_ = new ::BBSerializer::BBVector3f(*from.scale_); } else { scale_ = nullptr; } if (from._internal_has_localscale()) { localscale_ = new ::BBSerializer::BBVector3f(*from.localscale_); } else { localscale_ = nullptr; } // @@protoc_insertion_point(copy_constructor:BBSerializer.BBGameObject) } void BBGameObject::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); classname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); filepath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&position_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&localscale_) - reinterpret_cast<char*>(&position_)) + sizeof(localscale_)); } BBGameObject::~BBGameObject() { // @@protoc_insertion_point(destructor:BBSerializer.BBGameObject) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBGameObject::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); classname_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); filepath_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete position_; if (this != internal_default_instance()) delete localposition_; if (this != internal_default_instance()) delete rotation_; if (this != internal_default_instance()) delete localrotation_; if (this != internal_default_instance()) delete scale_; if (this != internal_default_instance()) delete localscale_; } void BBGameObject::ArenaDtor(void* object) { BBGameObject* _this = reinterpret_cast< BBGameObject* >(object); (void)_this; } void BBGameObject::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBGameObject::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBGameObject::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBGameObject) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { classname_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { filepath_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { if (GetArena() == nullptr && position_ != nullptr) { delete position_; } position_ = nullptr; } if (cached_has_bits & 0x00000010u) { if (GetArena() == nullptr && localposition_ != nullptr) { delete localposition_; } localposition_ = nullptr; } if (cached_has_bits & 0x00000020u) { if (GetArena() == nullptr && rotation_ != nullptr) { delete rotation_; } rotation_ = nullptr; } if (cached_has_bits & 0x00000040u) { if (GetArena() == nullptr && localrotation_ != nullptr) { delete localrotation_; } localrotation_ = nullptr; } if (cached_has_bits & 0x00000080u) { if (GetArena() == nullptr && scale_ != nullptr) { delete scale_; } scale_ = nullptr; } } if (cached_has_bits & 0x00000100u) { if (GetArena() == nullptr && localscale_ != nullptr) { delete localscale_; } localscale_ = nullptr; } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBGameObject::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // string name = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBGameObject.name")); CHK_(ptr); } else goto handle_unusual; continue; // string className = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_classname(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBGameObject.className")); CHK_(ptr); } else goto handle_unusual; continue; // string filePath = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { auto str = _internal_mutable_filepath(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBGameObject.filePath")); CHK_(ptr); } else goto handle_unusual; continue; // .BBSerializer.BBVector3f position = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { ptr = ctx->ParseMessage(_internal_mutable_position(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // .BBSerializer.BBVector3f localPosition = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { ptr = ctx->ParseMessage(_internal_mutable_localposition(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // .BBSerializer.BBVector3f rotation = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { ptr = ctx->ParseMessage(_internal_mutable_rotation(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // .BBSerializer.BBVector3f localRotation = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr = ctx->ParseMessage(_internal_mutable_localrotation(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // .BBSerializer.BBVector3f scale = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { ptr = ctx->ParseMessage(_internal_mutable_scale(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // .BBSerializer.BBVector3f localScale = 9; case 9: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) { ptr = ctx->ParseMessage(_internal_mutable_localscale(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBGameObject::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBGameObject) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (_internal_has_name()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_name().data(), static_cast<int>(this->_internal_name().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBGameObject.name"); target = stream->WriteStringMaybeAliased( 1, this->_internal_name(), target); } // string className = 2; if (_internal_has_classname()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_classname().data(), static_cast<int>(this->_internal_classname().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBGameObject.className"); target = stream->WriteStringMaybeAliased( 2, this->_internal_classname(), target); } // string filePath = 3; if (_internal_has_filepath()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_filepath().data(), static_cast<int>(this->_internal_filepath().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBGameObject.filePath"); target = stream->WriteStringMaybeAliased( 3, this->_internal_filepath(), target); } // .BBSerializer.BBVector3f position = 4; if (_internal_has_position()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 4, _Internal::position(this), target, stream); } // .BBSerializer.BBVector3f localPosition = 5; if (_internal_has_localposition()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 5, _Internal::localposition(this), target, stream); } // .BBSerializer.BBVector3f rotation = 6; if (_internal_has_rotation()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 6, _Internal::rotation(this), target, stream); } // .BBSerializer.BBVector3f localRotation = 7; if (_internal_has_localrotation()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 7, _Internal::localrotation(this), target, stream); } // .BBSerializer.BBVector3f scale = 8; if (_internal_has_scale()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 8, _Internal::scale(this), target, stream); } // .BBSerializer.BBVector3f localScale = 9; if (_internal_has_localscale()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 9, _Internal::localscale(this), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBGameObject) return target; } size_t BBGameObject::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBGameObject) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x000000ffu) { // string name = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_name()); } // string className = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_classname()); } // string filePath = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_filepath()); } // .BBSerializer.BBVector3f position = 4; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *position_); } // .BBSerializer.BBVector3f localPosition = 5; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *localposition_); } // .BBSerializer.BBVector3f rotation = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *rotation_); } // .BBSerializer.BBVector3f localRotation = 7; if (cached_has_bits & 0x00000040u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *localrotation_); } // .BBSerializer.BBVector3f scale = 8; if (cached_has_bits & 0x00000080u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *scale_); } } // .BBSerializer.BBVector3f localScale = 9; if (cached_has_bits & 0x00000100u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *localscale_); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBGameObject::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBGameObject) GOOGLE_DCHECK_NE(&from, this); const BBGameObject* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBGameObject>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBGameObject) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBGameObject) MergeFrom(*source); } } void BBGameObject::MergeFrom(const BBGameObject& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBGameObject) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); } if (cached_has_bits & 0x00000002u) { _internal_set_classname(from._internal_classname()); } if (cached_has_bits & 0x00000004u) { _internal_set_filepath(from._internal_filepath()); } if (cached_has_bits & 0x00000008u) { _internal_mutable_position()->::BBSerializer::BBVector3f::MergeFrom(from._internal_position()); } if (cached_has_bits & 0x00000010u) { _internal_mutable_localposition()->::BBSerializer::BBVector3f::MergeFrom(from._internal_localposition()); } if (cached_has_bits & 0x00000020u) { _internal_mutable_rotation()->::BBSerializer::BBVector3f::MergeFrom(from._internal_rotation()); } if (cached_has_bits & 0x00000040u) { _internal_mutable_localrotation()->::BBSerializer::BBVector3f::MergeFrom(from._internal_localrotation()); } if (cached_has_bits & 0x00000080u) { _internal_mutable_scale()->::BBSerializer::BBVector3f::MergeFrom(from._internal_scale()); } } if (cached_has_bits & 0x00000100u) { _internal_mutable_localscale()->::BBSerializer::BBVector3f::MergeFrom(from._internal_localscale()); } } void BBGameObject::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBGameObject) if (&from == this) return; Clear(); MergeFrom(from); } void BBGameObject::CopyFrom(const BBGameObject& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBGameObject) if (&from == this) return; Clear(); MergeFrom(from); } bool BBGameObject::IsInitialized() const { return true; } void BBGameObject::InternalSwap(BBGameObject* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); classname_.Swap(&other->classname_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); filepath_.Swap(&other->filepath_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(BBGameObject, localscale_) + sizeof(BBGameObject::localscale_) - PROTOBUF_FIELD_OFFSET(BBGameObject, position_)>( reinterpret_cast<char*>(&position_), reinterpret_cast<char*>(&other->position_)); } ::PROTOBUF_NAMESPACE_ID::Metadata BBGameObject::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBGameObject_2eproto_getter, &descriptor_table_BBGameObject_2eproto_once, file_level_metadata_BBGameObject_2eproto[0]); } // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::BBSerializer::BBGameObject* Arena::CreateMaybeMessage< ::BBSerializer::BBGameObject >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBGameObject >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> <|start_filename|>Code/BBearEditor/Engine/Physics/ClothSystem/BBCloth.h<|end_filename|> #ifndef BBCLOTH_H #define BBCLOTH_H #include "Base/BBGameObject.h" class BBClothMesh; class BBClothBody; class BBPBDSolver; class BBCloth : public BBGameObject { public: BBCloth(const QVector3D &position, int nWidth = 10, int nHeight = 6); ~BBCloth(); void init() override; void render(BBCamera *pCamera) override; void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; private: int m_nWidth; int m_nHeight; BBClothMesh *m_pClothMesh; BBClothBody *m_pClothBody; BBPBDSolver *m_pPBDSolver; }; #endif // BBCLOTH_H <|start_filename|>Code/BBearEditor/Engine/Render/OfflineRenderer/BBOfflineRenderer.cpp<|end_filename|> #include "BBOfflineRenderer.h" #include "Utils/BBUtils.h" #include "Scene/BBScene.h" #include "3D/BBModel.h" #include "BBCamera.h" #include "Geometry/BBPhotonMap.h" #include "Render/Lighting/GameObject/BBAreaLight.h" #include "Render/BBOfflineOpenGLWidget.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Scene/BBSceneManager.h" #include "OfflineRenderer/BBScatterMaterial.h" #include "Math/BBMath.h" #include "Render/BBMaterial.h" #include "Render/Texture/BBTexture.h" #include "2D/BBFullScreenQuad.h" BBOfflineRenderer::BBOfflineRenderer(BBScene *pScene) { m_pScene = pScene; m_pMaterial = nullptr; m_nWidth = pScene->getCamera()->getViewportWidth(); m_nHeight = pScene->getCamera()->getViewportHeight(); for (int i = 0; i < TestModelCount; i++) { m_pModels[i] = nullptr; } m_pAreaLight = nullptr; m_pPhotonMap = nullptr; m_nBlendFrameCount = 0; } BBOfflineRenderer::~BBOfflineRenderer() { for (int i = 0; i < TestModelCount; i++) { BB_SAFE_DELETE(m_pModels[i]); } BB_SAFE_DELETE(m_pAreaLight); BB_SAFE_DELETE(m_pPhotonMap); } void BBOfflineRenderer::createTestScene() { BB_PROCESS_ERROR_RETURN(!m_pModels[0]); // cornell box m_pModels[0] = m_pScene->createModel(BB_PATH_RESOURCE_MESH(plane.obj), QVector3D(-2, 0, 0), QVector3D(0, 0, -90), QVector3D(1, 1, 1)); m_pModels[1] = m_pScene->createModel(BB_PATH_RESOURCE_MESH(plane.obj), QVector3D(2, 0, 0), QVector3D(0, 0, 90), QVector3D(1, 1, 1)); m_pModels[2] = m_pScene->createModel(BB_PATH_RESOURCE_MESH(plane.obj), QVector3D(0, 0, 0), QVector3D(0, 0, 0), QVector3D(1, 1, 1)); m_pModels[3] = m_pScene->createModel(BB_PATH_RESOURCE_MESH(plane.obj), QVector3D(0, 2, 0), QVector3D(0, 0, -180), QVector3D(1, 1, 1)); m_pModels[4] = m_pScene->createModel(BB_PATH_RESOURCE_MESH(plane.obj), QVector3D(0, 0, -2), QVector3D(90, 0, 0), QVector3D(1, 1, 1)); m_pModels[5] = m_pScene->createModel(BB_PATH_RESOURCE_MESH(plane.obj), QVector3D(0, 0, 4), QVector3D(-90, 0, 0), QVector3D(1, 1, 1)); m_pModels[6] = m_pScene->createModel(BB_PATH_RESOURCE_MESH(cube.obj), QVector3D(0.4f, 0, 0), QVector3D(0, 0, 0), QVector3D(0.5f, 1.0f, 0.5f)); m_pModels[7] = m_pScene->createModel(BB_PATH_RESOURCE_MESH(cube.obj), QVector3D(-0.4f, 0, 0), QVector3D(0, 0, 0), QVector3D(0.25f, 1.0f, 0.5f)); // Arealight is a model m_pAreaLight = new BBAreaLight(-0.3f, 0.3f, 1.0f, 1.2f, 1.998f, QVector3D(1, 1, 1)); m_pAreaLight->init(); m_pScene->addModel(m_pAreaLight); m_pModels[8] = m_pAreaLight; // no need to set material for arealight for (int i = 0; i < TestModelCount - 1; i++) { m_pModels[i]->setBoundingBoxVisibility(false); m_pModels[i]->setScatterMaterial(new BBLambertian(QVector3D(1, 1, 1))); } m_pModels[6]->setScatterMaterial(new BBLambertian(QVector3D(0, 1, 0))); m_pModels[7]->setScatterMaterial(new BBMetal(QVector3D(1, 0, 0))); m_pScene->getCamera()->update(QVector3D(0, 1, 3.5f), QVector3D(0, 1, 2.5f)); m_pMaterial = new BBMaterial(); m_pMaterial->init("fullscreenquad_texture", BB_PATH_RESOURCE_SHADER(fullscreenquad_texture.vert), BB_PATH_RESOURCE_SHADER(fullscreenquad_texture.frag)); BBFullScreenQuad *pFullScreenQuad = m_pScene->getFinalFullScreenQuad(); pFullScreenQuad->setCurrentMaterial(m_pMaterial); m_pScene->setRenderingFunc(&BBScene::deferredRendering0_1); } void BBOfflineRenderer::startPhotonMapping() { generatePhotonMap(); m_pPhotonMap->balance(); // for (int i = 0; i < 3; i++) { renderFrame(); showFrame(); } showPhotonMap(); } void BBOfflineRenderer::renderFrame() { // Emit rays to each pixel of the screen BBCamera *pCamera = m_pScene->getCamera(); int w = pCamera->getViewportWidth(); int h = pCamera->getViewportHeight(); QImage image(w, h, QImage::Format_ARGB32); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { QVector3D color(0.0f, 0.0f, 0.0f); int nSampleCount = 4; for (int sample = 0; sample < nSampleCount; sample++) { BBRay ray = pCamera->createRayFromScreen(x + sfrandom(), y + sfrandom()); color += BBPhotonMap::traceRay(ray, m_pModels, TestModelCount, 0, m_pPhotonMap); } color /= nSampleCount; color.setX(clamp(color.x(), 0.0f, 1.0f)); color.setY(clamp(color.y(), 0.0f, 1.0f)); color.setZ(clamp(color.z(), 0.0f, 1.0f)); // qDebug() << color; // blend m_CurrentImage and image // Do not blend at the first time if (m_nBlendFrameCount > 0) { QColor currentColor = m_CurrentImage.pixelColor(x, h - y - 1); QVector3D currentColorVector(currentColor.redF(), currentColor.greenF(), currentColor.blueF()); color = currentColorVector * m_nBlendFrameCount / (m_nBlendFrameCount + 1) + color / (m_nBlendFrameCount + 1); color.setX(clamp(color.x(), 0.0f, 1.0f)); color.setY(clamp(color.y(), 0.0f, 1.0f)); color.setZ(clamp(color.z(), 0.0f, 1.0f)); } image.setPixelColor(x, h - y - 1, QColor::fromRgbF(color.x(), color.y(), color.z())); } } m_CurrentImage = image; m_nBlendFrameCount++; } void BBOfflineRenderer::showFrame() { qDebug() << m_nBlendFrameCount; m_pMaterial->setSampler2D(LOCATION_TEXTURE(0), BBTexture().createTexture2D(m_CurrentImage)); m_pScene->update(); } void BBOfflineRenderer::generatePhotonMap() { int nMaxPhotonNum = 10000; m_pPhotonMap = new BBPhotonMap(nMaxPhotonNum); QVector3D origin; QVector3D direction; QVector3D power(1.0f, 1.0f, 1.0f); float fPowerScale; for (int i = 0; i < nMaxPhotonNum; i++) { m_pAreaLight->generatePhoton(origin, direction, fPowerScale); BBRay ray(origin, direction); BBPhotonMap::tracePhoton(ray, m_pModels, TestModelCount, 0, power * fPowerScale, m_pPhotonMap, false); } } void BBOfflineRenderer::showPhotonMap() { // qDebug() << m_pPhotonMap->getBoxMin() << m_pPhotonMap->getBoxMax(); int nPhotonNum = m_pPhotonMap->getPhotonNum(); QVector3D *pPositions = m_pPhotonMap->getPhotonPositions(); // test BBNearestPhotons nearestPhotons(QVector3D(0, 0, -1), 100, 0.6f); m_pPhotonMap->getKNearestPhotons(&nearestPhotons, 1); m_pPhotonMap->markKNearestPhotons(&nearestPhotons); // m_pPhotonMap->debug(&nearestPhotons); BBVertexBufferObject *pVBO = new BBVertexBufferObject(nPhotonNum); for (int i = 0; i < nPhotonNum; i++) { // The index of m_pPhotonMap starts from 1 pVBO->setPosition(i, pPositions[i + 1]); if (m_pPhotonMap->isMarkedKNearestPhotons(i + 1)) pVBO->setColor(i, BBConstant::m_OrangeRed); else pVBO->setColor(i, BBConstant::m_LightGreen); } BB_SAFE_DELETE_ARRAY(pPositions); // Display in real-time scene for easy observation BBScene *pRealTimeScene = BBSceneManager::getScene(); BBModel *pScatterPlot = pRealTimeScene->createModel(pVBO, GL_POINTS, 0, nPhotonNum); pScatterPlot->setBoundingBoxVisibility(false); pRealTimeScene->update(); } <|start_filename|>Code/BBearEditor/Engine/Render/Lighting/GI/BBFLCGlobalIllumination.cpp<|end_filename|> #include "BBFLCGlobalIllumination.h" #include "BBGlobalIllumination.h" #include "Scene/BBScene.h" #include "2D/BBFullScreenQuad.h" #include "Render/BBMaterial.h" #include "Render/BBRenderPass.h" #include "3D/BBModel.h" #include "Render/BufferObject/BBShaderStorageBufferObject.h" #include "Render/BufferObject/BBAtomicCounterBufferObject.h" #include "Math/BBMath.h" float* BBFLCGlobalIllumination::m_S = nullptr; float* BBFLCGlobalIllumination::m_Sp = nullptr; float* BBFLCGlobalIllumination::m_Noise = nullptr; int BBFLCGlobalIllumination::m_nNoiseCount = 64; int BBFLCGlobalIllumination::m_SNum = 5; BBShaderStorageBufferObject* BBFLCGlobalIllumination::m_pTriangleCutSSBOSet = nullptr; int BBFLCGlobalIllumination::m_nSSBOCount = 0; BBAtomicCounterBufferObject* BBFLCGlobalIllumination::m_pTriangleIdACBO = nullptr; void BBFLCGlobalIllumination::open(BBScene *pScene) { if (!m_S) { m_S = generateS(); m_Sp = generateSp(m_S); m_Noise = generateNoise(); } clear(pScene); // used for the id of triangle cut m_pTriangleIdACBO = new BBAtomicCounterBufferObject(); BBGlobalIllumination::setGBufferPassByUsingExtraMaterial(pScene); // Divide triangles evenly setTriangleCutPass(pScene); setIndirectShadingPass(pScene); } void BBFLCGlobalIllumination::setTriangleCutPass(BBScene *pScene) { BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("GI_FLC_TriangleCut", BB_PATH_RESOURCE_SHADER(GI/FLC_TriangleCut_VS.vert), BB_PATH_RESOURCE_SHADER(GI/FLC_TriangleCut_FS.frag), BB_PATH_RESOURCE_SHADER(GI/FLC_TriangleCut_GS.shader)); // test float *pLightPosition = new float[4] {1.0f, 1.0f, 0.0f, 0.0f}; float *pLightColor = new float[4] {1.0f, 1.0f, 1.0f, 1.0f}; pMaterial->setVector4(LOCATION_LIGHT_POSITION, pLightPosition); pMaterial->setVector4(LOCATION_LIGHT_COLOR, pLightColor); pMaterial->setFloatArray("Sp[0]", m_Sp, 64); pMaterial->setFloatArray("Noise[0]", m_Noise, 64); QList<BBGameObject*> objects = pScene->getModels(); m_nSSBOCount = objects.count(); m_pTriangleCutSSBOSet = new BBShaderStorageBufferObject[m_nSSBOCount]; for (int i = 0; i < m_nSSBOCount; i++) { BBModel *pModel = (BBModel*)objects[i]; // 0 is used by GBuffer pModel->setExtraMaterial(1, pMaterial); BBMesh *pMesh = pModel->getMesh(); pMesh->appendACBO(m_pTriangleIdACBO, true); // Send SSBO to write the result of triangle cut // "1" is consistent with the "binding" in shader // struct TriangleCut // { // vec4 center; // vec4 normal_and_level; // vec4 color_and_area; // }; // 3x4 float m_pTriangleCutSSBOSet[i].createBufferObject<float>(1, 300000 * m_SNum * 12, GL_STATIC_DRAW, nullptr); m_pTriangleCutSSBOSet[i].submitData(); pMesh->appendSSBO(&m_pTriangleCutSSBOSet[i]); } } void BBFLCGlobalIllumination::setIndirectShadingPass(BBScene *pScene) { BBFullScreenQuad *pFullScreenQuad = pScene->getFullScreenQuad(0); BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("GI_FLC_IndirectShading", BB_PATH_RESOURCE_SHADER(GI/FullScreenQuad_SSBO.vert), BB_PATH_RESOURCE_SHADER(GI/FLC_IndirectShading.frag)); pMaterial->setFloatArray("S[0]", m_S, 64); pMaterial->setSampler2D("AlbedoTex", pScene->getColorFBO(0, 0)); pMaterial->setSampler2D("NormalTex", pScene->getColorFBO(0, 1)); pMaterial->setSampler2D("PositionTex", pScene->getColorFBO(0, 2)); // Used to debug trianglecutpass pMaterial->setSampler2D("TriangleCutPassDebugTex", pScene->getColorFBO(1, 0)); pFullScreenQuad->setCurrentMaterial(pMaterial); // Only one model is considered for the time being // do not clear ACBO, use data calculated in the TriangleCutPass pFullScreenQuad->appendACBO(m_pTriangleIdACBO, false); pFullScreenQuad->appendSSBO(&m_pTriangleCutSSBOSet[0]); } void BBFLCGlobalIllumination::clear(BBScene *pScene) { // remove TriangleCutSSBO that is setted last time QList<BBGameObject*> objects = pScene->getModels(); int nCount = objects.count(); for (int i = 0; i < nCount; i++) { BBModel *pModel = (BBModel*)objects[i]; BBMesh *pMesh = pModel->getMesh(); pMesh->removeACBO(); pMesh->removeSSBO(&m_pTriangleCutSSBOSet[i]); } BBFullScreenQuad *pFullScreenQuad = pScene->getFullScreenQuad(0); pFullScreenQuad->removeACBO(); pFullScreenQuad->removeSSBO(&m_pTriangleCutSSBOSet[0]); BB_SAFE_DELETE_ARRAY(m_pTriangleCutSSBOSet); BB_SAFE_DELETE(m_pTriangleIdACBO); } float* BBFLCGlobalIllumination::generateS() { // Scene radius static float R = 1; // The average number of virtual point lights near the current fragment // This can not be calculated directly, the author estimated the value static float D = 0.2 * R; // Value between 64-1024 (the larger it is, the smaller the triangle is) static float N = 64; // It is a number greater than 1 static float u = 1.2; float *pS = new float[m_SNum]; pS[0] = 4 * PI * D * D / N; float ui = u; for (int i = 1; i < m_SNum; i++) { pS[i] = pS[0] * ui; ui *= u; } return pS; } float* BBFLCGlobalIllumination::generateSp(float *pS) { float *pSp = new float[m_SNum]; pSp[0] = pS[0]; for (int i = 1; i < m_SNum; i++) { float sum = 0; for (int j = 0; j < i; j++) { sum += 1.0 / pS[j]; } pSp[i] = 1.0 / sum; } return pSp; } float* BBFLCGlobalIllumination::generateNoise() { std::uniform_real_distribution<GLfloat> randomFloats(0.0, 1.0); std::default_random_engine generator; float *pNoise = new float[m_nNoiseCount]; for (int i = 0; i < m_nNoiseCount; i++) { pNoise[i] = randomFloats(generator); } return pNoise; } <|start_filename|>Code/BBearEditor/Engine/Base/BBGameObjectSet.h<|end_filename|> #ifndef BBGAMEOBJECTSET_H #define BBGAMEOBJECTSET_H #include "BBGameObject.h" // manage a set of BBGameObject class BBGameObjectSet : public BBGameObject { public: BBGameObjectSet(const QList<BBGameObject*> &objects); BBGameObjectSet(const QList<BBGameObject*> &objects, const QVector3D &centerPos); void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; void setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform = true) override; void setRotation(const QVector3D &rotation, bool bUpdateLocalTransform = true) override; void setScale(const QVector3D &scale, bool bUpdateLocalTransform = true) override; private: QList<BBGameObject*> filterSelectedObjects(const QList<BBGameObject*> &gameObjects); QList<BBGameObject*> m_GameObjectSet; QList<QVector3D> m_OriginalPositions; QList<QVector3D> m_OriginalScales; }; #endif // BBGAMEOBJECTSET_H <|start_filename|>Resources/shaders/SkyBox/Irradiance_Convolution.frag<|end_filename|> #version 330 core #extension GL_NV_shadow_samplers_cube : enable in vec3 v2f_local_pos; layout (location = 0) out vec4 FragColor; uniform samplerCube EnvironmentMap; const float PI = 3.14159265359; void main(void) { vec3 N = normalize(v2f_local_pos); vec3 irradiance = vec3(0.0); // tangent space calculation from origin point vec3 up = vec3(0.0, 1.0, 0.0); vec3 right = normalize(cross(up, N)); up = normalize(cross(N, right)); // We traverse the hemisphere with a fixed sampledelta increment value. // Reducing (or increasing) this increment will increase (or decrease) the accuracy float sample_delta = 0.025; float sample_count = 0.0; for (float phi = 0.0; phi < 2.0 * PI; phi += sample_delta) { for (float theta = 0.0; theta < 0.5 * PI; theta += sample_delta) { // spherical to cartesian (in tangent space) vec3 tangent_sample = vec3(sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta)); // tangent space to world vec3 sample_vec = tangent_sample.x * right + tangent_sample.y * up + tangent_sample.z * N; // Use this vector to sample HDR environment map // cos(theta) : Light at larger angles is weaker // sin(theta) : The hemisphere's discrete sample area gets smaller the higher the zenith angle θ as the sample regions converge towards the center top. // sin(theta) : To compensate for the smaller areas, we weigh its contribution by scaling the area by sinθ. irradiance += texture(EnvironmentMap, sample_vec).rgb * cos(theta) * sin(theta); sample_count++; } } // average value irradiance = PI * irradiance * (1.0 / float(sample_count)); FragColor = vec4(irradiance, 1.0); } <|start_filename|>Resources/shaders/DeferredNormal.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBNormal; varying vec4 V_Normal; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { V_Normal = BBModelMatrix * BBNormal; gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * BBPosition; } <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFileSystemDataManager.cpp<|end_filename|> #include "BBFileSystemDataManager.h" #include <QDir> #include <QQueue> #include <QTreeWidgetItem> #include <QListWidgetItem> #include "BBFileListWidget.h" #include <QPainter> #include "Render/BBPreviewOpenGLWidget.h" #include "Scene/BBScene.h" #include "3D/BBModel.h" #include "BBTreeWidget.h" #include "Scene/BBSceneManager.h" #include "Render/BBEditViewDockWidget.h" #include <fstream> #include "Dialog/BBConfirmationDialog.h" #include "Scene/BBRendererManager.h" QList<QString> BBFileSystemDataManager::m_MeshSuffixs = {"obj", "fbx"}; QList<QString> BBFileSystemDataManager::m_TextureSuffixs = {"png", "jpg", "jpeg", "bmp", "ico", "dds"}; QList<QString> BBFileSystemDataManager::m_AudioSuffixs = {"mp3", "wav"}; QList<QString> BBFileSystemDataManager::m_SceneSuffixs = {"bbscene"}; QList<QString> BBFileSystemDataManager::m_ScriptSuffixs = {"py"}; QList<QString> BBFileSystemDataManager::m_MaterialSuffixs = {"bbmtl"}; QString BBFileSystemDataManager::m_MeshFileLogoColor = "#e85655"; QString BBFileSystemDataManager::m_TextureFileLogoColor = "#e49831"; QString BBFileSystemDataManager::m_AudioFileLogoColor = "#64abe4"; QString BBFileSystemDataManager::m_MaterialFileLogoColor = "#fab8b7"; BBFileSystemDataManager::BBFileSystemDataManager() { m_pCurrentViewedItem = NULL; m_pRootFileData = new BBFILE(); } BBFileSystemDataManager::~BBFileSystemDataManager() { for (QMap<QTreeWidgetItem*, BBFILE*>::Iterator it = m_TopLevelFileData.begin(); it != m_TopLevelFileData.end(); it++) { qDeleteAll(*it.value()); delete it.value(); delete it.key(); } for (QMap<QTreeWidgetItem*, BBFILE*>::Iterator it = m_FileData.begin(); it != m_FileData.end(); it++) { qDeleteAll(*it.value()); delete it.value(); // it.key() is child item // when delete top item of m_TopLevelFileData, their child items had been deleted // delete it.key(); } qDeleteAll(*m_pRootFileData); delete m_pRootFileData; } /** * @brief BBFileSystemDataManager::load read all files and build a tree */ void BBFileSystemDataManager::load() { QString rootPath = BBConstant::BB_PATH_PROJECT_USER; QDir dir(rootPath); if (dir.exists()) { buildFileData(rootPath, NULL, m_pRootFileData); } else { dir.mkpath(dir.absolutePath()); } } QList<QTreeWidgetItem*> BBFileSystemDataManager::getFolderTreeWidgetTopLevelItems() { QList<QTreeWidgetItem*> items; for (QMap<QTreeWidgetItem*, BBFILE*>::Iterator it = m_TopLevelFileData.begin(); it != m_TopLevelFileData.end(); it++) { items.append(it.key()); } return items; } bool BBFileSystemDataManager::getFileListWidgetItems(QTreeWidgetItem *pItem, BBFILE *&pOutFolderContent) { pOutFolderContent = getFolderContent(pItem); return true; } /** * @brief BBFileSystemDataManager::getItemByPath Find the corresponding tree item according to the path * @param absolutePath * @return */ QTreeWidgetItem* BBFileSystemDataManager::getFolderItemByPath(const QString &absolutePath) { QString path = absolutePath.mid(BBConstant::BB_PATH_PROJECT_USER.length()); if (path.length() == 0) { // "contents" folder return NULL; } else { QTreeWidgetItem *pItem = NULL; // remove "/" at the beginning path = path.mid(1); QStringList list = path.split('/'); // Find the item that is at the top level corresponds to item 0 in the list // Folders at the same level cannot have the same name for (QMap<QTreeWidgetItem*, BBFILE*>::Iterator it = m_TopLevelFileData.begin(); it != m_TopLevelFileData.end(); it++) { QString name = ((QTreeWidgetItem*) it.key())->text(0); if (name == list.at(0)) { pItem = it.key(); break; } } // Start from item 1 to find non-top items for (int i = 1; i < list.count(); i++) { for (int j = 0; j < pItem->childCount(); j++) { QTreeWidgetItem *pChild = pItem->child(j); if (list.at(i) == pChild->text(0)) { pItem = pChild; break; } } } return pItem; } } QTreeWidgetItem* BBFileSystemDataManager::getParentFolderItem(const QString &filePath) { // cannot use getItemByPath(filePath) and ->parent(), since filePath may be a file but not a folder return getFolderItemByPath(getParentPath(filePath)); } /** * @brief BBFileSystemDataManager::getFileItem find list item corresponding it in its parent * @param pFolderItem * @return */ QListWidgetItem* BBFileSystemDataManager::getFileItem(QTreeWidgetItem *pFolderItem) { QTreeWidgetItem *pParentFolderItem = pFolderItem->parent(); QString filePath = getAbsolutePath(pFolderItem); return getFileItem(pParentFolderItem, filePath); } QListWidgetItem* BBFileSystemDataManager::getFileItem(QTreeWidgetItem *pParentFolderItem, const QString &filePath) { BBFileInfo *pFileInfo = NULL; return getFileItem(pParentFolderItem, filePath, pFileInfo); } QListWidgetItem* BBFileSystemDataManager::getFileItem(QTreeWidgetItem *pParentFolderItem, const QString &filePath, BBFileInfo *&pOutFileInfo) { BBFILE *pFolderContent = getFolderContent(pParentFolderItem); QString fileName = getFileNameByPath(filePath); for (BBFILE::Iterator it = pFolderContent->begin(); it != pFolderContent->end(); it++) { pOutFileInfo = it.value(); if (pOutFileInfo->m_FileName == fileName) { return it.key(); } } return NULL; } /** * @brief BBFileSystemDataManager::openFile * @param filePath * @return returning false means that this is a folder */ bool BBFileSystemDataManager::openFile(const QString &filePath) { QFileInfo fileInfo(filePath); BB_PROCESS_ERROR_RETURN_FALSE(!fileInfo.isDir()); BBFileType eType = getFileType(filePath); if (eType == BBFileType::Scene) { openScene(getAbsolutePath(m_pCurrentViewedItem), filePath); } else if (eType == BBFileType::Script) { // open file QDesktopServices::openUrl(QUrl::fromLocalFile(filePath)); } return true; } /** * @brief BBFileSystemDataManager::newFolder * @param parentPath * @param pFolderItem current item in the folder tree after creating new folder * @param pFileList current item in the file list after creating new folder * @return */ bool BBFileSystemDataManager::newFolder(const QString &parentPath, QTreeWidgetItem *&pOutFolderItem, QListWidgetItem *&pOutFileItem) { QString fileName = "new folder"; QString filePath = getExclusiveFolderPath(parentPath, fileName); QDir dir; BB_PROCESS_ERROR_RETURN_FALSE(dir.mkdir(filePath)); // add its own folder tree item pOutFolderItem = new QTreeWidgetItem({fileName}); pOutFolderItem->setIcon(0, QIcon(BB_PATH_RESOURCE_ICON(folder5.png))); // find the tree item of its parent QTreeWidgetItem *pParent = getFolderItemByPath(parentPath); if (pParent) { // the map has nothing, since this is a new folder m_FileData.insert(pOutFolderItem, new BBFILE()); pParent->addChild(pOutFolderItem); } else { m_TopLevelFileData.insert(pOutFolderItem, new BBFILE()); } // find the BBFILE corresponding the tree item of its parent BBFILE *pParentContent = getFolderContent(pParent); // add file list item at the beginning of list of its parent pOutFileItem = addFileItem(QFileInfo(filePath), pParentContent); return true; } bool BBFileSystemDataManager::newFile(const QString &parentPath, int nType, QListWidgetItem *&pOutFileItem) { bool bRet = false; QString filePath; switch (nType) { case 0: bRet = newFile(parentPath, BBConstant::BB_NAME_DEFAULT_SCENE, filePath, pOutFileItem); break; case 1: bRet = newFile(parentPath, BBConstant::BB_NAME_DEFAULT_MATERIAL, filePath, pOutFileItem); BBRendererManager::saveDefaultMaterial(filePath); break; default: break; } return bRet; } bool BBFileSystemDataManager::newFile(const QString &parentPath, QString &outFileName, QString &outFilePath, QListWidgetItem *&pOutFileItem) { outFilePath = getExclusiveFilePath(parentPath, outFileName); std::ofstream file(outFilePath.toStdString().c_str()); BB_PROCESS_ERROR_RETURN_FALSE(file); BBFILE *pParentContent = getFolderContent(getFolderItemByPath(parentPath)); pOutFileItem = addFileItem(QFileInfo(outFilePath), pParentContent); return true; } bool BBFileSystemDataManager::openScene(const QString &defaultSavedParentPath, const QString &openedPath) { BB_PROCESS_ERROR_RETURN_FALSE(BBSceneManager::isSceneSwitched(openedPath)); // save current scene QListWidgetItem *pFileItem = NULL; if (saveScene(defaultSavedParentPath, pFileItem)) { // open selected scene BBSceneManager::openScene(openedPath); return true; } return false; } bool BBFileSystemDataManager::saveScene(const QString &defaultParentPath, QListWidgetItem *&pOutFileItem) { // no need to save when there is no change if (!BBSceneManager::isSceneChanged()) { return true; } // pop-up dialog BBConfirmationDialog dialog; dialog.setTitle("Unsaved changes!"); QString sceneFilePath = BBSceneManager::getCurrentSceneFilePath(); if (sceneFilePath.isEmpty()) { dialog.setMessage("Do you want to save these changes?"); if (dialog.exec()) { QString defaultFilePath = BBFileSystemDataManager::getExclusiveFilePath(defaultParentPath, BBConstant::BB_NAME_DEFAULT_SCENE); // pop-up file dialog and select path for new file QString filePath = QFileDialog::getSaveFileName(NULL, "Save Scene", defaultFilePath, "Scene (*.bbscene)"); if (!filePath.isEmpty()) { // create list item in the file list and empty file QString fileName = getFileNameByPath(filePath); newFile(getParentPath(filePath), fileName, filePath, pOutFileItem); // write file BBSceneManager::saveScene(filePath); return true; } } } else { dialog.setMessage("Do you want to save these changes into " + sceneFilePath + " ?"); if (dialog.exec()) { pOutFileItem = getFileItem(m_pCurrentViewedItem, sceneFilePath); BBSceneManager::saveScene(); return true; } } if (!dialog.isCanceled()) { // remove changes BBSceneManager::removeScene(); // open new scene return true; } return false; } bool BBFileSystemDataManager::showInFolder(const QString &filePath) { BB_PROCESS_ERROR_RETURN_FALSE(!filePath.isEmpty()); QProcess process; // just identify "\\" QString legalPath = filePath; legalPath.replace("/", "\\"); QString cmd = QString("explorer.exe /select,%1").arg(legalPath); qDebug() << cmd; return process.startDetached(cmd); } bool BBFileSystemDataManager::rename(QTreeWidgetItem *pParentFolderItem, QListWidgetItem *pFileItem, const QString &oldPath, const QString &newPath) { QString newName; QString legalNewPath; // find parent folder item of pFileItem BBFILE *pFolderContent = getFolderContent(pParentFolderItem); BBFileInfo *pFileInfo = pFolderContent->value(pFileItem); if (pFileInfo->m_eFileType == BBFileType::Dir) { QTreeWidgetItem *pFolderItem = getFolderItemByPath(oldPath); BB_PROCESS_ERROR_RETURN_FALSE(pFolderItem); legalNewPath = getExclusiveFolderPath(newPath); BB_PROCESS_ERROR_RETURN_FALSE(QFile::rename(oldPath, legalNewPath)); // rename corresponding folder in the engine folder QFile::rename(getEngineAuxiliaryFolderPath(oldPath), getEngineAuxiliaryFolderPath(legalNewPath)); // need to rename folder tree item newName = getFileNameByPath(legalNewPath); pFolderItem->setText(0, newName); } else { legalNewPath = getExclusiveFilePath(newPath); newName = getFileNameByPath(legalNewPath); BB_PROCESS_ERROR_RETURN_FALSE(QFile::rename(oldPath, legalNewPath)); if (pFileInfo->m_eFileType == BBFileType::Mesh) { // rename overview map QFile::rename(getOverviewMapPath(oldPath), getOverviewMapPath(legalNewPath)); } else if (pFileInfo->m_eFileType == BBFileType::Material) { // //材质文件 需要修改文件路径与材质对象的映射 // Material::rename(oldPath, newPath); } } // handle list item pFileInfo->m_FileName = newName; pFileItem->setText(getBaseName(newName)); // //如果该文件在剪贴板中 移除 // if (clipBoardPaths.contains(oldPath)) // { // clipBoardPaths.removeOne(oldPath); // } return true; } bool BBFileSystemDataManager::deleteFolder(QTreeWidgetItem *pItem) { BB_PROCESS_ERROR_RETURN_FALSE(pItem); // if showing its content, clear, and show root folder if (pItem == m_pCurrentViewedItem) { m_pCurrentViewedItem = NULL; } // find list item corresponding it in its parent QTreeWidgetItem *pParentFolderItem = pItem->parent(); QString filePath = getAbsolutePath(pItem); QString parentPath = getParentPath(filePath); QListWidgetItem *pFileItem = getFileItem(pParentFolderItem, filePath); QList<QListWidgetItem*> items; items.append(pFileItem); return deleteFiles(pParentFolderItem, parentPath, items); } bool BBFileSystemDataManager::deleteFiles(QTreeWidgetItem *pParentItem, const QString &parentPath, const QList<QListWidgetItem*> &items) { for (int i = 0; i < items.count(); i++) { QListWidgetItem* pItem = items.at(i); BBFILE *pFolderContent = getFolderContent(pParentItem); BBFileInfo *pFileInfo = pFolderContent->value(pItem); QString path = parentPath + "/" + pFileInfo->m_FileName; if (pFileInfo->m_eFileType == BBFileType::Dir) { QTreeWidgetItem *pFolderItem = getFolderItemByPath(path); BB_PROCESS_ERROR_RETURN_FALSE(pFolderItem); QDir dir(path); BB_PROCESS_ERROR_RETURN_FALSE(dir.removeRecursively()); // delete corresponding folder in the engine folder dir = QDir(getEngineAuxiliaryFolderPath(path)); dir.removeRecursively(); // //刷新材质文件的映射 被删除的材质文件的映射不再占用内存 // Material::updateMap(); // delete folder tree item deleteFolderItem(pFolderItem); } else { BB_PROCESS_ERROR_RETURN_FALSE(QFile::remove(path)); if (pFileInfo->m_eFileType == BBFileType::Mesh) { // remove overview map QFile::remove(getOverviewMapPath(path)); } // //材质文件 需要删除材质对象 // else if (pFileInfo->m_eFileType == BBFileType::Material) // { // Material::deleteOne(path); // } } // handle list item pFolderContent->remove(pItem); BB_SAFE_DELETE(pFileInfo); BB_SAFE_DELETE(pItem); // remove from clipboard // if (clipBoardPaths.contains(path)) // { // clipBoardPaths.removeOne(path); // } } return true; } bool BBFileSystemDataManager::importFiles(const QString &parentPath, const QList<QUrl> &urls) { for (int i = 0; i < urls.length(); i++) { QString importedAssetPath = urls.at(i).toLocalFile(); // if it is the folder, you need to traverse the sub-files // otherwise, directly operate QFileInfo fileInfo(importedAssetPath); if (fileInfo.isDir()) { // create the folder QString rootFolderName = getFileNameByPath(importedAssetPath); QString rootFolderPath = getExclusiveFolderPath(parentPath, rootFolderName); QDir dir; BB_PROCESS_ERROR_RETURN_FALSE(dir.mkpath(rootFolderPath)); // breadth-first traverse QQueue<QString> queue; queue.enqueue(importedAssetPath); while (!queue.isEmpty()) { QDir dir(queue.dequeue()); dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); // the folder exists, traverse sub-files QFileInfoList fileInfoList = dir.entryInfoList(); foreach (QFileInfo fileInfo, fileInfoList) { // Keep the path of the sub file relative to the root folder // and replace with the project file path in front // There is no duplicate name problem QString childPath = rootFolderPath + fileInfo.absoluteFilePath().mid(importedAssetPath.length()); if (fileInfo.isDir()) { // folder enqueue, waiting to traverse its sub-files queue.enqueue(fileInfo.absoluteFilePath()); BB_PROCESS_ERROR_RETURN_FALSE(dir.mkpath(childPath)); } else { // handle the file importFiles(fileInfo, childPath); } } } } else { // handle the file QFileInfo fileInfo(importedAssetPath); importFiles(fileInfo, parentPath + "/" + fileInfo.fileName()); } } // load folders' tree items and corresponding list items return loadImportedData(parentPath); } bool BBFileSystemDataManager::moveFolders(const QList<QTreeWidgetItem*> &items, QTreeWidgetItem *pNewParentItem, bool bCopy, QList<QListWidgetItem*> &outSelectedItems) { // record map between item and its parent // the items that have the same parent can be handled at the same time QMap<QTreeWidgetItem*, QTreeWidgetItem*> map; for (int i = 0; i < items.count(); i++) { QTreeWidgetItem *pItem = items.at(i); QTreeWidgetItem *pOldParentItem = pItem->parent(); // it just changes the order among the siblings, no need to perform follow-up operation if (pOldParentItem == pNewParentItem) { continue; } map.insertMulti(pOldParentItem, pItem); } QList<QTreeWidgetItem*> uniqueKeys = map.uniqueKeys(); for (int i = 0; i < uniqueKeys.count(); i++) { QTreeWidgetItem *pOldParentItem = uniqueKeys.at(i); QList<QTreeWidgetItem*> sameDirItems = map.values(pOldParentItem); QList<QListWidgetItem*> fileItems; for (int j = 0; j < sameDirItems.count(); j++) { // find corresponding file item fileItems.append(getFileItem(sameDirItems.at(j))); } BB_PROCESS_ERROR_RETURN_FALSE(moveFiles(fileItems, getAbsolutePath(pOldParentItem), pOldParentItem, getAbsolutePath(pNewParentItem), pNewParentItem, bCopy)); outSelectedItems.append(fileItems); } return true; } bool BBFileSystemDataManager::moveFolders(const QList<QString> &oldFilePaths, const QString &newParentPath, bool bCopy, QList<QListWidgetItem*> &outSelectedItems) { QList<QTreeWidgetItem*> items; for (int i = 0; i < oldFilePaths.count(); i++) { QString filePath = oldFilePaths.at(i); // check whether the movement is legal BB_PROCESS_ERROR_RETURN_FALSE(isMovablePath(filePath, newParentPath)); items.append(getFolderItemByPath(filePath)); } moveFolders(items, getFolderItemByPath(newParentPath), bCopy, outSelectedItems); } bool BBFileSystemDataManager::moveFiles(const QList<QString> &oldFilePaths, QTreeWidgetItem *pNewParentItem, bool bCopy, QList<QTreeWidgetItem*> &outSelectedItems) { // oldFilePaths share the same parent QString oldParentPath = getParentPath(oldFilePaths.first()); QTreeWidgetItem *pOldParentItem = getFolderItemByPath(oldParentPath); QString newParentPath = getAbsolutePath(pNewParentItem); QList<QListWidgetItem*> fileItems; for (int i = 0; i < oldFilePaths.count(); i++) { QString filePath = oldFilePaths.at(i); // check whether the movement is legal BB_PROCESS_ERROR_RETURN_FALSE(isMovablePath(filePath, newParentPath)); fileItems.append(getFileItem(pOldParentItem, filePath)); outSelectedItems.append(getFolderItemByPath(filePath)); } BB_PROCESS_ERROR_RETURN_FALSE(moveFiles(fileItems, oldParentPath, pOldParentItem, newParentPath, pNewParentItem, bCopy)); return true; } bool BBFileSystemDataManager::moveFiles(const QList<QListWidgetItem*> &items, const QString &oldParentPath, const QString &newParentPath, bool bCopy) { QTreeWidgetItem *pOldParentItem = getFolderItemByPath(oldParentPath); QTreeWidgetItem *pNewParentItem = getFolderItemByPath(newParentPath); return moveFiles(items, oldParentPath, pOldParentItem, newParentPath, pNewParentItem, bCopy); } /** * @brief BBFileSystemDataManager::moveFiles move or copy items from old path into new path * @param items * @param pOldParentItem * @param oldParentPath * @param pNewParentItem * @param newParentPath * @param bCopy * @return */ bool BBFileSystemDataManager::moveFiles(const QList<QListWidgetItem*> &items, const QString &oldParentPath, QTreeWidgetItem *pOldParentItem, const QString &newParentPath, QTreeWidgetItem *pNewParentItem, bool bCopy) { // move or copy BBFILE from pOldParentFolderContent into pNewParentFolderContent BBFILE *pOldParentFolderContent = getFolderContent(pOldParentItem); for (int i = 0; i < items.count(); i++) { QListWidgetItem *pFileItem = items.at(i); BBFileInfo *pFileInfo = pOldParentFolderContent->value(pFileItem); QString name = pFileInfo->m_FileName; QString oldPath = oldParentPath + "/" + name; QString newPath; if (pFileInfo->m_eFileType == BBFileType::Dir) { newPath = getExclusiveFolderPath(newParentPath, name); BB_PROCESS_ERROR_RETURN_FALSE(moveFolder(oldPath, newPath, bCopy)); // need to move corresponding tree item QTreeWidgetItem *pFolderItem = getFolderItemByPath(oldPath); moveFolderItem(pFolderItem, pOldParentItem, pNewParentItem); // need to rename folder tree item pFolderItem->setText(0, name); } else { newPath = getExclusiveFilePath(newParentPath, name); BB_PROCESS_ERROR_RETURN_FALSE(moveFile(oldPath, newPath, pFileInfo->m_eFileType, bCopy)); } // handle list item pFileInfo->m_FileName = name; pFileItem->setText(getBaseName(name)); // //如果该文件在剪贴板中 移除 // if (clipBoardPaths.contains(oldPath)) // { // clipBoardPaths.removeOne(oldPath); // } if (bCopy) { // new those that is in the old path } } return true; } QString BBFileSystemDataManager::getAbsolutePath(const QString &relativePath) { if (relativePath.isEmpty()) { return BBConstant::BB_PATH_PROJECT_USER; } else { return BBConstant::BB_PATH_PROJECT_USER + "/" + relativePath; } } QString BBFileSystemDataManager::getAbsolutePath(QTreeWidgetItem *pItem) { return getAbsolutePath(BBTreeWidget::getLevelPath(pItem)); } QString BBFileSystemDataManager::getExclusiveFolderPath(const QString &parentPath, QString &fileName) { QDir dir; QString filePath = parentPath + "/" + fileName; if (dir.exists(filePath)) { // if exist, number that is at the end will increase filePath += " "; int i = 2; while (dir.exists(filePath + QString::number(i))) { i++; } fileName = fileName + " " + QString::number(i); return filePath + QString::number(i); } else { // there is no the same name return filePath; } } QString BBFileSystemDataManager::getExclusiveFolderPath(const QString &filePath) { QDir dir; if (dir.exists(filePath)) { // if exist, number that is at the end will increase int i = 2; while (dir.exists(filePath + " " + QString::number(i))) { i++; } return filePath + " " + QString::number(i); } else { // there is no the same name return filePath; } } QString BBFileSystemDataManager::getExclusiveFilePath(const QString &parentPath, QString &fileName) { QFile file; QString filePath = parentPath + "/" + fileName; if (file.exists(filePath)) { QString suffix = getFileSuffix(fileName); QString baseName = getBaseName(fileName); filePath = parentPath + "/" + baseName + " "; int i = 2; while (file.exists(filePath + QString::number(i) + "." + suffix)) { i++; } fileName = baseName + " " + QString::number(i) + "." + suffix; return filePath + QString::number(i) + "." + suffix; } else { return filePath; } } QString BBFileSystemDataManager::getExclusiveFilePath(const QString &filePath) { QFile file; if (file.exists(filePath)) { QString fileName = getFileNameByPath(filePath); QString suffix = getFileSuffix(fileName); // remove suffix QString newPath = filePath.mid(0, filePath.lastIndexOf('.')); newPath += " "; int i = 2; while (file.exists(newPath + QString::number(i) + "." + suffix)) { i++; } return newPath + QString::number(i) + "." + suffix; } else { return filePath; } } QString BBFileSystemDataManager::getFileSuffix(const QFileInfo &fileInfo) { return fileInfo.fileName().mid(fileInfo.fileName().lastIndexOf('.') + 1); } QString BBFileSystemDataManager::getFileSuffix(const QString &name) { int nIndex = name.lastIndexOf('.'); if (nIndex < 0) { return ""; } else { return name.mid(nIndex + 1); } } QString BBFileSystemDataManager::getBaseName(const QString &name) { return name.mid(0, name.lastIndexOf('.')); } QString BBFileSystemDataManager::getFileNameByPath(const QString &filePath) { return filePath.mid(filePath.lastIndexOf('/') + 1); } QString BBFileSystemDataManager::getParentPath(const QString &filePath) { return filePath.mid(0, filePath.lastIndexOf('/')); } QString BBFileSystemDataManager::getOverviewMapPath(const QString &sourcePath) { QString fileName = getFileNameByPath(sourcePath); QString suffix = getFileSuffix(fileName); QString baseName = getBaseName(fileName); if (m_MeshSuffixs.contains(suffix)) { fileName = "mesh_" + baseName + ".jpg"; } else if (m_MaterialSuffixs.contains(suffix)) { fileName = "material_" + baseName + ".jpg"; } // remove the name of sourcePath, there is a '/' at the end for the convenience of calculation QString relativePath = sourcePath.mid(0, sourcePath.lastIndexOf('/') + 1); // the path relative to the engine folder is the same as the path relative to the contents folder relativePath = relativePath.mid(BBConstant::BB_PATH_PROJECT_USER.length() + 1); relativePath = relativePath + fileName; return BBConstant::BB_PATH_PROJECT_ENGINE + "/" + BBConstant::BB_NAME_FILE_SYSTEM_USER + "/" + relativePath; } QColor BBFileSystemDataManager::getFileLogoColor(const BBFileType &eFileType) { if (eFileType == BBFileType::Mesh) { return QColor(m_MeshFileLogoColor); } else if (eFileType == BBFileType::Texture) { return QColor(m_TextureFileLogoColor); } else if (eFileType == BBFileType::Audio) { return QColor(m_AudioFileLogoColor); } else if (eFileType == BBFileType::Material) { return QColor(m_MaterialFileLogoColor); } else { return nullptr; } } QString BBFileSystemDataManager::getEngineAuxiliaryFolderPath(const QString &sourcePath) { // the path relative to the engine folder is the same as the path relative to the contents folder QString relativePath = sourcePath.mid(BBConstant::BB_PATH_PROJECT_USER.length()); return BBConstant::BB_PATH_PROJECT_ENGINE + "/" + BBConstant::BB_NAME_FILE_SYSTEM_USER + relativePath; } QIcon BBFileSystemDataManager::getIcon(const QString &path) { // Cut into a square QPixmap pix(path); if (pix.isNull()) { return QIcon(BB_PATH_RESOURCE_ICON(empty2)); } else { int h = pix.height(); int w = pix.width(); int size = h < w ? h : w; pix = pix.copy((w - size) / 2, (h - size) / 2, size, size); return QIcon(pix); } } QIcon BBFileSystemDataManager::getTextureIcon(const QString &path) { QPixmap pix(path); int h = pix.height(); int w = pix.width(); int size = h > w ? h : w; pix = pix.copy((w - size) / 2, (h - size) / 2, size, size); // Transparent pictures need to add background // When the image is smaller than the icon size, use the icon size. The image is showed in the center int nBackgroundSize = size > BBFileListWidget::m_ItemSize.width() ? size : BBFileListWidget::m_ItemSize.width(); QPixmap background(nBackgroundSize, nBackgroundSize); background.fill(QColor("#d6dfeb")); QPainter painter(&background); painter.drawPixmap((nBackgroundSize - size) / 2, (nBackgroundSize - size) / 2, pix); painter.end(); return QIcon(background); } bool BBFileSystemDataManager::copyFolder(const QString &fromDir, const QString &toDir) { QDir sourceDir(fromDir); QDir targetDir(toDir); if (!targetDir.exists()) { // if it does not exist, create it BB_PROCESS_ERROR_RETURN_FALSE(targetDir.mkpath(targetDir.absolutePath())); } QFileInfoList fileInfoList = sourceDir.entryInfoList(); foreach (QFileInfo fileInfo, fileInfoList) { // fileInfo.filePath() has /./ if (fileInfo.fileName() == "." || fileInfo.fileName() == "..") continue; if (fileInfo.isDir()) { // recursive BB_PROCESS_ERROR_RETURN_FALSE(copyFolder(fileInfo.filePath(), targetDir.filePath(fileInfo.fileName()))); } else { // copy files BB_PROCESS_ERROR_RETURN_FALSE(QFile::copy(fileInfo.filePath(), targetDir.filePath(fileInfo.fileName()))); // //材质文件需要新建材质对象 // QString suffix = fileInfo.fileName().mid(fileInfo.fileName().lastIndexOf('.') + 1); // if (suffix == "mtl") // { // new Material(fileInfo.absoluteFilePath()); // } } } return true; } bool BBFileSystemDataManager::isMovablePath(const QString &sourcePath, const QString &destParentPath) { // Folders can’t be moved into oneself, nor can they be moved into their own subfolders BB_PROCESS_ERROR_RETURN_FALSE(!(destParentPath.mid(0, sourcePath.length()) == sourcePath)); // It can’t become its own brother and move into its own parent folder BB_PROCESS_ERROR_RETURN_FALSE(!(getParentPath(sourcePath) == destParentPath)); return true; } bool BBFileSystemDataManager::moveFolder(const QString &oldPath, const QString &newPath, bool bCopy) { // newPath has been checked for duplicate name problem // copy folder BB_PROCESS_ERROR_RETURN_FALSE(copyFolder(oldPath, newPath)); // handle corresponding folder in the engine folder QString oldAuxiliaryFolderPath = getEngineAuxiliaryFolderPath(oldPath); QString newAuxiliaryFolderPath = getEngineAuxiliaryFolderPath(newPath); copyFolder(oldAuxiliaryFolderPath, newAuxiliaryFolderPath); if (!bCopy) { // delete original folder QDir dir(oldPath); BB_PROCESS_ERROR_RETURN_FALSE(dir.removeRecursively()); dir = QDir(oldAuxiliaryFolderPath); dir.removeRecursively(); } return true; } bool BBFileSystemDataManager::moveFile(const QString &oldPath, const QString &newPath, BBFileType eFileType, bool bCopy) { // newPath has been checked for duplicate name problem // copy file BB_PROCESS_ERROR_RETURN_FALSE(QFile::copy(oldPath, newPath)); // handle corresponding folder in the engine folder QString oldOverviewMapPath; QString newOverviewMapPath; if (eFileType == BBFileType::Mesh) { oldOverviewMapPath = getOverviewMapPath(oldPath); newOverviewMapPath = getOverviewMapPath(newPath); QFile::copy(oldOverviewMapPath, newOverviewMapPath); } // //材质文件需要新建材质对象 // else if (fileInfo->mFileType == FileType::material) // { // new Material(newPath); // } if (!bCopy) { // delete original file BB_PROCESS_ERROR_RETURN_FALSE(QFile::remove(oldPath)); QFile::remove(oldOverviewMapPath); } return true; } bool BBFileSystemDataManager::judgeFileType(const QString &filePath, const BBFileType &eReferenceFileType) { QString fileName = getFileNameByPath(filePath); QString suffix = getFileSuffix(fileName); BBFileType eFileType = Other; if (m_MeshSuffixs.contains(suffix)) eFileType = Mesh; else if (m_TextureSuffixs.contains(suffix)) eFileType = Texture; else if (m_AudioSuffixs.contains(suffix)) eFileType = Audio; else if (m_SceneSuffixs.contains(suffix)) eFileType = Scene; else if (m_ScriptSuffixs.contains(suffix)) eFileType = Script; else if (m_MaterialSuffixs.contains(suffix)) eFileType = Material; return eFileType == eReferenceFileType; } /** * @brief BBFileSystemDataManager::buildFileData * @param rootPath * @param pRootItem * @param nameFilter the file item whose name is included in the nameFilter will not be created */ void BBFileSystemDataManager::buildFileData(const QString &rootPath, QTreeWidgetItem *pRootItem, BBFILE *&pRootFileData, const QList<QString> &nameFilter) { QList<QListWidgetItem*> newItems; // the content of root folder BBFILE *pRootFolderContent = loadFolderContent(rootPath, newItems, nameFilter); while (m_SelectedFileItems.count() > 0) { m_SelectedFileItems.takeFirst(); } // record and then select these items newly created in the file list m_SelectedFileItems.append(newItems); pRootFileData->unite(*pRootFolderContent); BB_SAFE_DELETE(pRootFolderContent); // The queue of the parent node of the node to be created QQueue<BBFOLDER> queue; // init queue.enqueue(BBFOLDER(rootPath, pRootItem)); // Traverse the root folder buildFileData(queue, nameFilter); // breadth-first traverse subfolders while (!queue.isEmpty()) { buildFileData(queue, nameFilter); } } /** * @brief BBFileSystemDataManager::buildFileData * @param queue * @param nameFilter */ void BBFileSystemDataManager::buildFileData(QQueue<BBFOLDER> &queue, const QList<QString> &nameFilter) { BBFOLDER folder = queue.dequeue(); QDir dir(folder.path); dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); QFileInfoList fileInfoList = dir.entryInfoList(); foreach (QFileInfo fileInfo, fileInfoList) { if (nameFilter.contains(fileInfo.fileName())) { continue; } // is folder if (fileInfo.isDir()) { QTreeWidgetItem *pItem = new QTreeWidgetItem({fileInfo.fileName()}); pItem->setIcon(0, QIcon(BB_PATH_RESOURCE_ICON(folder5.png))); QList<QListWidgetItem*> newItems; BBFILE *pFolderContent = loadFolderContent(fileInfo.absoluteFilePath(), newItems); if (folder.pItem) { // is not at the top level folder.pItem->addChild(pItem); m_FileData.insert(pItem, pFolderContent); } else { // add it at the top level m_TopLevelFileData.insert(pItem, pFolderContent); } // push queue, used for adding child item queue.enqueue(BBFOLDER(fileInfo.absoluteFilePath(), pItem)); } else { // QString suffix = getFileSuffix(fileInfo); // if (m_MaterialSuffixs.contains(suffix)) // { // loadMaterial(fileInfo.absoluteFilePath()); // } } } } BBFILE* BBFileSystemDataManager::loadFolderContent(const QString &parentPath, QList<QListWidgetItem*> &newItems, const QList<QString> &nameFilter) { BBFILE *pFolderContent = new BBFILE(); QDir dir(parentPath); dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); QFileInfoList fileInfoList = dir.entryInfoList(); foreach (QFileInfo fileInfo, fileInfoList) { if (nameFilter.contains(fileInfo.fileName())) { continue; } QListWidgetItem *pItem = addFileItem(fileInfo, pFolderContent); newItems.append(pItem); } return pFolderContent; } QListWidgetItem* BBFileSystemDataManager::addFileItem(const QFileInfo &fileInfo, BBFILE *&pOutFolderContent) { QListWidgetItem *pItem = new QListWidgetItem; pItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled); pItem->setSizeHint(BBFileListWidget::m_ItemSize); if (fileInfo.isDir()) { // is folder pItem->setText(fileInfo.fileName()); pItem->setIcon(getIcon(BB_PATH_RESOURCE_ICON(folder5.png))); pOutFolderContent->insert(pItem, new BBFileInfo(fileInfo.fileName(), BBFileType::Dir)); } else { // is file pItem->setText(fileInfo.baseName()); QString suffix = fileInfo.suffix(); if (m_MeshSuffixs.contains(suffix)) { // QString sourcePath = fileInfo.absoluteFilePath(); // QIcon icon = getMeshOverviewMap(sourcePath); // pItem->setIcon(icon); pItem->setIcon(getIcon(BB_PATH_RESOURCE_ICON(model.png))); pOutFolderContent->insert(pItem, new BBFileInfo(fileInfo.fileName(), BBFileType::Mesh)); } else if (m_TextureSuffixs.contains(suffix)) { // Picture files use themselves as icons pItem->setIcon(getTextureIcon(fileInfo.absoluteFilePath())); pOutFolderContent->insert(pItem, new BBFileInfo(fileInfo.fileName(), BBFileType::Texture)); } else if (m_AudioSuffixs.contains(suffix)) { pItem->setIcon(getIcon(BB_PATH_RESOURCE_PICTURE(audio.jpg))); pOutFolderContent->insert(pItem, new BBFileInfo(fileInfo.fileName(), BBFileType::Audio)); } else if (m_SceneSuffixs.contains(suffix)) { pItem->setIcon(getIcon(BB_PATH_RESOURCE_ICON(scene2.png))); pOutFolderContent->insert(pItem, new BBFileInfo(fileInfo.fileName(), BBFileType::Scene)); } else if (m_ScriptSuffixs.contains(suffix)) { pItem->setIcon(getIcon(BB_PATH_RESOURCE_ICON(python.png))); pOutFolderContent->insert(pItem, new BBFileInfo(fileInfo.fileName(), BBFileType::Script)); } else if (m_MaterialSuffixs.contains(suffix)) { pItem->setIcon(getIcon(BB_PATH_RESOURCE_ICON(material3.png))); pOutFolderContent->insert(pItem, new BBFileInfo(fileInfo.fileName(), BBFileType::Material)); } else { pOutFolderContent->insert(pItem, new BBFileInfo(fileInfo.fileName(), BBFileType::Other)); } } return pItem; } QIcon BBFileSystemDataManager::getMeshOverviewMap(const QString &sourcePath) { // read icon from engine folder if it is created before // if it does not exist, create QString overviewMapPath = getOverviewMapPath(sourcePath); QFile file(overviewMapPath); if (!file.exists()) { //createMeshOverviewMap(sourcePath, overviewMapPath); } return getIcon(overviewMapPath); } void BBFileSystemDataManager::createMeshOverviewMap(const QString &sourcePath, const QString &overviewMapPath) { // set default skybox // m_pPreviewOpenGLWidget->getScene()->setSkyBox(QString(BB_PATH_RESOURCE) + "skyboxs/3/"); // preview of mesh BBGameObject *pModel = m_pPreviewOpenGLWidget->getScene()->createModelForPreview(sourcePath); // Take a screenshot of the overview map as an icon QPixmap pix = m_pPreviewOpenGLWidget->grab(); // Check whether the folder that the overviewMapPath belongs to exists and create it if it does not exist QString parentPath = QFileInfo(overviewMapPath).absolutePath(); QDir dir(parentPath); if (!dir.exists()) dir.mkpath(parentPath); pix.save(overviewMapPath); // remove the mesh m_pPreviewOpenGLWidget->getScene()->deleteGameObject(pModel); } BBFileType BBFileSystemDataManager::getFileType(const QString &filePath) { QTreeWidgetItem *pParentFolderItem = getFolderItemByPath(getParentPath(filePath)); BBFileInfo *pFileInfo = NULL; if (getFileItem(pParentFolderItem, filePath, pFileInfo)) { return pFileInfo->m_eFileType; } else { return BBFileType::Other; } } BBFILE* BBFileSystemDataManager::getFolderContent(QTreeWidgetItem *pItem) { BBFILE *pFolderContent; if (pItem == NULL) { pFolderContent = m_pRootFileData; } else if (pItem->parent()) { pFolderContent = m_FileData.value(pItem); } else { pFolderContent = m_TopLevelFileData.value(pItem); } return pFolderContent; } bool BBFileSystemDataManager::deleteFolderItem(QTreeWidgetItem *pItem) { // release BBFILE corresponding the pItem BBFILE *pFolderContent = getFolderContent(pItem); qDeleteAll(*pFolderContent); if (pItem) { if (pItem->parent()) { m_FileData.remove(pItem); } else { m_TopLevelFileData.remove(pItem); } } BB_SAFE_DELETE(pFolderContent); BB_SAFE_DELETE(pItem); return true; } bool BBFileSystemDataManager::moveFolderItem(QTreeWidgetItem *pFolderItem, QTreeWidgetItem *pOldParentItem, QTreeWidgetItem *pNewParentItem) { // also need to move corresponding list item // must perform it before changing the parent of pFolderItem QListWidgetItem *pFileItem = getFileItem(pFolderItem); BBFILE *pOldParentFolderContent = getFolderContent(pOldParentItem); BBFILE *pNewParentFolderContent = getFolderContent(pNewParentItem); BBFileInfo *pFileInfo = pOldParentFolderContent->take(pFileItem); pNewParentFolderContent->insert(pFileItem, pFileInfo); if (pOldParentItem) { if (pNewParentItem) { // pItem was not in the top level before // pItem is not in the top level now pOldParentItem->removeChild(pFolderItem); pNewParentItem->addChild(pFolderItem); } else { // pItem was not in the top level before // pItem is in the top level now pOldParentItem->removeChild(pFolderItem); BBFILE *pFolderContent = m_FileData.take(pFolderItem); m_TopLevelFileData.insert(pFolderItem, pFolderContent); } } else { if (pNewParentItem) { // pItem was in the top level before // pItem is not in the top level now pNewParentItem->addChild(pFolderItem); BBFILE *pFolderContent = m_TopLevelFileData.take(pFolderItem); m_FileData.insert(pFolderItem, pFolderContent); } // else // { // pItem was in the top level before // pItem is in the top level now // } } return true; } bool BBFileSystemDataManager::importFiles(const QFileInfo &fileInfo, const QString &newPath) { QString suffix = fileInfo.suffix(); if (m_TextureSuffixs.contains(suffix) || m_ScriptSuffixs.contains(suffix)) { // import directly BB_PROCESS_ERROR_RETURN_FALSE(QFile::copy(fileInfo.absoluteFilePath(), getExclusiveFilePath(newPath))); } else if (m_MeshSuffixs.contains(suffix)) { QString targetPath = getExclusiveFilePath(newPath); BB_PROCESS_ERROR_RETURN_FALSE(QFile::copy(fileInfo.absoluteFilePath(), targetPath)); //createMeshOverviewMap(targetPath, getOverviewMapPath(targetPath)); } return true; } /** * @brief BBFileSystemDataManager::loadImportedAsset * Traverse the child files of parentPath and construct corresponding items for the newly imported files * @param parentPath * @return */ bool BBFileSystemDataManager::loadImportedData(const QString &parentPath) { QTreeWidgetItem *pParentFolderItem = getFolderItemByPath(parentPath); BBFILE *pFolderContent = getFolderContent(pParentFolderItem); BB_PROCESS_ERROR_RETURN_FALSE(pFolderContent); // the names of all sub files QList<QString> names; for (BBFILE::Iterator it = pFolderContent->begin(); it != pFolderContent->end(); it++) { names.append(it.value()->m_FileName); } buildFileData(parentPath, pParentFolderItem, pFolderContent, names); return true; } <|start_filename|>Resources/shaders/GI/FLC_IndirectShading.frag<|end_filename|> #version 430 core in vec2 v2f_texcoord; out vec4 FragColor; struct TriangleCut { vec4 center; vec4 normal_and_level; vec4 color_and_area; }; layout (std140, binding = 1) buffer Triangles { TriangleCut triangles[]; }; layout (binding = 0, offset = 0) uniform atomic_uint TriangleID; uniform float S[64]; uniform sampler2D AlbedoTex; uniform sampler2D NormalTex; uniform sampler2D PositionTex; uniform sampler2D TriangleCutPassDebugTex; const float PI = 3.1415926; float getF(int k, float d) { if (k == 0) return 1; float DkMinus = sqrt(S[k - 1]); float Dk = sqrt(S[k]); float DkPlus = sqrt(S[k + 1]); if (d <= sqrt(S[0])) return 0; else if (d >= DkMinus && d <= Dk) return (d - DkMinus) / (Dk - DkMinus); else if (d >= Dk && d <= DkPlus) return (DkPlus - d) / (DkPlus - Dk); else return 0; } float getSumSF(int level, float d) { float sum = 0.0; for (int i = 0; i <= level; i++) { sum += S[i] * getF(i, d); } return sum; } void main(void) { int VPL_num = int(atomicCounter(TriangleID)); VPL_num = 5000; // GBuffer vec3 color = texture(AlbedoTex, v2f_texcoord).xyz; vec3 normal = texture(NormalTex, v2f_texcoord).xyz; vec3 position = texture(PositionTex, v2f_texcoord).xyz; vec3 indirect_light = vec3(0.0); for (int i = 0; i < VPL_num; i++) { vec3 VPL_position = triangles[i].center.xyz; vec3 VPL_normal = normalize(triangles[i].normal_and_level.xyz); // L * P / PI vec3 VPL_radiance = triangles[i].color_and_area.xyz * color * 1.5 / PI; vec3 w = position - VPL_position; float d2 = dot(w, w); int level = int(triangles[i].normal_and_level.w); float d = sqrt(d2); // SumSF * H // indirect_light += getSumSF(level, d) * VPL_radiance * max(dot(VPL_normal, w), 0.0) * max(dot(normal, -w), 0.0) / d2; indirect_light += getSumSF(1, d) * VPL_radiance * max(dot(VPL_normal, w), 0.0) * max(dot(normal, -w), 0.0) / d2; } FragColor = vec4(indirect_light, 1.0); // FragColor = texture(TriangleCutPassDebugTex, v2f_texcoord); } <|start_filename|>Resources/shaders/base.frag<|end_filename|> varying vec4 V_Color; void main(void) { gl_FragColor = V_Color; } <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFileSystemDockWidget.h<|end_filename|> #ifndef BBFILESYSTEMDOCKWIDGET_H #define BBFILESYSTEMDOCKWIDGET_H #include <QDockWidget> #include "Utils/BBUtils.h" #include <QUrl> using namespace BBFileSystem; class BBFileSystemManager; class BBPreviewOpenGLWidget; namespace Ui { class BBFileSystemDockWidget; } class BBFileSystemDockWidget : public QDockWidget { Q_OBJECT public: explicit BBFileSystemDockWidget(QWidget *pParent = 0); ~BBFileSystemDockWidget(); void bindPreviewOpenGLWidget(BBPreviewOpenGLWidget *pPreviewOpenGLWidget); void createProject(); void openProject(); BBFileSystemManager* getFileSystemManager() { return m_pFileSystemManager; } private slots: void removeCurrentItem(); void clickItemInFolderTree(const QString &filePath, QTreeWidgetItem *pItem); void clickItemInFileList(const QString &filePath, const BBFileType &eType); void pressItemInFileList(const BBFileType &eType); void doubleClickItemInFileList(const QString &filePath, const BBFileType &eType); void changeCurrentItemInFileList(BBFileType eCurrentType, BBFileType ePreviousType); void inFocusInFileList(); void clickItemInFolderPathBar(const QString &filePath); void newFolder(const QString &parentPath, const BBSignalSender &eSender); void newFile(const QString &parentPath, int nType); void saveScene(); void showInFolder(const QString &filePath); void renameInFolderTree(QTreeWidgetItem *pParentFolderItem, const QString &oldPath, const QString &newPath); void renameInFileList(QListWidgetItem *pFileItem, const QString &oldPath, const QString &newPath); void deleteFolderInFolderTree(QTreeWidgetItem *pItem); void deleteFilesInFileList(const QList<QListWidgetItem*> &items); void importAsset(const QString &parentPath, const QList<QUrl> &urls); void moveFolders(const QList<QTreeWidgetItem*> &items, QTreeWidgetItem *pNewParentItem, bool bCopy); void moveFolders(const QList<QString> &oldFilePaths, const QString &newParentPath, bool bCopy); void moveFiles(const QList<QString> &oldFilePaths, QTreeWidgetItem *pNewParentItem, bool bCopy); void moveFiles(const QList<QListWidgetItem*> &items, const QString &oldParentPath, const QString &newParentPath, bool bCopy); void updateAll(); signals: void updateFolderPathBar(); void updateFolderPathBar(const QString &filePath); void showMaterialPreview(const QString &filePath); void showMaterialInPropertyManager(const QString &filePath); void removeMaterialPreview(); void removeCurrentItemInHierarchyTree(); private: void setConnect(); Ui::BBFileSystemDockWidget *m_pUi; BBFileSystemManager *m_pFileSystemManager; }; #endif // BBFILESYSTEMDOCKWIDGET_H <|start_filename|>Resources/shaders/translucent.frag<|end_filename|> varying vec3 V_view_dir; varying vec4 V_texcoord; varying vec4 V_normal; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; uniform float Normal_Distortion; uniform float Attenuation; uniform float Strength; uniform sampler2D Thickness_Map; uniform float Thickness; vec3 lightingTranslucent(vec3 light_dir, vec3 normal, vec3 light_color, float thickness) { vec3 H = light_dir + normal * Normal_Distortion; float _LdotV = dot(-H, V_view_dir); float I = pow(clamp(_LdotV, 0.0, 1.0), Attenuation) * Strength; return I * thickness * light_color; } void main(void) { Attenuation *= 10.0; vec4 final_color = vec4(1.0); // diffuse vec3 N = normalize(V_normal); vec3 L = normalize(BBLightPosition.xyz); float NdotL = max(0.3, dot(N, L)); final_color *= NdotL; float thickness_tex = 1 - texture2D(Thickness_Map, V_texcoord.xy).r; thickness_tex = mix(1, thickness_tex, Thickness); // transmission // Facing the light, the effect is strong final_color.xyz += lightingTranslucent(L, N, BBLightColor, thickness_tex); gl_FragColor = final_color; } <|start_filename|>Code/BBearEditor/Engine/Render/Lighting/BBSphericalHarmonicLighting.cpp<|end_filename|> #include "BBSphericalHarmonicLighting.h" #include "Utils/BBUtils.h" #include <QImage> #include "Scene/BBSceneManager.h" #include "Scene/BBScene.h" #include "3D/BBSkyBox.h" #include "Math/BBMath.h" int BBSphericalHarmonicLighting::m_nDegree = 9; int BBSphericalHarmonicLighting::m_nWidth = 1024; int BBSphericalHarmonicLighting::m_nHeight = 1024; QList<QVector3D> BBSphericalHarmonicLighting::m_CoefficientL; void BBSphericalHarmonicLighting::computeLightingData(int nAlgorithmIndex) { if (nAlgorithmIndex == 0) { bakeLightingMap(); } else { computeCoefficientL(); } } const float* BBSphericalHarmonicLighting::getCoefficientL() { float *L = new float[m_nDegree * 4]; for (int i = 0; i < m_nDegree; i++) { L[i * 4] = m_CoefficientL[i].x(); L[i * 4 + 1] = m_CoefficientL[i].y(); L[i * 4 + 2] = m_CoefficientL[i].z(); L[i * 4 + 3] = 0.0f; } return L; } int BBSphericalHarmonicLighting::getCoefficientLCount() { return m_CoefficientL.count(); } void BBSphericalHarmonicLighting::bakeLightingMap() { QImage *pSkyBoxSides = loadSkyBox(); m_nWidth = pSkyBoxSides[0].width(); m_nHeight = pSkyBoxSides[0].height(); // test m_nWidth = 20; m_nHeight = 20; // Generally, 9 coefficients are taken // A coefficient exists in a channel of a image -> 3 images // 6 sides of skybox needs 18 images m_CoefficientL.clear(); for (int d = 0; d < m_nDegree; d++) { m_CoefficientL.append(QVector3D()); } // RGB 3 channels, save 1 coefficient respectively // compute 1 x m_nDegree coefficient corresponding to 1 normal // 1 coefficient is 1 channel of 1 pixel in 1 image // m_nDegree channels for (int k = 0; k < 6; k++) { int nMapCount = ceil((float)m_nDegree / 3); QImage bakedMaps[nMapCount]; for (int nMapIndex = 0; nMapIndex < nMapCount; nMapIndex++) { bakedMaps[nMapIndex] = QImage(m_nWidth, m_nHeight, QImage::Format_RGB32); } for (int j = 0; j < m_nWidth; j++) { for (int i = 0; i < m_nHeight; i++) { float px = (float)i + 0.5f; float py = (float)j + 0.5f; float u = 2.0f * (px / (float)m_nWidth) - 1.0f; float v = 2.0f * (py / (float)m_nHeight) - 1.0f; float dx = 1.0f / (float)m_nWidth; float x0 = u - dx; float y0 = v - dx; float x1 = u + dx; float y1 = v + dx; float da = computeSphereSurfaceArea(x0, y0) - computeSphereSurfaceArea(x0, y1) - computeSphereSurfaceArea(x1, y0) + computeSphereSurfaceArea(x1, y1); u = (float)j / (m_nWidth - 1); v = 1.0f - (float)i / (m_nHeight - 1); QColor skyBoxPixelColor = pSkyBoxSides[k].pixelColor(i, j); QVector3D skyBoxColor = QVector3D(skyBoxPixelColor.redF(), skyBoxPixelColor.greenF(), skyBoxPixelColor.blueF()); // The pixel position of the sky box is normalized and projected onto the sphere QVector3D normalizedSkyBoxPixel = cubeUV2XYZ(k, u, v).normalized(); QList<float> Y = getYBasis(normalizedSkyBoxPixel); for (int d = 0; d < m_nDegree; d++) { m_CoefficientL[d] += skyBoxColor * Y[d] * da; } // normals of sphere for (int nk = 0; nk < 6; nk++) { for (int nj = 0; nj < m_nWidth; nj++) { for (int ni = 0; ni < m_nHeight; ni++) { float nu = (float)nj / (m_nWidth - 1); float nv = 1.0f - (float)ni / (m_nHeight - 1); QVector3D sphereNormal = cubeUV2XYZ(nk, nu, nv).normalized(); for (int nMapIndex = 0, d = 0; nMapIndex < nMapCount; nMapIndex++, d += 3) { QColor color = bakedMaps[nMapIndex].pixelColor(ni, nj); float r = color.redF(); float g = color.greenF(); float b = color.blueF(); float tmp = QVector3D::dotProduct(sphereNormal, normalizedSkyBoxPixel) * da; // Channel exceeding m_nDegree is 0 if (d < m_nDegree) r += Y[d] * tmp; if (d + 1 < m_nDegree) g += Y[d + 1] * tmp; if (d + 2 < m_nDegree) b += Y[d + 2] * tmp; if (r > 1.0f) r = 1.0f; if (g > 1.0f) g = 1.0f; if (b > 1.0f) b = 1.0f; if (r < 0.0f) r = 0.0f; if (g < 0.0f) g = 0.0f; if (b < 0.0f) b = 0.0f; color.setRgbF(r, g, b); bakedMaps[nMapIndex].setPixelColor(ni, nj, color); } } } } } } // save map for (int nMapIndex = 0; nMapIndex < nMapCount; nMapIndex++) { bakedMaps[nMapIndex].save(BBConstant::BB_PATH_PROJECT_ENGINE + "SH_LightMap_t" + QString::number(k) + "_" + QString::number(nMapIndex) + ".png"); } } } void BBSphericalHarmonicLighting::computeCoefficientL() { QImage *pSkyBoxSides = loadSkyBox(); m_nWidth = pSkyBoxSides[0].width(); m_nHeight = pSkyBoxSides[0].height(); // Generally, 9 coefficients are taken // A coefficient exists in a channel of a image -> 3 images // 6 sides of skybox needs 18 images m_CoefficientL.clear(); for (int d = 0; d < m_nDegree; d++) { m_CoefficientL.append(QVector3D()); } // RGB 3 channels, save 1 coefficient respectively // compute 1 x m_nDegree coefficient corresponding to 1 normal // 1 coefficient is 1 channel of 1 pixel in 1 image // m_nDegree channels for (int k = 0; k < 6; k++) { for (int j = 0; j < m_nWidth; j++) { for (int i = 0; i < m_nHeight; i++) { float px = (float)i + 0.5f; float py = (float)j + 0.5f; float u = 2.0f * (px / (float)m_nWidth) - 1.0f; float v = 2.0f * (py / (float)m_nHeight) - 1.0f; float dx = 1.0f / (float)m_nWidth; float x0 = u - dx; float y0 = v - dx; float x1 = u + dx; float y1 = v + dx; float da = computeSphereSurfaceArea(x0, y0) - computeSphereSurfaceArea(x0, y1) - computeSphereSurfaceArea(x1, y0) + computeSphereSurfaceArea(x1, y1); u = (float)j / (m_nWidth - 1); v = 1.0f - (float)i / (m_nHeight - 1); QColor skyBoxPixelColor = pSkyBoxSides[k].pixelColor(i, j); QVector3D skyBoxColor = QVector3D(skyBoxPixelColor.redF(), skyBoxPixelColor.greenF(), skyBoxPixelColor.blueF()); // The pixel position of the sky box is normalized and projected onto the sphere QVector3D normalizedSkyBoxPixel = cubeUV2XYZ(k, u, v).normalized(); QList<float> Y = getYBasis(normalizedSkyBoxPixel); for (int d = 0; d < m_nDegree; d++) { m_CoefficientL[d] += skyBoxColor * Y[d] * da; } } } } } QImage* BBSphericalHarmonicLighting::loadSkyBox() { QImage *pSkyBoxSides = new QImage[6]; QString filePath = BBSceneManager::getScene()->getSkyBox()->getSkyBoxFilePath(); pSkyBoxSides[0] = QImage(filePath + "right"); pSkyBoxSides[1] = QImage(filePath + "left"); pSkyBoxSides[2] = QImage(filePath + "bottom"); pSkyBoxSides[3] = QImage(filePath + "top"); pSkyBoxSides[4] = QImage(filePath + "back"); pSkyBoxSides[5] = QImage(filePath + "front"); return pSkyBoxSides; } float BBSphericalHarmonicLighting::computeSphereSurfaceArea(double x, double y) { return atan2(x * y, sqrt(x * x + y * y + 1.0)); } QVector3D BBSphericalHarmonicLighting::cubeUV2XYZ(int nSkyBoxSideIndex, double u, double v) { u = u * 2.0f - 1.0f; v = v * 2.0f - 1.0f; switch (nSkyBoxSideIndex) { case 0: // +x return QVector3D(1, v, -u); case 1: // -x return QVector3D(-1, v, u); case 2: // +y return QVector3D(u, 1, -v); case 3: // -y return QVector3D(u, -1, v); case 4: // +z return QVector3D(u, v, 1); case 5: // -z return QVector3D(-u, v, -1); } return QVector3D(); } QList<float> BBSphericalHarmonicLighting::getYBasis(const QVector3D &normal) { QList<float> Y; float x = normal.x(); float y = normal.y(); float z = normal.z(); Y.append(1.0f / 2.0f * sqrt(1.0f / PI)); Y.append(sqrt(3.0f / (4.0f * PI)) * z); Y.append(sqrt(3.0f / (4.0f * PI)) * y); Y.append(sqrt(3.0f / (4.0f * PI)) * x); Y.append(1.0f / 2.0f * sqrt(15.0f / PI) * x * z); Y.append(1.0f / 2.0f * sqrt(15.0f / PI) * z * y); Y.append(1.0f / 4.0f * sqrt(5.0f / PI) * (-x * x - z * z + 2 * y * y)); Y.append(1.0f / 2.0f * sqrt(15.0f / PI) * y * x); Y.append(1.0f / 4.0f * sqrt(15.0f / PI) * (x * x - z * z)); Y.append(1.0f / 4.0f * sqrt(35.0f / (2.f * PI)) * (3 * x * x - z * z) * z); Y.append(1.0f / 2.0f * sqrt(105.0f / PI) * x * z * y); Y.append(1.0f / 4.0f * sqrt(21.0f / (2.f * PI)) * z * (4 * y * y - x * x - z * z)); Y.append(1.0f / 4.0f * sqrt(7.0f / PI) * y * (2 * y * y - 3 * x * x - 3 * z * z)); Y.append(1.0f / 4.0f * sqrt(21.0f / (2.f * PI)) * x * (4 * y * y - x * x - z * z)); Y.append(1.0f / 4.0f * sqrt(105.0f / PI) * (x * x - z * z) * y); Y.append(1.0f / 4.0f * sqrt(35.0f / (2 * PI)) * (x * x - 3 * z * z) * x); return Y; } <|start_filename|>Code/BBearEditor/Editor/Dialog/BBResourceDialog.h<|end_filename|> #ifndef BBRESOURCEDIALOG_H #define BBRESOURCEDIALOG_H #include <QDialog> namespace Ui { class BBResourceDialog; } class BBResourceDialog : public QDialog { Q_OBJECT public: explicit BBResourceDialog(const QString &folderPath, QWidget *pParent = 0); ~BBResourceDialog(); QString getCurrentItemFilePath(); private: bool loadListItems(const QString &folderPath); Ui::BBResourceDialog *m_pUi; static QSize m_ItemSize; QList<QString> m_ItemFilePaths; }; #endif // BBRESOURCEDIALOG_H <|start_filename|>External/ProtoBuffer/lib/CMakeFiles/libprotobuf.dir/cmake_clean.cmake<|end_filename|> file(REMOVE_RECURSE "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj.d" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.obj" "CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.obj.d" "libprotobuf.a" "libprotobuf.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/libprotobuf.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <|start_filename|>Code/BBearEditor/Engine/Physics/FluidSystem/BBSPHParticleSystem.h<|end_filename|> #ifndef BBSPHPARTICLESYSTEM_H #define BBSPHPARTICLESYSTEM_H #include <QVector3D> #define MAX_PARTICLE 500 struct BBSPHParticle { QVector3D m_Position; QVector3D m_Acceleration; QVector3D m_Velocity; QVector3D m_EvalVelocity; float m_fDensity; float m_fPressure; QVector3D m_SumGradient; float m_SumGradient2; QVector3D m_PredictedPosition; float m_fPredictedDensity; float m_fCorrectPressure; QVector3D m_CorrectPressureForce; float m_fDensityError; float m_fKernel; // Index to the next particle int m_nNextIndex; BBSPHParticle() { m_Position = QVector3D(0, 0, 0); m_Acceleration = QVector3D(0, 0, 0); m_Velocity = QVector3D(0, 0, 0); m_EvalVelocity = QVector3D(0, 0, 0); m_fDensity = 0.0f; m_fPressure = 0.0f; m_SumGradient = QVector3D(0, 0, 0); m_SumGradient2 = 0.0f; m_PredictedPosition = QVector3D(0, 0, 0); m_fPredictedDensity = 0.0f; m_fCorrectPressure = 0.0f; m_CorrectPressureForce = QVector3D(0, 0, 0); m_fDensityError = 0.0f; m_fKernel = 0.0f; m_nNextIndex = -1; } }; class BBSPHParticleSystem { public: BBSPHParticleSystem(); virtual ~BBSPHParticleSystem(); void reset(unsigned int nCapacity); BBSPHParticle* addParticle(float x, float y, float z); BBSPHParticle* getParticle(unsigned int nIndex); int getSize() { return m_nParticleCount; } private: BBSPHParticle *m_pParticleBuffer; unsigned int m_nParticleCount; unsigned int m_nBufferCapacity; }; #endif // BBSPHPARTICLESYSTEM_H <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFileSystemDataManager.h<|end_filename|> #ifndef BBFILESYSTEMDATAMANAGER_H #define BBFILESYSTEMDATAMANAGER_H #include <QMap> #include <QIcon> #include <QColor> #include "Utils/BBUtils.h" using namespace BBFileSystem; class QFileInfo; class BBPreviewOpenGLWidget; class BBFileSystemDataManager { public: BBFileSystemDataManager(); ~BBFileSystemDataManager(); public: void bindPreviewOpenGLWidget(BBPreviewOpenGLWidget *pPreviewOpenGLWidget) { m_pPreviewOpenGLWidget = pPreviewOpenGLWidget; } inline void setCurrentViewedItem(QTreeWidgetItem *pItem) { m_pCurrentViewedItem = pItem; } inline QTreeWidgetItem* getCurrentViewedItem() { return m_pCurrentViewedItem; } void load(); QList<QTreeWidgetItem*> getFolderTreeWidgetTopLevelItems(); bool getFileListWidgetItems(QTreeWidgetItem *pItem, BBFILE *&pOutFolderContent); QTreeWidgetItem* getFolderItemByPath(const QString &absolutePath); QTreeWidgetItem* getParentFolderItem(const QString &filePath); QListWidgetItem* getFileItem(QTreeWidgetItem *pFolderItem); QListWidgetItem* getFileItem(QTreeWidgetItem *pParentFolderItem, const QString &filePath); QListWidgetItem* getFileItem(QTreeWidgetItem *pParentFolderItem, const QString &filePath, BBFileInfo *&pOutFileInfo); inline QList<QListWidgetItem*> getSelectedFileItems() { return m_SelectedFileItems; } bool openFile(const QString &filePath); bool newFolder(const QString &parentPath, QTreeWidgetItem *&pOutFolderItem, QListWidgetItem *&pOutFileItem); bool newFile(const QString &parentPath, int nType, QListWidgetItem *&pOutFileItem); bool newFile(const QString &parentPath, QString &outFileName, QString &outFilePath, QListWidgetItem *&pOutFileItem); /* Scene */ bool openScene(const QString &defaultSavedParentPath, const QString &openedPath); bool saveScene(const QString &defaultParentPath, QListWidgetItem *&pOutFileItem); /* Material */ bool showInFolder(const QString &filePath); bool rename(QTreeWidgetItem *pParentFolderItem, QListWidgetItem *pFileItem, const QString &oldPath, const QString &newPath); bool deleteFolder(QTreeWidgetItem *pItem); bool deleteFiles(QTreeWidgetItem *pParentItem, const QString &parentPath, const QList<QListWidgetItem*> &items); bool importFiles(const QString &parentPath, const QList<QUrl> &urls); bool moveFolders(const QList<QTreeWidgetItem*> &items, QTreeWidgetItem *pNewParentItem, bool bCopy, QList<QListWidgetItem*> &outSelectedItems); bool moveFolders(const QList<QString> &oldFilePaths, const QString &newParentPath, bool bCopy, QList<QListWidgetItem*> &outSelectedItems); bool moveFiles(const QList<QString> &oldFilePaths, QTreeWidgetItem *pNewParentItem, bool bCopy, QList<QTreeWidgetItem*> &outSelectedItems); bool moveFiles(const QList<QListWidgetItem*> &items, const QString &oldParentPath, const QString &newParentPath, bool bCopy); bool moveFiles(const QList<QListWidgetItem*> &items, const QString &oldParentPath, QTreeWidgetItem *pOldParentItem, const QString &newParentPath, QTreeWidgetItem *pNewParentItem, bool bCopy); public: static QString getAbsolutePath(const QString &relativePath); static QString getAbsolutePath(QTreeWidgetItem *pItem); static QString getExclusiveFolderPath(const QString &parentPath, QString &fileName); static QString getExclusiveFolderPath(const QString &filePath); static QString getExclusiveFilePath(const QString &parentPath, QString &fileName); static QString getExclusiveFilePath(const QString &filePath); static QString getFileSuffix(const QFileInfo &fileInfo); static QString getFileSuffix(const QString &name); static QString getBaseName(const QString &name); static QString getFileNameByPath(const QString &filePath); static QString getParentPath(const QString &filePath); static QString getOverviewMapPath(const QString &sourcePath); static QColor getFileLogoColor(const BBFileType &eFileType); static QString getEngineAuxiliaryFolderPath(const QString &sourcePath); static QIcon getIcon(const QString &path); static QIcon getTextureIcon(const QString &path); static bool copyFolder(const QString &fromDir, const QString &toDir); static bool isMovablePath(const QString &sourcePath, const QString &destParentPath); static bool moveFolder(const QString &oldPath, const QString &newPath, bool bCopy = false); static bool moveFile(const QString &oldPath, const QString &newPath, BBFileType eFileType, bool bCopy = false); static bool judgeFileType(const QString &filePath, const BBFileType &eReferenceFileType); static QList<QString> m_MeshSuffixs; static QList<QString> m_TextureSuffixs; static QList<QString> m_AudioSuffixs; static QList<QString> m_SceneSuffixs; static QList<QString> m_ScriptSuffixs; static QList<QString> m_MaterialSuffixs; static QString m_MeshFileLogoColor; static QString m_TextureFileLogoColor; static QString m_AudioFileLogoColor; static QString m_MaterialFileLogoColor; private: void buildFileData(const QString &rootPath, QTreeWidgetItem *pRootItem, BBFILE *&pRootFileData, const QList<QString> &nameFilter = QList<QString>()); void buildFileData(QQueue<BBFOLDER> &queue, const QList<QString> &nameFilter = QList<QString>()); BBFILE* loadFolderContent(const QString &parentPath, QList<QListWidgetItem*> &newItems, const QList<QString> &nameFilter = QList<QString>()); QListWidgetItem* addFileItem(const QFileInfo &fileInfo, BBFILE *&pOutFolderContent); QIcon getMeshOverviewMap(const QString &sourcePath); void createMeshOverviewMap(const QString &sourcePath, const QString &overviewMapPath); BBFileType getFileType(const QString &filePath); BBFILE* getFolderContent(QTreeWidgetItem *pItem); bool deleteFolderItem(QTreeWidgetItem *pItem); bool moveFolderItem(QTreeWidgetItem *pFolderItem, QTreeWidgetItem *pOldParentItem, QTreeWidgetItem *pNewParentItem); bool importFiles(const QFileInfo &fileInfo, const QString &newPath); bool loadImportedData(const QString &parentPath); BBPreviewOpenGLWidget *m_pPreviewOpenGLWidget; BBFILE *m_pRootFileData; QMap<QTreeWidgetItem*, BBFILE*> m_TopLevelFileData; QMap<QTreeWidgetItem*, BBFILE*> m_FileData; QTreeWidgetItem *m_pCurrentViewedItem; QList<QListWidgetItem*> m_SelectedFileItems; }; #endif // BBFILESYSTEMDATAMANAGER_H <|start_filename|>Code/BBearEditor/Editor/Common/BBResizableWidget.cpp<|end_filename|> #include "BBResizableWidget.h" BBResizableWidget::BBResizableWidget(QWidget *parent) : QWidget(parent) { m_Size = geometry().size(); } QSize BBResizableWidget::sizeHint() const { return m_Size; } void BBResizableWidget::updateSizeHint(const QSize &size) { m_Size = size; updateGeometry(); } <|start_filename|>Resources/shaders/water.frag<|end_filename|> varying vec4 V_texcoord; varying vec4 V_normal_uv; varying vec4 V_world_space_pos; varying vec4 V_world_space_normal; varying vec4 V_clip_space_pos; varying vec4 V_view_space_pos; varying mat3 V_TBN; varying mat4 V_viewMatrix_I; uniform sampler2D BBCameraDepthTexture; uniform sampler2D BBCameraColorTexture; uniform vec4 BBLightPosition; uniform vec4 BBCameraPosition; uniform vec4 BBTime; uniform vec4 BBColor_Water_Color01; uniform vec4 BBColor_Water_Color02; uniform sampler2D Foam; uniform float FoamRange; uniform float FoamNoise; uniform vec4 BBColor_Foam_Color; uniform sampler2D Normal_Map; uniform float Distort; uniform vec4 BBColor_Specular_Color; uniform float Specular_Intensity; uniform float Specular_Smoothness; uniform samplerCube Reflection_Cube; uniform sampler2D Caustics_Map; uniform float Speed; float computeLinearEyeDepth(float z, vec4 z_buffer_params) { return 1.0 / (z_buffer_params.z * z + z_buffer_params.w); } vec3 decodeNormalMap(sampler2D normal_map, vec2 uv) { vec3 normal = vec3(texture2D(normal_map, uv)); // 0~1 -> -1~1 normal = normal * 2.0 - vec3(1.0); normal = normalize(normal); normal = V_TBN * normal; normal = normalize(normal); return normal; } void main(void) { // params float z_near = 0.1; float z_far = 1000.0; float zc0 = (1.0 - z_far / z_near) / 2.0; float zc1 = (1.0 + z_far / z_near) / 2.0; vec4 z_buffer_params = vec4(zc0, zc1, zc0 / z_far, zc1 / z_far); vec4 final_color = vec4(1.0); // water depth (static) vec2 screen_space_uv = V_clip_space_pos.xy / V_clip_space_pos.w * 0.5 + vec2(0.5); float depth_scene = texture2D(BBCameraDepthTexture, screen_space_uv).r; depth_scene = computeLinearEyeDepth(depth_scene, z_buffer_params); float depth_water = V_view_space_pos.z; depth_water *= 2.0; depth_water += depth_scene; // water color vec4 water_color = mix(BBColor_Water_Color01, BBColor_Water_Color02, depth_water); // water foam // 0~1 -> 0~5 FoamRange *= 5.0; float foam_range = depth_water * FoamRange; float foam_tex = texture2D(Foam, V_texcoord.xy).r; foam_tex = pow(foam_tex, FoamNoise); float foam_mask = step(foam_range, foam_tex); // vec4 foam_color = foam_mask * BBColor_Foam_Color; // water distort vec3 normal_tex01 = decodeNormalMap(Normal_Map, V_normal_uv.xy); vec3 normal_tex02 = decodeNormalMap(Normal_Map, V_normal_uv.zw); vec3 normal_tex = normal_tex01 * normal_tex02; vec2 distort_uv = mix(screen_space_uv, normal_tex01.rr, Distort); // Remove the distortion effect of objects on the water float distort_depth_scene = texture2D(BBCameraDepthTexture, distort_uv).r; distort_depth_scene = computeLinearEyeDepth(distort_depth_scene, z_buffer_params); float distort_depth_water = V_view_space_pos.z; distort_depth_water *= 2.0; distort_depth_water += distort_depth_scene; vec2 final_distort_uv = distort_uv; if (distort_depth_water < 0) { // the region of objects on the water final_distort_uv = screen_space_uv; } vec4 distort_color = texture2D(BBCameraColorTexture, final_distort_uv); // Caustics vec4 view_space_depth = vec4(1.0); view_space_depth.xy = V_view_space_pos.xy * distort_depth_scene / (-V_view_space_pos.z); view_space_depth.z = distort_depth_scene; // Coordinates of points on the depth map in view space -> world space of current object vec4 world_space_depth = V_viewMatrix_I * view_space_depth; vec2 caustics_uv01 = world_space_depth.xz * 0.3 + vec2(0.0005) * Speed * BBTime.z; vec4 caustics_tex01 = texture2D(Caustics_Map, caustics_uv01); vec2 caustics_uv02 = world_space_depth.xz * 0.4 + vec2(-0.000535, 0.000675) * Speed * BBTime.z; vec4 caustics_tex02 = texture2D(Caustics_Map, caustics_uv02); vec4 caustics_tex = min(caustics_tex01, caustics_tex02); // Specular vec3 N = mix(normalize(V_world_space_normal.xyz), normal_tex, 0.5); vec3 L = normalize(BBLightPosition.xyz); vec3 V = normalize(BBCameraPosition.xyz - V_world_space_pos.xyz); vec3 H = normalize(L + V); float NdotH = dot(N, H); Specular_Smoothness *= 50; vec3 specular = BBColor_Specular_Color * Specular_Intensity * pow(clamp(dot(N, H), 0.0, 1.0), Specular_Smoothness); // Reflection vec3 reflection_uvw = reflect(-V, N); vec4 reflection_tex = textureCube(Reflection_Cube, reflection_uvw); // If the line of sight is perpendicular to the plane, the reflection effect is small float fresnel = 1 - clamp(dot(N, V), 0.0, 1.0); // Weaken reflection effect fresnel = pow(fresnel, 3); vec4 reflection = reflection_tex * fresnel; if (foam_mask == 0.0) { final_color.rgb = distort_color.rgb * water_color.rgb; } else { final_color.rgb = BBColor_Foam_Color.rgb; } final_color.rgb += specular; final_color.rgb += reflection.rgb; final_color.rgb += caustics_tex.rgb; gl_FragColor = final_color; } <|start_filename|>Code/BBearEditor/Engine/Python/BBPythonVM.cpp<|end_filename|> #include "BBPythonVM.h" #include "Utils/BBUtils.h" #include <iostream> PyObject* BBPythonVM::m_pModule = nullptr; void BBPythonVM::runScript(const QString &path) { bool bResult = false; do { // set home path for python Py_SetPythonHome(L"../../Code/BBearEditor/Engine/Python"); Py_Initialize(); // PyRun_SimpleString("print('Hello World!')"); PyObject *pObj = Py_BuildValue("s", path.toStdString().c_str()); FILE *pFile = _Py_fopen_obj(pObj, "r+"); BB_PROCESS_ERROR(pFile); BB_PROCESS_ERROR(emitValues()); PyRun_SimpleFile(pFile, path.toStdString().c_str()); loadMainModule(); BB_PROCESS_ERROR(m_pModule); BB_PROCESS_ERROR(emitFunc()); // BB_PROCESS_ERROR(loadDictionary()); // BB_PROCESS_ERROR(loadClass()); // BB_PROCESS_ERROR(loadFunc()); bResult = true; } while(0); if (!bResult) { qDebug() << "error"; PyErr_Print(); } Py_XDECREF(m_pModule); Py_Finalize(); } bool BBPythonVM::loadMainModule() { PyObject *pKey = PyUnicode_FromString("__main__"); m_pModule = PyImport_GetModule(pKey); // clear Py_XDECREF(pKey); return true; } bool BBPythonVM::loadDictionary() { // get object by module and name PyObject *pDict = PyObject_GetAttrString(m_pModule, "config"); BB_PROCESS_ERROR_RETURN_FALSE(pDict); PyObject *pKey = PyUnicode_FromString("width"); int nWidth = PyLong_AsLong(PyDict_GetItem(pDict, pKey)); Py_XDECREF(pKey); pKey = PyUnicode_FromString("height"); int nHeight = PyLong_AsLong(PyDict_GetItem(pDict, pKey)); Py_XDECREF(pKey); pKey = PyUnicode_FromString("title"); wchar_t title[1024] = { 0 }; int nSize = PyUnicode_AsWideChar(PyDict_GetItem(pDict, pKey), title, 1023); Py_XDECREF(pKey); qDebug() << "w" << nWidth << "h" << nHeight << "title" << title[0]; Py_XDECREF(pDict); return true; } bool BBPythonVM::loadClass() { // get class PyObject *pPyClass = PyObject_GetAttrString(m_pModule, "BBPythonBase"); BB_PROCESS_ERROR_RETURN_FALSE(pPyClass); // Instantiate object, and invoke __init__, and pass params to constructor (there is no parameter here) PyObject *pObj = PyObject_CallObject(pPyClass, nullptr); BB_PROCESS_ERROR_RETURN_FALSE(pObj); // invoke member func // params: i(int), s(str) PyObject *pRet = PyObject_CallMethod(pObj, "func0", "is", 2021, "Bear"); qDebug() << PyLong_AsLong(pRet); // Member variable PyObject *pVar = PyObject_GetAttrString(pObj, "id"); qDebug() << PyLong_AsLong(pVar); Py_XDECREF(pVar); Py_XDECREF(pRet); Py_XDECREF(pObj); Py_XDECREF(pPyClass); return true; } bool BBPythonVM::loadFunc() { PyObject *pFunc0 = PyObject_GetAttrString(m_pModule, "main"); if (pFunc0 && PyCallable_Check(pFunc0)) { // func obj + params PyObject_CallObject(pFunc0, 0); } PyObject *pFunc1 = PyObject_GetAttrString(m_pModule, "func1"); if (pFunc1 && PyCallable_Check(pFunc1)) { // param list, count = 1 PyObject *pArgs = PyTuple_New(1); PyObject *pList = PyList_New(0); for (int i = 0; i < 5; i++) { PyList_Append(pList, PyLong_FromLong(i + 100)); } PyTuple_SetItem(pArgs, 0, pList); PyObject *pRet = PyObject_CallObject(pFunc1, pArgs); if (pRet) { int nSize = PyList_Size(pRet); for (int i = 0; i < nSize; i++) { PyObject *pVar = PyList_GetItem(pRet, i); if (!pVar) continue; qDebug() << PyLong_AsLong(pVar); } Py_XDECREF(pRet); } // pList has been passed into pArgs Py_XDECREF(pArgs); } Py_XDECREF(pFunc0); Py_XDECREF(pFunc1); return true; } bool BBPythonVM::emitValues() { PyRun_SimpleString("Bear = 100"); return true; } bool BBPythonVM::emitFunc() { PyMethodDef cfuncs[] = { {"cfunc", cfunc, METH_VARARGS, 0}, {NULL} }; PyModule_AddFunctions(m_pModule, cfuncs); return true; } PyObject* BBPythonVM::cfunc(PyObject *pSelf, PyObject *pArgs) { std::cout << "cfunc" << endl; // Py_RETURN_TRUE; } <|start_filename|>Code/BBearEditor/Engine/3D/BBLightIndicator.cpp<|end_filename|> #include "BBLightIndicator.h" #include "Render/BBMaterial.h" #include "Render/BBRenderPass.h" #include "Render/BBDrawCall.h" #include "Render/BBCamera.h" #include "Render/BufferObject/BBVertexBufferObject.h" /** * @brief BBLightIndicator::BBLightIndicator */ BBLightIndicator::BBLightIndicator() : BBLightIndicator(QVector3D(0, 0, 0), QVector3D(0, 0, 0)) { } BBLightIndicator::BBLightIndicator(const QVector3D &position, const QVector3D &rotation) : BBRenderableObject(position, rotation, QVector3D(1, 1, 1)) { } void BBLightIndicator::init() { m_pCurrentMaterial->init("base", BB_PATH_RESOURCE_SHADER(base.vert), BB_PATH_RESOURCE_SHADER(base.frag)); BBRenderableObject::init(); } /** * @brief BBDirectionalLightIndicator::BBDirectionalLightIndicator */ BBDirectionalLightIndicator::BBDirectionalLightIndicator() : BBDirectionalLightIndicator(QVector3D(0, 0, 0), QVector3D(0, 0, 0)) { } BBDirectionalLightIndicator::BBDirectionalLightIndicator(const QVector3D &position, const QVector3D &rotation) : BBLightIndicator(position, rotation) { } void BBDirectionalLightIndicator::init() { m_pVBO = new BBVertexBufferObject(32); for (int i = 0, j = 24; i < 24; i++) { float c = 0.45f * cosf(0.261799f * i); float s = 0.45f * sinf(0.261799f * i); m_pVBO->setPosition(i, c, 1.4f, s); m_pVBO->setColor(i, 0.909804f, 0.337255f, 0.333333f); if (i % 3 == 0) { m_pVBO->setPosition(j, c, -1.4f, s); m_pVBO->setColor(j, 0.909804f, 0.337255f, 0.333333f); j++; } } m_nIndexCount = 64; m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0; i < 24; i++) { m_pIndexes[2 * i] = i; m_pIndexes[2 * i + 1] = i + 1; } m_pIndexes[47] = 0; for (int i = 0; i < 8; i++) { m_pIndexes[48 + 2 * i] = 3 * i; m_pIndexes[48 + 2 * i + 1] = 24 + i; } BBLightIndicator::init(); m_pCurrentMaterial->getBaseRenderPass()->setZTestState(false); BBDrawCall *pDrawCall = new BBDrawCall(); pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_LINES, m_nIndexCount, 0); appendDrawCall(pDrawCall); } void BBDirectionalLightIndicator::render(BBCamera *pCamera) { QMatrix4x4 modelMatrix; modelMatrix.translate(m_Position); // the size does not change with distance float fDistance = (pCamera->getPosition() - m_Position).length(); modelMatrix.scale(fDistance / 12); modelMatrix.rotate(m_Quaternion); BBLightIndicator::render(modelMatrix, pCamera); } /** * @brief BBPointLightIndicator::BBPointLightIndicator */ BBPointLightIndicator::BBPointLightIndicator() : BBPointLightIndicator(QVector3D(0, 0, 0)) { } BBPointLightIndicator::BBPointLightIndicator(const QVector3D &position) : BBLightIndicator(position, QVector3D(0, 0, 0)) { } void BBPointLightIndicator::init() { m_pVBO = new BBVertexBufferObject(144); for (int i = 0; i < 48; i++) { float c = cosf(0.1309f * i); float s = sinf(0.1309f * i); m_pVBO->setPosition(i, c, 0.0f, s); m_pVBO->setNormal(i, c, 0.0f, s); m_pVBO->setColor(i, 0.909804f, 0.337255f, 0.333333f); m_pVBO->setPosition(i + 48, 0.0f, c, s); m_pVBO->setNormal(i + 48, 0.0f, c, s); m_pVBO->setColor(i + 48, 0.909804f, 0.337255f, 0.333333f); m_pVBO->setPosition(i + 96, c, s, 0.0f); m_pVBO->setNormal(i + 96, c, s, 0.0f); m_pVBO->setColor(i + 96, 0.909804f, 0.337255f, 0.333333f); } m_nIndexCount = 288; m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0; i < 48; i++) { m_pIndexes[2 * i] = i; m_pIndexes[2 * i + 1] = i + 1; m_pIndexes[2 * i + 96] = i + 48; m_pIndexes[2 * i + 97] = i + 49; m_pIndexes[2 * i + 192] = i + 96; m_pIndexes[2 * i + 193] = i + 97; } m_pIndexes[95] = 0; m_pIndexes[191] = 48; m_pIndexes[287] = 96; m_pCurrentMaterial->init("diffuse_indicator", BB_PATH_RESOURCE_SHADER(diffuse_indicator.vert), BB_PATH_RESOURCE_SHADER(diffuse.frag)); m_pCurrentMaterial->getBaseRenderPass()->setZTestState(false); // default float *pLightPosition = new float[4] {1.0f, 1.0f, 0.0f, 0.0f}; float *pLightColor = new float[4] {1.0f, 1.0f, 1.0f, 1.0f}; m_pCurrentMaterial->setVector4(LOCATION_LIGHT_POSITION, pLightPosition); m_pCurrentMaterial->setVector4(LOCATION_LIGHT_COLOR, pLightColor); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall(); pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_LINES, m_nIndexCount, 0); appendDrawCall(pDrawCall); } void BBPointLightIndicator::render(BBCamera *pCamera) { QMatrix4x4 modelMatrix; modelMatrix.translate(m_Position); modelMatrix.scale(m_Scale); BBLightIndicator::render(modelMatrix, pCamera); } /** * @brief BBSpotLightIndicator::BBSpotLightIndicator */ BBSpotLightIndicator::BBSpotLightIndicator() : BBSpotLightIndicator(QVector3D(0, 0, 0), QVector3D(0, 0, 0)) { } BBSpotLightIndicator::BBSpotLightIndicator(const QVector3D &position, const QVector3D &rotation) : BBLightIndicator(position, rotation) { } void BBSpotLightIndicator::init() { m_pVBO = new BBVertexBufferObject(25); for (int i = 0; i < 24; i++) { float c = 0.267949f * cosf(0.261799f * i); float s = 0.267949f * sinf(0.261799f * i); m_pVBO->setPosition(i, c, -1.0f, s); m_pVBO->setColor(i, 0.909804f, 0.337255f, 0.333333f); } m_pVBO->setPosition(24, 0.0f, 0.0f, 0.0f); m_pVBO->setColor(24, 0.909804f, 0.337255f, 0.333333f); m_nIndexCount = 56; m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0; i < 24; i++) { m_pIndexes[2 * i] = i; m_pIndexes[2 * i + 1] = i + 1; } m_pIndexes[47] = 0; for (int i = 0; i < 4; i++) { m_pIndexes[2 * i + 48] = 24; m_pIndexes[2 * i + 49] = 6 * i; } BBLightIndicator::init(); BBDrawCall *pDrawCall = new BBDrawCall(); pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_LINES, m_nIndexCount, 0); appendDrawCall(pDrawCall); } void BBSpotLightIndicator::render(BBCamera *pCamera) { QMatrix4x4 modelMatrix; modelMatrix.translate(m_Position); BBLightIndicator::render(modelMatrix, pCamera); } <|start_filename|>Code/BBearEditor/Engine/Render/BBRenderState.cpp<|end_filename|> #include "BBRenderState.h" #define SetBlendState(bEnable) \ do { \ bEnable? glEnable(GL_BLEND) : glDisable(GL_BLEND); \ } while(0) #define SetZTestState(bEnable) \ do { \ bEnable? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); \ } while(0) #define SetAlphaTestState(bEnable) \ do { \ bEnable? glEnable(GL_ALPHA_TEST) : glDisable(GL_ALPHA_TEST); \ } while(0) #define SetCullState(bEnable) \ do { \ bEnable? glEnable(GL_CULL_FACE) : glDisable(GL_CULL_FACE); \ } while(0) #define SetPointSpriteState(bEnable) \ do { \ bEnable? glEnable(GL_POINT_SPRITE) : glDisable(GL_POINT_SPRITE); \ } while(0) #define SetProgramPointSizeState(bEnable) \ do { \ bEnable? glEnable(GL_PROGRAM_POINT_SIZE) : glDisable(GL_PROGRAM_POINT_SIZE); \ } while(0) #define SetCubeMapSeamlessState(bEnable) \ do { \ bEnable? glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS) : glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); \ } while(0) /** * @brief BBRenderState::BBRenderState */ BBRenderState::BBRenderState() { m_PrimitiveType = GL_TRIANGLES; m_bBlend = false; m_bZTest = true; m_bAlphaTest = false; m_ZTestFunc = GL_LEQUAL; m_bWriteR = true; m_bWriteG = true; m_bWriteB = true; m_bWriteZ = true; m_bWriteStencil = false; m_bUseStencil = false; m_bCull = false; m_CullFace = GL_BACK; m_bEnablePointSprite = true; m_bEnableProgramPointSize = true; m_AlphaTestFunc = GL_GREATER; m_fAlphaTestValue = 0.1f; m_fOffsetFactor = 0.0f; m_fOffsetUnit = 0.0f; m_SRCBlendFunc = GL_SRC_ALPHA; m_DSTBlendFunc = GL_ONE_MINUS_SRC_ALPHA; m_ClearStencilValue = -1; m_DrawFace = GL_FRONT; m_PolygonMode = GL_FILL; m_fLineWidth = 1.0f; m_bCubeMapSeamless = true; } void BBRenderState::operator =(const BBRenderState &rs) { memcpy(this, &rs, sizeof(BBRenderState)); } /** * @brief BBGlobalRenderState::BBGlobalRenderState */ BBRenderState BBGlobalRenderState::m_RenderState; void BBGlobalRenderState::init() { SetBlendState(m_RenderState.m_bBlend); glBlendFunc(m_RenderState.m_SRCBlendFunc, m_RenderState.m_DSTBlendFunc); SetZTestState(m_RenderState.m_bZTest); SetAlphaTestState(m_RenderState.m_bAlphaTest); glColorMask(m_RenderState.m_bWriteR, m_RenderState.m_bWriteG, m_RenderState.m_bWriteB, m_RenderState.m_bWriteA); glDepthMask(m_RenderState.m_bWriteZ); glDepthFunc(m_RenderState.m_ZTestFunc); glPolygonMode(m_RenderState.m_DrawFace, m_RenderState.m_PolygonMode); glAlphaFunc(m_RenderState.m_AlphaTestFunc, m_RenderState.m_fAlphaTestValue); glLineWidth(m_RenderState.m_fLineWidth); SetPointSpriteState(m_RenderState.m_bEnablePointSprite); SetProgramPointSizeState(m_RenderState.m_bEnableProgramPointSize); SetCullState(m_RenderState.m_bCull); glCullFace(m_RenderState.m_CullFace); // Correct filtering of cube map SetCubeMapSeamlessState(m_RenderState.m_bCubeMapSeamless); } void BBGlobalRenderState::updateBlendState(bool bEnable) { if (m_RenderState.m_bBlend != bEnable) { m_RenderState.m_bBlend = bEnable; SetBlendState(m_RenderState.m_bBlend); } } void BBGlobalRenderState::updateBlendFunc(unsigned int src, unsigned int dst) { if (m_RenderState.m_SRCBlendFunc != src || m_RenderState.m_DSTBlendFunc != dst) { m_RenderState.m_SRCBlendFunc = src; m_RenderState.m_DSTBlendFunc = dst; glBlendFunc(m_RenderState.m_SRCBlendFunc, m_RenderState.m_DSTBlendFunc); } } void BBGlobalRenderState::updateZTestState(bool bEnable) { if (m_RenderState.m_bZTest != bEnable) { m_RenderState.m_bZTest = bEnable; SetZTestState(m_RenderState.m_bZTest); } } void BBGlobalRenderState::updateAlphaTestState(bool bEnable) { if (m_RenderState.m_bAlphaTest != bEnable) { m_RenderState.m_bAlphaTest = bEnable; SetAlphaTestState(m_RenderState.m_bAlphaTest); } } void BBGlobalRenderState::updateColorMask(bool r, bool g, bool b, bool a) { if (m_RenderState.m_bWriteR != r || m_RenderState.m_bWriteG != g || m_RenderState.m_bWriteB != b || m_RenderState.m_bWriteA != a) { m_RenderState.m_bWriteR = r; m_RenderState.m_bWriteG = g; m_RenderState.m_bWriteB = b; m_RenderState.m_bWriteA = a; glColorMask(m_RenderState.m_bWriteR, m_RenderState.m_bWriteG, m_RenderState.m_bWriteB, m_RenderState.m_bWriteA); } } void BBGlobalRenderState::updateStencilMask(bool bEnable) { if (m_RenderState.m_bWriteStencil != bEnable) { m_RenderState.m_bWriteStencil = bEnable; glStencilMask(bEnable); } } void BBGlobalRenderState::updateZMask(bool bEnable) { if (m_RenderState.m_bWriteZ != bEnable) { m_RenderState.m_bWriteZ = bEnable; glDepthMask(m_RenderState.m_bWriteZ); } } void BBGlobalRenderState::updateZFunc(unsigned int func) { if (m_RenderState.m_ZTestFunc != func) { m_RenderState.m_ZTestFunc = func; glDepthFunc(m_RenderState.m_ZTestFunc); } } void BBGlobalRenderState::updatePolygonMode(unsigned int face, unsigned int mode) { if (m_RenderState.m_DrawFace != face || m_RenderState.m_PolygonMode != mode) { m_RenderState.m_DrawFace = face; m_RenderState.m_PolygonMode = mode; glPolygonMode(m_RenderState.m_DrawFace, m_RenderState.m_PolygonMode); } } void BBGlobalRenderState::updateAlphaFunc(unsigned int func, float value) { if (m_RenderState.m_AlphaTestFunc != func || m_RenderState.m_fAlphaTestValue != value) { m_RenderState.m_AlphaTestFunc = func; m_RenderState.m_fAlphaTestValue = value; glAlphaFunc(m_RenderState.m_AlphaTestFunc, m_RenderState.m_fAlphaTestValue); } } void BBGlobalRenderState::updateLineWidth(float fWidth) { if (m_RenderState.m_fLineWidth != fWidth) { m_RenderState.m_fLineWidth = fWidth; glLineWidth(m_RenderState.m_fLineWidth); } } void BBGlobalRenderState::updateCullState(bool bEnable) { if (m_RenderState.m_bCull != bEnable) { m_RenderState.m_bCull = bEnable; SetCullState(m_RenderState.m_bCull); } } void BBGlobalRenderState::updateCullFace(int face) { if (m_RenderState.m_CullFace != face) { m_RenderState.m_CullFace = face; glCullFace(m_RenderState.m_CullFace); } } void BBGlobalRenderState::updatePointSpriteState(bool bEnable) { if (m_RenderState.m_bEnablePointSprite != bEnable) { m_RenderState.m_bEnablePointSprite = bEnable; SetPointSpriteState(m_RenderState.m_bEnablePointSprite); } } void BBGlobalRenderState::updateProgramPointSizeState(bool bEnable) { if (m_RenderState.m_bEnableProgramPointSize != bEnable) { m_RenderState.m_bEnableProgramPointSize = bEnable; SetProgramPointSizeState(m_RenderState.m_bEnableProgramPointSize); } } void BBGlobalRenderState::clearStencil(int value) { if (m_RenderState.m_ClearStencilValue != value) { m_RenderState.m_ClearStencilValue = value; glClearStencil(m_RenderState.m_ClearStencilValue); } } <|start_filename|>Code/BBearEditor/Engine/Geometry/BBPlane.cpp<|end_filename|> #include "BBPlane.h" BBPlane::BBPlane() : BBPlane(QVector3D(0, 0, 0), QVector3D(1, 0, 0), QVector3D(0, 0, 1)) { } BBPlane::BBPlane(const QVector3D &point1, const QVector3D &point2, const QVector3D &point3) { m_Point1 = point1; m_Point2 = point2; m_Point3 = point3; m_Normal = QVector3D::normal(point1, point2, point3); } float BBPlane::distance(const QVector3D &point) const { return point.distanceToPlane(m_Point1, m_Point2, m_Point3); } float BBPlane::distance(const QVector3D &pointOnPlane, const QVector3D &planeNormal, const QVector3D &point) { return point.distanceToPlane(pointOnPlane, planeNormal); } BBPlane BBPlane::invert(const BBPlane &plane) { return BBPlane(plane.getPoint3(), plane.getPoint2(), plane.getPoint1()); } <|start_filename|>Resources/shaders/SH_Lighting.frag<|end_filename|> varying vec3 V_normal; uniform vec4 BBSphericalHarmonicLightingCoefficients[16]; const float PI = 3.1415926535897932384626433832795; void main(void) { vec4 final_color = vec4(0.0); if ((abs(V_normal.x) < 0.0001) && (abs(V_normal.y) < 0.0001) && (abs(V_normal.z) < 0.0001)) { final_color = vec4(0.0, 0.0, 0.0, 1.0); } else { float x = V_normal.x; float y = V_normal.y; float z = V_normal.z; float x2 = x * x; float y2 = y * y; float z2 = z * z; // Spherical Harmonic float basis[9]; basis[0] = 1.0 / 2.0 * sqrt(1.0 / PI); basis[1] = 2.0 / 3.0 * sqrt(3.0 / (4.0 * PI)) * z; basis[2] = 2.0 / 3.0 * sqrt(3.0 / (4.0 * PI)) * y; basis[3] = 2.0 / 3.0 * sqrt(3.0 / (4.0 * PI)) * x; basis[4] = 1.0 / 4.0 * 1.0 / 2.0 * sqrt(15.0 / PI) * x * z; basis[5] = 1.0 / 4.0 * 1.0 / 2.0 * sqrt(15.0 / PI) * z * y; basis[6] = 1.0 / 4.0 * 1.0 / 4.0 * sqrt(5.0 / PI) * (-x2 - z2 + 2 * y2); basis[7] = 1.0 / 4.0 * 1.0 / 2.0 * sqrt(15.0 / PI) * y * x; basis[8] = 1.0 / 4.0 * 1.0 / 4.0 * sqrt(15.0 / PI) * (x2 - z2); vec3 diffuse = vec3(0.0); for (int i = 0; i < 9; i++) { diffuse += BBSphericalHarmonicLightingCoefficients[i] * basis[i]; } final_color = vec4(diffuse, 1.0); } gl_FragColor = final_color; } <|start_filename|>Code/BBearEditor/Engine/2D/BBClipArea2D.cpp<|end_filename|> #include "BBClipArea2D.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BBDrawCall.h" #include "Scene/BBRendererManager.h" BBClipArea2D::BBClipArea2D(int x, int y, int nWidth, int nHeight) : BBRenderableObject2D(x, y, nWidth, nHeight) { } void BBClipArea2D::init() { m_pVBO = new BBVertexBufferObject(4); m_pVBO->setPosition(0, 1.0f, 1.0f, 0); m_pVBO->setPosition(1, -1.0f, 1.0f, 0); m_pVBO->setPosition(2, -1.0f, -1.0f, 0); m_pVBO->setPosition(3, 1.0f, -1.0f, 0); m_pVBO->setTexcoord(0, 1.0f, 1.0f); m_pVBO->setTexcoord(1, 0.0f, 1.0f); m_pVBO->setTexcoord(2, 0.0f, 0.0f); m_pVBO->setTexcoord(3, 1.0f, 0.0f); for (int i = 0; i < m_pVBO->getVertexCount(); i++) { m_pVBO->setColor(i, 1.0f, 1.0f, 1.0f); } m_pCurrentMaterial = BBRendererManager::createStencilUIMaterial(); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, GL_QUADS, 0, 4); appendDrawCall(pDrawCall); } <|start_filename|>External/ProtoBuffer/lib/CMakeFiles/Export/lib/cmake/protobuf/protobuf-targets-noconfig.cmake<|end_filename|> #---------------------------------------------------------------- # Generated CMake target import file. #---------------------------------------------------------------- # Commands may need to know the format version. set(CMAKE_IMPORT_FILE_VERSION 1) # Import target "protobuf::libprotobuf-lite" for configuration "" set_property(TARGET protobuf::libprotobuf-lite APPEND PROPERTY IMPORTED_CONFIGURATIONS NOCONFIG) set_target_properties(protobuf::libprotobuf-lite PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_NOCONFIG "CXX" IMPORTED_LOCATION_NOCONFIG "${_IMPORT_PREFIX}/lib/libprotobuf-lite.a" ) list(APPEND _IMPORT_CHECK_TARGETS protobuf::libprotobuf-lite ) list(APPEND _IMPORT_CHECK_FILES_FOR_protobuf::libprotobuf-lite "${_IMPORT_PREFIX}/lib/libprotobuf-lite.a" ) # Import target "protobuf::libprotobuf" for configuration "" set_property(TARGET protobuf::libprotobuf APPEND PROPERTY IMPORTED_CONFIGURATIONS NOCONFIG) set_target_properties(protobuf::libprotobuf PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_NOCONFIG "CXX" IMPORTED_LOCATION_NOCONFIG "${_IMPORT_PREFIX}/lib/libprotobuf.a" ) list(APPEND _IMPORT_CHECK_TARGETS protobuf::libprotobuf ) list(APPEND _IMPORT_CHECK_FILES_FOR_protobuf::libprotobuf "${_IMPORT_PREFIX}/lib/libprotobuf.a" ) # Commands beyond this point should not need to know the version. set(CMAKE_IMPORT_FILE_VERSION) <|start_filename|>Code/BBearEditor/Engine/Allocator/BBAllocator.h<|end_filename|> #pragma once #ifndef BBALLOCATOR_H #define BBALLOCATOR_H #define BB_USE_POOL 1 #include <new> #include "bbmemorylabel.h" static void initMemory(); static void* getMemory(std::size_t size); static void recycle(void *ptr); void *operator new(std::size_t size); void *operator new[](std::size_t size); void *operator new(std::size_t size, BBMemoryLabel eID); void *operator new[](std::size_t size, BBMemoryLabel eID); void operator delete(void *ptr) noexcept; void operator delete[](void *ptr) noexcept; void operator delete(void *ptr, BBMemoryLabel eID) noexcept; void operator delete[](void *ptr, BBMemoryLabel eID) noexcept; #endif // BBALLOCATOR_H <|start_filename|>Code/BBearEditor/Engine/Python/BBPythonModule.c<|end_filename|> #include "Python.h" // module function static PyObject *BBearModuleFunc(PyObject *pSelf) { // create py long, python to release, reference count +1 in C return PyLong_FromLong(101); } // module function list static PyMethodDef BBearModule_Func[] = { { "BBearModule Func", // function name BBearModuleFunc, // function pointer METH_NOARGS, // module flag: no parameter "BBearModule Func instruction" // function instruction, use help(func name) to get }, {0, 0, 0, 0} }; static PyModuleDef moduleDef = { PyModuleDef_HEAD_INIT, "BBearModule", // module name "BBearModule instruction", // module instruction, use help(module name) to get -1, // module space, using by sub interpreter, we do not use it for the time BBearModule_Func // module function }; // Extension library entry function // PyInit_ fixed prefix PyMODINIT_FUNC PyInit_BBearModule(void) { // create module return PyModule_Create(&moduleDef); } <|start_filename|>Code/BBearEditor/Engine/Render/Lighting/GameObject/BBAreaLight.h<|end_filename|> #ifndef BBAREALIGHT_H #define BBAREALIGHT_H #include "3D/BBModel.h" class BBRectBoundingBox3D; class BBAreaLight : public BBModel { public: BBAreaLight(float fMin0, float fMax0, float fMin1, float fMax1, float fFixedValue, const QVector3D &color); ~BBAreaLight(); void init() override; void generatePhoton(QVector3D &origin, QVector3D &direction, float &fPowerScale, const QVector3D &normal = QVector3D(0, -1, 0)); void generatePhoton(QVector3D &origin, QVector3D &direction, float &fPowerScale, const BBHitInfo &hitInfo); QVector3D getColor() { return m_Color; } private: // Define location and size // For example, an area light source in an xoz plane, m_nFixedValue means y, // m_nMin0 and m_nMax0 indicates the range of x, m_nMin1 and m_nMax1 indicates the range of z float m_fMin0; float m_fMax0; float m_fMin1; float m_fMax1; float m_fFixedValue; QVector3D m_Normal; QVector3D m_Color; }; #endif // BBAREALIGHT_H <|start_filename|>Code/BBearEditor/Engine/3D/Mesh/BBStaticMesh.cpp<|end_filename|> #include "BBStaticMesh.h" #include "Utils/BBUtils.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BufferObject/BBShaderStorageBufferObject.h" #include <sstream> #include "Geometry/BBBoundingBox.h" #include "Render/BBMaterial.h" #include "Render/Texture/BBTexture.h" #include "Render/BBRenderPass.h" #include "Render/BBDrawCall.h" BBStaticMesh::BBStaticMesh() : BBStaticMesh(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBStaticMesh::BBStaticMesh(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBMesh(px, py, pz, rx, ry, rz, sx, sy, sz) { } void BBStaticMesh::init(const QString &path, BBBoundingBox3D *&pOutBoundingBox) { BBMesh::init(path, pOutBoundingBox); // SSBO version // QList<QVector4D> positions; // load(path, positions); // m_pVBO->computeTangent(m_pIndexes, m_nIndexCount); // // create bounding box // pOutBoundingBox = new BBAABBBoundingBox3D(m_Position.x(), m_Position.y(), m_Position.z(), // m_Rotation.x(), m_Rotation.y(), m_Rotation.z(), // m_Scale.x(), m_Scale.y(), m_Scale.z(), // positions); // pOutBoundingBox->init(); // // VBO -> SSBO // m_pSSBO = new BBShaderStorageBufferObject(m_pVBO); // m_pCurrentMaterial->initMultiPass("Diffuse_SSBO", BB_PATH_RESOURCE_SHADER(Diffuse_SSBO.vert), BB_PATH_RESOURCE_SHADER(Diffuse_SSBO.frag)); // m_pCurrentMaterial->getAdditiveRenderPass()->setBlendState(true); // // default // float *pLightPosition = new float[4] {1.0f, 1.0f, 0.0f, 0.0f}; // float *pLightColor = new float[4] {1.0f, 1.0f, 1.0f, 1.0f}; // m_pCurrentMaterial->setVector4(LOCATION_LIGHT_POSITION, pLightPosition); // m_pCurrentMaterial->setVector4(LOCATION_LIGHT_COLOR, pLightColor); // m_pCurrentMaterial->setSampler2D(LOCATION_TEXTURE(0), BBTexture().createTexture2D()); // BBRenderableObject::init(); // BBDrawCall *pDrawCall = new BBDrawCall; // pDrawCall->setMaterial(m_pCurrentMaterial); // pDrawCall->setVBO(m_pVBO); // pDrawCall->setSSBO(m_pSSBO); // pDrawCall->setEBO(m_pEBO, m_eDrawPrimitiveType, m_nIndexCount, 0); // appendDrawCall(pDrawCall); // Using the shader, we can get a 2-channel shadow map in the color buffer storing the depth and the square of the depth respectively BBMaterial *pMaterial = new BBMaterial(); pMaterial->init("VSM_ShadowMap", BB_PATH_RESOURCE_SHADER(Shadow/VSM_ShadowMap.vert), BB_PATH_RESOURCE_SHADER(Shadow/VSM_ShadowMap.frag)); setExtraMaterial(INDEX_SHADOWMAP, pMaterial); } void BBStaticMesh::load(const QString &path, QList<QVector4D> &outPositions) { struct VertexDefine { int posIndex; int texcoordIndex; int normalIndex; }; int fileSize = 0; char *pFileContent = BBUtils::loadFileContent(path.toStdString().c_str(), fileSize); if (pFileContent == NULL) { return; } // in the file, v... refers to vertex, f... refers to drawing instructions (How to organize the vertices) QList<QVector4D> positions, texcoords, normals; std::vector<VertexDefine> vertexes; std::vector<int> triangleIndexes; std::vector<int> quadIndexes; std::stringstream ssFileContent(pFileContent); std::string temp; char oneLine[256]; while (!ssFileContent.eof()) { memset(oneLine, 0, 256); ssFileContent.getline(oneLine, 256); // there are empty lines if (strlen(oneLine) > 0) { if (oneLine[0] == 'v') { // push a row of data into the stream // output from stream until space std::stringstream ssOneLine(oneLine); if (oneLine[1] == 't') { // texcoord ssOneLine >> temp; // vt... float u, v; // uv coordinate ssOneLine >> u; ssOneLine >> v; // Put in the container texcoords.append(QVector4D(u, v, 0, 0)); } else if (oneLine[1] == 'n') { // normal ssOneLine >> temp; float x, y, z; ssOneLine >> x; ssOneLine >> y; ssOneLine >> z; normals.append(QVector4D(x, y, z, 1.0)); } else { // vertex position ssOneLine >> temp; float x, y, z; ssOneLine >> x; ssOneLine >> y; ssOneLine >> z; positions.append(QVector4D(x, y, z, 1.0)); } } else if (oneLine[0] == 'f') { // face, What points are made of each face GLenum primitiveType = GL_QUADS; std::vector<int> primitiveIndexes; std::stringstream ssOneLine(oneLine); ssOneLine >> temp; // f... // Triangle, 3 pieces of data per line, separated by spaces for (int i = 0; i < 4; i++) { std::string vertexStr; ssOneLine >> vertexStr; if (vertexStr.length() == 0) { // test primitiveType = GL_TRIANGLES; break; } // The index value of pos and tex of each point, separated by / size_t pos = vertexStr.find_first_of('/'); std::string posIndexStr = vertexStr.substr(0, pos); size_t pos2 = vertexStr.find_first_of('/', pos + 1); std::string texcoordIndexStr = vertexStr.substr(pos + 1, pos2 - pos - 1); std::string normalIndexStr = vertexStr.substr(pos2 + 1, vertexStr.length() - pos2 - 1); VertexDefine vd; // string to int vd.posIndex = atoi(posIndexStr.c_str()); vd.texcoordIndex = atoi(texcoordIndexStr.c_str()); vd.normalIndex = atoi(normalIndexStr.c_str()); // Check if it is a duplicate point. The same position, different normals, different points int currentVertexIndex = -1; int currentVertexCount = (int)vertexes.size(); for (int j = 0; j < currentVertexCount; j++) { if (vertexes[j].posIndex == vd.posIndex && vertexes[j].normalIndex == vd.normalIndex && vertexes[j].texcoordIndex == vd.texcoordIndex) { currentVertexIndex = j; break; } } // If the point does not exist, add the point container if (currentVertexIndex == -1) { currentVertexIndex = (int)vertexes.size(); vertexes.push_back(vd); } // Regardless of whether it exists, record the index value of the point in the point container primitiveIndexes.push_back(currentVertexIndex); } // Primitiveindexes store the vertex index of a primitive. // Judge the type of primitive according to the number of vertices, // and then push it to the total index table of the corresponding primitive if (primitiveType == GL_TRIANGLES) { triangleIndexes.push_back(primitiveIndexes[0]); triangleIndexes.push_back(primitiveIndexes[1]); triangleIndexes.push_back(primitiveIndexes[2]); } else if (primitiveType == GL_QUADS) { quadIndexes.push_back(primitiveIndexes[0]); quadIndexes.push_back(primitiveIndexes[1]); quadIndexes.push_back(primitiveIndexes[2]); quadIndexes.push_back(primitiveIndexes[3]); } } } } m_nIndexCount = (int)triangleIndexes.size(); m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0; i < m_nIndexCount; i++) { m_pIndexes[i] = triangleIndexes[i]; } // Some meshes are composed of multiple primitivetypes and require multiple sets of data representation m_nIndexCount2 = (int)quadIndexes.size(); if (m_nIndexCount2 > 0) { m_pIndexes2 = new unsigned short[m_nIndexCount2]; for (int i = 0; i < m_nIndexCount2; i++) { m_pIndexes2[i] = quadIndexes[i]; } } // How many unique points m_nVertexCount = (int)vertexes.size(); m_pVBO = new BBVertexBufferObject(m_nVertexCount); for (int i = 0; i < m_nVertexCount; i++) { // vertexes[i].posIndex - 1 // The index starts from 1 in .obj QVector4D temp; temp = positions.at(vertexes[i].posIndex - 1); m_pVBO->setPosition(i, temp); m_pVBO->setColor(i, m_DefaultColor); temp = texcoords.at(vertexes[i].texcoordIndex - 1); m_pVBO->setTexcoord(i, temp.x(), temp.y()); temp = normals.at(vertexes[i].normalIndex - 1); m_pVBO->setNormal(i, temp); } // for creating bounding box outPositions = positions; BB_SAFE_DELETE(pFileContent); } <|start_filename|>Code/BBearEditor/Editor/PropertyManager/BBPropertyManager.h<|end_filename|> #ifndef BBPROPERTYMANAGER_H #define BBPROPERTYMANAGER_H #include <QWidget> class BBBaseInformationManager; class BBSetBaseInformationManager; class BBGroupManager; class BBTransformGroupManager; class BBGameObject; class BBScene; class BBOfflineRenderer; class BBPreviewOpenGLWidget; class BBPropertyManager : public QWidget { Q_OBJECT public: explicit BBPropertyManager(QWidget *pParent = nullptr); ~BBPropertyManager(); public slots: void clear(); inline void bindPreviewOpenGLWidget(BBPreviewOpenGLWidget *pWidget) { m_pPreviewOpenGLWidget = pWidget; } void showGameObjectProperty(BBGameObject *pGameObject); void showGameObjectSetProperty(BBGameObject *pCenterGameObject, const QList<BBGameObject*> &gameObjectSet); void showGlobalSettingsProperty(BBScene *pScene); void showOfflineRendererProperty(BBOfflineRenderer *pOfflineRenderer); void showMaterialProperty(const QString &filePath); void updateCoordinateSystem(); void updateTransform(BBGameObject *pGameObject, char transformModeKey); void updateFileList(); signals: void coordinateSystemUpdated(); void fileListUpdated(); private: void setWidgetStyle(); void addBaseInformationManager(BBGameObject *pGameObject); void addSetBaseInformationManager(BBGameObject *pCenterGameObject, const QList<BBGameObject*> &gameObjectSet); BBGroupManager* addGroupManager(const QString &name, const QString &iconPath); void addTransformGroupManager(BBGameObject *pGameObject); void addGlobalSettingsGroupManager(BBScene *pScene); void addOfflineRendererManager(BBOfflineRenderer *pOfflineRenderer); void addMaterialGroupManager(const QString &filePath); BBPreviewOpenGLWidget *m_pPreviewOpenGLWidget; BBBaseInformationManager *m_pBaseInformationManager; BBSetBaseInformationManager *m_pSetBaseInformationManager; BBTransformGroupManager *m_pTransformGroupManager; BBGameObject *m_pCurrentGameObject; }; #endif // BBPROPERTYMANAGER_H //class PropertyManager : public QWidget //{ //public: // void bindPreview(BaseOpenGLWidget *preview); //private: // MaterialFactory *materialFactory; // BaseOpenGLWidget *mPreview; //signals: // void updateCoordinateSignal(); // void renameGameObjectInHierarchySignal(GameObject *gameObject); // void changeActivationSignal(GameObject *gameObject, bool isActive); // void setSelectedObjects(QList<GameObject*> gameObjects); // void updateMaterialPreviewInOtherWidgetSignal(QString filePath); //public slots: // void showSceneProperty(Scene *scene); //private slots: // void showMaterialProperty(QString filePath); // void showFbxProperty(QString filePath); // void renameGameObject(GameObject *gameObject, QString newName); // void renameGameObjectInHierarchy(GameObject *gameObject); // void changeActivation(GameObject *gameObject, bool isActive); // void changeActivation(QList<GameObject*> gameObjects, bool isActive); // void changeButtonActiveCheckState(GameObject *gameObject, bool isActive); // void updateMaterialPreviewInOtherWidget(QString filePath); // void updateMaterialFactory(Model* model); //}; ////高度图 //class HeightMapFactory : public IconFactory //{ // Q_OBJECT //public: // HeightMapFactory(Model* model, QWidget *parent = 0); //private slots: // void changeHeight(QString mapPath); //private: // void showHeightMap(); // Model* mModel; //}; //class AnimFactory : public QComboBox //{ // Q_OBJECT //public: // AnimFactory(Model *model, BaseOpenGLWidget *preview, QWidget *parent = 0); //private: // void showPopup() override; // void hidePopup() override; // bool eventFilter(QObject *watched, QEvent *event) override; // Model *mModel; // BaseOpenGLWidget *mPreview; // Model *mPreviewModel; //private slots: // void changeCurrentAnim(int index); //}; ////场景各项属性 //class SceneManager : public QWidget //{ // Q_OBJECT //public: // SceneManager(Scene *scene, QWidget *parent = 0); //private slots: // void switchFog(bool b); // void setFogColor(float r, float g, float b); // void switchMode(int id); // void setFogStart(float start); // void setFogEnd(float end); // void setFogDensity(int density); // void setFogPower(float power); //private: // Scene *mScene; // GroupManager *fogManager; // LineEditFactory *startEditFactory; // LineEditFactory *endEditFactory; // SliderFactory *densitySliderFactory; // LineEditFactory *powerEditFactory; //}; //class PointLightManager : public GroupManager //{ // Q_OBJECT //public: // PointLightManager(PointLight *light, QWidget *parent, QString name, QString iconPath); //protected slots: // void changeConstantFactory(float value); // void changeLinearFactory(float value); // void changeQuadricFactory(float value); // void changeIntensity(int value); //private: // PointLight *mLight; //}; //class SpotLightManager : public PointLightManager //{ // Q_OBJECT //public: // SpotLightManager(SpotLight *light, QWidget *parent, QString name, QString iconPath); //private slots: // void changeSpotAngle(float value); // void changeSpotLevel(int value); //private: // SpotLight *mLight; //}; <|start_filename|>External/ProtoBuffer/lib/Makefile<|end_filename|> # CMAKE generated file: DO NOT EDIT! # Generated by "MinGW Makefiles" Generator, CMake Version 3.20 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Disable VCS-based implicit rules. % : %,v # Disable VCS-based implicit rules. % : RCS/% # Disable VCS-based implicit rules. % : RCS/%,v # Disable VCS-based implicit rules. % : SCCS/s.% # Disable VCS-based implicit rules. % : s.% .SUFFIXES: .hpux_make_needs_suffix_list # Command-line flag to silence nested $(MAKE). $(VERBOSE)MAKESILENT = -s #Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. SHELL = cmd.exe # The CMake executable. CMAKE_COMMAND = D:\cmake-3.20.3-windows-x86_64\bin\cmake.exe # The command to remove a file. RM = D:\cmake-3.20.3-windows-x86_64\bin\cmake.exe -E rm -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = D:\workspace\protobuf-3.16.0\cmake # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = D:\workspace\output #============================================================================= # Targets provided globally by CMake. # Special rule for the target list_install_components list_install_components: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\" \"libprotobuf\" \"libprotobuf-lite\" \"protobuf-export\" \"protobuf-headers\" \"protobuf-protos\"" .PHONY : list_install_components # Special rule for the target list_install_components list_install_components/fast: list_install_components .PHONY : list_install_components/fast # Special rule for the target install/local install/local: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." D:\cmake-3.20.3-windows-x86_64\bin\cmake.exe -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local # Special rule for the target install/local install/local/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." D:\cmake-3.20.3-windows-x86_64\bin\cmake.exe -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local/fast # Special rule for the target install install: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." D:\cmake-3.20.3-windows-x86_64\bin\cmake.exe -P cmake_install.cmake .PHONY : install # Special rule for the target install install/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." D:\cmake-3.20.3-windows-x86_64\bin\cmake.exe -P cmake_install.cmake .PHONY : install/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..." D:\cmake-3.20.3-windows-x86_64\bin\cmake-gui.exe -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." D:\cmake-3.20.3-windows-x86_64\bin\cmake.exe --regenerate-during-build -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target install/strip install/strip: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." D:\cmake-3.20.3-windows-x86_64\bin\cmake.exe -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip # Special rule for the target install/strip install/strip/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." D:\cmake-3.20.3-windows-x86_64\bin\cmake.exe -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip/fast # The main all target all: cmake_check_build_system $(CMAKE_COMMAND) -E cmake_progress_start D:\workspace\output\CMakeFiles D:\workspace\output\\CMakeFiles\progress.marks $(MAKE) $(MAKESILENT) -f CMakeFiles\Makefile2 all $(CMAKE_COMMAND) -E cmake_progress_start D:\workspace\output\CMakeFiles 0 .PHONY : all # The main clean target clean: $(MAKE) $(MAKESILENT) -f CMakeFiles\Makefile2 clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all $(MAKE) $(MAKESILENT) -f CMakeFiles\Makefile2 preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: $(MAKE) $(MAKESILENT) -f CMakeFiles\Makefile2 preinstall .PHONY : preinstall/fast # clear depends depend: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles\Makefile.cmake 1 .PHONY : depend #============================================================================= # Target rules for targets named libprotobuf-lite # Build rule for target. libprotobuf-lite: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles\Makefile2 libprotobuf-lite .PHONY : libprotobuf-lite # fast build rule for target. libprotobuf-lite/fast: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/build .PHONY : libprotobuf-lite/fast #============================================================================= # Target rules for targets named libprotobuf # Build rule for target. libprotobuf: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles\Makefile2 libprotobuf .PHONY : libprotobuf # fast build rule for target. libprotobuf/fast: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/build .PHONY : libprotobuf/fast D_/workspace/protobuf-3.16.0/src/google/protobuf/any.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/any.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/any.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/map.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/map.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/map.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/message.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/message.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/message.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/service.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/service.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/service.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/service.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/service.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/service.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/service.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.i $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf-lite.dir\build.make CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.s $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.s D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.obj: D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.obj # target to build an object file D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.obj .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.obj D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.i: D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.i # target to preprocess a source file D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.i .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.i D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.s: D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.s # target to generate assembly for a file D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\libprotobuf.dir\build.make CMakeFiles/libprotobuf.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.s .PHONY : D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.cc.s # Help Target help: @echo The following are some of the valid targets for this Makefile: @echo ... all (the default if no target is provided) @echo ... clean @echo ... depend @echo ... edit_cache @echo ... install @echo ... install/local @echo ... install/strip @echo ... list_install_components @echo ... rebuild_cache @echo ... libprotobuf @echo ... libprotobuf-lite @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/any.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/any.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/any.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/any.pb.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/api.pb.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/importer.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/compiler/parser.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor.pb.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/descriptor_database.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/duration.pb.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/dynamic_message.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/empty.pb.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set_heavy.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/field_mask.pb.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_reflection.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/gzip_stream.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/printer.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/tokenizer.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/map.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/map.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/map.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/map_field.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/message.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/message.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/message.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/reflection_ops.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/service.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/service.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/service.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/source_context.pb.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/struct.pb.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/substitute.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/text_format.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/timestamp.pb.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/type.pb.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/unknown_field_set.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/delimited_message_util.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_comparator.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/field_mask_util.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/datapiece.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/default_value_objectwriter.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/error_listener.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/field_mask_utility.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_escaping.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_objectwriter.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/json_stream_parser.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/object_writer.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/proto_writer.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectsource.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/protostream_objectwriter.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/type_info_test_helper.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/internal/utility.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/json_util.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/message_differencer.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/time_util.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/util/type_resolver_util.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.s @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.obj @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.i @echo ... D_/workspace/protobuf-3.16.0/src/google/protobuf/wrappers.pb.s .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles\Makefile.cmake 0 .PHONY : cmake_check_build_system <|start_filename|>Code/BBearEditor/Engine/Python/BBPythonVM.h<|end_filename|> #ifndef BBPYTHONVM_H #define BBPYTHONVM_H #include <Python.h> #include <QString> class BBPythonVM { public: static void runScript(const QString &path); private: static bool loadMainModule(); static bool loadDictionary(); static bool loadClass(); static bool loadFunc(); static bool emitValues(); static bool emitFunc(); static PyObject* cfunc(PyObject *pSelf, PyObject *pArgs); private: static PyObject *m_pModule; }; #endif // BBPYTHONVM_H <|start_filename|>Code/BBearEditor/Engine/Scene/CoordinateSystem/BBTransformCoordinateSystem.cpp<|end_filename|> #include "BBTransformCoordinateSystem.h" #include "BBCoordinateSystem.h" #include "BBCoordinateSystem2D.h" #include "Base/BBGameObjectSet.h" #include "Scene/BBSceneManager.h" #include "Render/BBCamera.h" BBTransformCoordinateSystem::BBTransformCoordinateSystem() : BBGameObject() { m_pPositionCoordinateSystem = new BBPositionCoordinateSystem(); m_pRotationCoordinateSystem = new BBRotationCoordinateSystem(); m_pScaleCoordinateSystem = new BBScaleCoordinateSystem(); m_pPositionCoordinateSystem2D = new BBPositionCoordinateSystem2D(); m_pRotationCoordinateSystem2D = new BBRotationCoordinateSystem2D(); m_pScaleCoordinateSystem2D = new BBScaleCoordinateSystem2D(); // default is m_pPositionCoordinateSystem m_ModeKey = m_PositionCoordinateSystemModeKey; m_pSelectedObject = nullptr; m_bTransforming = false; switchSpaceMode(Space3D); } BBTransformCoordinateSystem::~BBTransformCoordinateSystem() { BB_SAFE_DELETE(m_pPositionCoordinateSystem); BB_SAFE_DELETE(m_pRotationCoordinateSystem); BB_SAFE_DELETE(m_pScaleCoordinateSystem); BB_SAFE_DELETE(m_pPositionCoordinateSystem2D); BB_SAFE_DELETE(m_pRotationCoordinateSystem2D); BB_SAFE_DELETE(m_pScaleCoordinateSystem2D); } void BBTransformCoordinateSystem::init() { m_pPositionCoordinateSystem->init(); m_pRotationCoordinateSystem->init(); m_pScaleCoordinateSystem->init(); m_pPositionCoordinateSystem2D->init(); m_pRotationCoordinateSystem2D->init(); m_pScaleCoordinateSystem2D->init(); } void BBTransformCoordinateSystem::render(BBCamera *pCamera) { if (m_pSelectedObject == NULL) return; if (m_eSpaceMode == Space3D) { m_pPositionCoordinateSystem->render(pCamera); m_pRotationCoordinateSystem->render(pCamera); m_pScaleCoordinateSystem->render(pCamera); } else { m_pPositionCoordinateSystem2D->render(pCamera); m_pRotationCoordinateSystem2D->render(pCamera); m_pScaleCoordinateSystem2D->render(pCamera); } } void BBTransformCoordinateSystem::setSelectedObject(BBGameObject *pObject) { // The selected operation object has not changed, no additional operation is required if (m_pSelectedObject == pObject) { return; } // Operation object changed // Clear multiple options for (int i = 0; i < m_SelectedObjects.count(); i++) { m_SelectedObjects.at(i)->setVisibility(false); } m_SelectedObjects.clear(); // single selection if (m_pSelectedObject != nullptr) { // The bounding box and indicator of the original operation object are hidden m_pSelectedObject->setVisibility(false); } if (pObject != nullptr) { // show bounding box and indicator of now operation object pObject->setVisibility(true); // UI use 2D Coordinate System if (pObject->getClassName() == BB_CLASSNAME_CANVAS || pObject->getClassName() == BB_CLASSNAME_SPRITEOBJECT2D) { switchSpaceMode(Space2D); } else { switchSpaceMode(Space3D); } } m_pSelectedObject = pObject; setCoordinateSystem(m_ModeKey); } void BBTransformCoordinateSystem::setSelectedObjects(QList<BBGameObject*> gameObjects, BBGameObjectSet *pSet) { // The operation object has not changed, no additional operations are required if (m_SelectedObjects == gameObjects) return; int count = m_SelectedObjects.count(); for (int i = 0; i < count; i++) { m_SelectedObjects.at(i)->setVisibility(false); } count = gameObjects.count(); for (int i = 0; i < count; i++) { gameObjects.at(i)->setVisibility(true); } m_SelectedObjects = gameObjects; // select center of gravity m_pSelectedObject = pSet; setCoordinateSystem(m_ModeKey); } /** * @brief BBTransformCoordinateSystem::mouseMoveEvent * @param x original point is the center of screen * @param y * @param ray * @param bMousePressed * @return */ bool BBTransformCoordinateSystem::mouseMoveEvent(int x, int y, const BBRay &ray, bool bMousePressed) { m_bTransforming = false; if (m_eSpaceMode == Space3D) { if (m_ModeKey == m_PositionCoordinateSystemModeKey) { m_bTransforming = m_pPositionCoordinateSystem->mouseMoveEvent(ray, bMousePressed); } else if (m_ModeKey == m_RotationCoordinateSystemModeKey) { m_bTransforming = m_pRotationCoordinateSystem->mouseMoveEvent(ray, bMousePressed); } else if (m_ModeKey == m_ScaleCoordinateSystemModeKey) { m_bTransforming = m_pScaleCoordinateSystem->mouseMoveEvent(ray, bMousePressed); } } else { BBSceneManager::getCamera()->switchCoordinate(x, y); if (m_ModeKey == m_PositionCoordinateSystemModeKey) { m_bTransforming = m_pPositionCoordinateSystem2D->mouseMoveEvent(x, y, bMousePressed); } else if (m_ModeKey == m_RotationCoordinateSystemModeKey) { m_bTransforming = m_pRotationCoordinateSystem2D->mouseMoveEvent(x, y, bMousePressed); } else if (m_ModeKey == m_ScaleCoordinateSystemModeKey) { m_bTransforming = m_pScaleCoordinateSystem2D->mouseMoveEvent(x, y, bMousePressed); } } // if false, other mouse events will be processed return m_bTransforming; } void BBTransformCoordinateSystem::setCoordinateSystem(char modeKey) { m_ModeKey = modeKey; if (m_eSpaceMode == Space3D) { if (m_ModeKey == m_PositionCoordinateSystemModeKey) { m_pPositionCoordinateSystem->setSelectedObject(m_pSelectedObject); m_pRotationCoordinateSystem->setSelectedObject(nullptr); m_pScaleCoordinateSystem->setSelectedObject(nullptr); } else if (m_ModeKey == m_RotationCoordinateSystemModeKey) { m_pPositionCoordinateSystem->setSelectedObject(nullptr); m_pRotationCoordinateSystem->setSelectedObject(m_pSelectedObject); m_pScaleCoordinateSystem->setSelectedObject(nullptr); } else if (m_ModeKey == m_ScaleCoordinateSystemModeKey) { m_pPositionCoordinateSystem->setSelectedObject(nullptr); m_pRotationCoordinateSystem->setSelectedObject(nullptr); m_pScaleCoordinateSystem->setSelectedObject(m_pSelectedObject); } } else { if (m_ModeKey == m_PositionCoordinateSystemModeKey) { m_pPositionCoordinateSystem2D->setSelectedObject(m_pSelectedObject); m_pRotationCoordinateSystem2D->setSelectedObject(nullptr); m_pScaleCoordinateSystem2D->setSelectedObject(nullptr); } else if (m_ModeKey == m_RotationCoordinateSystemModeKey) { m_pPositionCoordinateSystem2D->setSelectedObject(nullptr); m_pRotationCoordinateSystem2D->setSelectedObject(m_pSelectedObject); m_pScaleCoordinateSystem2D->setSelectedObject(nullptr); } else if (m_ModeKey == m_ScaleCoordinateSystemModeKey) { m_pPositionCoordinateSystem2D->setSelectedObject(nullptr); m_pRotationCoordinateSystem2D->setSelectedObject(nullptr); m_pScaleCoordinateSystem2D->setSelectedObject(m_pSelectedObject); } } } void BBTransformCoordinateSystem::stopTransform() { m_pPositionCoordinateSystem->stopTransform(); m_pRotationCoordinateSystem->stopTransform(); m_pScaleCoordinateSystem->stopTransform(); m_pPositionCoordinateSystem2D->stopTransform(); m_pRotationCoordinateSystem2D->stopTransform(); m_pScaleCoordinateSystem2D->stopTransform(); m_bTransforming = false; } void BBTransformCoordinateSystem::update() { setCoordinateSystem(m_ModeKey); } void BBTransformCoordinateSystem::switchSpaceMode(const BBCoordinateSystemSpaceMode &eMode) { m_eSpaceMode = eMode; if (m_eSpaceMode == Space3D) { } else { } } <|start_filename|>Resources/shaders/Shadow/VSM_GBuffer.vert<|end_filename|> #version 430 core in vec4 BBPosition; in vec4 BBNormal; out vec3 v2f_normal; out vec3 v2f_world_space_pos; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { vec4 world_pos = BBModelMatrix * BBPosition; v2f_world_space_pos = world_pos.xyz; gl_Position = BBProjectionMatrix * BBViewMatrix * world_pos; v2f_normal = normalize(mat3(transpose(inverse(BBViewMatrix * BBModelMatrix))) * BBNormal.xyz); } <|start_filename|>Code/BBearEditor/Engine/Math/BBMath.cpp<|end_filename|> #include <stdlib.h> #include "BBMath.h" #include <QDebug> float lerp(float a, float b, float f) { return a + f * (b - a); } QVector2D lerp(const QVector2D &a, const QVector2D &b, float f) { return QVector2D(lerp(a.x(), b.x(), f), lerp(a.y(), b.y(), f)); } QVector2D lerp(const QVector2D &a, const QVector2D &b, const QVector2D &c, float u, float v) { // Any point on the plane can be expressed as P = A + u * (C – A) + v * (B - A) // u >= 0 v >= 0 u + v <= 1, point is within the triangle return lerp(a, c, u) + lerp(a, b, v); } float trilinearInterpolate(QVector3D c[2][2][2], float u, float v, float w) { // Version 1 // float sum = 0.0f; // for (int i = 0; i < 2; i++) // { // for (int j = 0; j < 2; j++) // { // for (int k = 0; k < 2; k++) // { // sum += (i * u + (1 - i) * (1 - u)) * // (j * v + (1 - j) * (1 - v)) * // (k * w + (1 - k) * (1 - w)) * c[i][j][k]; // } // } // } // Version 2 float uu = u * u * (3 - 2 * u); float vv = v * v * (3 - 2 * v); float ww = w * w * (3 - 2 * w); float sum = 0.0f; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { QVector3D weight(u - i, v - j, w - k); sum += (i * uu + (1 - i) * (1 - uu)) * (j * vv + (1 - j) * (1 - vv)) * (k * ww + (1 - k) * (1 - ww)) * QVector3D::dotProduct(c[i][j][k], weight); } } } return sum; } /** * @brief reflect * @param L incident light * @param N normal * @return */ QVector3D reflect(const QVector3D &L, const QVector3D &N) { return L - 2.0f * QVector3D::dotProduct(L, N) * N; } bool refract(const QVector3D &L, const QVector3D &N, float fRefractivity, QVector3D &refracted) { float dt = QVector3D::dotProduct(L, N); float discrimination = 1.0f - fRefractivity * fRefractivity * (1.0f - dt * dt); if (discrimination > 0.0f) { refracted = fRefractivity * (L - N * dt) - N * sqrtf(discrimination); return true; } return false; } /** * @brief frandom * @return 0~1 */ float frandom() { return rand() / (float)RAND_MAX; } /** * @brief sfrandom * @return -1~1 */ float sfrandom() { return frandom() * 2.0f - 1.0f; } /** * @brief hemisphericalRandom Generate a random vector on the hemisphere corresponding to a normal * @return */ QVector3D hemisphericalRandom(const QVector3D &normal) { QVector3D v; float mode; do { v = QVector3D(sfrandom(), sfrandom(), sfrandom()); mode = v.length(); } while(mode >= 1.0f || mode == 0.0f || QVector3D::dotProduct(v, normal) < 0.0f); return v.normalized(); } QVector3D sphericalRandom() { QVector3D v; float mode; do { v = QVector3D(sfrandom(), sfrandom(), sfrandom()); mode = v.length(); } while(mode >= 1.0f || mode == 0.0f); return v.normalized(); } // KD Tree /** * @brief getMedian Find the location of the median, when you build a complete binary tree * The all data can be divided into two parts, one is smaller than the median and the other is larger than the median * @param start * @param end * @return This position is the offset from the start */ int getMedian(int start, int end) { int count = end - start + 1; int median; // Total number of nodes in the first k layer int nTotalNodeNum = 1; // Node number of each layer int nLayerNodeNum = 2; while (nTotalNodeNum < count) { nTotalNodeNum += nLayerNodeNum; nLayerNodeNum *= 2; } // full binary tree if (nTotalNodeNum == count) { return start + count / 2; } nLayerNodeNum /= 2; if (nTotalNodeNum - nLayerNodeNum / 2 < count) { // On the last layer, more than half, but not full binary tree return start + nTotalNodeNum / 2; } else { // On the last floor, no more than half return start + nTotalNodeNum / 2 - (nTotalNodeNum - nLayerNodeNum / 2 - count); } } /** * @brief schlick Schlick Fresnel approximation * @param cos * @param fRefractivity * @return */ float schlick(float cos, float fRefractivity) { float f0 = (1 - fRefractivity) / (1 + fRefractivity); f0 *= f0; return f0 + (1 - f0) * pow((1 - cos), 5); } float radians(float angle) { return angle * PI / 180.0f; } <|start_filename|>Code/BBearEditor/Engine/Render/BufferObject/BBTranslateFeedbackObject.cpp<|end_filename|> #include "BBTranslateFeedbackObject.h" #include "BBVertexBufferObject.h" BBTranslateFeedbackObject::BBTranslateFeedbackObject(int nVertexCount, GLenum hint, GLenum eDrawPrimitiveType) : BBBufferObject() { m_nVertexCount = nVertexCount; m_eDrawPrimitiveType = eDrawPrimitiveType; createTFO(); } void BBTranslateFeedbackObject::bind() { glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, m_TFO); // all data of TFO will be written into the buffer glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, m_Name); glBeginTransformFeedback(m_eDrawPrimitiveType); } void BBTranslateFeedbackObject::unbind() { glEndTransformFeedback(); glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0); } void BBTranslateFeedbackObject::debug() { BBBufferObject::bind(); // extract from gpu BBVertex *pVertexes = new BBVertex[m_nVertexCount]; glGetBufferSubData(GL_TRANSFORM_FEEDBACK_BUFFER, 0, sizeof(BBVertex) * m_nVertexCount, pVertexes); if (pVertexes) { for (int i = 0; i < m_nVertexCount; i++) { qDebug() << pVertexes[i].m_fPosition[0] << pVertexes[i].m_fPosition[1] << pVertexes[i].m_fPosition[2]; } } else { qDebug() << "error"; } glUnmapBuffer(m_BufferType); BBBufferObject::unbind(); } GLuint BBTranslateFeedbackObject::createTFO() { glGenTransformFeedbacks(1, &m_TFO); glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, m_TFO); m_Name = createBufferObject(m_BufferType, sizeof(BBVertex) * m_nVertexCount, GL_STATIC_DRAW, nullptr); glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0); return m_TFO; } <|start_filename|>Code/BBearEditor/Engine/Physics/Solver/BBPBDSolver.h<|end_filename|> #ifndef BBPBDSOLVER_H #define BBPBDSOLVER_H #include <vector> class BBForce; class BBBaseBody; class BBPBDSolver { public: BBPBDSolver(int nSolverIteration = 4, int nCollisionIteration = 2); ~BBPBDSolver(); void addForce(BBForce *pForce); void removeForce(BBForce *pForce); void addBody(BBBaseBody *pBody); void removeBody(BBBaseBody *pBody); void solve(float fDeltaTime); private: void applyForce(float fDeltaTime); void predictPositions(float fDeltaTime); void projectConstraints(); void updateVelocities(float fDeltaTime); void updatePositions(); private: int m_nSolverIteration; int m_nCollisionIteration; float m_fStopThreshold; std::vector<BBForce*> m_Forces; std::vector<BBBaseBody*> m_PhysicsBodies; }; #endif // BBPBDSOLVER_H <|start_filename|>Code/BBearEditor/Engine/Physics/Constraint/BBPinConstraint.cpp<|end_filename|> #include "BBPinConstraint.h" #include "../Body/BBBaseBody.h" BBPinConstraint::BBPinConstraint(BBBaseBody *pBody, int nParticleIndex, const QVector3D &fixedPosition) : BBBaseConstraint(pBody) { m_nParticleIndex = nParticleIndex; m_FixedPosition = fixedPosition; } void BBPinConstraint::doConstraint(float fDeltaTime) { Q_UNUSED(fDeltaTime); m_pBody->setParticlePosition(m_nParticleIndex, m_FixedPosition); m_pBody->setParticlePredictedPosition(m_nParticleIndex, m_FixedPosition); } <|start_filename|>Resources/shaders/standard.frag<|end_filename|> varying vec4 V_world_pos; varying vec4 V_Color; varying vec4 V_Texcoords; varying vec4 V_Normal; varying vec4 V_world_pos_light_space; uniform vec4 BBLightSettings0; uniform vec4 BBLightSettings1; uniform vec4 BBLightSettings2; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; uniform vec4 BBCameraPosition; uniform vec4 BBCameraParameters; uniform sampler2D BBShadowMap; // test uniform sampler2D PerlinNoiseTex2D; uniform sampler3D PerlinNoiseTex3D; float Near = BBCameraParameters.z; float LightSize = 0.1; float getLambertPointLightIntensity(vec3 normal, float radius, float distance, float attenuation, vec3 L) { float delta = radius - distance; float intensity = 0.0; if (delta >= 0) { intensity = max(0.0, dot(L, normal) * attenuation * delta / radius); } return intensity; } float getLambertSpotLightIntensity(vec3 normal, float radius, float distance, float attenuation, vec3 L) { float intensity = max(0.0, dot(normal, L)); if (intensity > 0.0) { vec3 spot_direction = normalize(BBLightSettings2.xyz); // Cosine of the angle between the current point and the spotlight direction float current_cos = max(0.0, dot(spot_direction, -L)); // cutoff cosine float cutoff_radian = BBLightSettings0.z / 2 * 3.14 / 180.0; float cutoff_cos = cos(cutoff_radian); if (current_cos > cutoff_cos) { // Within the cutoff range float delta = radius - distance; intensity = pow(current_cos, BBLightSettings0.w) * 2.0 * attenuation * delta / radius; } else { intensity = 0.0; } } return intensity; } // shadow // nvidia 2008 PCSS_DirectionalLight_Integration float getSearchWidth(float uv_light_size, float receiver_distance) { return uv_light_size * (receiver_distance - Near) / BBCameraPosition.z; } float findBlockerDistance_DirectionalLight(vec3 shadow_coords, float uv_light_size) { int blocker_count = 0; float d_blocker = 0; float search_size = getSearchWidth(uv_light_size, shadow_coords.z); for (int y = -2; y <= 2; y++) { for (int x = -2; x <= 2; x++) { float z = texture(BBShadowMap, shadow_coords.xy + vec2(x, y) * search_size).r; if (z < (shadow_coords.z - 0.0004)) { blocker_count++; d_blocker += z; } } } if (blocker_count > 0) return d_blocker / blocker_count; else return -1; } float calculateShadow() { vec3 shadow_coords = V_world_pos_light_space.xyz / V_world_pos_light_space.w; // -1~1 -> 0~1 shadow_coords = shadow_coords * 0.5 + vec3(0.5); // For the current fragment, get the corresponding depth from the depth map in the light viewport // float depth_shadow_map = texture2D(BBShadowMap, uv).r; // actual depth value of current fragment float current_depth = shadow_coords.z; current_depth = clamp(current_depth, 0.0, 1.0); float shadow = 0.0; // PCF // { // vec2 texel_size = 1.0 / textureSize(BBShadowMap, 0); // for (int y = -1; y <= 1; y++) // { // for (int x = -1; x <= 1; x++) // { // float depth_shadow_map = texture2D(BBShadowMap, shadow_coords.xy + texel_size * vec2(x, y)).r; // shadow += (current_depth - 0.004) > depth_shadow_map ? 1.0 : 0.0; // } // } // shadow /= 9.0; // } // PCSS { // blocker search float d_blocker = findBlockerDistance_DirectionalLight(shadow_coords, LightSize); if (d_blocker == -1) shadow = 0.0; // penumbra estimation float w_penumbra = (shadow_coords.z - d_blocker) / d_blocker; // PCF float search_size = w_penumbra * LightSize * Near / shadow_coords.z; for (int y = -1; y <= 1; y++) { for (int x = -1; x <= 1; x++) { float depth_shadow_map = texture2D(BBShadowMap, shadow_coords.xy + search_size * vec2(x, y)).r; shadow += (current_depth - 0.004) > depth_shadow_map ? 1.0 : 0.0; } } shadow /= 9.0; } // shadow = (current_depth - 0.004) > texture2D(BBShadowMap, shadow_coords.xy).r ? 1.0 : 0.0; return shadow; } void main(void) { vec4 final_color = V_Color; vec3 normal = normalize(V_Normal.xyz); if (BBLightPosition.w == 0.0) { // there is a directional light // Lambert vec3 L = normalize(BBLightPosition.xyz); float intensity = max(0.0, dot(normal, L)); final_color = intensity * BBLightColor; // // phong // if (intensity > 0.0) // { // vec3 view_dir = normalize(cameraPosition.xyz - V_world_pos.xyz); // vec3 reflect_dir = normalize(reflect(-L, normal)); // float phong_intensity = pow(max(0.0, dot(reflect_dir, view_dir)), 4.0f); // final_color += phong_intensity * lightColor; // } // blinn-phong // if (intensity > 0.0) // { // vec3 view_dir = normalize(BBCameraPosition.xyz - V_world_pos.xyz); // vec3 half_vector = normalize(L + view_dir); // float phong_intensity = pow(max(0.0, dot(normal, half_vector)), 4.0f); // final_color += phong_intensity * BBLightColor; // } } else if (BBLightPosition.w == 1.0) { float radius = BBLightSettings1.x; float constant_factor = BBLightSettings1.y; float linear_factor = BBLightSettings1.z; float quadric_factor = BBLightSettings1.w; vec3 L = BBLightPosition.xyz - V_world_pos.xyz; float distance = length(L); float attenuation = 1.0 / (constant_factor + linear_factor * distance + quadric_factor * quadric_factor * distance); L = normalize(L); float intensity; if (BBLightSettings0.x == 2.0) { // there is a spot light intensity = getLambertSpotLightIntensity(normal, radius, distance, attenuation, L); } else { // there is a point light intensity = getLambertPointLightIntensity(normal, radius, distance, attenuation, L); } final_color = BBLightColor * intensity * BBLightSettings0.y; } // shadow final_color = final_color * vec4(vec3(1.0 - calculateShadow()), 1.0); gl_FragColor = final_color * V_Color; // test perlin noise // gl_FragColor = texture2D(PerlinNoiseTex2D, V_Texcoords.xy); // gl_FragColor = texture3D(PerlinNoiseTex3D, V_world_pos.xyz); } <|start_filename|>Resources/shaders/KajiyaKayHair.frag<|end_filename|> #version 330 core in vec2 v2f_texcoords; in vec3 v2f_world_pos; in vec3 v2f_normal; in vec3 v2f_view_dir; out vec4 FragColor; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; uniform vec4 BBLightSettings0; uniform vec4 BBLightSettings1; uniform vec4 BBLightSettings2; uniform sampler2D BaseMap; // Base color (RGB), Cutoff (A) uniform vec4 BBColor_BaseColor; uniform vec4 BBColor_ShadowColor; uniform float Cutoff; uniform sampler2D ShiftingNoiseMap; uniform vec4 BBColor_PrimaryColor; uniform float PrimaryStrength; // 1.5 uniform float PrimaryFade; // 80 uniform float PrimaryShift; // -1~0 uniform float PrimaryDistort; // 0~1 uniform vec4 BBColor_SecondaryColor; uniform float SecondaryStrength; // 1.5 uniform float SecondaryFade; // 80 uniform float SecondaryShift; // -1~0 uniform float SecondaryDistort; // 0~1 float getLambertPointLightIntensity(vec3 normal, float radius, float distance, float attenuation, vec3 L) { float delta = radius - distance; float intensity = 0.0; if (delta >= 0) { intensity = max(0.0, dot(L, normal) * attenuation * delta / radius); } return intensity; } float getLambertSpotLightIntensity(vec3 normal, float radius, float distance, float attenuation, vec3 L) { float intensity = max(0.0, dot(normal, L)); if (intensity > 0.0) { vec3 spot_direction = normalize(BBLightSettings2.xyz); // Cosine of the angle between the current point and the spotlight direction float current_cos = max(0.0, dot(spot_direction, -L)); // cutoff cosine float cutoff_radian = BBLightSettings0.z / 2 * 3.14 / 180.0; float cutoff_cos = cos(cutoff_radian); if (current_cos > cutoff_cos) { // Within the cutoff range float delta = radius - distance; intensity = pow(current_cos, BBLightSettings0.w) * 2.0 * attenuation * delta / radius; } else { intensity = 0.0; } } return intensity; } vec3 computeAnisotropicSpecular(float noise, vec3 color, float strength, float fade, float shift, float distort, vec3 T, vec3 H, vec3 N, vec3 V) { vec3 specular = vec3(0.0); // Shifting specular highlights, T approaches H // Overall offset & additional offset given by noise // 0~1 -> -0.5~0.5 float offset = distort * noise - 0.5 + shift * (-1); T = normalize(T + offset * H); float TdotH = dot(T, H); float sinTH = sqrt(1 - TdotH * TdotH); // It's dark above and bright below // float dirAtten = smoothstep(-1, 0, TdotH); // Fresnel can also be used float atten = clamp(dot(N, V), 0.0, 1.0); sinTH = clamp(sinTH, 0.0, 1.0); specular = vec3(atten * (strength * 2) * pow(sinTH, fade * 80)); specular *= color; return specular; } void main(void) { vec4 base_color = texture(BaseMap, v2f_texcoords); if (base_color.a < Cutoff) discard; float noise = texture(ShiftingNoiseMap, v2f_texcoords).r; vec3 N = normalize(v2f_normal); vec3 V = normalize(v2f_view_dir); // Lambert diffuse vec3 L = normalize(BBLightPosition.xyz); float intensity = dot(N, L); // brighten, -1~1 -> 0.2~1 intensity = intensity * 0.4 + 0.6; vec3 hair_color = mix(BBColor_ShadowColor.rgb, BBColor_BaseColor.rgb, intensity); vec3 diffuse = intensity * hair_color * base_color.rgb * BBLightColor.rgb; vec3 H = normalize(L + V); vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); vec3 T = normalize(cross(up, N)); vec3 B = normalize(cross(N, T)); // Whether to use T or B depends on the UV direction of the hair T = B; vec3 primary_specular = computeAnisotropicSpecular(noise, BBColor_PrimaryColor.rgb, PrimaryStrength, PrimaryFade, PrimaryShift, PrimaryDistort, T, H, N, V); // Double highlights vec3 secondary_specular = computeAnisotropicSpecular(noise, BBColor_SecondaryColor.rgb, SecondaryStrength, SecondaryFade, SecondaryShift, SecondaryDistort, T, H, N, V); vec3 final_color = diffuse + primary_specular + secondary_specular; FragColor = vec4(final_color, 1.0); } <|start_filename|>Code/BBearEditor/Engine/ParticleSystem/BBParticleSystem.cpp<|end_filename|> #include "BBParticleSystem.h" #include "BBParticle.h" BBParticleSystem::BBParticleSystem(const QVector3D &position) : BBGameObject(position, QVector3D(0, 0, 0), QVector3D(1, 1, 1)) { m_pParticle = new BBParticle(position); } BBParticleSystem::~BBParticleSystem() { BB_SAFE_DELETE(m_pParticle); } void BBParticleSystem::init() { m_pParticle->init(); } void BBParticleSystem::render(BBCamera *pCamera) { m_pParticle->render(pCamera); } void BBParticleSystem::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { BBGameObject::setPosition(position, bUpdateLocalTransform); m_pParticle->setPosition(position, bUpdateLocalTransform); } <|start_filename|>Code/BBearEditor/Engine/Serializer/BBMaterial.pb.cc<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBMaterial.proto #include "BBMaterial.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace BBSerializer { constexpr BBMaterial::BBMaterial( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : texturename_() , texturepath_() , floatname_() , floatvalue_() , vec4name_() , vec4value_() , shadername_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , vshaderpath_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , fshaderpath_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , cubemapname_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , cubemappaths_(nullptr) , srcblendfunc_(0) , blendstate_(false) , cullstate_(false) , dstblendfunc_(0) , cullface_(0){} struct BBMaterialDefaultTypeInternal { constexpr BBMaterialDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBMaterialDefaultTypeInternal() {} union { BBMaterial _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBMaterialDefaultTypeInternal _BBMaterial_default_instance_; } // namespace BBSerializer static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_BBMaterial_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_BBMaterial_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_BBMaterial_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_BBMaterial_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, shadername_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, vshaderpath_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, fshaderpath_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, texturename_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, texturepath_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, floatname_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, floatvalue_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, vec4name_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, vec4value_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, blendstate_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, srcblendfunc_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, dstblendfunc_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cullstate_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cullface_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cubemapname_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cubemappaths_), 0, 1, 2, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, 6, 5, 8, 7, 9, 3, 4, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 21, sizeof(::BBSerializer::BBMaterial)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBMaterial_default_instance_), }; const char descriptor_table_protodef_BBMaterial_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\020BBMaterial.proto\022\014BBSerializer\032\016BBVect" "or.proto\032\017BBCubeMap.proto\"\321\004\n\nBBMaterial" "\022\027\n\nshaderName\030\001 \001(\tH\000\210\001\001\022\030\n\013vShaderPath" "\030\002 \001(\tH\001\210\001\001\022\030\n\013fShaderPath\030\003 \001(\tH\002\210\001\001\022\023\n" "\013textureName\030\004 \003(\t\022\023\n\013texturePath\030\005 \003(\t\022" "\021\n\tfloatName\030\006 \003(\t\022\022\n\nfloatValue\030\007 \003(\002\022\020" "\n\010vec4Name\030\010 \003(\t\022+\n\tvec4Value\030\t \003(\0132\030.BB" "Serializer.BBVector4f\022\027\n\nblendState\030\n \001(" "\010H\003\210\001\001\022\031\n\014SRCBlendFunc\030\013 \001(\005H\004\210\001\001\022\031\n\014DST" "BlendFunc\030\014 \001(\005H\005\210\001\001\022\026\n\tcullState\030\r \001(\010H" "\006\210\001\001\022\025\n\010cullFace\030\016 \001(\005H\007\210\001\001\022\030\n\013cubeMapNa" "me\030\017 \001(\tH\010\210\001\001\0222\n\014cubeMapPaths\030\020 \001(\0132\027.BB" "Serializer.BBCubeMapH\t\210\001\001B\r\n\013_shaderName" "B\016\n\014_vShaderPathB\016\n\014_fShaderPathB\r\n\013_ble" "ndStateB\017\n\r_SRCBlendFuncB\017\n\r_DSTBlendFun" "cB\014\n\n_cullStateB\013\n\t_cullFaceB\016\n\014_cubeMap" "NameB\017\n\r_cubeMapPathsb\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_BBMaterial_2eproto_deps[2] = { &::descriptor_table_BBCubeMap_2eproto, &::descriptor_table_BBVector_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_BBMaterial_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBMaterial_2eproto = { false, false, 669, descriptor_table_protodef_BBMaterial_2eproto, "BBMaterial.proto", &descriptor_table_BBMaterial_2eproto_once, descriptor_table_BBMaterial_2eproto_deps, 2, 1, schemas, file_default_instances, TableStruct_BBMaterial_2eproto::offsets, file_level_metadata_BBMaterial_2eproto, file_level_enum_descriptors_BBMaterial_2eproto, file_level_service_descriptors_BBMaterial_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_BBMaterial_2eproto_getter() { return &descriptor_table_BBMaterial_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_BBMaterial_2eproto(&descriptor_table_BBMaterial_2eproto); namespace BBSerializer { // =================================================================== class BBMaterial::_Internal { public: using HasBits = decltype(std::declval<BBMaterial>()._has_bits_); static void set_has_shadername(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_vshaderpath(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_fshaderpath(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_blendstate(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static void set_has_srcblendfunc(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_dstblendfunc(HasBits* has_bits) { (*has_bits)[0] |= 256u; } static void set_has_cullstate(HasBits* has_bits) { (*has_bits)[0] |= 128u; } static void set_has_cullface(HasBits* has_bits) { (*has_bits)[0] |= 512u; } static void set_has_cubemapname(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static const ::BBSerializer::BBCubeMap& cubemappaths(const BBMaterial* msg); static void set_has_cubemappaths(HasBits* has_bits) { (*has_bits)[0] |= 16u; } }; const ::BBSerializer::BBCubeMap& BBMaterial::_Internal::cubemappaths(const BBMaterial* msg) { return *msg->cubemappaths_; } void BBMaterial::clear_vec4value() { vec4value_.Clear(); } void BBMaterial::clear_cubemappaths() { if (GetArena() == nullptr && cubemappaths_ != nullptr) { delete cubemappaths_; } cubemappaths_ = nullptr; _has_bits_[0] &= ~0x00000010u; } BBMaterial::BBMaterial(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), texturename_(arena), texturepath_(arena), floatname_(arena), floatvalue_(arena), vec4name_(arena), vec4value_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBMaterial) } BBMaterial::BBMaterial(const BBMaterial& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), texturename_(from.texturename_), texturepath_(from.texturepath_), floatname_(from.floatname_), floatvalue_(from.floatvalue_), vec4name_(from.vec4name_), vec4value_(from.vec4value_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); shadername_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_shadername()) { shadername_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_shadername(), GetArena()); } vshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_vshaderpath()) { vshaderpath_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_vshaderpath(), GetArena()); } fshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_fshaderpath()) { fshaderpath_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_fshaderpath(), GetArena()); } cubemapname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_cubemapname()) { cubemapname_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_cubemapname(), GetArena()); } if (from._internal_has_cubemappaths()) { cubemappaths_ = new ::BBSerializer::BBCubeMap(*from.cubemappaths_); } else { cubemappaths_ = nullptr; } ::memcpy(&srcblendfunc_, &from.srcblendfunc_, static_cast<size_t>(reinterpret_cast<char*>(&cullface_) - reinterpret_cast<char*>(&srcblendfunc_)) + sizeof(cullface_)); // @@protoc_insertion_point(copy_constructor:BBSerializer.BBMaterial) } void BBMaterial::SharedCtor() { shadername_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); vshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); fshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); cubemapname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&cubemappaths_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&cullface_) - reinterpret_cast<char*>(&cubemappaths_)) + sizeof(cullface_)); } BBMaterial::~BBMaterial() { // @@protoc_insertion_point(destructor:BBSerializer.BBMaterial) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBMaterial::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); shadername_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); vshaderpath_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); fshaderpath_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); cubemapname_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete cubemappaths_; } void BBMaterial::ArenaDtor(void* object) { BBMaterial* _this = reinterpret_cast< BBMaterial* >(object); (void)_this; } void BBMaterial::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBMaterial::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBMaterial::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBMaterial) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; texturename_.Clear(); texturepath_.Clear(); floatname_.Clear(); floatvalue_.Clear(); vec4name_.Clear(); vec4value_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000001fu) { if (cached_has_bits & 0x00000001u) { shadername_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { vshaderpath_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { fshaderpath_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { cubemapname_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { if (GetArena() == nullptr && cubemappaths_ != nullptr) { delete cubemappaths_; } cubemappaths_ = nullptr; } } if (cached_has_bits & 0x000000e0u) { ::memset(&srcblendfunc_, 0, static_cast<size_t>( reinterpret_cast<char*>(&cullstate_) - reinterpret_cast<char*>(&srcblendfunc_)) + sizeof(cullstate_)); } if (cached_has_bits & 0x00000300u) { ::memset(&dstblendfunc_, 0, static_cast<size_t>( reinterpret_cast<char*>(&cullface_) - reinterpret_cast<char*>(&dstblendfunc_)) + sizeof(cullface_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBMaterial::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // string shaderName = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_shadername(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.shaderName")); CHK_(ptr); } else goto handle_unusual; continue; // string vShaderPath = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_vshaderpath(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.vShaderPath")); CHK_(ptr); } else goto handle_unusual; continue; // string fShaderPath = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { auto str = _internal_mutable_fshaderpath(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.fShaderPath")); CHK_(ptr); } else goto handle_unusual; continue; // repeated string textureName = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_texturename(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.textureName")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<34>(ptr)); } else goto handle_unusual; continue; // repeated string texturePath = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_texturepath(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.texturePath")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<42>(ptr)); } else goto handle_unusual; continue; // repeated string floatName = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_floatname(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.floatName")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<50>(ptr)); } else goto handle_unusual; continue; // repeated float floatValue = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedFloatParser(_internal_mutable_floatvalue(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 61) { _internal_add_floatvalue(::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr)); ptr += sizeof(float); } else goto handle_unusual; continue; // repeated string vec4Name = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_vec4name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.vec4Name")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<66>(ptr)); } else goto handle_unusual; continue; // repeated .BBSerializer.BBVector4f vec4Value = 9; case 9: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_vec4value(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<74>(ptr)); } else goto handle_unusual; continue; // bool blendState = 10; case 10: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80)) { _Internal::set_has_blendstate(&has_bits); blendstate_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 SRCBlendFunc = 11; case 11: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 88)) { _Internal::set_has_srcblendfunc(&has_bits); srcblendfunc_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 DSTBlendFunc = 12; case 12: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 96)) { _Internal::set_has_dstblendfunc(&has_bits); dstblendfunc_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // bool cullState = 13; case 13: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 104)) { _Internal::set_has_cullstate(&has_bits); cullstate_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 cullFace = 14; case 14: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 112)) { _Internal::set_has_cullface(&has_bits); cullface_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // string cubeMapName = 15; case 15: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 122)) { auto str = _internal_mutable_cubemapname(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.cubeMapName")); CHK_(ptr); } else goto handle_unusual; continue; // .BBSerializer.BBCubeMap cubeMapPaths = 16; case 16: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 130)) { ptr = ctx->ParseMessage(_internal_mutable_cubemappaths(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBMaterial::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBMaterial) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string shaderName = 1; if (_internal_has_shadername()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_shadername().data(), static_cast<int>(this->_internal_shadername().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.shaderName"); target = stream->WriteStringMaybeAliased( 1, this->_internal_shadername(), target); } // string vShaderPath = 2; if (_internal_has_vshaderpath()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_vshaderpath().data(), static_cast<int>(this->_internal_vshaderpath().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.vShaderPath"); target = stream->WriteStringMaybeAliased( 2, this->_internal_vshaderpath(), target); } // string fShaderPath = 3; if (_internal_has_fshaderpath()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_fshaderpath().data(), static_cast<int>(this->_internal_fshaderpath().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.fShaderPath"); target = stream->WriteStringMaybeAliased( 3, this->_internal_fshaderpath(), target); } // repeated string textureName = 4; for (int i = 0, n = this->_internal_texturename_size(); i < n; i++) { const auto& s = this->_internal_texturename(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.textureName"); target = stream->WriteString(4, s, target); } // repeated string texturePath = 5; for (int i = 0, n = this->_internal_texturepath_size(); i < n; i++) { const auto& s = this->_internal_texturepath(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.texturePath"); target = stream->WriteString(5, s, target); } // repeated string floatName = 6; for (int i = 0, n = this->_internal_floatname_size(); i < n; i++) { const auto& s = this->_internal_floatname(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.floatName"); target = stream->WriteString(6, s, target); } // repeated float floatValue = 7; if (this->_internal_floatvalue_size() > 0) { target = stream->WriteFixedPacked(7, _internal_floatvalue(), target); } // repeated string vec4Name = 8; for (int i = 0, n = this->_internal_vec4name_size(); i < n; i++) { const auto& s = this->_internal_vec4name(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.vec4Name"); target = stream->WriteString(8, s, target); } // repeated .BBSerializer.BBVector4f vec4Value = 9; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_vec4value_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(9, this->_internal_vec4value(i), target, stream); } // bool blendState = 10; if (_internal_has_blendstate()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(10, this->_internal_blendstate(), target); } // int32 SRCBlendFunc = 11; if (_internal_has_srcblendfunc()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(11, this->_internal_srcblendfunc(), target); } // int32 DSTBlendFunc = 12; if (_internal_has_dstblendfunc()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(12, this->_internal_dstblendfunc(), target); } // bool cullState = 13; if (_internal_has_cullstate()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(13, this->_internal_cullstate(), target); } // int32 cullFace = 14; if (_internal_has_cullface()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(14, this->_internal_cullface(), target); } // string cubeMapName = 15; if (_internal_has_cubemapname()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_cubemapname().data(), static_cast<int>(this->_internal_cubemapname().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.cubeMapName"); target = stream->WriteStringMaybeAliased( 15, this->_internal_cubemapname(), target); } // .BBSerializer.BBCubeMap cubeMapPaths = 16; if (_internal_has_cubemappaths()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 16, _Internal::cubemappaths(this), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBMaterial) return target; } size_t BBMaterial::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBMaterial) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated string textureName = 4; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(texturename_.size()); for (int i = 0, n = texturename_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( texturename_.Get(i)); } // repeated string texturePath = 5; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(texturepath_.size()); for (int i = 0, n = texturepath_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( texturepath_.Get(i)); } // repeated string floatName = 6; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(floatname_.size()); for (int i = 0, n = floatname_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( floatname_.Get(i)); } // repeated float floatValue = 7; { unsigned int count = static_cast<unsigned int>(this->_internal_floatvalue_size()); size_t data_size = 4UL * count; if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } total_size += data_size; } // repeated string vec4Name = 8; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(vec4name_.size()); for (int i = 0, n = vec4name_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( vec4name_.Get(i)); } // repeated .BBSerializer.BBVector4f vec4Value = 9; total_size += 1UL * this->_internal_vec4value_size(); for (const auto& msg : this->vec4value_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x000000ffu) { // string shaderName = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_shadername()); } // string vShaderPath = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_vshaderpath()); } // string fShaderPath = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_fshaderpath()); } // string cubeMapName = 15; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_cubemapname()); } // .BBSerializer.BBCubeMap cubeMapPaths = 16; if (cached_has_bits & 0x00000010u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *cubemappaths_); } // int32 SRCBlendFunc = 11; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_srcblendfunc()); } // bool blendState = 10; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } // bool cullState = 13; if (cached_has_bits & 0x00000080u) { total_size += 1 + 1; } } if (cached_has_bits & 0x00000300u) { // int32 DSTBlendFunc = 12; if (cached_has_bits & 0x00000100u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_dstblendfunc()); } // int32 cullFace = 14; if (cached_has_bits & 0x00000200u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_cullface()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBMaterial::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBMaterial) GOOGLE_DCHECK_NE(&from, this); const BBMaterial* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBMaterial>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBMaterial) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBMaterial) MergeFrom(*source); } } void BBMaterial::MergeFrom(const BBMaterial& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBMaterial) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; texturename_.MergeFrom(from.texturename_); texturepath_.MergeFrom(from.texturepath_); floatname_.MergeFrom(from.floatname_); floatvalue_.MergeFrom(from.floatvalue_); vec4name_.MergeFrom(from.vec4name_); vec4value_.MergeFrom(from.vec4value_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { _internal_set_shadername(from._internal_shadername()); } if (cached_has_bits & 0x00000002u) { _internal_set_vshaderpath(from._internal_vshaderpath()); } if (cached_has_bits & 0x00000004u) { _internal_set_fshaderpath(from._internal_fshaderpath()); } if (cached_has_bits & 0x00000008u) { _internal_set_cubemapname(from._internal_cubemapname()); } if (cached_has_bits & 0x00000010u) { _internal_mutable_cubemappaths()->::BBSerializer::BBCubeMap::MergeFrom(from._internal_cubemappaths()); } if (cached_has_bits & 0x00000020u) { srcblendfunc_ = from.srcblendfunc_; } if (cached_has_bits & 0x00000040u) { blendstate_ = from.blendstate_; } if (cached_has_bits & 0x00000080u) { cullstate_ = from.cullstate_; } _has_bits_[0] |= cached_has_bits; } if (cached_has_bits & 0x00000300u) { if (cached_has_bits & 0x00000100u) { dstblendfunc_ = from.dstblendfunc_; } if (cached_has_bits & 0x00000200u) { cullface_ = from.cullface_; } _has_bits_[0] |= cached_has_bits; } } void BBMaterial::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBMaterial) if (&from == this) return; Clear(); MergeFrom(from); } void BBMaterial::CopyFrom(const BBMaterial& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBMaterial) if (&from == this) return; Clear(); MergeFrom(from); } bool BBMaterial::IsInitialized() const { return true; } void BBMaterial::InternalSwap(BBMaterial* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); texturename_.InternalSwap(&other->texturename_); texturepath_.InternalSwap(&other->texturepath_); floatname_.InternalSwap(&other->floatname_); floatvalue_.InternalSwap(&other->floatvalue_); vec4name_.InternalSwap(&other->vec4name_); vec4value_.InternalSwap(&other->vec4value_); shadername_.Swap(&other->shadername_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); vshaderpath_.Swap(&other->vshaderpath_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); fshaderpath_.Swap(&other->fshaderpath_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); cubemapname_.Swap(&other->cubemapname_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(BBMaterial, cullface_) + sizeof(BBMaterial::cullface_) - PROTOBUF_FIELD_OFFSET(BBMaterial, cubemappaths_)>( reinterpret_cast<char*>(&cubemappaths_), reinterpret_cast<char*>(&other->cubemappaths_)); } ::PROTOBUF_NAMESPACE_ID::Metadata BBMaterial::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBMaterial_2eproto_getter, &descriptor_table_BBMaterial_2eproto_once, file_level_metadata_BBMaterial_2eproto[0]); } // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::BBSerializer::BBMaterial* Arena::CreateMaybeMessage< ::BBSerializer::BBMaterial >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBMaterial >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> <|start_filename|>Resources/shaders/standard.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBColor; attribute vec4 BBTexcoord; attribute vec4 BBNormal; varying vec4 V_world_pos; varying vec4 V_Color; varying vec4 V_Texcoords; varying vec4 V_Normal; varying vec4 V_world_pos_light_space; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; uniform mat4 BBLightProjectionMatrix; uniform mat4 BBLightViewMatrix; void main() { V_world_pos = BBModelMatrix * BBPosition; V_Color = BBColor; V_Texcoords = BBTexcoord; V_Normal.xyz = mat3(transpose(inverse(BBModelMatrix))) * BBNormal.xyz; V_Normal.a = 1.0; V_Normal = normalize(V_Normal); V_world_pos_light_space = BBLightProjectionMatrix * BBLightViewMatrix * V_world_pos; gl_Position = BBProjectionMatrix * BBViewMatrix * V_world_pos; } <|start_filename|>Code/BBearEditor/Engine/Render/RayTracing/BBScreenSpaceRayTracker.h<|end_filename|> #ifndef BBSCREENSPACERAYTRACKER_H #define BBSCREENSPACERAYTRACKER_H class BBScene; class BBScreenSpaceRayTracker { public: static void open(BBScene *pScene); private: static void setGBufferPass(BBScene *pScene); static void setRayTracingPass(BBScene *pScene); }; #endif // BBSCREENSPACERAYTRACKER_H <|start_filename|>Code/BBearEditor/Engine/Physics/Body/BBClothBody.h<|end_filename|> #ifndef BBCLOTHBODY_H #define BBCLOTHBODY_H #include "BBBaseBody.h" enum BBClothPinConstraintType { Left, TopLeft }; class BBClothMesh; class BBClothBody : public BBBaseBody { public: BBClothBody(BBClothMesh *pMesh, float fMass, float fElasticModulus); void initPinConstraints(const BBClothPinConstraintType &eType); private: void initPositions(); void initConstraints(); void initDistanceConstraint(int nTriangleIndex1, int nTriangleIndex2); BBClothMesh *m_pClothMesh; float m_fElasticModulus; }; #endif // BBCLOTHBODY_H <|start_filename|>Code/BBearEditor/Engine/2D/BBFullScreenQuad.h<|end_filename|> #ifndef BBFULLSCREENQUAD_H #define BBFULLSCREENQUAD_H #include "Base/BBRenderableObject.h" class BBLight; class BBFullScreenQuad; typedef void (BBFullScreenQuad::*BBRenderFunc)(BBCamera *pCamera); class BBFullScreenQuad : public BBRenderableObject { public: BBFullScreenQuad(); BBFullScreenQuad(float fScale, float fOffsetX, float fOffsetY, int nFrustumIndexX, int nFrustumIndexY); void init() override; void init(BBMaterial *pMaterial); void render(BBCamera *pCamera) override; // void setAABB(float fWidth, float fHeight); public: void setRenderFunc(const BBRenderFunc &func) { m_RenderFunc = func; } void defaultRender(BBCamera *pCamera); void cullLightRender(BBCamera *pCamera); private: BBRenderFunc m_RenderFunc; float m_fScale; float m_fOffsetX; float m_fOffsetY; int m_nFrustumIndexX; int m_nFrustumIndexY; // projecting screen space is imprecise // QRectF m_AABB; }; class BBTiledFullScreenQuad : public BBGameObject { public: BBTiledFullScreenQuad(); ~BBTiledFullScreenQuad(); void init() override; void render(BBCamera *pCamera) override; // void setTiledAABB(float fWidth, float fHeight); void setCurrentMaterial(BBMaterial *pMaterial) override; void setMatrix4(const std::string &uniformName, const float *pMatrix4) override; void setVector4(const std::string &uniformName, float x, float y, float z, float w) override; void setTexture(const std::string &uniformName, GLuint textureName) override; void openLight() override; void closeLight() override; private: BBFullScreenQuad *m_pFullScreenQuad[4]; int m_nQuadCount; }; #endif // BBFULLSCREENQUAD_H <|start_filename|>Code/BBearEditor/Engine/Render/BBRenderQueue.cpp<|end_filename|> #include "BBRenderQueue.h" #include "Utils/BBUtils.h" #include "BBDrawCall.h" BBRenderQueue::BBRenderQueue(BBCamera *pCamera) { m_pCamera = pCamera; m_pOpaqueDrawCall = nullptr; m_pTransparentDrawCall = nullptr; m_pUIDrawCall = nullptr; } BBRenderQueue::~BBRenderQueue() { BB_SAFE_DELETE(m_pOpaqueDrawCall); BB_SAFE_DELETE(m_pTransparentDrawCall); BB_SAFE_DELETE(m_pUIDrawCall); } void BBRenderQueue::appendOpaqueDrawCall(BBDrawCall *pDC) { if (m_pOpaqueDrawCall == nullptr) { m_pOpaqueDrawCall = pDC; } else { m_pOpaqueDrawCall->pushBack(pDC); } } void BBRenderQueue::appendTransparentDrawCall(BBDrawCall *pDC) { if (m_pTransparentDrawCall == nullptr) { m_pTransparentDrawCall = pDC; } else { m_pTransparentDrawCall->pushBack(pDC); } } void BBRenderQueue::appendUIDrawCall(BBDrawCall *pDC) { } void BBRenderQueue::removeOpaqueDrawCall(BBDrawCall *pDC) { BB_PROCESS_ERROR_RETURN(m_pOpaqueDrawCall); if (m_pOpaqueDrawCall->isEnd()) { m_pOpaqueDrawCall = nullptr; } else { if (m_pOpaqueDrawCall == pDC) { m_pOpaqueDrawCall = m_pOpaqueDrawCall->removeSelf<BBDrawCall>(); } else { m_pOpaqueDrawCall->remove(pDC); } } } void BBRenderQueue::removeTransparentDrawCall(BBDrawCall *pDC) { BB_PROCESS_ERROR_RETURN(m_pTransparentDrawCall); if (m_pTransparentDrawCall->isEnd()) { m_pTransparentDrawCall = nullptr; } else { if (m_pTransparentDrawCall == pDC) { m_pTransparentDrawCall = m_pTransparentDrawCall->removeSelf<BBDrawCall>(); } else { m_pTransparentDrawCall->remove(pDC); } } } void BBRenderQueue::removeUIDrawCall(BBDrawCall *pDC) { } void BBRenderQueue::render() { renderOpaque(); renderTransparent(); renderUI(); } void BBRenderQueue::renderOpaque() { BB_PROCESS_ERROR_RETURN(m_pOpaqueDrawCall); m_pOpaqueDrawCall->draw(m_pCamera); } void BBRenderQueue::renderTransparent() { BB_PROCESS_ERROR_RETURN(m_pTransparentDrawCall); m_pTransparentDrawCall->draw(m_pCamera); } void BBRenderQueue::renderUI() { BB_PROCESS_ERROR_RETURN(m_pUIDrawCall); m_pUIDrawCall->draw(m_pCamera); } void BBRenderQueue::updateAllDrawCallOrder() { updateAllOpaqueDrawCallOrder(); updateAllTransparentDrawCallOrder(); // to do ... } void BBRenderQueue::updateOpaqueDrawCallOrder(BBDrawCall *pNode) { BB_PROCESS_ERROR_RETURN(m_pOpaqueDrawCall); // There is only one node in this queue, so there is no need to update the order if (!m_pOpaqueDrawCall->isEnd()) { if (m_pOpaqueDrawCall == pNode) { // remove head and make next as head m_pOpaqueDrawCall = pNode->removeSelf<BBDrawCall>(); } else { // remove the node from the queue m_pOpaqueDrawCall->remove(pNode); } // reinsert in the new pos m_pOpaqueDrawCall = appendAscendingRenderQueue(m_pOpaqueDrawCall, pNode); } } void BBRenderQueue::updateTransparentDrawCallOrder(BBDrawCall *pNode) { BB_PROCESS_ERROR_RETURN(m_pTransparentDrawCall); // There is only one node in this queue, so there is no need to update the order if (!m_pTransparentDrawCall->isEnd()) { if (m_pTransparentDrawCall == pNode) { // remove head and make next as head m_pTransparentDrawCall = pNode->removeSelf<BBDrawCall>(); } else { // remove the node from the queue m_pTransparentDrawCall->remove(pNode); } // reinsert in the new pos m_pTransparentDrawCall = appendDescendingRenderQueue(m_pTransparentDrawCall, pNode); } } void BBRenderQueue::switchQueue(BBMaterial *pPrevious, BBMaterial *pCurrent, BBDrawCall *pDrawCall) { bool bPreviousBlendState = pPrevious->getBlendState(); bool bCurrentBlendState = pCurrent->getBlendState(); BB_PROCESS_ERROR_RETURN(bPreviousBlendState != bCurrentBlendState); switchQueue(!bPreviousBlendState, pDrawCall); } void BBRenderQueue::switchQueue(bool bEnableBlend, BBDrawCall *pDrawCall) { if (bEnableBlend) { // false -> true // opaque -> transparent removeOpaqueDrawCall(pDrawCall); appendTransparentDrawCall(pDrawCall); } else { // true -> false // transparent -> opaque removeTransparentDrawCall(pDrawCall); appendOpaqueDrawCall(pDrawCall); } } void BBRenderQueue::updateAllOpaqueDrawCallOrder() { BB_PROCESS_ERROR_RETURN(m_pOpaqueDrawCall); // reorder the nodes in the pHead into another queue // There is only one node in this queue, so there is no need to update the order if (!m_pOpaqueDrawCall->isEnd()) { BBDrawCall *pCurrent = m_pOpaqueDrawCall; // remove pCurrent from old queue BBDrawCall *pNext = pCurrent->removeSelf<BBDrawCall>(); BBDrawCall *pNewHead = pCurrent; // start from the second in the old queue pCurrent = pNext; while (pCurrent) { pNext = pCurrent->removeSelf<BBDrawCall>(); // insert in new queue orderly pNewHead = appendAscendingRenderQueue(pNewHead, pCurrent); pCurrent = pNext; } m_pOpaqueDrawCall = pNewHead; } } void BBRenderQueue::updateAllTransparentDrawCallOrder() { BB_PROCESS_ERROR_RETURN(m_pTransparentDrawCall); // reorder the nodes in the pHead into another queue // There is only one node in this queue, so there is no need to update the order if (!m_pTransparentDrawCall->isEnd()) { BBDrawCall *pCurrent = m_pTransparentDrawCall; // remove pCurrent from old queue BBDrawCall *pNext = pCurrent->removeSelf<BBDrawCall>(); BBDrawCall *pNewHead = pCurrent; // start from the second in the old queue pCurrent = pNext; while (pCurrent) { pNext = pCurrent->removeSelf<BBDrawCall>(); // insert in new queue orderly pNewHead = appendDescendingRenderQueue(pNewHead, pCurrent); pCurrent = pNext; } m_pTransparentDrawCall = pNewHead; } } /** * @brief BBRenderQueue::appendAscendingRenderQueue * @param pHead * @param pNewNode * @return new head */ BBDrawCall* BBRenderQueue::appendAscendingRenderQueue(BBDrawCall *pHead, BBDrawCall *pNewNode) { BBDrawCall *pCurrent = pHead; BBDrawCall *pPrevious = nullptr; while (pCurrent != nullptr) { if (pNewNode->getDistanceToCamera(m_pCamera) <= pCurrent->getDistanceToCamera(m_pCamera)) { if (pPrevious == nullptr) { // change head pNewNode->pushBack(pCurrent); return pNewNode; } else { pNewNode->insertAfter(pPrevious); pPrevious = nullptr; break; } } pPrevious = pCurrent; pCurrent = pCurrent->next<BBDrawCall>(); } if (pPrevious != nullptr) { pPrevious->pushBack(pNewNode); } return pHead; } BBDrawCall* BBRenderQueue::appendDescendingRenderQueue(BBDrawCall *pHead, BBDrawCall *pNewNode) { BBDrawCall *pCurrent = pHead; BBDrawCall *pPrevious = nullptr; while (pCurrent != nullptr) { if (pNewNode->getDistanceToCamera(m_pCamera) >= pCurrent->getDistanceToCamera(m_pCamera)) { if (pPrevious == nullptr) { // change head pNewNode->pushBack(pCurrent); return pNewNode; } else { pNewNode->insertAfter(pPrevious); pPrevious = nullptr; break; } } pPrevious = pCurrent; pCurrent = pCurrent->next<BBDrawCall>(); } if (pPrevious != nullptr) { pPrevious->pushBack(pNewNode); } return pHead; } <|start_filename|>Code/BBearEditor/Editor/PropertyManager/BBFactoryComponent.h<|end_filename|> #ifndef BBFACTORYCOMPONENT_H #define BBFACTORYCOMPONENT_H #include <QPushButton> #include <QDialog> #include <QLabel> #include <QLineEdit> // When hovering, it shows an arrow cursor, press and then move left and right to adjust the parameter class BBSliderLabel : public QPushButton { Q_OBJECT public: explicit BBSliderLabel(QWidget *pParent = nullptr); private: void mouseMoveEvent(QMouseEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; QPoint m_LastPos; bool m_bPressed; signals: void slide(int nDeltaX); }; class BBColorButton : public QPushButton { Q_OBJECT public: explicit BBColorButton(QWidget *pParent = nullptr); ~BBColorButton(); void setColor(int r, int g, int b, int a = 255); void setColor(float *color); private slots: void click(); private: QWidget *m_pBlackBackGroundContent; QWidget *m_pWhiteBackGroundContent; }; /** * @brief The BBScreenDialog class Capture the full-screen for color picking of dropper */ class BBScreenDialog : public QDialog { Q_OBJECT public: BBScreenDialog(QWidget *pParent = 0); ~BBScreenDialog(); signals: void setColor(float r, float g, float b); private: void setBackground(); void mousePressEvent(QMouseEvent *event) override; QLabel *m_pBackground; QPixmap m_PixBackground; static int m_nCursorSize; }; /** * @brief The BBDragAcceptedEdit class */ class BBDragAcceptedEdit : public QLineEdit { Q_OBJECT public: BBDragAcceptedEdit(QWidget *pParent = 0); void setFilter(const QStringList &acceptableSuffixs) { m_Filter = acceptableSuffixs; } signals: void currentFilePathChanged(const QString &path); protected: void dragEnterEvent(QDragEnterEvent *event) override; void dropEvent(QDropEvent *event) override; QStringList m_Filter; QString m_CurrentFilePath; }; /** * @brief The BBIconLabel class */ class BBIconLabel : public BBDragAcceptedEdit { Q_OBJECT public: BBIconLabel(QWidget *pParent = 0); void setIcon(const QString &filePath); protected: static QSize m_DefaultSize; }; #endif // BBFACTORYCOMPONENT_H <|start_filename|>Code/BBearEditor/Engine/Base/BBRenderableObject.cpp<|end_filename|> #include "BBRenderableObject.h" #include "Render/BBDrawCall.h" #include "Render/BBMaterial.h" #include "Utils/BBUtils.h" #include "Render/BBCamera.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BufferObject/BBShaderStorageBufferObject.h" #include "Render/BufferObject/BBElementBufferObject.h" #include "Render/BBUniformUpdater.h" #include "Render/BBRenderPass.h" #include "Render/BBRenderQueue.h" #include "Scene/BBSceneManager.h" #include "OfflineRenderer/BBScatterMaterial.h" /** * @brief BBRenderableObject::BBRenderableObject 3D */ BBRenderableObject::BBRenderableObject() : BBRenderableObject(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBRenderableObject::BBRenderableObject(const QVector3D &position, const QVector3D &rotation, const QVector3D &scale) : BBRenderableObject(position.x(), position.y(), position.z(), rotation.x(), rotation.y(), rotation.z(), scale.x(), scale.y(), scale.z()) { } BBRenderableObject::BBRenderableObject(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBGameObject(px, py, pz, rx, ry, rz, sx, sy, sz) { sharedInit(); } /** * @brief BBRenderableObject::BBRenderableObject 2D * @param x * @param y * @param nWidth * @param nHeight */ BBRenderableObject::BBRenderableObject(int x, int y, int nWidth, int nHeight) : BBGameObject(x, y, nWidth, nHeight) { sharedInit(); } BBRenderableObject::~BBRenderableObject() { BB_SAFE_DELETE(m_pVBO); BB_SAFE_DELETE(m_pSSBO); BB_SAFE_DELETE(m_pACBO); BB_SAFE_DELETE(m_pEBO); BB_SAFE_DELETE_ARRAY(m_pIndexes); BB_SAFE_DELETE(m_pScatterMaterial); } void BBRenderableObject::init() { m_pCurrentMaterial->setMatrix4(LOCATION_MODELMATRIX, m_ModelMatrix.data()); if (m_nIndexCount > 0) { m_pEBO = new BBElementBufferObject(m_nIndexCount); m_pEBO->submitData(m_pIndexes, m_nIndexCount); } closeLight(); if (m_pVBO) { m_pVBO->submitData(); m_nVertexCount = m_pVBO->getVertexCount(); } if (m_pSSBO) { m_pSSBO->submitData(); m_nVertexCount = m_pSSBO->getVertexCount(); } } void BBRenderableObject::render(BBCamera *pCamera) { render(m_ModelMatrix, pCamera); } void BBRenderableObject::render(const QMatrix4x4 &modelMatrix, BBCamera *pCamera) { if (m_bActive && m_bVisible) { m_pDrawCalls->draw(pCamera); } } void BBRenderableObject::insertInRenderQueue(BBRenderQueue *pQueue) { if (m_bActive && m_bVisible) { bool bTransparent = m_pDrawCalls->getMaterial()->getBlendState(); if (bTransparent) { pQueue->appendTransparentDrawCall(m_pDrawCalls); } else { pQueue->appendOpaqueDrawCall(m_pDrawCalls); } m_bInRenderQueue = true; // init m_pDrawCalls->updateOrderInRenderQueue(m_Position); } } void BBRenderableObject::removeFromRenderQueue(BBRenderQueue *pQueue) { pQueue->removeOpaqueDrawCall(m_pDrawCalls); m_bInRenderQueue = false; } void BBRenderableObject::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { BBGameObject::setPosition(position, bUpdateLocalTransform); if (m_bInRenderQueue) { m_pDrawCalls->updateOrderInRenderQueue(m_Position); } } void BBRenderableObject::setModelMatrix(float px, float py, float pz, const QQuaternion &r, float sx, float sy, float sz) { BBGameObject::setModelMatrix(px, py, pz, r, sx, sy, sz); } void BBRenderableObject::setVisibility(bool bVisible) { BBGameObject::setVisibility(bVisible); m_pDrawCalls->setVisibility(bVisible); } void BBRenderableObject::setCurrentMaterial(BBMaterial *pMaterial) { m_pLastMaterial = m_pCurrentMaterial; m_pCurrentMaterial = pMaterial; m_pCurrentMaterial->setMatrix4(LOCATION_MODELMATRIX, m_ModelMatrix.data()); m_pCurrentMaterial->setMatrix4(LOCATION_VIEWMODELMATRIX_IT, m_ViewModelMatrix_IT.data()); m_pDrawCalls->setMaterial(m_pCurrentMaterial); } void BBRenderableObject::setCurrentMaterial(int nExtraMaterialIndex) { BBMaterial *pMaterial = m_pExtraMaterial[nExtraMaterialIndex]; BB_PROCESS_ERROR_RETURN(pMaterial); setCurrentMaterial(pMaterial); } void BBRenderableObject::setExtraMaterial(int nMaterialIndex, BBMaterial *pMaterial) { // 0 is used by GBuffer // 2 is used by shadow map // 3, 4, 5 are used by multi materials rendering, which is setted in the object property panel m_pExtraMaterial[nMaterialIndex] = pMaterial; } void BBRenderableObject::rollbackMaterial() { setCurrentMaterial(m_pLastMaterial); m_pLastMaterial = m_pDefaultMaterial; } void BBRenderableObject::restoreMaterial() { m_pLastMaterial = m_pCurrentMaterial; setCurrentMaterial(m_pDefaultMaterial); } void BBRenderableObject::setMatrix4(const std::string &uniformName, const float *pMatrix4) { m_pCurrentMaterial->setMatrix4(uniformName, pMatrix4); } void BBRenderableObject::setVector4(const std::string &uniformName, float x, float y, float z, float w) { m_pCurrentMaterial->setVector4(uniformName, x, y, z, w); } void BBRenderableObject::setArrayVector4(const std::string &uniformName, const float *pArrayVector4, int nArrayCount) { m_pCurrentMaterial->setVector4Array(uniformName, pArrayVector4, nArrayCount); } void BBRenderableObject::setTexture(const std::string &uniformName, GLuint textureName) { m_pCurrentMaterial->setVector4(LOCATION_TEXTURE_SETTING0, 1.0f, 0.0f, 0.0f, 0.0f); m_pCurrentMaterial->setSampler2D(uniformName, textureName); } void BBRenderableObject::openLight() { // x: is there a light m_pCurrentMaterial->setVector4(LOCATION_LIGHT_SETTINGS(0), 1.0f, 0.0f, 0.0f, 0.0f); m_pCurrentMaterial->setVector4(LOCATION_LIGHT_SETTINGS(1), 0.0f, 0.0f, 0.0f, 0.0f); } void BBRenderableObject::closeLight() { m_pCurrentMaterial->setVector4(LOCATION_LIGHT_SETTINGS(0), 0.0f, 0.0f, 0.0f, 0.0f); m_pCurrentMaterial->setVector4(LOCATION_LIGHT_SETTINGS(1), 0.0f, 0.0f, 0.0f, 0.0f); } void BBRenderableObject::appendSSBO(BBShaderStorageBufferObject *pSSBO) { if (m_pSSBO == nullptr) { m_pSSBO = pSSBO; } else { m_pSSBO->pushBack(pSSBO); } } void BBRenderableObject::removeSSBO(BBShaderStorageBufferObject *pSSBO) { BB_PROCESS_ERROR_RETURN(m_pSSBO); BB_PROCESS_ERROR_RETURN(pSSBO); if (m_pSSBO->isEnd()) { m_pSSBO = nullptr; } else { if (m_pSSBO == pSSBO) { m_pSSBO = m_pSSBO->removeSelf<BBShaderStorageBufferObject>(); } else { m_pSSBO->remove(pSSBO); } } } void BBRenderableObject::appendACBO(BBAtomicCounterBufferObject *pACBO, bool bClear) { // set ACBO for drawcall BBDrawCall *pDrawCall = m_pDrawCalls; while (pDrawCall != nullptr) { pDrawCall->setACBO(pACBO, bClear); pDrawCall = pDrawCall->next<BBDrawCall>(); } } void BBRenderableObject::removeACBO() { BBDrawCall *pDrawCall = m_pDrawCalls; while (pDrawCall != nullptr) { pDrawCall->removeACBO(); pDrawCall = pDrawCall->next<BBDrawCall>(); } } void BBRenderableObject::setScatterMaterial(BBScatterMaterial *pScatterMaterial) { m_pScatterMaterial = pScatterMaterial; } void BBRenderableObject::appendDrawCall(BBDrawCall *pDrawCall) { if (m_pDrawCalls == nullptr) { m_pDrawCalls = pDrawCall; } else { m_pDrawCalls->pushBack(pDrawCall); } } void BBRenderableObject::sharedInit() { m_bInRenderQueue = false; m_pDrawCalls = nullptr; m_bVisible = true; m_pDefaultMaterial = new BBMaterial(); m_pCurrentMaterial = m_pDefaultMaterial; m_pLastMaterial = m_pDefaultMaterial; for (int i = 0; i < EXTRA_MATERIAL_COUNT; i++) { m_pExtraMaterial[i] = nullptr; } m_pVBO = nullptr; m_pSSBO = nullptr; m_pACBO = nullptr; m_pEBO = nullptr; m_pIndexes = nullptr; m_nIndexCount = 0; m_nVertexCount = 0; m_DefaultColor = QVector3D(1.0f, 1.0f, 1.0f); m_pScatterMaterial = nullptr; } <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBOfflineRendererManager.cpp<|end_filename|> #include "BBOfflineRendererManager.h" #include "Utils/BBUtils.h" #include "../BBPropertyFactory.h" #include "OfflineRenderer/BBOfflineRenderer.h" BBOfflineRendererManager::BBOfflineRendererManager(BBOfflineRenderer *pOfflineRenderer, QWidget *pParent) : BBGroupManager("Offline Renderer", BB_PATH_RESOURCE_ICON(teapot.png), pParent) { m_pOfflineRenderer = pOfflineRenderer; QStringList photonMappingAlgorithmName = {"Common"}; BBEnumExpansionFactory *pPhotonMappingFactory = new BBEnumExpansionFactory("Photon Mapping", photonMappingAlgorithmName, "Bake", "", this, 1, 1); pPhotonMappingFactory->enableTrigger(false); QObject::connect(pPhotonMappingFactory, SIGNAL(buttonClicked()), this, SLOT(startPhotonMapping())); addFactory(pPhotonMappingFactory); } BBOfflineRendererManager::~BBOfflineRendererManager() { } void BBOfflineRendererManager::startPhotonMapping() { m_pOfflineRenderer->startPhotonMapping(); } <|start_filename|>Code/BBearEditor/Engine/Physics/Body/BBClothBody.cpp<|end_filename|> #include "BBClothBody.h" #include "../ClothSystem/BBClothMesh.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "../Constraint/BBDistanceConstraint.h" #include "../Constraint/BBPinConstraint.h" BBClothBody::BBClothBody(BBClothMesh *pMesh, float fMass, float fElasticModulus) : BBBaseBody(pMesh->getVertexCount(), fMass) { m_pClothMesh = pMesh; m_fElasticModulus = fElasticModulus; initPositions(); initConstraints(); } void BBClothBody::initPinConstraints(const BBClothPinConstraintType &eType) { if (eType == Left) { std::vector<int> leftVertexIndexes = m_pClothMesh->getLeftVertexIndexes(); for (int i = 0; i < leftVertexIndexes.size(); i++) { int nIndex = leftVertexIndexes[i]; BBPinConstraint *pConstraint = new BBPinConstraint(this, nIndex, m_pClothMesh->getVBO()->getPosition(nIndex)); m_Constraints.push_back(pConstraint); } } else if (eType == TopLeft) { int nTopLeftVertexIndex = m_pClothMesh->getTopLeftVertexIndex(); BBPinConstraint *pConstraint = new BBPinConstraint(this, nTopLeftVertexIndex, m_pClothMesh->getVBO()->getPosition(nTopLeftVertexIndex)); m_Constraints.push_back(pConstraint); } } void BBClothBody::initPositions() { for (int i = 0; i < m_nParticleCount; i++) { m_pPositions[i] = m_pClothMesh->getVBO()->getPosition(i); m_pPredictedPositions[i] = m_pPositions[i]; } } void BBClothBody::initConstraints() { unsigned short *pVertexIndexes = m_pClothMesh->getVertexIndexes(); int nIndexCount = m_pClothMesh->getIndexCount(); for (int i = 0; i < nIndexCount; i += 3) { int nIndex0 = pVertexIndexes[i]; int nIndex1 = pVertexIndexes[i + 1]; int nIndex2 = pVertexIndexes[i + 2]; // form three pairs initDistanceConstraint(nIndex0, nIndex1); initDistanceConstraint(nIndex1, nIndex2); initDistanceConstraint(nIndex0, nIndex2); } } void BBClothBody::initDistanceConstraint(int nTriangleIndex1, int nTriangleIndex2) { int nParticleIndex1; int nParticleIndex2; if (nTriangleIndex1 < nTriangleIndex2) { nParticleIndex1 = nTriangleIndex1; nParticleIndex2 = nTriangleIndex2; } else { nParticleIndex1 = nTriangleIndex2; nParticleIndex2 = nTriangleIndex1; } BBDistanceConstraint *pConstraint = new BBDistanceConstraint(this, nParticleIndex1, nParticleIndex2, m_fElasticModulus); m_Constraints.push_back(pConstraint); } <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBLightManager.cpp<|end_filename|> #include "BBLightManager.h" #include "Lighting/GameObject/BBPointLight.h" #include "../BBPropertyFactory.h" #include "Lighting/GameObject/BBSpotLight.h" /** * @brief BBPointLightManager::BBPointLightManager * @param pLight * @param pParent */ BBPointLightManager::BBPointLightManager(BBPointLight *pLight, QWidget *pParent) : BBGroupManager("Render", BB_PATH_RESOURCE_ICON(render.png), pParent) { m_pLight = pLight; BBLightColorFactory *pColorFactory = new BBLightColorFactory(pLight); addFactory("Color", pColorFactory, 1); BBLineEditFactory *pRadiusFactory = addFactory("Radius", pLight->getRadius()); pRadiusFactory->setSlideStep(0.005f); pRadiusFactory->setRange(0, 1000); QObject::connect(pRadiusFactory, SIGNAL(valueChanged(float)), this, SLOT(setRadius(float))); BBLineEditFactory *pConstantFactory = addFactory("Constant Factor", pLight->getConstantFactor()); pConstantFactory->setSlideStep(0.005f); pConstantFactory->setRange(0, 10); QObject::connect(pConstantFactory, SIGNAL(valueChanged(float)), this, SLOT(setConstantFactor(float))); BBLineEditFactory *pLinearFactory = addFactory("Linear Factor", pLight->getLinearFactor()); pLinearFactory->setSlideStep(0.005f); pLinearFactory->setRange(0, 10); QObject::connect(pLinearFactory, SIGNAL(valueChanged(float)), this, SLOT(setLinearFactor(float))); BBLineEditFactory *pQuadricFactory = addFactory("Quadric Factor", pLight->getQuadricFactor()); pQuadricFactory->setSlideStep(0.005f); pQuadricFactory->setRange(0, 10); QObject::connect(pQuadricFactory, SIGNAL(valueChanged(float)), this, SLOT(setQuadricFactor(float))); } BBPointLightManager::~BBPointLightManager() { } void BBPointLightManager::setRadius(float fRadius) { m_pLight->setRadius(fRadius); } void BBPointLightManager::setConstantFactor(float fValue) { m_pLight->setConstantFactor(fValue); } void BBPointLightManager::setLinearFactor(float fValue) { m_pLight->setLinearFactor(fValue); } void BBPointLightManager::setQuadricFactor(float fValue) { m_pLight->setQuadricFactor(fValue); } /** * @brief BBSpotLightManager::BBSpotLightManager * @param pLight * @param pParent */ BBSpotLightManager::BBSpotLightManager(BBSpotLight *pLight, QWidget *pParent) : BBPointLightManager(pLight, pParent) { } BBSpotLightManager::~BBSpotLightManager() { } <|start_filename|>Code/BBearEditor/Engine/Scene/BBSceneManager.h<|end_filename|> #ifndef BBSCENEMANAGER_H #define BBSCENEMANAGER_H #include <QMap> #include <QVector3D> #include "Serializer/BBVector.pb.h" class BBRenderQueue; class QTreeWidgetItem; class BBGameObject; class BBEditViewOpenGLWidget; class BBScene; class BBCamera; class BBHierarchyTreeWidget; class BBCanvas; class BBSpriteObject2D; class BBSceneManager { public: static QString getCurrentSceneFilePath() { return m_CurrentSceneFilePath; } static BBScene* getScene() { return m_pScene; } static BBRenderQueue* getRenderQueue(); static BBCamera* getCamera(); static void bindEditViewOpenGLWidget(BBEditViewOpenGLWidget *pWidget); static BBEditViewOpenGLWidget* getEditViewOpenGLWidget() { return m_pEditViewOpenGLWidget; } static void bindHierarchyTreeWidget(BBHierarchyTreeWidget *pWidget) { m_pHierarchyTreeWidget = pWidget; } static BBHierarchyTreeWidget* getHierarchyTreeWidget() { return m_pHierarchyTreeWidget; } static void insertObjectMap(QTreeWidgetItem *pItem, BBGameObject *pGameObject); static void removeObjectMap(QTreeWidgetItem *pItem); static QTreeWidgetItem* getSceneTreeItem(BBGameObject *pGameObject); static QList<QTreeWidgetItem*> getSceneTreeItems(const QList<BBGameObject*> &gameObjects); static BBGameObject* getGameObject(QTreeWidgetItem *pItem); static bool isSceneSwitched(const QString &filePath); static void changeScene(BBGameObject *pGameObject = NULL); static bool isSceneChanged() { return m_bSceneChanged; } static void openScene(const QString &filePath); static void saveScene(const QString &filePath = m_CurrentSceneFilePath); static void removeScene(); static void enableDeferredRendering(int nAlgorithmIndex, int nSubAlgorithmIndex, bool bEnable); static void addSpriteObject2DForCanvas(BBCanvas *pCanvas, BBSpriteObject2D *pSpriteObject2D); private: static void setVector3f(const QVector3D &value, BBSerializer::BBVector3f *&pOutVector3f); // Save the mapping between each scene tree item and its corresponding GameObject static QMap<QTreeWidgetItem*, BBGameObject*> m_ObjectMap; static QString m_CurrentSceneFilePath; static BBEditViewOpenGLWidget *m_pEditViewOpenGLWidget; static BBScene *m_pScene; static BBHierarchyTreeWidget *m_pHierarchyTreeWidget; static bool m_bSceneChanged; }; #endif // BBSCENEMANAGER_H <|start_filename|>Code/BBearEditor/Engine/Render/Lighting/GameObject/BBPointLight.h<|end_filename|> #ifndef BBPOINTLIGHT_H #define BBPOINTLIGHT_H #include "BBLight.h" class BBAABBBoundingBox3D; class BBPointLight : public BBLight { public: BBPointLight(BBScene *pScene); BBPointLight(BBScene *pScene, const QVector3D &position); BBPointLight(BBScene *pScene, const QVector3D &position, const QVector3D &rotation); ~BBPointLight(); void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; void setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform = true) override; void setRotation(const QVector3D &rotation, bool bUpdateLocalTransform = true) override; void setRadius(float fRadius); void setConstantFactor(float fValue) { m_Setting1[1] = fValue; } void setLinearFactor(float fValue) { m_Setting1[2] = fValue; } void setQuadricFactor(float fValue) { m_Setting1[3] = fValue; } inline float getRadius() { return m_Setting1[0]; } inline float getConstantFactor() { return m_Setting1[1]; } inline float getLinearFactor() { return m_Setting1[2]; } inline float getQuadricFactor() { return m_Setting1[3]; } bool cull(BBCamera *pCamera, const QRectF &displayBox) override; bool cull(BBCamera *pCamera, int nFrustumIndexX, int nFrustumIndexY) override; private: BBAABBBoundingBox3D *m_pAABBBoundingBox3D; }; #endif // BBPOINTLIGHT_H <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBGeometricProcessingManager.h<|end_filename|> #ifndef BBGEOMETRICPROCESSINGMANAGER_H #define BBGEOMETRICPROCESSINGMANAGER_H #include "BBGroupManager.h" class BBProcedureMesh; class BBGeometricProcessingManager : public BBGroupManager { Q_OBJECT public: BBGeometricProcessingManager(BBProcedureMesh *pMesh, QWidget *pParent = 0); ~BBGeometricProcessingManager(); private slots: void triggerCatmullClarkAlgorithm(bool bEnable); private: BBProcedureMesh *m_pMesh; }; #endif // BBGEOMETRICPROCESSINGMANAGER_H <|start_filename|>Code/BBearEditor/Engine/Serializer/BBHierarchyTreeWidgetItem.pb.cc<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBHierarchyTreeWidgetItem.proto #include "BBHierarchyTreeWidgetItem.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace BBSerializer { constexpr BBHierarchyTreeWidgetItem::BBHierarchyTreeWidgetItem( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : parentindex_(0){} struct BBHierarchyTreeWidgetItemDefaultTypeInternal { constexpr BBHierarchyTreeWidgetItemDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBHierarchyTreeWidgetItemDefaultTypeInternal() {} union { BBHierarchyTreeWidgetItem _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBHierarchyTreeWidgetItemDefaultTypeInternal _BBHierarchyTreeWidgetItem_default_instance_; } // namespace BBSerializer static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_BBHierarchyTreeWidgetItem_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_BBHierarchyTreeWidgetItem_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_BBHierarchyTreeWidgetItem_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_BBHierarchyTreeWidgetItem_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::BBSerializer::BBHierarchyTreeWidgetItem, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBHierarchyTreeWidgetItem, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBHierarchyTreeWidgetItem, parentindex_), 0, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 6, sizeof(::BBSerializer::BBHierarchyTreeWidgetItem)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBHierarchyTreeWidgetItem_default_instance_), }; const char descriptor_table_protodef_BBHierarchyTreeWidgetItem_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\037BBHierarchyTreeWidgetItem.proto\022\014BBSer" "ializer\"E\n\031BBHierarchyTreeWidgetItem\022\030\n\013" "parentIndex\030\001 \001(\005H\000\210\001\001B\016\n\014_parentIndexb\006" "proto3" ; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_BBHierarchyTreeWidgetItem_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBHierarchyTreeWidgetItem_2eproto = { false, false, 126, descriptor_table_protodef_BBHierarchyTreeWidgetItem_2eproto, "BBHierarchyTreeWidgetItem.proto", &descriptor_table_BBHierarchyTreeWidgetItem_2eproto_once, nullptr, 0, 1, schemas, file_default_instances, TableStruct_BBHierarchyTreeWidgetItem_2eproto::offsets, file_level_metadata_BBHierarchyTreeWidgetItem_2eproto, file_level_enum_descriptors_BBHierarchyTreeWidgetItem_2eproto, file_level_service_descriptors_BBHierarchyTreeWidgetItem_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_BBHierarchyTreeWidgetItem_2eproto_getter() { return &descriptor_table_BBHierarchyTreeWidgetItem_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_BBHierarchyTreeWidgetItem_2eproto(&descriptor_table_BBHierarchyTreeWidgetItem_2eproto); namespace BBSerializer { // =================================================================== class BBHierarchyTreeWidgetItem::_Internal { public: using HasBits = decltype(std::declval<BBHierarchyTreeWidgetItem>()._has_bits_); static void set_has_parentindex(HasBits* has_bits) { (*has_bits)[0] |= 1u; } }; BBHierarchyTreeWidgetItem::BBHierarchyTreeWidgetItem(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBHierarchyTreeWidgetItem) } BBHierarchyTreeWidgetItem::BBHierarchyTreeWidgetItem(const BBHierarchyTreeWidgetItem& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); parentindex_ = from.parentindex_; // @@protoc_insertion_point(copy_constructor:BBSerializer.BBHierarchyTreeWidgetItem) } void BBHierarchyTreeWidgetItem::SharedCtor() { parentindex_ = 0; } BBHierarchyTreeWidgetItem::~BBHierarchyTreeWidgetItem() { // @@protoc_insertion_point(destructor:BBSerializer.BBHierarchyTreeWidgetItem) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBHierarchyTreeWidgetItem::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void BBHierarchyTreeWidgetItem::ArenaDtor(void* object) { BBHierarchyTreeWidgetItem* _this = reinterpret_cast< BBHierarchyTreeWidgetItem* >(object); (void)_this; } void BBHierarchyTreeWidgetItem::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBHierarchyTreeWidgetItem::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBHierarchyTreeWidgetItem::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBHierarchyTreeWidgetItem) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; parentindex_ = 0; _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBHierarchyTreeWidgetItem::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // int32 parentIndex = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_parentindex(&has_bits); parentindex_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBHierarchyTreeWidgetItem::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBHierarchyTreeWidgetItem) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 parentIndex = 1; if (_internal_has_parentindex()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->_internal_parentindex(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBHierarchyTreeWidgetItem) return target; } size_t BBHierarchyTreeWidgetItem::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBHierarchyTreeWidgetItem) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // int32 parentIndex = 1; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_parentindex()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBHierarchyTreeWidgetItem::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBHierarchyTreeWidgetItem) GOOGLE_DCHECK_NE(&from, this); const BBHierarchyTreeWidgetItem* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBHierarchyTreeWidgetItem>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBHierarchyTreeWidgetItem) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBHierarchyTreeWidgetItem) MergeFrom(*source); } } void BBHierarchyTreeWidgetItem::MergeFrom(const BBHierarchyTreeWidgetItem& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBHierarchyTreeWidgetItem) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from._internal_has_parentindex()) { _internal_set_parentindex(from._internal_parentindex()); } } void BBHierarchyTreeWidgetItem::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBHierarchyTreeWidgetItem) if (&from == this) return; Clear(); MergeFrom(from); } void BBHierarchyTreeWidgetItem::CopyFrom(const BBHierarchyTreeWidgetItem& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBHierarchyTreeWidgetItem) if (&from == this) return; Clear(); MergeFrom(from); } bool BBHierarchyTreeWidgetItem::IsInitialized() const { return true; } void BBHierarchyTreeWidgetItem::InternalSwap(BBHierarchyTreeWidgetItem* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); swap(parentindex_, other->parentindex_); } ::PROTOBUF_NAMESPACE_ID::Metadata BBHierarchyTreeWidgetItem::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBHierarchyTreeWidgetItem_2eproto_getter, &descriptor_table_BBHierarchyTreeWidgetItem_2eproto_once, file_level_metadata_BBHierarchyTreeWidgetItem_2eproto[0]); } // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::BBSerializer::BBHierarchyTreeWidgetItem* Arena::CreateMaybeMessage< ::BBSerializer::BBHierarchyTreeWidgetItem >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBHierarchyTreeWidgetItem >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> <|start_filename|>Code/BBearEditor/Engine/Geometry/BBMarchingCubeMesh.h<|end_filename|> #ifndef BBMARCHINGCUBEMESH_H #define BBMARCHINGCUBEMESH_H #include "Base/BBRenderableObject.h" struct BBMCScalarField { // size of x y z unsigned int m_nNum[3]; // width of each grid QVector3D m_UnitWidth; // min pos QVector3D m_Min; }; struct BBMCVertex { unsigned int m_nID; QVector3D m_Position; }; struct BBMCTriangle { unsigned int m_VertexID[3]; }; // A list of isosurface vertices (with edge index as key and isosurface points as value) typedef std::map<unsigned int, BBMCVertex> BBMCEVMap; typedef std::vector<BBMCTriangle> BBMCTriangleVector; class BBMarchingCubeMesh : public BBRenderableObject { public: BBMarchingCubeMesh(); ~BBMarchingCubeMesh(); void init(unsigned int *pNum, const QVector3D &unitWidth, const QVector3D &min, float fThreshold); bool createMCMesh(float *pField); private: void generateIsoSurface(); void generateEdgeVertexMap(unsigned int x, unsigned int y, unsigned int z, unsigned int nEdge); BBMCVertex computeIntersection(unsigned int x, unsigned int y, unsigned int z, unsigned int nEdge); unsigned int getEdgeID(unsigned int x, unsigned int y, unsigned int z, unsigned int nEdge); unsigned int getVertexID(unsigned int x, unsigned int y, unsigned int z); void generateVBOAndEBO(); void deleteSurface(); private: static unsigned int m_EdgeTable[256]; static int m_TriangleTable[256][16]; // Scalar field info BBMCScalarField m_Grid; const float *m_pScalarField; float m_fIsoLevel; BBMCEVMap m_EVMap; BBMCTriangleVector m_TriangleVector; bool m_bValidSurface; }; #endif // BBMARCHINGCUBEMESH_H <|start_filename|>Resources/shaders/GI/SSAO.frag<|end_filename|> #version 430 core in vec2 v2f_texcoord; layout (location = 0) out float FragColor; uniform vec4 BBCameraParameters; uniform mat4 BBProjectionMatrix; uniform sampler2D NormalTex; uniform sampler2D PositionTex; uniform sampler2D NoiseTex; uniform vec4 Samples[64]; const int kernel_size = 64; const float radius = 1.0; float linearizeDepth(float depth) { float z_near = BBCameraParameters.z; float z_far = BBCameraParameters.w; float z = depth * 2.0 - 1.0; return (2.0 * z_near * z_far) / (z_far + z_near - z * (z_far - z_near)); } void main(void) { float width = BBCameraParameters.x; float height = BBCameraParameters.y; vec2 noise_scale = vec2(width, height) / 4.0; vec3 pos = texture(PositionTex, v2f_texcoord).xyz; vec3 N = texture(NormalTex, v2f_texcoord).xyz; vec3 random_vec = texture(NoiseTex, noise_scale * v2f_texcoord).xyz; vec3 T = normalize(random_vec - N * dot(random_vec, N)); vec3 B = cross(N, T); mat3 TBN = mat3(T, B, N); float occlusion = 0.0; for (int i = 0; i < kernel_size; i++) { vec3 sample_point = TBN * Samples[i].xyz; sample_point = pos + sample_point * radius; vec4 offset = vec4(sample_point, 1.0); offset = BBProjectionMatrix * offset; offset.xyz /= offset.w; offset.xyz = offset.xyz * 0.5 + 0.5; float sample_depth = -texture(PositionTex, offset.xy).w; float weight = smoothstep(0.0, 1.0, radius / abs(pos.z - sample_depth)); occlusion += (sample_depth >= sample_point.z ? 1.0 : 0.0) * weight; } occlusion = 1.0 - (occlusion / kernel_size); FragColor = occlusion; } <|start_filename|>Code/BBearEditor/Engine/Math/BBMath.h<|end_filename|> #pragma once #ifndef BBMATH_H #define BBMATH_H #include <QVector2D> #include <QVector3D> #define PI 3.14159265359 float lerp(float a, float b, float f); QVector2D lerp(const QVector2D &a, const QVector2D &b, float f); QVector2D lerp(const QVector2D &a, const QVector2D &b, const QVector2D &c, float u, float v); float trilinearInterpolate(QVector3D c[2][2][2], float u, float v, float w); QVector3D reflect(const QVector3D &L, const QVector3D &N); bool refract(const QVector3D &L, const QVector3D &N, float fRefractivity, QVector3D &refracted); template<class T> T clamp(T x, T min, T max) { if (x > max) return max; if (x < min) return min; return x; } float frandom(); float sfrandom(); QVector3D hemisphericalRandom(const QVector3D &normal); QVector3D sphericalRandom(); // KD Tree int getMedian(int start, int end); float schlick(float cos, float fRefractivity); template<class T> static inline T max(const T &a, const T &b) { return ((a > b) ? a : b); } float radians(float angle); #endif // BBMATH_H <|start_filename|>Resources/shaders/test_VS.vert<|end_filename|> #version 430 core struct Vertex { vec4 BBPosition; vec4 BBColor; vec4 BBTexcoord; vec4 BBNormal; vec4 BBTangent; vec4 BBBiTangent; }; layout (std140, binding = 0) buffer Bundle { Vertex vertexes[]; } bundle; out V2G { vec3 world_pos; vec4 color; vec3 normal; } v2g; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { v2g.color = bundle.vertexes[gl_VertexID].BBColor; v2g.normal = mat3(transpose(inverse(BBModelMatrix))) * bundle.vertexes[gl_VertexID].BBNormal.xyz; vec4 world_pos = BBModelMatrix * bundle.vertexes[gl_VertexID].BBPosition; v2g.world_pos = world_pos.xyz; gl_Position = BBProjectionMatrix * BBViewMatrix * world_pos; } <|start_filename|>Resources/shaders/DeferredColor.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBColor; attribute vec4 BBTexcoord; varying vec4 V_Color; varying vec4 V_Texcoord; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { V_Color = BBColor; V_Texcoord = BBModelMatrix * BBTexcoord; gl_Position = BBProjectionMatrix * BBViewMatrix * BBModelMatrix * BBPosition; } <|start_filename|>Resources/shaders/stencilUI.frag<|end_filename|> varying vec4 V_Color; varying vec4 V_Texcoord; varying vec4 V_Light; varying vec4 V_Dark; uniform vec4 BBTextureSettings; uniform sampler2D BBTexture0; void main(void) { gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); } <|start_filename|>Resources/shaders/Physics/FluidSystem/SSF_VS_GBuffer.vert<|end_filename|> #version 430 core in vec4 BBPosition; out float v2g_view_space_particle_radius; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; uniform float ParticleRadius; void main() { mat4 VM = BBViewMatrix * BBModelMatrix; v2g_view_space_particle_radius = length(VM * vec4(ParticleRadius, 0.0, 0.0, 0.0)); gl_Position = VM * BBPosition; } <|start_filename|>Code/BBearEditor/Editor/Dialog/BBProjectDialog.cpp<|end_filename|> #include "BBProjectDialog.h" #include "ui_BBProjectDialog.h" #include "Utils/BBUtils.h" #include <QSettings> #include <QDir> #include <QFileDialog> QString BBProjectDialog::m_ProjectDirArrayKey = "ProjectDirArrayKey"; QString BBProjectDialog::m_ProjectDirKey = "ProjectDirKey"; QString BBProjectDialog::m_WorkSpaceDirKey = "WorkSpaceDirKey"; BBProjectDialog::BBProjectDialog(QWidget *pParent) : QDialog(pParent), m_pUi(new Ui::BBProjectDialog) { m_pUi->setupUi(this); QObject::connect(m_pUi->buttonClose, SIGNAL(clicked()), this, SLOT(closeDialog())); QObject::connect(m_pUi->buttonOpenLocation, SIGNAL(clicked()), this, SLOT(selectFolder())); QObject::connect(m_pUi->buttonCreate, SIGNAL(clicked()), this, SLOT(createNewProject())); setButtonTabBar(); loadExistingProject(); setListWidget(); setLineEdit(); m_pUi->stackedFolderAndNew->setCurrentIndex(0); } BBProjectDialog::~BBProjectDialog() { BB_SAFE_DELETE(m_pUi); } void BBProjectDialog::switchDiskAndCloud(QAbstractButton *pButton) { if (pButton->objectName() == "buttonDisk") { m_pUi->stackedDiskAndCloud->setCurrentIndex(0); } else if (pButton->objectName() == "buttonCloud") { m_pUi->stackedDiskAndCloud->setCurrentIndex(1); } } void BBProjectDialog::switchFolderAndNew(QAbstractButton *pButton) { if (pButton->objectName() == "buttonFolder") { m_pUi->stackedFolderAndNew->setCurrentIndex(0); } else if (pButton->objectName() == "buttonNew") { m_pUi->stackedFolderAndNew->setCurrentIndex(1); } } void BBProjectDialog::selectFolder() { QSettings settings(BB_USER_NAME, BB_USER_PROJECT_NAME); QString directory = settings.value(m_WorkSpaceDirKey).value<QString>(); QString filePath = QFileDialog::getExistingDirectory(this, "Select Folder", directory); if (!filePath.isNull()) { // The line edit shows the address of the workspace m_pUi->lineEditLocation->setText(filePath); // Save the default workspace address and show it next time settings.setValue(m_WorkSpaceDirKey, filePath); } } void BBProjectDialog::createNewProject() { // create project folder QDir dir; QString fileName = m_pUi->lineEditProjectName->text(); QString filePath = m_pUi->lineEditLocation->text() + "/" + fileName; BB_PROCESS_ERROR_RETURN(!dir.exists(filePath)); m_pUi->lineEditProjectName->setFocus(); m_pUi->lineEditProjectName->selectAll(); BB_PROCESS_ERROR_RETURN(dir.mkdir(filePath)); // Successfully created the project // Create subfolders required for the project // Used to save user's files BB_PROCESS_ERROR_RETURN(dir.mkdir(filePath + "/" + BBConstant::BB_NAME_FILE_SYSTEM_USER)); // Used to save engine-related files BB_PROCESS_ERROR_RETURN(dir.mkdir(filePath + "/" + BBConstant::BB_NAME_FILE_SYSTEM_ENGINE)); // save constant BBConstant::BB_NAME_PROJECT = fileName; BBConstant::BB_PATH_PROJECT = filePath + "/"; BBConstant::BB_PATH_PROJECT_USER = BBConstant::BB_PATH_PROJECT + BBConstant::BB_NAME_FILE_SYSTEM_USER; BBConstant::BB_PATH_PROJECT_ENGINE = BBConstant::BB_PATH_PROJECT + BBConstant::BB_NAME_FILE_SYSTEM_ENGINE; // Place a project overview map in the engine folder BB_PROCESS_ERROR_RETURN(QFile::copy(BB_PATH_RESOURCE_PICTURE(BBConstant::BB_NAME_OVERVIEW_MAP), BBConstant::BB_PATH_PROJECT_ENGINE + "/" + BBConstant::BB_NAME_OVERVIEW_MAP)); // save the project into QSettings QSettings settings(BB_USER_NAME, BB_USER_PROJECT_NAME); settings.beginWriteArray(m_ProjectDirArrayKey); // Add to the end of the project catalog settings.setArrayIndex(m_nProjectCount); settings.setValue(m_ProjectDirKey, filePath); settings.endArray(); // Close the dialog accept(); createProject(); } void BBProjectDialog::closeDialog() { reject(); } void BBProjectDialog::openSelectedProject(QListWidgetItem *pItem) { QString filePath = m_ProjectDirs.at(m_pUi->listDiskProject->row(pItem)); // save constant BBConstant::BB_NAME_PROJECT = pItem->text(); BBConstant::BB_PATH_PROJECT = filePath + "/"; BBConstant::BB_PATH_PROJECT_USER = BBConstant::BB_PATH_PROJECT + BBConstant::BB_NAME_FILE_SYSTEM_USER; BBConstant::BB_PATH_PROJECT_ENGINE = BBConstant::BB_PATH_PROJECT + BBConstant::BB_NAME_FILE_SYSTEM_ENGINE; // Close the dialog accept(); openProject(); } void BBProjectDialog::setButtonTabBar() { QButtonGroup *pGroup = new QButtonGroup; pGroup->addButton(m_pUi->buttonDisk); pGroup->addButton(m_pUi->buttonCloud); QObject::connect(pGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(switchDiskAndCloud(QAbstractButton*))); pGroup = new QButtonGroup; pGroup->addButton(m_pUi->buttonFolder); pGroup->addButton(m_pUi->buttonNew); QObject::connect(pGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(switchFolderAndNew(QAbstractButton*))); } void BBProjectDialog::loadExistingProject() { // Read the existing project on this computer QSettings settings(BB_USER_NAME, BB_USER_PROJECT_NAME); int nCount = settings.beginReadArray(m_ProjectDirArrayKey); m_nProjectCount = nCount; // clear the project list that is saved the last time m_ProjectDirs.clear(); for (int i = 0; i < nCount; i++) { settings.setArrayIndex(i); QString projectDir = settings.value(m_ProjectDirKey).toString(); QDir dir; if (dir.exists(projectDir)) { // if the project exists, record it m_ProjectDirs.append(projectDir); } else { // user has deleted the project m_nProjectCount--; } } settings.endArray(); // update project list settings.beginWriteArray(m_ProjectDirArrayKey, m_nProjectCount); for (int i = 0; i < m_nProjectCount; i++) { settings.setArrayIndex(i); settings.setValue(m_ProjectDirKey, m_ProjectDirs.at(i)); } settings.endArray(); } void BBProjectDialog::setListWidget() { QObject::connect(m_pUi->listDiskProject, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(openSelectedProject(QListWidgetItem*))); // icon is at the top, and text is at the bottom m_pUi->listDiskProject->setViewMode(QListView::IconMode); m_pUi->listDiskProject->setIconSize(QSize(135, 135)); m_pUi->listDiskProject->setSpacing(0); // show existing projects in the list widget for (int i = 0; i < m_ProjectDirs.count(); i++) { QString projectDir = m_ProjectDirs.at(i); QFileInfo info(projectDir); QString projectName = info.fileName(); QString iconPath = projectDir + "/" + BBConstant::BB_NAME_FILE_SYSTEM_ENGINE + "/" + BBConstant::BB_NAME_OVERVIEW_MAP; // Cut the overview image into a square QPixmap pix(iconPath); int h = pix.height(); int w = pix.width(); int size = h < w ? h : w; pix = pix.copy((w - size) / 2, (h - size) / 2, size, size); QListWidgetItem *pItem = new QListWidgetItem(m_pUi->listDiskProject); pItem->setIcon(QIcon(pix)); pItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); pItem->setText(projectName); pItem->setSizeHint(QSize(141, 160)); } } void BBProjectDialog::setLineEdit() { // The dir default is the last used dir QSettings settings(BB_USER_NAME, BB_USER_PROJECT_NAME); m_pUi->lineEditLocation->setText(settings.value(m_WorkSpaceDirKey).value<QString>()); // Give an initial project name, if it exists, increase the number QDir dir; int i = 1; while (dir.exists(m_pUi->lineEditLocation->text() + "/New Project " + QString::number(i))) { i++; } m_pUi->lineEditProjectName->setText("New Project " + QString::number(i)); } <|start_filename|>Code/BBearEditor/main.cpp<|end_filename|> #include <QApplication> #include "NcFramelessHelper.h" #include <QVBoxLayout> #include "MainInterface/BBTitleBar.h" #include "MainInterface/BBMainWindow.h" #include "Dialog/BBProjectDialog.h" #include "Profiler/BBProfiler.h" #include <QDesktopWidget> #include <QStyleFactory> int main(int argc, char *argv[]) { // otherwise, there is context conflict when there are several opengl // QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); QApplication a(argc, argv); // main interface QWidget mainWidget; // mainWidget.setWindowState(Qt::WindowMaximized); mainWidget.resize(1920, 1200); mainWidget.setWindowFlags(Qt::FramelessWindowHint | mainWidget.windowFlags()); NcFramelessHelper mainWidgetHelper; mainWidgetHelper.activateOn(&mainWidget); QVBoxLayout mainVlayout(&mainWidget); mainVlayout.setMargin(0); mainVlayout.setSpacing(0); // parent object must be passed in // and invoke the close function of the parent object to close the window // to prevent errors BBTitleBar titleBar(&mainWidget); mainVlayout.addWidget(&titleBar); BBMainWindow mainWindow; mainVlayout.addWidget(&mainWindow); // mainWidget.hide(); mainWidget.show(); // BBProjectDialog, select project to open BBProjectDialog dialog; dialog.resize(QSize(800, 480)); dialog.setWindowFlags(Qt::FramelessWindowHint | dialog.windowFlags()); NcFramelessHelper dialogHelper; dialogHelper.activateOn(&dialog); dialog.move((QApplication::desktop()->width() - dialog.sizeHint().width()) / 2, (QApplication::desktop()->height() - dialog.sizeHint().height()) / 2); dialog.show(); // Retina screen a.setAttribute(Qt::AA_UseHighDpiPixmaps); // do not use the style of mac a.setStyle(QStyleFactory::create("Fusion")); QObject::connect(&dialog, SIGNAL(createProject()), &mainWindow, SLOT(createProject())); QObject::connect(&dialog, SIGNAL(openProject()), &mainWindow, SLOT(openProject())); //QObject::connect(&a, SIGNAL(pressTransformSignal(char)), &mainWindow, SLOT(globalPressTransformKey(char))); //QObject::connect(&a, SIGNAL(multipleSelectKey(bool)), &mainWindow, SLOT(multipleSelectKey(bool))); //QObject::connect(&titleBar, SIGNAL(run(bool)), &mainWindow, SLOT(run(bool))); return a.exec(); } <|start_filename|>Code/BBearEditor/Engine/Render/BBAttribute.cpp<|end_filename|> #include "BBAttribute.h" BBAttribute::BBAttribute(GLint location, int nComponentCount, unsigned int nBasicDataType, bool bNormalized, int nDataStride, int nDataOffset) : BBBaseRenderComponent() { m_Location = location; m_nComponentCount = nComponentCount; m_nBasicDataType = nBasicDataType; m_bNormalized = bNormalized; m_nDataStride = nDataStride; m_nDataOffset = nDataOffset; } void BBAttribute::active() { glEnableVertexAttribArray(m_Location); glVertexAttribPointer(m_Location, m_nComponentCount, m_nBasicDataType, m_bNormalized, m_nDataStride, (void*)m_nDataOffset); // activate the entire attribute chain if (m_pNext != nullptr) { next<BBAttribute>()->active(); } } <|start_filename|>Code/BBearEditor/Engine/Allocator/BBAllocator.cpp<|end_filename|> #include "BBAllocator.h" #include "tlsf/tlsf.h" #include "stdlib.h" #include "Profiler/BBProfiler.h" // 1024 1KB // 1024x1024 1MB 1048576 // 1024x1024x1024 1GB 1073741824 static tlsf_t g_TLSF = NULL; static unsigned int g_ReservedSize = 209715200; // 200MB static void initMemory() { if (g_TLSF == NULL) { void *pBuffer = malloc(g_ReservedSize); g_TLSF = tlsf_create_with_pool(pBuffer, g_ReservedSize); } } static void* getMemory(std::size_t size) { if (g_TLSF == NULL) { initMemory(); } void *pMemory = tlsf_malloc(g_TLSF, size); while (pMemory == NULL) { void *pAddPool = malloc(104857600); // 100MB tlsf_add_pool(g_TLSF, pAddPool, 104857600); pMemory = tlsf_malloc(g_TLSF, size); } return pMemory; } static void recycle(void *ptr) { #if BB_USE_POOL if (BBProfiler::deleteMemoryObject(ptr)) { tlsf_free(g_TLSF, ptr); } else { free(ptr); } #else free(ptr); #endif } void *operator new(std::size_t size) { #if BB_USE_POOL void *ptr = getMemory(size); BBProfiler::addMemoryObject(ptr, BBMemoryLabel::Default, tlsf_block_size(ptr)); return ptr; #else void *ptr = malloc(size); return ptr; #endif } void *operator new[](std::size_t size) { #if BB_USE_POOL void *ptr = getMemory(size); BBProfiler::addMemoryObject(ptr, BBMemoryLabel::Default, tlsf_block_size(ptr)); return ptr; #else void *ptr = malloc(size); return ptr; #endif } void *operator new(std::size_t size, BBMemoryLabel eID) { #if BB_USE_POOL void *ptr = getMemory(size); BBProfiler::addMemoryObject(ptr, eID, tlsf_block_size(ptr)); return ptr; #else void *ptr = malloc(size); return ptr; #endif } void *operator new[](std::size_t size, BBMemoryLabel eID) { #if BB_USE_POOL void *ptr = getMemory(size); BBProfiler::addMemoryObject(ptr, eID, tlsf_block_size(ptr)); return ptr; #else void *ptr = malloc(size); return ptr; #endif } void operator delete(void *ptr) noexcept { recycle(ptr); } void operator delete[](void *ptr) noexcept { recycle(ptr); } void operator delete(void *ptr, BBMemoryLabel eID) noexcept { recycle(ptr); } void operator delete[](void *ptr, BBMemoryLabel eID) noexcept { recycle(ptr); } <|start_filename|>Code/BBearEditor/Engine/Scene/CoordinateSystem/BBCoordinateSystem.h<|end_filename|> #ifndef BBCOORDINATE_H #define BBCOORDINATE_H #include "Scene/CoordinateSystem/BBCoordinateComponent.h" class BBBoundingBox; class BBRectBoundingBox3D; class BBTriangleBoundingBox3D; class BBQuarterCircleBoundingBox3D; class BBBoundingBox3D; // base class of pos rot scale 3 Coordinate System class BBCoordinateSystem : public BBGameObject { protected: BBCoordinateSystem(); virtual ~BBCoordinateSystem(); void render(BBCamera *pCamera) override; bool hit(const BBRay &ray, BBBoundingBox *pBoundingBox1, const BBAxisFlags &axis1, BBBoundingBox *pBoundingBox2, const BBAxisFlags &axis2, BBBoundingBox *pBoundingBox3, const BBAxisFlags &axis3, float &fDistance); virtual void transform(const BBRay &ray) = 0; BBAxisFlags m_SelectedAxis; QVector3D m_LastMousePos; BBGameObject *m_pSelectedObject; bool m_bTransforming; public: void setSelectedObject(BBGameObject *pObject); virtual void setSelectedAxis(const BBAxisFlags &axis) = 0; virtual bool mouseMoveEvent(const BBRay &ray, bool bMousePressed) = 0; void stopTransform(); }; class BBPositionCoordinateSystem : public BBCoordinateSystem { public: BBPositionCoordinateSystem(); virtual ~BBPositionCoordinateSystem(); void init() override; void render(BBCamera *pCamera) override; void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; void setScale(float scale, bool bUpdateLocalTransform = true) override; void setSelectedAxis(const BBAxisFlags &axis) override; bool mouseMoveEvent(const BBRay &ray, bool bMousePressed) override; private: void transform(const BBRay &ray) override; BBCoordinateArrow *m_pCoordinateArrow; BBCoordinateAxis *m_pCoordinateAxis; BBCoordinateRectFace *m_pCoordinateRectFace; BBBoundingBox3D *m_pBoundingBoxX; BBBoundingBox3D *m_pBoundingBoxY; BBBoundingBox3D *m_pBoundingBoxZ; BBRectBoundingBox3D *m_pBoundingBoxYOZ; BBRectBoundingBox3D *m_pBoundingBoxXOZ; BBRectBoundingBox3D *m_pBoundingBoxXOY; }; class BBRotationCoordinateSystem : public BBCoordinateSystem { public: BBRotationCoordinateSystem(); ~BBRotationCoordinateSystem(); void init() override; void render(BBCamera *pCamera) override; void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; void setScale(const QVector3D &scale, bool bUpdateLocalTransform = true) override; void setSelectedAxis(const BBAxisFlags &axis) override; bool mouseMoveEvent(const BBRay &ray, bool bMousePressed) override; private: void transform(const BBRay &ray) override; BBCoordinateQuarterCircle *m_pCoordinateQuarterCircle; BBQuarterCircleBoundingBox3D *m_pBoundingBoxYOZ; BBQuarterCircleBoundingBox3D *m_pBoundingBoxXOZ; BBQuarterCircleBoundingBox3D *m_pBoundingBoxXOY; // when transforming, appear BBCoordinateCircle *m_pCoordinateCircle; BBCoordinateTickMark *m_pCoordinateTickMark; BBCoordinateSector *m_pCoordinateSector; QVector3D m_LastMousePosDir; }; class BBScaleCoordinateSystem : public BBCoordinateSystem { public: BBScaleCoordinateSystem(); ~BBScaleCoordinateSystem(); void init() override; void render(BBCamera *pCamera) override; void setPosition(const QVector3D &position, bool bUpdateLocalTransform = true) override; void setRotation(const QVector3D &rotation, bool bUpdateLocalTransform = true) override; void setScale(const QVector3D &scale, bool bUpdateLocalTransform = true) override; void setSelectedAxis(const BBAxisFlags &axis) override; bool mouseMoveEvent(const BBRay &ray, bool bMousePressed) override; private: void transform(const BBRay &ray) override; BBCoordinateCube *m_pCoordinateCube; BBCoordinateAxis *m_pCoordinateAxis; BBCoordinateTriangleFace *m_pCoordinateTriangleFace; BBBoundingBox3D *m_pBoundingBoxX; BBBoundingBox3D *m_pBoundingBoxY; BBBoundingBox3D *m_pBoundingBoxZ; BBRectBoundingBox3D *m_pBoundingBoxYOZ; BBRectBoundingBox3D *m_pBoundingBoxXOZ; BBRectBoundingBox3D *m_pBoundingBoxXOY; BBTriangleBoundingBox3D *m_pBoundingBoxXYZ; QVector3D m_SelectedObjectOriginalScale; }; #endif // BBCOORDINATE_H <|start_filename|>Code/BBearEditor/Engine/Render/BufferObject/BBShaderStorageBufferObject.h<|end_filename|> #ifndef BBSHADERSTORAGEBUFFEROBJECT_H #define BBSHADERSTORAGEBUFFEROBJECT_H #include "BBVertexBufferObject.h" #include "../BBLinkedList.h" class BBShaderStorageBufferObject : public BBVertexBufferObject, public BBLinkedList { public: BBShaderStorageBufferObject(); BBShaderStorageBufferObject(BBVertexBufferObject *pVBO); BBShaderStorageBufferObject(int nVertexCount); ~BBShaderStorageBufferObject(); void bind() override; void bind(int location); void unbind() override; template<typename T> /** * @brief createBufferObject allocate nCount T * @param location Consistent with layout binding in shader * @param nCount * @param hint * @param pData */ void createBufferObject(GLint location, int nCount, GLenum hint = GL_STATIC_DRAW, void *pData = nullptr) { m_Location = location; BBVertexBufferObject::createBufferObject(m_BufferType, sizeof(T) * nCount, hint, pData); } private: GLint m_Location; }; #endif // BBSHADERSTORAGEBUFFEROBJECT_H <|start_filename|>Resources/shaders/Volumetric/Cloud.vert<|end_filename|> #version 330 core in vec4 BBPosition; in vec4 BBTexcoord; out vec2 v2f_texcoord; out mat4 v2f_inverse_projection_matrix; out mat4 v2f_inverse_view_matrix; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { gl_Position = BBPosition; v2f_texcoord = BBTexcoord.xy; v2f_inverse_projection_matrix = inverse(BBProjectionMatrix); v2f_inverse_view_matrix = inverse(BBViewMatrix); } <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFolderTreeWidget.cpp<|end_filename|> #include "BBFolderTreeWidget.h" #include <QMenu> #include <QWidgetAction> #include <QHBoxLayout> #include <QLabel> #include <QDragMoveEvent> #include <QMimeData> #include "BBFileSystemDataManager.h" BBFolderTreeWidget::BBFolderTreeWidget(QWidget *pParent) : BBTreeWidget(pParent), m_eSenderTag(BBSignalSender::FolderTree) { // //初始时 需要加载材质 // isLoadMaterial = true; setMenu(); QObject::connect(this, SIGNAL(itemClicked(QTreeWidgetItem*, int)), this, SLOT(clickItem(QTreeWidgetItem*, int))); } void BBFolderTreeWidget::removeTopLevelItems() { recordItemExpansionState(); while (topLevelItemCount() > 0) { takeTopLevelItem(0); } } void BBFolderTreeWidget::loadTopLevelItems(const QList<QTreeWidgetItem*> &items) { addTopLevelItems(items); resumeItemExpansionState(); sortItems(0, Qt::AscendingOrder); } void BBFolderTreeWidget::expandCurrentViewedItem(QTreeWidgetItem *pItem) { setCurrentItem(pItem); setItemExpanded(pItem, true); } void BBFolderTreeWidget::setSelectedItems(const QList<QTreeWidgetItem*> &items) { // the items share the same parent // setItemExpanded(items.first()->parent(), true); for (int i = 0; i < items.count(); i++) { setItemSelected(items.at(i), true); } } void BBFolderTreeWidget::pressRootButton() { setCurrentItem(NULL); // show the files in the root dir in the file list on the right // use NULL to indicate root item updateCorrespondingWidget(NULL); } void BBFolderTreeWidget::pressSettingButton() { setCurrentItem(NULL); m_pMenu->exec(cursor().pos()); } void BBFolderTreeWidget::clickItem(QTreeWidgetItem *pItem, int nColumn) { Q_UNUSED(nColumn); updateCorrespondingWidget(pItem); } void BBFolderTreeWidget::newFolder() { QTreeWidgetItem *pParent = currentItem(); QString parentPath = BBFileSystemDataManager::getAbsolutePath(pParent); emit newFolder(parentPath, m_eSenderTag); // Open the edit box to let the user set name openRenameEditor(); } void BBFolderTreeWidget::newSceneAction() { newFile(0); } void BBFolderTreeWidget::newMaterialAction() { newFile(1); } void BBFolderTreeWidget::showInFolder() { QTreeWidgetItem *pItem = currentItem(); QString filePath = BBFileSystemDataManager::getAbsolutePath(pItem); emit showInFolder(filePath); } void BBFolderTreeWidget::copyAction() { } void BBFolderTreeWidget::pasteAction() { } void BBFolderTreeWidget::finishRename() { BB_PROCESS_ERROR_RETURN(m_pEditingItem); // whether name is changed // new name cannot be null QString oldname = m_pEditingItem->text(0); QString newName = m_pRenameEditor->text(); if (oldname != newName && !newName.isEmpty()) { QTreeWidgetItem *pParentFolderItem = m_pEditingItem->parent(); QString parentPath = BBFileSystemDataManager::getAbsolutePath(pParentFolderItem); BBTreeWidget::finishRename(); emit rename(pParentFolderItem, parentPath + "/" + oldname, parentPath + "/" + newName); sortItems(0, Qt::AscendingOrder); } else { BBTreeWidget::finishRename(); } } void BBFolderTreeWidget::deleteAction() { BBTreeWidget::deleteAction(); emit finishDeleteAction(); } void BBFolderTreeWidget::setMenu() { // first level menu m_pMenu = new QMenu(this); QAction *pActionNewFolder = new QAction(tr("New Folder")); // second level menu QMenu *pMenuNewAsset = new QMenu(tr("New Asset"), m_pMenu); QWidgetAction *pActionNewScene = createWidgetAction(pMenuNewAsset, BB_PATH_RESOURCE_ICON(scene.png), tr("Scene")); QWidgetAction *pActionNewMaterial = createWidgetAction(pMenuNewAsset, BB_PATH_RESOURCE_ICON(material.png), tr("Material")); QAction *pActionShowInFolder = new QAction(tr("Show In Folder")); QAction *pActionCopy = new QAction(tr("Copy")); pActionCopy->setShortcut(QKeySequence(tr("Ctrl+C"))); QAction *pActionPaste = new QAction(tr("Paste")); pActionPaste->setShortcut(QKeySequence(tr("Ctrl+V"))); QAction *pActionRename = new QAction(tr("Rename")); #if defined(Q_OS_WIN32) pActionRename->setShortcut(Qt::Key_F2); #elif defined(Q_OS_MAC) pActionRename->setShortcut(Qt::Key_Return); #endif QAction *pActionDelete = new QAction(tr("Delete")); pMenuNewAsset->addAction(pActionNewScene); pMenuNewAsset->addAction(pActionNewMaterial); pMenuNewAsset->addAction(createWidgetAction(pMenuNewAsset, BB_PATH_RESOURCE_ICON(animation.png), tr("Animation"))); pMenuNewAsset->addAction(createWidgetAction(pMenuNewAsset, BB_PATH_RESOURCE_ICON(particle.png), tr("Particle"))); pMenuNewAsset->addAction(createWidgetAction(pMenuNewAsset, BB_PATH_RESOURCE_ICON(script.png), tr("Script"))); // first level menu m_pMenu->addAction(pActionNewFolder); m_pMenu->addMenu(pMenuNewAsset); m_pMenu->addSeparator(); m_pMenu->addAction(pActionShowInFolder); m_pMenu->addSeparator(); m_pMenu->addAction(pActionCopy); m_pMenu->addAction(pActionPaste); m_pMenu->addSeparator(); m_pMenu->addAction(pActionRename); m_pMenu->addAction(pActionDelete); QObject::connect(pActionNewFolder, SIGNAL(triggered()), this, SLOT(newFolder())); QObject::connect(pActionNewScene, SIGNAL(triggered()), this, SLOT(newSceneAction())); QObject::connect(pActionNewMaterial, SIGNAL(triggered()), this, SLOT(newMaterialAction())); QObject::connect(pActionShowInFolder, SIGNAL(triggered()), this, SLOT(showInFolder())); QObject::connect(pActionCopy, SIGNAL(triggered()), this, SLOT(copyAction())); QObject::connect(pActionPaste, SIGNAL(triggered()), this, SLOT(pasteAction())); QObject::connect(pActionRename, SIGNAL(triggered()), this, SLOT(openRenameEditor())); QObject::connect(pActionDelete, SIGNAL(triggered()), this, SLOT(deleteAction())); } QWidgetAction* BBFolderTreeWidget::createWidgetAction(QMenu *pParent, const QString &iconPath, const QString &name) { QWidgetAction *pAction = new QWidgetAction(pParent); QWidget *pWidget = new QWidget(this); pWidget->setObjectName("widgetAction"); pWidget->setStyleSheet("#widgetAction:hover {background: #0ebf9c;}"); QHBoxLayout *pLayout = new QHBoxLayout(pWidget); pLayout->setContentsMargins(6, 2, 6, 2); QLabel *pIcon = new QLabel(pWidget); QPixmap pix(iconPath); pix.setDevicePixelRatio(devicePixelRatio()); pix = pix.scaled(13 * devicePixelRatio(), 13 * devicePixelRatio(), Qt::KeepAspectRatio, Qt::SmoothTransformation); pIcon->setPixmap(pix); pLayout->addWidget(pIcon); QLabel *pText = new QLabel(pWidget); pText->setText(name); pText->setStyleSheet("color: #d6dfeb; font: 9pt \"Arial\";"); pLayout->addWidget(pText, Qt::AlignLeft); pAction->setDefaultWidget(pWidget); return pAction; } void BBFolderTreeWidget::newFile(int nType) { // 0 scene QTreeWidgetItem *pItem = currentItem(); QString parentPath = BBFileSystemDataManager::getAbsolutePath(pItem); emit newFile(parentPath, nType); } void BBFolderTreeWidget::deleteOne(QTreeWidgetItem *pItem) { emit deleteFolder(pItem); } void BBFolderTreeWidget::dragMoveEvent(QDragMoveEvent *event) { if (!event->mimeData()->hasFormat(getMimeType()) && !event->mimeData()->hasFormat(BB_MIMETYPE_FILELISTWIDGET)) { event->ignore(); return; } BBTreeWidget::dragMoveEvent(event); } bool BBFolderTreeWidget::moveItem() { BB_PROCESS_ERROR_RETURN_FALSE(m_pIndicatorItem); // drop position of moving item int index = -1; QTreeWidgetItem *pParent = getParentOfMovingItem(index); // The movable item has been filtered in startDrag QList<QTreeWidgetItem*> items = selectedItems(); // Cannot move to an item that are moving and its descendants // parent and its ancestors cannot be included in items for (QTreeWidgetItem *pForeParent = pParent; pForeParent; pForeParent = pForeParent->parent()) { BB_PROCESS_ERROR_RETURN_FALSE(!items.contains(pForeParent)); } emit moveFolders(items, pParent, false); sortItems(0, Qt::AscendingOrder); return true; } bool BBFolderTreeWidget::moveItemFromFileList(const QMimeData *pMimeData) { BB_PROCESS_ERROR_RETURN_FALSE(m_pIndicatorItem); // drop position of moving item int index = -1; QTreeWidgetItem *pParent = getParentOfMovingItem(index); // get all file paths from drag QList<QString> oldFilePaths; QByteArray data = pMimeData->data(BB_MIMETYPE_FILELISTWIDGET); QDataStream dataStream(&data, QIODevice::ReadOnly); QString oldFilePath; // the first is the path of current item, which we do not need // we need the paths of selected items which are saved behind dataStream >> oldFilePath; dataStream >> oldFilePath; while (!oldFilePath.isEmpty()) { oldFilePaths.append(oldFilePath); dataStream >> oldFilePath; } emit moveFiles(oldFilePaths, pParent, false); sortItems(0, Qt::AscendingOrder); return true; } void BBFolderTreeWidget::updateCorrespondingWidget(QTreeWidgetItem *pItem) { QString folderPath = BBFileSystemDataManager::getAbsolutePath(pItem); emit accessFolder(folderPath, pItem); } /** * @brief BBFolderTreeWidget::recordItemExpansionState record expansion state of items before reconstructing the tree */ void BBFolderTreeWidget::recordItemExpansionState() { // clear the last while (m_ExpandedItems.count() > 0) { m_ExpandedItems.takeFirst(); } QTreeWidgetItemIterator it(this); for (; *it; it++) { if ((*it)->isExpanded()) { m_ExpandedItems.append(*it); } } } /** * @brief BBFolderTreeWidget::setItemExpansionState set expansion state of all items for new tree reconstructed */ void BBFolderTreeWidget::resumeItemExpansionState() { for(int i = 0; i < m_ExpandedItems.count(); i++) { m_ExpandedItems.at(i)->setExpanded(true); } } //void ProjectTree::copyAction() //{ // //重置剪贴板 // BaseTree::copyAction(); // //遍历剪贴板的项 算出对应的路径 // QList<QString> folderPaths; // int count = clipBoardItems.count(); // for (int i = 0; i < count; i++) // { // QString folderPath = getFilePath(getLevelPath(clipBoardItems.at(i))); // folderPath = folderPath.mid(0, folderPath.length() - 1); // folderPaths.append(folderPath); // } // //发送信号给文件列表 修改文件列表的剪贴板 // copyToFileList(folderPaths); //} //void ProjectTree::copyByFileList(QList<QString> filePaths) //{ // //在文件列表中复制 修改文件夹树的剪贴板 // //清空上一次剪贴板存下的复制内容 // clipBoardItems.clear(); // clipBoardFilePaths.clear(); // //父亲孩子不会同时被选中 // int count = filePaths.count(); // for (int i = 0; i < count; i++) // { // QString path = filePaths.at(i); // QFileInfo *fileInfo = new QFileInfo(path); // if (fileInfo->isDir()) // { // clipBoardItems.append(getItemByPath(path)); // } // else // { // //不是文件夹的文件没有对应树结点 存入路径 粘贴时只进行文件粘贴操作 不进行树节点的粘贴操作 // clipBoardFilePaths.append(path); // } // } //} //void ProjectTree::pasteAction() //{ // //清空用于存粘贴的副本文件夹名字 用于高亮显示 // pastedFolderNames.clear(); // BaseTree::pasteAction(); //} //void ProjectTree::pasteEnd() //{ // //粘贴结束后调用 粘贴不合法时 不会调用 // //树重新排序 // sortItems(0, Qt::AscendingOrder); // //处理剪贴板中的非文件夹文件 同时传副本文件夹的路径 用于高亮显示 // QString destPath = getFilePath(getLevelPath(currentItem())); // pasteFile(clipBoardFilePaths, destPath.mid(0, destPath.length() - 1), pastedFolderNames); // //可能复制到当前显示的文件夹下了 更新文件列表 这个操作放在pasteFile里执行 //} //void ProjectTree::pasteOne(QTreeWidgetItem *source, QTreeWidgetItem* transcript) //{ // //复制文件夹 // QString sourcePath = getFilePath(getLevelPath(source)); // sourcePath = sourcePath.mid(0, sourcePath.length() - 1); // QString transcriptPath = getFilePath(getLevelPath(transcript)); // transcriptPath = transcriptPath.mid(0, transcriptPath.length() - 1); // copyDirectoryFiles(sourcePath, transcriptPath); // //复制对应meta文件夹 // copyDirectoryFiles(FileList::getMetaFilePath(sourcePath), FileList::getMetaFilePath(transcriptPath)); // //存副本文件夹名字 用于文件列表的高亮显示 // pastedFolderNames.append(transcriptPath.mid(transcriptPath.lastIndexOf('/') + 1)); //} //void ProjectTree::pasteItemWithoutPasteFile(QList<QString> clipBoardTranscriptFolderNames) //{ // //只粘贴树节点 不粘贴文件 粘贴文件的操作已经在FileList中执行了 // //修改目的结点currentItem为FileList所指 下次在ProjectTree中粘贴 也使用这个目的结点 // setCurrentItem(currentShowFolderContentItem); // //能执行到这个函数 粘贴操作一定合法 // //去掉选中项的高亮 // QList<QTreeWidgetItem*> selected = selectedItems(); // int count = selected.count(); // for (int i = 0; i < count; i++) // { // setItemSelected(selected.at(i), false); // } // //遍历剪贴板 // count = clipBoardItems.count(); // for (int i = 0; i < count; i++) // { // QTreeWidgetItem *item = clipBoardItems.at(i); // //拷贝结点 // QTreeWidgetItem *transcript = item->clone(); // //副本的名字可能重复 重命名 // transcript->setText(0, clipBoardTranscriptFolderNames.at(i)); // //在目的结点下接入拷贝的结点 // if (currentShowFolderContentItem) // { // currentShowFolderContentItem->addChild(transcript); // } // else // { // addTopLevelItem(transcript); // } // //粘贴项高亮 // setItemSelected(transcript, true); // } // //展开目的结点 // if (currentShowFolderContentItem) // setItemExpanded(currentShowFolderContentItem, true); // //重新排序 // sortItems(0, Qt::AscendingOrder); //} <|start_filename|>Resources/shaders/GI.vert<|end_filename|> attribute vec4 BBPosition; attribute vec4 BBTexcoord; attribute vec4 BBNormal; varying vec4 V_World_pos; varying vec4 V_Texcoord; varying vec4 V_Normal; uniform mat4 BBProjectionMatrix; uniform mat4 BBViewMatrix; uniform mat4 BBModelMatrix; void main() { V_World_pos = BBModelMatrix * BBPosition; V_Texcoord = BBTexcoord; V_Normal.xyz = mat3(transpose(inverse(BBModelMatrix))) * BBNormal.xyz; gl_Position = BBProjectionMatrix * BBViewMatrix * V_World_pos; } <|start_filename|>Code/BBearEditor/Engine/Physics/Constraint/BBDistanceConstraint.cpp<|end_filename|> #include "BBDistanceConstraint.h" #include "../Body/BBBaseBody.h" BBDistanceConstraint::BBDistanceConstraint(BBBaseBody *pBody, int nParticleIndex1, int nParticleIndex2, float fElasticModulus) : BBBaseConstraint(pBody) { m_nParticleIndex1 = nParticleIndex1; m_nParticleIndex2 = nParticleIndex2; m_fElasticModulus = fElasticModulus; m_fOriginLength = pBody->getParticlePosition(nParticleIndex1).distanceToPoint(pBody->getParticlePosition(nParticleIndex2)); } void BBDistanceConstraint::doConstraint(float fDeltaTime) { QVector3D position1 = m_pBody->getParticlePredictedPosition(m_nParticleIndex1); QVector3D position2 = m_pBody->getParticlePredictedPosition(m_nParticleIndex2); QVector3D n = position2 - position1; float d = n.length(); n.normalize(); QVector3D correction = m_fElasticModulus * n * (d - m_fOriginLength) * fDeltaTime; m_pBody->setParticlePredictedPosition(m_nParticleIndex1, position1 + correction); m_pBody->setParticlePredictedPosition(m_nParticleIndex2, position2 - correction); } <|start_filename|>Resources/shaders/Physics/FluidSystem/FullScreenQuad.vert<|end_filename|> #version 430 core in vec4 BBPosition; in vec4 BBTexcoord; out vec2 v2f_texcoords; void main() { v2f_texcoords = BBTexcoord.xy; gl_Position = BBPosition; } <|start_filename|>Code/BBearEditor/Engine/Geometry/BBMeshSubdivision.h<|end_filename|> #ifndef BBMESHSUBDIVISION_H #define BBMESHSUBDIVISION_H #include <QVector3D> #include <QList> class BBProcedureMesh; enum BBMeshSubdivisionMeshType { Triangle, Quadrangle, TriangleAndQuadrangle }; class BBMeshSubdivision { public: BBMeshSubdivision(const BBMeshSubdivisionMeshType &eType); protected: int m_nMeshUnitPointNum; }; // Catmull-Clark class BBCatmullClarkMeshSubdivision : public BBMeshSubdivision { public: BBCatmullClarkMeshSubdivision(BBProcedureMesh *pMesh, const BBMeshSubdivisionMeshType &eType = Quadrangle); private: QList<QVector3D> getFacePoints(); void generateEdgeFaceList(); private: QList<QVector4D> m_InputPositions; unsigned short *m_pInputVertexIndexes; int m_nInputIndexCount; }; #endif // BBMESHSUBDIVISION_H <|start_filename|>Resources/shaders/Physics/FluidSystem/SSF_FS_3_Screen_Normal.frag<|end_filename|> #version 430 core in vec2 v2f_texcoords; layout (location = 0) out vec4 FragColor; uniform vec4 BBCameraParameters; uniform vec4 BBCameraParameters1; uniform sampler2D DepthMap; const float epo = 1e-7; float near; float far; float aspect; float near_height; // Clip space to view space vec3 clip2view(vec2 texcoords, float depth) { vec2 uv = (2.0 * texcoords - vec2(1.0, 1.0)) * vec2(aspect, 1.0); // near vec2 pos = 0.5 * near_height * uv * depth / near; return vec3(pos, -depth); } vec3 getViewSpacePos(vec2 texcoords) { // DepthMap is linear depth float depth = texture(DepthMap, texcoords).r; return clip2view(texcoords, depth); } void main() { near = BBCameraParameters.z; far = BBCameraParameters.w; aspect = BBCameraParameters1.y; near_height = BBCameraParameters1.z; float depth = texture(DepthMap, v2f_texcoords).r; if (depth >= far - 1.0) { discard; } vec2 tex_size = vec2(1.0 / textureSize(DepthMap, 0).s, 1.0 / textureSize(DepthMap, 0).t); // current vec3 view_space_pos = clip2view(v2f_texcoords, depth); // Differentiation of u and v // Use two opposite directions for differentiation, and select the one with smaller absolute value // Because if a single differentiation is used, the normal will suddenly change at the edge of the object, resulting in errors vec3 du1 = getViewSpacePos(v2f_texcoords + vec2(tex_size.x, 0.0)) - view_space_pos; vec3 du2 = view_space_pos - getViewSpacePos(v2f_texcoords - vec2(tex_size.x, 0.0)); vec3 du = abs(du1.z) < abs(du2.z) ? du1 : du2; vec3 dv1 = getViewSpacePos(v2f_texcoords + vec2(0.0, tex_size.y)) - view_space_pos; vec3 dv2 = view_space_pos - getViewSpacePos(v2f_texcoords - vec2(0.0, tex_size.y)); vec3 dv = abs(dv1.z) < abs(dv2.z) ? dv1 : dv2; vec3 N = cross(du, dv); N = normalize(N); FragColor = vec4(N, 1.0); } <|start_filename|>Resources/shaders/Diffuse_SSBO.frag<|end_filename|> #version 430 core in V2F { vec4 color; vec3 normal; } v2f; out vec4 FragColor; uniform vec4 BBLightPosition; uniform vec4 BBLightColor; // Lambert vec4 getLambertLight() { vec3 light_pos_normalized = normalize(BBLightPosition.xyz); vec3 normal_normalized = normalize(v2f.normal); vec4 light_color = dot(light_pos_normalized, normal_normalized) * BBLightColor; return light_color; } void main(void) { FragColor = v2f.color * getLambertLight(); } <|start_filename|>Code/BBearEditor/Engine/Physics/Body/BBBaseBody.cpp<|end_filename|> #include "BBBaseBody.h" #include "../Constraint/BBBaseConstraint.h" #include "Utils/BBUtils.h" BBBaseBody::BBBaseBody(int nParticleCount, float fMass) { m_nParticleCount = nParticleCount; m_fParticleMass = fMass; m_fDamping = 1.0f; m_pPositions = new QVector3D[nParticleCount]; m_pPredictedPositions = new QVector3D[nParticleCount]; m_pVelocities = new QVector3D[nParticleCount]; } BBBaseBody::~BBBaseBody() { BB_SAFE_DELETE_ARRAY(m_pPositions); BB_SAFE_DELETE_ARRAY(m_pPredictedPositions); BB_SAFE_DELETE_ARRAY(m_pVelocities); } void BBBaseBody::dampenVelocities(float fDeltaTime) { for (int i = 0; i < m_nParticleCount; i++) { m_pVelocities[i] *= 1 - m_fDamping * fDeltaTime; } } void BBBaseBody::predictPositions(float fDeltaTime) { for (int i = 0; i < m_nParticleCount; i++) { m_pPredictedPositions[i] = m_pPositions[i] + m_pVelocities[i] * fDeltaTime; } } void BBBaseBody::projectConstraints(float fDeltaTime) { for (int i = 0; i < m_Constraints.size(); i++) { m_Constraints[i]->doConstraint(fDeltaTime); } } void BBBaseBody::updateVelocities(float fDeltaTime, float fStopThreshold2) { for (int i = 0; i < m_nParticleCount; i++) { QVector3D d = m_pPredictedPositions[i] - m_pPositions[i]; m_pVelocities[i] = d / fDeltaTime; if (m_pVelocities[i].lengthSquared() < fStopThreshold2) { m_pVelocities[i] = QVector3D(0, 0, 0); } } } void BBBaseBody::updatePositions() { for (int i = 0; i < m_nParticleCount; i++) { m_pPositions[i] = m_pPredictedPositions[i]; } } <|start_filename|>External/ProtoBuffer/lib/CMakeFiles/libprotobuf-lite.dir/DependInfo.cmake<|end_filename|> # Consider dependencies only in project. set(CMAKE_DEPENDS_IN_PROJECT_ONLY OFF) # The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES ) # The set of dependency files which are needed: set(CMAKE_DEPENDS_DEPENDENCY_FILES "D:/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/any_lite.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arena.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/arenastring.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/extension_set.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_enum_util.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_table_driven_lite.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/generated_message_util.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/implicit_weak_message.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/coded_stream.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/io_win32.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/strtod.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/io/zero_copy_stream_impl_lite.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/map.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/map.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/message_lite.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/parse_context.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/repeated_field.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/bytestream.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/common.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/int128.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/status.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/statusor.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringpiece.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/stringprintf.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/structurally_valid.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/strutil.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/stubs/time.cc.obj.d" "D:/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj" "gcc" "CMakeFiles/libprotobuf-lite.dir/D_/workspace/protobuf-3.16.0/src/google/protobuf/wire_format_lite.cc.obj.d" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <|start_filename|>Resources/shaders/fullscreenquad_ray_tracing.vert<|end_filename|> attribute vec4 position; attribute vec4 texcoord; varying vec4 V_Position; varying vec4 V_Texcoord; void main() { V_Texcoord = texcoord; gl_Position = position; } <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFileListWidget.cpp<|end_filename|> #include "BBFileListWidget.h" #include <QWidgetAction> #include <QMenu> #include <QHBoxLayout> #include <QLabel> #include "Dialog/BBConfirmationDialog.h" #include <QMimeData> #include <QScrollBar> #include <QDrag> #include "BBFileSystemDataManager.h" #include <QPainter> #include <QFileInfo> //--------------------------------------------------------------------------------------------------- // BBPlainTextEdit //--------------------------------------------------------------------------------------------------- BBPlainTextEdit::BBPlainTextEdit(QWidget *pParent) : QPlainTextEdit(pParent) { } void BBPlainTextEdit::focusOutEvent(QFocusEvent *event) { Q_UNUSED(event); editFinished(); } void BBPlainTextEdit::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Return) { editFinished(); } else { QPlainTextEdit::keyPressEvent(event); } } //--------------------------------------------------------------------------------------------------- // BBFileListWidget //--------------------------------------------------------------------------------------------------- QSize BBFileListWidget::m_ItemSize = m_StandardItemSize; QSize BBFileListWidget::m_StandardIconSize = QSize(43, 43); QSize BBFileListWidget::m_StandardItemSize = QSize(180, 45); //QSize BBFileListWidget::m_StandardIconSize = QSize(53, 53); //QSize BBFileListWidget::m_StandardItemSize = QSize(55, 100); BBFileListWidget::BBFileListWidget(QWidget *pParent) : QListWidget(pParent), m_eSenderTag(BBSignalSender::FileList) { m_pEditingItem = NULL; m_pRenameEditor = NULL; m_pIndicatorItem = NULL; m_pFileData = NULL; setFlow(QListView::LeftToRight); // icon is at the top, and text is at the bottom // setViewMode(QListView::IconMode); // Dynamically adjust the layout position according to the size of the list container // From left to right and from top to bottom setResizeMode(QListView::Adjust); setIconSize(m_StandardIconSize); setSpacing(2); // Text can be showed in multiple lines setWordWrap(true); setWrapping(true); setAcceptDrops(true); setDragEnabled(true); // You can press shift and cmd to select multiple setSelectionMode(QAbstractItemView::ExtendedSelection); setMenu(); QObject::connect(this, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(clickItem(QListWidgetItem*))); QObject::connect(this, SIGNAL(itemPressed(QListWidgetItem*)), this, SLOT(pressItem(QListWidgetItem*))); QObject::connect(this, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(doubleClickItem(QListWidgetItem*))); QObject::connect(this, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(changeCurrentItem(QListWidgetItem*, QListWidgetItem*))); } BBFileListWidget::~BBFileListWidget() { BB_SAFE_DELETE(m_pMenu); } void BBFileListWidget::loadItems(const QString &parentPath, BBFILE *pFileData, QListWidgetItem *pCurrentItem) { // show the contents of the newly selected folder, the original list is cleared // just remove from the list, cannot delete the items, so cannot use clear(); while (count() > 0) { takeItem(0); } for (BBFILE::Iterator it = pFileData->begin(); it != pFileData->end(); it++) { addItem(it.key()); } m_pFileData = pFileData; m_ParentPath = parentPath; sortItems(); setCurrentItem(pCurrentItem); } void BBFileListWidget::setSelectedItems(const QList<QListWidgetItem*> &items) { for (int i = 0; i < items.count(); i++) { setItemSelected(items.at(i), true); } } void BBFileListWidget::clickItem(QListWidgetItem *pItem) { emit clickItem(getPathByItem(pItem), m_pFileData->value(pItem)->m_eFileType); } void BBFileListWidget::pressItem(QListWidgetItem *pItem) { emit pressItem(m_pFileData->value(pItem)->m_eFileType); } void BBFileListWidget::doubleClickItem(QListWidgetItem *pItem) { emit openFile(getPathByItem(pItem), m_pFileData->value(pItem)->m_eFileType); } void BBFileListWidget::changeCurrentItem(QListWidgetItem *pCurrent, QListWidgetItem *pPrevious) { BBFileType eCurrentType = BBFileType::Other; BBFileType ePreviousType = BBFileType::Other; BBFileInfo *pFileInfo = m_pFileData->value(pCurrent); if (pFileInfo) { eCurrentType = pFileInfo->m_eFileType; } pFileInfo = m_pFileData->value(pPrevious); if (pFileInfo) { ePreviousType = pFileInfo->m_eFileType; } emit changeCurrentItem(eCurrentType, ePreviousType); } void BBFileListWidget::changeItemSize(int factor) { } void BBFileListWidget::newFolder() { // Otherwise, after creating, several items will be selected QList<QListWidgetItem*> items = selectedItems(); for (int i = 0; i < items.count(); i++) { setItemSelected(items.at(i), false); } emit newFolder(m_ParentPath, m_eSenderTag); openRenameEditor(); } void BBFileListWidget::newSceneAction() { newFile(0); } void BBFileListWidget::newMaterialAction() { newFile(1); } void BBFileListWidget::newScript() { } void BBFileListWidget::showInFolder() { emit showInFolder(getPathByItem(currentItem())); } void BBFileListWidget::copyAction() { } void BBFileListWidget::pasteAction() { } void BBFileListWidget::openRenameEditor() { QList<QListWidgetItem*> items = selectedItems(); if (items.count() == 1) { m_pEditingItem = items.first(); QWidget *pWidget = new QWidget(this); QVBoxLayout *pLayout = new QVBoxLayout(pWidget); pLayout->setContentsMargins(1, 2, 1, 2); pLayout->setSpacing(3); m_pRenameEditor = new BBPlainTextEdit(pWidget); m_pRenameEditor->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // margin: 47px 1px 2px 1px; m_pRenameEditor->setStyleSheet("border: none; background: #d6dfeb; color: #191f28;" "selection-color: #d6dfeb; selection-background-color: #8193bc;" "font: 9pt \"Arial\"; padding: -2px;"); m_pRenameEditor->setPlainText(m_pEditingItem->text()); m_pRenameEditor->selectAll(); QObject::connect(m_pRenameEditor, SIGNAL(editFinished()), this, SLOT(finishRename())); pLayout->addWidget(m_pRenameEditor, 1); setItemWidget(m_pEditingItem, pWidget); m_pRenameEditor->setFocus(); } } void BBFileListWidget::finishRename() { BB_PROCESS_ERROR_RETURN(m_pEditingItem); // without suffix QString newBaseName = m_pRenameEditor->toPlainText(); QString oldName = m_pFileData->value(m_pEditingItem)->m_FileName; QString suffix = BBFileSystemDataManager::getFileSuffix(oldName); QString newName = newBaseName; if (suffix.count() > 0) { newName += "." + suffix; } if (oldName != newName) { emit rename(m_pEditingItem, m_ParentPath + "/" + oldName, m_ParentPath + "/" + newName); } removeItemWidget(m_pEditingItem); BB_SAFE_DELETE(m_pRenameEditor); m_pEditingItem = NULL; // Otherwise, the list has no focus and no longer triggers key events setFocus(); sortItems(); } void BBFileListWidget::deleteAction() { QList<QListWidgetItem*> items = selectedItems(); BB_PROCESS_ERROR_RETURN(items.count() > 0); BBConfirmationDialog dialog; dialog.setTitle("Delete selected?"); if (items.count() == 1) { dialog.setMessage("You cannot undo this action.\n\nAre you sure to delete this?"); } else { dialog.setMessage("You cannot undo this action.\n\nAre you sure to delete these " + QString::number(items.count()) + " items?"); } if (dialog.exec()) { emit deleteFiles(items); setCurrentItem(NULL); // //清空属性栏 包括场景 层级视图选中 // cancelHierarchyTreeSelectedItems(); // itemClickedSlot(NULL); } } void BBFileListWidget::setMenu() { // first level menu m_pMenu = new QMenu(this); QAction *pActionNewFolder = new QAction(tr("New Folder")); QAction *pLabelNewAsset = new QAction(tr("New Asset ...")); // As the title of a column, not clickable pLabelNewAsset->setEnabled(false); QWidgetAction *pActionNewScene = createWidgetAction(BB_PATH_RESOURCE_ICON(scene.png), tr("Scene")); QWidgetAction *pActionNewMaterial = createWidgetAction(BB_PATH_RESOURCE_ICON(material.png), tr("Material")); QWidgetAction *pActionNewScript = createWidgetAction(BB_PATH_RESOURCE_ICON(script.png), tr("Script")); QAction *pActionShowInFolder = new QAction(tr("Show In Folder")); QAction *pActionCopy = new QAction(tr("Copy")); pActionCopy->setShortcut(QKeySequence(tr("Ctrl+C"))); QAction *pActionPaste = new QAction(tr("Paste")); pActionPaste->setShortcut(QKeySequence(tr("Ctrl+V"))); QAction *pActionRename = new QAction(tr("Rename")); #if defined(Q_OS_WIN32) pActionRename->setShortcut(Qt::Key_F2); #elif defined(Q_OS_MAC) pActionRename->setShortcut(Qt::Key_Return); #endif QAction *pActionDelete = new QAction(tr("Delete")); // second level menu QMenu *pMenuSort = new QMenu(tr("Sort By"), m_pMenu); QAction *pActionNameSort = new QAction(tr("Name")); QAction *pActionTypeSort = new QAction(tr("Type")); QAction *pActionCreateDateSort = new QAction(tr("Create Date")); QAction *pActionModifyDateSort = new QAction(tr("Modify Date")); pMenuSort->addAction(pActionNameSort); pMenuSort->addAction(pActionTypeSort); pMenuSort->addAction(pActionCreateDateSort); pMenuSort->addAction(pActionModifyDateSort); // slider QWidgetAction *pActionSlider = new QWidgetAction(m_pMenu); QWidget *pWidget = new QWidget(this); QHBoxLayout *pLayout = new QHBoxLayout(pWidget); pLayout->setContentsMargins(6, 1, 6, 1); QLabel *pLabel = new QLabel("Size", pWidget); pLabel->setStyleSheet("color: #d6dfeb; font: 9pt \"Arial\";"); pLayout->addWidget(pLabel); QSlider *pSlider = new QSlider(Qt::Horizontal, pWidget); pSlider->setRange(-2, 2); pSlider->setValue(0); QObject::connect(pSlider, SIGNAL(valueChanged(int)), this, SLOT(changeItemSize(int))); pLayout->addWidget(pSlider); pActionSlider->setDefaultWidget(pWidget); m_pMenu->addAction(pActionNewFolder); m_pMenu->addSeparator(); m_pMenu->addAction(pLabelNewAsset); m_pMenu->addAction(pActionNewScene); m_pMenu->addAction(pActionNewMaterial); m_pMenu->addAction(createWidgetAction(BB_PATH_RESOURCE_ICON(animation.png), tr("Animation"))); m_pMenu->addAction(createWidgetAction(BB_PATH_RESOURCE_ICON(particle.png), tr("Particle"))); m_pMenu->addAction(pActionNewScript); m_pMenu->addSeparator(); m_pMenu->addAction(pActionShowInFolder); m_pMenu->addSeparator(); m_pMenu->addAction(pActionCopy); m_pMenu->addAction(pActionPaste); m_pMenu->addSeparator(); m_pMenu->addAction(pActionRename); m_pMenu->addAction(pActionDelete); m_pMenu->addSeparator(); m_pMenu->addMenu(pMenuSort); m_pMenu->addSeparator(); m_pMenu->addAction(pActionSlider); QObject::connect(pActionNewFolder, SIGNAL(triggered()), this, SLOT(newFolder())); QObject::connect(pActionNewScene, SIGNAL(triggered()), this, SLOT(newSceneAction())); QObject::connect(pActionNewMaterial, SIGNAL(triggered()), this, SLOT(newMaterialAction())); QObject::connect(pActionNewScript, SIGNAL(triggered()), this, SLOT(newScript())); QObject::connect(pActionShowInFolder, SIGNAL(triggered()), this, SLOT(showInFolder())); QObject::connect(pActionCopy, SIGNAL(triggered()), this, SLOT(copyAction())); QObject::connect(pActionPaste, SIGNAL(triggered()), this, SLOT(pasteAction())); QObject::connect(pActionRename, SIGNAL(triggered()), this, SLOT(openRenameEditor())); QObject::connect(pActionDelete, SIGNAL(triggered()), this, SLOT(deleteAction())); } QWidgetAction* BBFileListWidget::createWidgetAction(const QString &iconPath, const QString &name) { QWidgetAction *pAction = new QWidgetAction(m_pMenu); QWidget *pWidget = new QWidget(this); pWidget->setObjectName("widgetAction"); pWidget->setStyleSheet("#widgetAction:hover {background: #0ebf9c;}"); QHBoxLayout *pLayout = new QHBoxLayout(pWidget); pLayout->setContentsMargins(6, 2, 6, 2); QLabel *pIcon = new QLabel(pWidget); QPixmap pix(iconPath); pix.setDevicePixelRatio(devicePixelRatio()); pix = pix.scaled(13 * devicePixelRatio(), 13 * devicePixelRatio(), Qt::KeepAspectRatio, Qt::SmoothTransformation); pIcon->setPixmap(pix); pLayout->addWidget(pIcon); QLabel *pText = new QLabel(pWidget); pText->setText(name); pText->setStyleSheet("color: #d6dfeb; font: 9pt \"Arial\";"); pLayout->addWidget(pText, Qt::AlignLeft); pAction->setDefaultWidget(pWidget); return pAction; } void BBFileListWidget::newFile(int nType) { // 0 scene emit newFile(m_ParentPath, nType); openRenameEditor(); } void BBFileListWidget::startDrag(Qt::DropActions supportedActions) { Q_UNUSED(supportedActions); QListWidgetItem *pCenterItem = currentItem(); QRect centerItemRect = visualItemRect(pCenterItem); // Used to calculate the absolute position of each item that needs to be dragged int hPos = horizontalScrollBar()->sliderPosition(); int vPos = verticalScrollBar()->sliderPosition(); // step of each item int hStep = centerItemRect.width() + spacing(); int vStep = centerItemRect.height() + spacing(); // The size of a single icon static int nSize = iconSize().width() * devicePixelRatio(); // Record the row and column value and icon of the selected item struct Info { int nRow; int nColumn; QPixmap icon; }; QList<Info> infos; // Used for the size of final icon int nMaxRow = 0; int nMaxColumn = 0; int nMinRow = INT_MAX; int nMinColumn = INT_MAX; // drag all selected items QList<QListWidgetItem*> items = selectedItems(); for (int i = 0; i < items.count(); i++) { Info info; QListWidgetItem *pItem = items.at(i); QRect rect = visualItemRect(pItem); // rect is relative to the position of the scroll bar // translate and make it relative to 0 rect.translate(hPos - spacing(), vPos - spacing()); // Calculate the row and column value of the item based on the step info.nColumn = rect.left() / hStep; info.nRow = rect.top() / vStep; if (info.nColumn > nMaxColumn) { nMaxColumn = info.nColumn; } if (info.nColumn < nMinColumn) { nMinColumn = info.nColumn; } if (info.nRow > nMaxRow) { nMaxRow = info.nRow; } if (info.nRow < nMinRow) { nMinRow = info.nRow; } info.icon = pItem->icon().pixmap(nSize); info.icon.setDevicePixelRatio(devicePixelRatio()); info.icon = info.icon.scaled(nSize, nSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); infos.append(info); } QPoint hotSpot; // final icon QPixmap pixmap((nSize + 6) * (nMaxColumn - nMinColumn + 1), (nSize + 6) * (nMaxRow - nMinRow + 1)); pixmap.setDevicePixelRatio(devicePixelRatio()); pixmap.fill(Qt::transparent); QPainter painter(&pixmap); // paint the icon of each item to the final icon according to the row and column value of each item for (int i = 0; i < infos.count(); i++) { int x = (infos.at(i).nColumn - nMinColumn) * (nSize + 6) / devicePixelRatio(); int y = (infos.at(i).nRow - nMinRow) * (nSize + 6) / devicePixelRatio(); painter.drawPixmap(x, y, infos.at(i).icon); if (items.at(i) == pCenterItem) { // Take the center of pCenterItem as the mouse position hotSpot.setX(x + nSize / devicePixelRatio() / 2); hotSpot.setY(y + nSize / devicePixelRatio() / 2); } } painter.end(); // Pack relevant data QByteArray itemData; QDataStream dataStream(&itemData, QIODevice::WriteOnly); // The pCenterItem is written in the first one, used for the situation that you just can read one item QString filePath = getPathByItem(pCenterItem); dataStream << filePath; // all selected items is written, used for the situation that you can read all selected items for (int i = 0; i < items.count(); i++) { filePath = getPathByItem(items.at(i)); dataStream << filePath; } QMimeData *pMimeData = new QMimeData; // Give this data a unique identifying name pMimeData->setData(getMimeType(), itemData); QDrag drag(this); drag.setMimeData(pMimeData); drag.setHotSpot(hotSpot); drag.setPixmap(pixmap); drag.exec(Qt::MoveAction); } void BBFileListWidget::dragEnterEvent(QDragEnterEvent *event) { if (!event->mimeData()->urls().isEmpty()) { // the outside of the editor event->accept(); } else if (event->mimeData()->hasFormat(getMimeType())) { // internal drag event->accept(); } else if (event->mimeData()->hasFormat(BB_MIMETYPE_FOLDERTREEWIDGET)) { event->accept(); } else { event->ignore(); } } void BBFileListWidget::dragMoveEvent(QDragMoveEvent *event) { event->accept(); // Scroll up and down when the mouse is at the top or bottom // QListWidget::dragMoveEvent(event); invalidates dropEvent int y = event->pos().y(); if (y < 10) { verticalScrollBar()->setSliderPosition(verticalScrollBar()->sliderPosition() - 10); } else if (y >= height() - 10) { verticalScrollBar()->setSliderPosition(verticalScrollBar()->sliderPosition() + 10); } // Drop position indicator QListWidgetItem *pItem = itemAt(event->pos()); // Clear the last indicator position painted m_pIndicatorItem = NULL; if (pItem) { // only folder can show drop indicator QFileInfo fileInfo(getPathByItem(pItem)); if (fileInfo.isDir()) { // When dragging internally, the drop position cannot be the folder being dragged // It doesn't matter if it is dragged from the folder tree, since the item has been judged if ((event->mimeData()->hasFormat(getMimeType()) && !selectedItems().contains(pItem)) || event->mimeData()->hasFormat(BB_MIMETYPE_FOLDERTREEWIDGET)) { m_pIndicatorItem = pItem; } } } repaint(); } void BBFileListWidget::dragLeaveEvent(QDragLeaveEvent *event) { Q_UNUSED(event); // No need for indicator when dragLeave m_pIndicatorItem = NULL; repaint(); } void BBFileListWidget::dropEvent(QDropEvent *event) { if (!event->mimeData()->urls().isEmpty()) { // from outside of the editor event->accept(); QString parentPath = m_ParentPath; if (m_pIndicatorItem) { // Drag to the folder in the file list and import the asset into this folder parentPath += "/" + m_pFileData->value(m_pIndicatorItem)->m_FileName; } emit importAsset(parentPath, event->mimeData()->urls()); // Open the asset import management dialog // BBAssetManager assetManager; // assetManager.exec(); } else if (event->mimeData()->hasFormat(getMimeType())) { if (m_pIndicatorItem) { // there is a drop spot if (moveItem()) { event->accept(); } else { event->ignore(); } } else { event->ignore(); } } else if (event->mimeData()->hasFormat(BB_MIMETYPE_FOLDERTREEWIDGET)) { if (moveItemFromFolderTree(event->mimeData())) { event->accept(); } else { event->ignore(); } } else { event->ignore(); } // The indicator is no longer needed after drop m_pIndicatorItem = NULL; repaint(); } bool BBFileListWidget::moveItem() { // move selected items into m_pIndicatorItem QList<QListWidgetItem*> items = selectedItems(); emit moveFiles(items, m_ParentPath, m_ParentPath + "/" + m_pFileData->value(m_pIndicatorItem)->m_FileName, false); return true; } bool BBFileListWidget::moveItemFromFolderTree(const QMimeData *pMimeData) { QString newParentPath = m_ParentPath; if (m_pIndicatorItem) { // Drag to the folder in the file list and move the asset into this folder newParentPath += "/" + m_pFileData->value(m_pIndicatorItem)->m_FileName; } QList<QString> oldFilePaths; QByteArray data = pMimeData->data(BB_MIMETYPE_FOLDERTREEWIDGET); QDataStream dataStream(&data, QIODevice::ReadOnly); QString levelPath; dataStream >> levelPath; while (!levelPath.isEmpty()) { QString oldFilePath = BBConstant::BB_PATH_PROJECT_USER + "/" + levelPath; oldFilePaths.append(oldFilePath); dataStream >> levelPath; } emit moveFolders(oldFilePaths, newParentPath, false); return true; } void BBFileListWidget::paintEvent(QPaintEvent *event) { QListWidget::paintEvent(event); // using "this" is wrong QPainter painter(viewport()); // The file type logo color is painted in the top left corner for (int i = 0; i < count(); i++) { // Get the logo color of the corresponding file type of the item QColor color = BBFileSystemDataManager::getFileLogoColor(m_pFileData->value(item(i))->m_eFileType); if (color == nullptr) continue; QPen pen(color); painter.setPen(pen); // item position QRect rect = visualItemRect(item(i)); for (int j = 8; j < 20; j++) { QPoint p1 = rect.topLeft() + QPoint(4, -1 + j); QPoint p2 = rect.topLeft() + QPoint(4 + j, -1); painter.drawLine(p1, p2); } } // paint drop indicator if (m_pIndicatorItem) { painter.setPen(QColor("#d6dfeb")); QRect rect = visualItemRect(m_pIndicatorItem); painter.drawRect(rect); } painter.end(); } void BBFileListWidget::mousePressEvent(QMouseEvent *event) { QListWidget::mousePressEvent(event); if (event->buttons() & Qt::LeftButton || event->buttons() & Qt::RightButton) { // There is no item at the mouse click position, remove the selection QListWidgetItem *pItem = itemAt(event->pos()); if (!pItem) { setCurrentItem(NULL); } } } void BBFileListWidget::contextMenuEvent(QContextMenuEvent *event) { Q_UNUSED(event); m_pMenu->exec(cursor().pos()); } void BBFileListWidget::keyPressEvent(QKeyEvent *event) { // Handling menu shortcut events int key; #if defined(Q_OS_WIN32) key = Qt::Key_F2; #elif defined(Q_OS_MAC) key = Qt::Key_Return; #endif if (event->key() == key) { openRenameEditor(); } } void BBFileListWidget::focusInEvent(QFocusEvent *event) { // parent class, when the focus is obtained, the first item will show a blue box, which is ugly Q_UNUSED(event); setFocus(); emit inFocus(); } QString BBFileListWidget::getPathByItem(QListWidgetItem *pItem) { if (pItem) { return m_ParentPath + "/" + m_pFileData->value(pItem)->m_FileName; } else { return m_ParentPath; } } //void FileList::changeItemSize(int factor) //{ // /*//修改图标大小item大小 // setIconSize(standardIconSize + factor * 5 * QSize(1, 1)); // itemSize = standardItemSize + factor * 5 * QSize(1, 1); // //刷新列表 // showFolderContent(mFolderPath);*/ //} //void FileList::updateMaterialFileIcon(QString filePath) //{ // QString onlyPath = filePath.mid(0, filePath.lastIndexOf('/')); // if (mFolderPath == onlyPath) // { // //被修改的材质文件当前正在文件列表中被显示 // QString fileName = filePath.mid(filePath.lastIndexOf('/') + 1); // //findItems(fileName, Qt::MatchExactly);不行 因为text被换行了 // //找该文件对应的item // QMap<QListWidgetItem*, FileInfo*>::Iterator itr; // for (itr = mMap.begin(); itr != mMap.end(); itr++) // { // FileInfo *fileInfo = itr.value(); // if (fileInfo->mFileName == fileName) // { // //找该文件对应的item 修改图标 // QListWidgetItem *item = itr.key(); // Material *material = Material::mtlMap.value(filePath); // item->setIcon(QIcon(material->getPreview())); // break; // } // } // } //} <|start_filename|>Code/BBearEditor/Engine/Serializer/BBCubeMap.pb.cc<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBCubeMap.proto #include "BBCubeMap.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace BBSerializer { constexpr BBCubeMap::BBCubeMap( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : positivex_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , negativex_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , positivey_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , negativey_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , positivez_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , negativez_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string){} struct BBCubeMapDefaultTypeInternal { constexpr BBCubeMapDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBCubeMapDefaultTypeInternal() {} union { BBCubeMap _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBCubeMapDefaultTypeInternal _BBCubeMap_default_instance_; } // namespace BBSerializer static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_BBCubeMap_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_BBCubeMap_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_BBCubeMap_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_BBCubeMap_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::BBSerializer::BBCubeMap, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBCubeMap, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBCubeMap, positivex_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBCubeMap, negativex_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBCubeMap, positivey_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBCubeMap, negativey_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBCubeMap, positivez_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBCubeMap, negativez_), 0, 1, 2, 3, 4, 5, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 11, sizeof(::BBSerializer::BBCubeMap)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBCubeMap_default_instance_), }; const char descriptor_table_protodef_BBCubeMap_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\017BBCubeMap.proto\022\014BBSerializer\"\357\001\n\tBBCu" "beMap\022\026\n\tpositiveX\030\001 \001(\tH\000\210\001\001\022\026\n\tnegativ" "eX\030\002 \001(\tH\001\210\001\001\022\026\n\tpositiveY\030\003 \001(\tH\002\210\001\001\022\026\n" "\tnegativeY\030\004 \001(\tH\003\210\001\001\022\026\n\tpositiveZ\030\005 \001(\t" "H\004\210\001\001\022\026\n\tnegativeZ\030\006 \001(\tH\005\210\001\001B\014\n\n_positi" "veXB\014\n\n_negativeXB\014\n\n_positiveYB\014\n\n_nega" "tiveYB\014\n\n_positiveZB\014\n\n_negativeZb\006proto" "3" ; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_BBCubeMap_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBCubeMap_2eproto = { false, false, 281, descriptor_table_protodef_BBCubeMap_2eproto, "BBCubeMap.proto", &descriptor_table_BBCubeMap_2eproto_once, nullptr, 0, 1, schemas, file_default_instances, TableStruct_BBCubeMap_2eproto::offsets, file_level_metadata_BBCubeMap_2eproto, file_level_enum_descriptors_BBCubeMap_2eproto, file_level_service_descriptors_BBCubeMap_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_BBCubeMap_2eproto_getter() { return &descriptor_table_BBCubeMap_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_BBCubeMap_2eproto(&descriptor_table_BBCubeMap_2eproto); namespace BBSerializer { // =================================================================== class BBCubeMap::_Internal { public: using HasBits = decltype(std::declval<BBCubeMap>()._has_bits_); static void set_has_positivex(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_negativex(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_positivey(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_negativey(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_positivez(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_negativez(HasBits* has_bits) { (*has_bits)[0] |= 32u; } }; BBCubeMap::BBCubeMap(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBCubeMap) } BBCubeMap::BBCubeMap(const BBCubeMap& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); positivex_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_positivex()) { positivex_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_positivex(), GetArena()); } negativex_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_negativex()) { negativex_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_negativex(), GetArena()); } positivey_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_positivey()) { positivey_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_positivey(), GetArena()); } negativey_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_negativey()) { negativey_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_negativey(), GetArena()); } positivez_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_positivez()) { positivez_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_positivez(), GetArena()); } negativez_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_negativez()) { negativez_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_negativez(), GetArena()); } // @@protoc_insertion_point(copy_constructor:BBSerializer.BBCubeMap) } void BBCubeMap::SharedCtor() { positivex_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); negativex_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); positivey_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); negativey_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); positivez_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); negativez_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } BBCubeMap::~BBCubeMap() { // @@protoc_insertion_point(destructor:BBSerializer.BBCubeMap) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBCubeMap::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); positivex_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); negativex_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); positivey_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); negativey_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); positivez_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); negativez_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void BBCubeMap::ArenaDtor(void* object) { BBCubeMap* _this = reinterpret_cast< BBCubeMap* >(object); (void)_this; } void BBCubeMap::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBCubeMap::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBCubeMap::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBCubeMap) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { positivex_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { negativex_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { positivey_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { negativey_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { positivez_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000020u) { negativez_.ClearNonDefaultToEmpty(); } } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBCubeMap::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // string positiveX = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_positivex(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBCubeMap.positiveX")); CHK_(ptr); } else goto handle_unusual; continue; // string negativeX = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_negativex(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBCubeMap.negativeX")); CHK_(ptr); } else goto handle_unusual; continue; // string positiveY = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { auto str = _internal_mutable_positivey(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBCubeMap.positiveY")); CHK_(ptr); } else goto handle_unusual; continue; // string negativeY = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { auto str = _internal_mutable_negativey(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBCubeMap.negativeY")); CHK_(ptr); } else goto handle_unusual; continue; // string positiveZ = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { auto str = _internal_mutable_positivez(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBCubeMap.positiveZ")); CHK_(ptr); } else goto handle_unusual; continue; // string negativeZ = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { auto str = _internal_mutable_negativez(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBCubeMap.negativeZ")); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBCubeMap::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBCubeMap) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string positiveX = 1; if (_internal_has_positivex()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_positivex().data(), static_cast<int>(this->_internal_positivex().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBCubeMap.positiveX"); target = stream->WriteStringMaybeAliased( 1, this->_internal_positivex(), target); } // string negativeX = 2; if (_internal_has_negativex()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_negativex().data(), static_cast<int>(this->_internal_negativex().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBCubeMap.negativeX"); target = stream->WriteStringMaybeAliased( 2, this->_internal_negativex(), target); } // string positiveY = 3; if (_internal_has_positivey()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_positivey().data(), static_cast<int>(this->_internal_positivey().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBCubeMap.positiveY"); target = stream->WriteStringMaybeAliased( 3, this->_internal_positivey(), target); } // string negativeY = 4; if (_internal_has_negativey()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_negativey().data(), static_cast<int>(this->_internal_negativey().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBCubeMap.negativeY"); target = stream->WriteStringMaybeAliased( 4, this->_internal_negativey(), target); } // string positiveZ = 5; if (_internal_has_positivez()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_positivez().data(), static_cast<int>(this->_internal_positivez().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBCubeMap.positiveZ"); target = stream->WriteStringMaybeAliased( 5, this->_internal_positivez(), target); } // string negativeZ = 6; if (_internal_has_negativez()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_negativez().data(), static_cast<int>(this->_internal_negativez().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBCubeMap.negativeZ"); target = stream->WriteStringMaybeAliased( 6, this->_internal_negativez(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBCubeMap) return target; } size_t BBCubeMap::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBCubeMap) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003fu) { // string positiveX = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_positivex()); } // string negativeX = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_negativex()); } // string positiveY = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_positivey()); } // string negativeY = 4; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_negativey()); } // string positiveZ = 5; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_positivez()); } // string negativeZ = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_negativez()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBCubeMap::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBCubeMap) GOOGLE_DCHECK_NE(&from, this); const BBCubeMap* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBCubeMap>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBCubeMap) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBCubeMap) MergeFrom(*source); } } void BBCubeMap::MergeFrom(const BBCubeMap& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBCubeMap) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { _internal_set_positivex(from._internal_positivex()); } if (cached_has_bits & 0x00000002u) { _internal_set_negativex(from._internal_negativex()); } if (cached_has_bits & 0x00000004u) { _internal_set_positivey(from._internal_positivey()); } if (cached_has_bits & 0x00000008u) { _internal_set_negativey(from._internal_negativey()); } if (cached_has_bits & 0x00000010u) { _internal_set_positivez(from._internal_positivez()); } if (cached_has_bits & 0x00000020u) { _internal_set_negativez(from._internal_negativez()); } } } void BBCubeMap::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBCubeMap) if (&from == this) return; Clear(); MergeFrom(from); } void BBCubeMap::CopyFrom(const BBCubeMap& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBCubeMap) if (&from == this) return; Clear(); MergeFrom(from); } bool BBCubeMap::IsInitialized() const { return true; } void BBCubeMap::InternalSwap(BBCubeMap* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); positivex_.Swap(&other->positivex_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); negativex_.Swap(&other->negativex_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); positivey_.Swap(&other->positivey_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); negativey_.Swap(&other->negativey_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); positivez_.Swap(&other->positivez_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); negativez_.Swap(&other->negativez_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } ::PROTOBUF_NAMESPACE_ID::Metadata BBCubeMap::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBCubeMap_2eproto_getter, &descriptor_table_BBCubeMap_2eproto_once, file_level_metadata_BBCubeMap_2eproto[0]); } // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::BBSerializer::BBCubeMap* Arena::CreateMaybeMessage< ::BBSerializer::BBCubeMap >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBCubeMap >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> <|start_filename|>Code/BBearEditor/Engine/Scene/CoordinateSystem/BBCoordinateComponent.h<|end_filename|> #ifndef BBCOORDINATECOMPONENT_H #define BBCOORDINATECOMPONENT_H #include "Base/BBRenderableObject.h" #include "Utils/BBUtils.h" // The base class of each component to be rendered in the coordinate system class BBCoordinateComponent : public BBRenderableObject { protected: BBCoordinateComponent(); BBCoordinateComponent(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init() override; BBAxisFlags m_SelectedAxis; public: void setSelectedAxis(const BBAxisFlags &axis); private: void setVertexColor(const BBAxisFlags &axis, bool bSelected); void setVertexColor(int start, int end, const QVector3D &color); void setVertexColor(int start, int end, const QVector4D &color); }; // Conical arrow of the position Coordinate system class BBCoordinateArrow : public BBCoordinateComponent { public: BBCoordinateArrow(); BBCoordinateArrow(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init() override; }; // Straight line of coordinate axis class BBCoordinateAxis : public BBCoordinateComponent { public: BBCoordinateAxis(); BBCoordinateAxis(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init() override; }; // Face of the position Coordinate system class BBCoordinateRectFace : public BBCoordinateComponent { public: BBCoordinateRectFace(); BBCoordinateRectFace(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init() override; }; // Quarter circle of rotation Coordinate system class BBCoordinateQuarterCircle : public BBCoordinateComponent { public: BBCoordinateQuarterCircle(); BBCoordinateQuarterCircle(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init() override; }; class BBCoordinateCircle : public BBCoordinateComponent { public: BBCoordinateCircle(); BBCoordinateCircle(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init() override; }; // Tick marks on the Circle class BBCoordinateTickMark : public BBCoordinateComponent { public: BBCoordinateTickMark(); BBCoordinateTickMark(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init() override; }; // Sector of rotation angle class BBCoordinateSector : public BBCoordinateComponent { public: BBCoordinateSector(); BBCoordinateSector(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init() override; void render(BBCamera *pCamera) override; void setAngle(int nDeltaAngle); void reset(); private: int m_nAngle; }; // Cube of Scale Coordinate system class BBCoordinateCube : public BBCoordinateComponent { public: BBCoordinateCube(); BBCoordinateCube(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init() override; void move(const QVector3D &delta); private: float m_fHalfLength; static QVector3D m_Sign[8]; }; // Triangle face of Scale Coordinate system class BBCoordinateTriangleFace : public BBCoordinateComponent { public: BBCoordinateTriangleFace(); BBCoordinateTriangleFace(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init() override; }; #endif // BBCOORDINATECOMPONENT_H <|start_filename|>Code/BBearEditor/Engine/Render/BBLinkedList.cpp<|end_filename|> #include "BBLinkedList.h" BBLinkedList::BBLinkedList() { m_pNext = nullptr; } int BBLinkedList::getCount() { if (m_pNext == nullptr) { return 1; } else { return 1 + m_pNext->getCount(); } } void BBLinkedList::pushBack(BBLinkedList *pNode) { if (m_pNext == nullptr) { m_pNext = pNode; } else { m_pNext->pushBack(pNode); } } void BBLinkedList::insertAfter(BBLinkedList *pNode) { m_pNext = pNode->m_pNext; pNode->m_pNext = this; } void BBLinkedList::remove(BBLinkedList *pNode) { if (m_pNext == pNode) { m_pNext = m_pNext->m_pNext; pNode->m_pNext = nullptr; } else { m_pNext->remove(pNode); } } bool BBLinkedList::isEnd() { if (m_pNext == nullptr) return true; else return false; } void BBLinkedList::clear() { // to do } <|start_filename|>Code/BBearEditor/Engine/3D/Mesh/BBStaticMesh.h<|end_filename|> #ifndef BBSTATICMESH_H #define BBSTATICMESH_H #include "BBMesh.h" class BBStaticMesh : public BBMesh { public: BBStaticMesh(); BBStaticMesh(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init(const QString &path, BBBoundingBox3D *&pOutBoundingBox) override; private: void load(const QString &path, QList<QVector4D> &outPositions) override; }; #endif // BBSTATICMESH_H <|start_filename|>Code/BBearEditor/Engine/Physics/ClothSystem/BBCloth.cpp<|end_filename|> #include "BBCloth.h" #include "BBClothMesh.h" #include "../Body/BBClothBody.h" #include "../Solver/BBPBDSolver.h" #include "../Force/BBDirectionalForce.h" BBCloth::BBCloth(const QVector3D &position, int nWidth, int nHeight) : BBGameObject(position, QVector3D(0, 0, 0), QVector3D(1, 1, 1)) { m_nWidth = nWidth; m_nHeight = nHeight; m_pClothMesh = nullptr; m_pClothBody = nullptr; m_pPBDSolver = nullptr; } BBCloth::~BBCloth() { BB_SAFE_DELETE(m_pPBDSolver); BB_SAFE_DELETE(m_pClothBody); BB_SAFE_DELETE(m_pClothMesh); } void BBCloth::init() { m_pClothMesh = new BBClothMesh(m_nWidth, m_nHeight); m_pClothMesh->init(); m_pClothBody = new BBClothBody(m_pClothMesh, 0.5f, 0.5f); m_pClothBody->initPinConstraints(BBClothPinConstraintType::Left); m_pPBDSolver = new BBPBDSolver(); m_pPBDSolver->addBody(m_pClothBody); BBDirectionalForce *pWindForce = new BBDirectionalForce(5, 0, 0); m_pPBDSolver->addForce(pWindForce); BBDirectionalForce *pGravity = new BBDirectionalForce(0, -9.8f, 0); m_pPBDSolver->addForce(pGravity); } void BBCloth::render(BBCamera *pCamera) { m_pPBDSolver->solve(BB_CONSTANT_UPDATE_RATE_MS); m_pClothMesh->updatePhysicsCalculatedPositions(m_pClothBody); m_pClothMesh->render(pCamera); } void BBCloth::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { BBGameObject::setPosition(position, bUpdateLocalTransform); m_pClothMesh->setPosition(position, bUpdateLocalTransform); } <|start_filename|>Code/BBearEditor/Editor/PropertyManager/GroupManager/BBFluidRendererManager.cpp<|end_filename|> #include "BBFluidRendererManager.h" #include "Physics/FluidSystem/BBSPHFluidRenderer.h" BBFluidRendererManager::BBFluidRendererManager(BBSPHFluidRenderer *pFluidRenderer, QWidget *pParent) : BBGroupManager("Render", BB_PATH_RESOURCE_ICON(render.png), pParent) { m_pFluidRenderer = pFluidRenderer; QCheckBox *pTriggerSSF = new QCheckBox(this); QObject::connect(pTriggerSSF, SIGNAL(clicked(bool)), this, SLOT(switchSSF(bool))); addFactory("SSF", pTriggerSSF); QPushButton *pButtonReset = new QPushButton("Reset Particles", this); pButtonReset->setStyleSheet("QPushButton { border: none; border-radius: 2px; padding-left: 3px; padding-right: 3px; color: #d6dfeb; font: 9pt \"Arial\"; background: #0ebf9c; }" "QPushButton:hover { background: #8c0ebf9c; }"); QObject::connect(pButtonReset, SIGNAL(clicked()), this, SLOT(resetFluidParticles())); addFactory("", pButtonReset, 1, Qt::AlignLeft); } BBFluidRendererManager::~BBFluidRendererManager() { } void BBFluidRendererManager::switchSSF(bool bEnable) { m_pFluidRenderer->switchSSF(bEnable); } void BBFluidRendererManager::resetFluidParticles() { m_pFluidRenderer->resetFluidParticles(); } <|start_filename|>Code/BBearEditor/Editor/FileSystem/BBFilePathBarWidget.h<|end_filename|> #ifndef BBFILEPATHBARWIDGET_H #define BBFILEPATHBARWIDGET_H #include <QWidget> #include <QScrollArea> class BBFilePathBarScrollArea : public QScrollArea { Q_OBJECT public: BBFilePathBarScrollArea(QWidget *pParent = nullptr); private slots: void moveToEnd(); void moveToLeft(); void moveToRight(); private: void scroll(int nStep); }; class BBFilePathBarWidget : public QWidget { Q_OBJECT public: BBFilePathBarWidget(QWidget *pParent = nullptr); void showFolderPath(const QString &path); private slots: void accessFolder(int id); signals: void accessFolder(const QString &folderPath); private: QString m_CurrentPath; QStringList m_HierarchyDirs; }; #endif // BBFILEPATHBARWIDGET_H <|start_filename|>Code/BBearEditor/Engine/Render/Shader/BBBaseShader.h<|end_filename|> #ifndef BBBASESHADER_H #define BBBASESHADER_H #include "Render/BBBaseRenderComponent.h" #include "Render/BBMaterialProperty.h" class BBAttribute; class BBUniformUpdater; enum BBVertexBufferType { VBO, SSBO }; class BBBaseShader : public BBBaseRenderComponent { public: BBBaseShader(); inline GLuint getProgram() const { return m_Program; } void activeAttributes(); inline BBVertexBufferType getVertexBufferType() { return m_eVertexBufferType; } inline BBUniformUpdater* getUniforms() { return m_pUniforms; } inline bool isWriteFBO() { return m_bWriteFBO; } protected: void initAttributes(); void initUniforms(); BBUniformUpdater* initUniformFloat(GLint location, const char *pUniformName); BBUniformUpdater* initUniformFloatArray(GLint location, const char *pUniformName, int nArrayCount); BBUniformUpdater* initUniformMatrix4(GLint location, const char *pUniformName); BBUniformUpdater* initUniformVector4(GLint location, const char *pUniformName); BBUniformUpdater* initUniformVector4Array(GLint location, const char *pUniformName, int nArrayCount); BBUniformUpdater* initUniformSampler2D(GLint location, const char *pUniformName, int &nSlotIndex); BBUniformUpdater* initUniformSampler3D(GLint location, const char *pUniformName, int &nSlotIndex); BBUniformUpdater* initUniformSamplerCube(GLint location, const char *pUniformName, int &nSlotIndex); void appendUniformUpdater(BBUniformUpdater *pUniformUpdater); GLuint compileShader(GLenum shaderType, const char *shaderCode); GLuint m_Program; BBAttribute *m_pAttributes; // Used to determine whether to bind VBO or SSBO when rendering in drawcall BBVertexBufferType m_eVertexBufferType; BBUniformUpdater *m_pUniforms; QMap<std::string, BBMaterialProperty*> m_Properties; bool m_bWriteFBO; }; #endif // BBBASESHADER_H <|start_filename|>Code/BBearEditor/Engine/2D/BBSelectionRegion.h<|end_filename|> #ifndef BBSELECTIONREGION_H #define BBSELECTIONREGION_H #include <QVector3D> class BBSelectionRegion { public: BBSelectionRegion(); void setRect(float x, float y, float w, float h); void render(); void setVisibility(bool bVisible); private: QVector3D m_Vertexes[4]; bool m_bVisible; }; #endif // BBSELECTIONREGION_H <|start_filename|>Resources/shaders/HeatDistort.frag<|end_filename|> varying vec4 V_Texcoord; varying vec4 V_ScreenUV; uniform sampler2D BBColorFBO; uniform sampler2D DistortTex; uniform float Distort; void main(void) { vec4 distort_color = texture2D(DistortTex, V_Texcoord.xy); vec2 uv = mix(V_ScreenUV.xy, distort_color.xy, Distort); gl_FragColor = texture2D(BBColorFBO, uv); } <|start_filename|>External/ProtoBuffer/lib/CMakeFiles/Makefile.cmake<|end_filename|> # CMAKE generated file: DO NOT EDIT! # Generated by "MinGW Makefiles" Generator, CMake Version 3.20 # The generator used is: set(CMAKE_DEPENDS_GENERATOR "MinGW Makefiles") # The top level Makefile was generated from the following files: set(CMAKE_MAKEFILE_DEPENDS "CMakeCache.txt" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CMakeCInformation.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CMakeCXXInformation.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CMakeCommonLanguageInclude.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CMakeDependentOption.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CMakeGenericSystem.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CMakeInitializeConfigs.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CMakeLanguageInformation.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CMakeRCInformation.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CMakeSystemSpecificInformation.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CMakeSystemSpecificInitialize.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CheckCSourceCompiles.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CheckCXXSourceCompiles.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CheckIncludeFile.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/CheckLibraryExists.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Compiler/CMakeCommonCompilerMacros.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Compiler/GNU-C.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Compiler/GNU-CXX.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Compiler/GNU.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/FindPackageHandleStandardArgs.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/FindPackageMessage.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/FindThreads.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/GNUInstallDirs.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Internal/CheckSourceCompiles.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Platform/Windows-GNU-C-ABI.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Platform/Windows-GNU-C.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Platform/Windows-GNU-CXX-ABI.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Platform/Windows-GNU-CXX.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Platform/Windows-GNU.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Platform/Windows-windres.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Platform/Windows.cmake" "D:/cmake-3.20.3-windows-x86_64/share/cmake-3.20/Modules/Platform/WindowsPaths.cmake" "CMakeFiles/3.20.3/CMakeCCompiler.cmake" "CMakeFiles/3.20.3/CMakeCXXCompiler.cmake" "CMakeFiles/3.20.3/CMakeRCCompiler.cmake" "CMakeFiles/3.20.3/CMakeSystem.cmake" "D:/workspace/protobuf-3.16.0/cmake/CMakeLists.txt" "D:/workspace/protobuf-3.16.0/cmake/install.cmake" "D:/workspace/protobuf-3.16.0/cmake/libprotobuf-lite.cmake" "D:/workspace/protobuf-3.16.0/cmake/libprotobuf.cmake" "D:/workspace/protobuf-3.16.0/cmake/protobuf-config-version.cmake.in" "D:/workspace/protobuf-3.16.0/cmake/protobuf-config.cmake.in" "D:/workspace/protobuf-3.16.0/cmake/protobuf-lite.pc.cmake" "D:/workspace/protobuf-3.16.0/cmake/protobuf-module.cmake.in" "D:/workspace/protobuf-3.16.0/cmake/protobuf-options.cmake" "D:/workspace/protobuf-3.16.0/cmake/protobuf.pc.cmake" ) # The corresponding makefile is: set(CMAKE_MAKEFILE_OUTPUTS "Makefile" "CMakeFiles/cmake.check_cache" ) # Byproducts of CMake generate step: set(CMAKE_MAKEFILE_PRODUCTS "protobuf.pc" "protobuf-lite.pc" "lib/cmake/protobuf/protobuf-config.cmake" "lib/cmake/protobuf/protobuf-config-version.cmake" "lib/cmake/protobuf/protobuf-module.cmake" "lib/cmake/protobuf/protobuf-options.cmake" "CMakeFiles/CMakeDirectoryInformation.cmake" ) # Dependency information for all targets: set(CMAKE_DEPEND_INFO_FILES "CMakeFiles/libprotobuf-lite.dir/DependInfo.cmake" "CMakeFiles/libprotobuf.dir/DependInfo.cmake" ) <|start_filename|>Code/BBearEditor/Engine/Render/BufferObject/BBElementBufferObject.h<|end_filename|> #ifndef BBELEMENTBUFFEROBJECT_H #define BBELEMENTBUFFEROBJECT_H #include "BBBufferObject.h" class BBElementBufferObject : public BBBufferObject { public: BBElementBufferObject(int nIndexCount); void setSize(int nIndexCount, GLenum hint = GL_STATIC_DRAW); void submitData(const unsigned short *pIndexes, int nIndexCount); void draw(GLenum eDrawPrimitiveType, int nIndexCount, int nDrawStartIndex); private: }; #endif // BBELEMENTBUFFEROBJECT_H <|start_filename|>Code/BBearEditor/Engine/Geometry/BBRay.h<|end_filename|> #ifndef BBRAY_H #define BBRAY_H #include "Render/BBBaseRenderComponent.h" #include <cfloat> class BBModel; enum BBPlaneName { XOY = 0, XOZ = 1, YOZ = 2 }; struct BBHitInfo { BBHitInfo() { m_fDistance = FLT_MAX; m_pModel = nullptr; } QVector3D m_Position; QVector2D m_Texcoords; QVector3D m_Normal; float m_fDistance; BBModel *m_pModel; }; class BBRay { public: BBRay(const QVector3D &origin = QVector3D(0, 0, 0), const QVector3D &direction = QVector3D(0, 0, -1)); BBRay(const GLdouble &nearX, const GLdouble &nearY, const GLdouble &nearZ, const GLdouble &farX, const GLdouble &farY, const GLdouble &farZ); void setRay(const QVector3D &origin = QVector3D(0, 0, 0), const QVector3D &direction = QVector3D(0, 0, -1)); QVector3D computeIntersectWithXOZPlane(float y) const; QVector3D computeIntersectWithXOYPlane(float z) const; QVector3D computeIntersectWithYOZPlane(float x) const; bool computeIntersectWithPlane(const QVector3D &point1, const QVector3D &point2, const QVector3D &point3, QVector3D &outIntersection) const; bool computeIntersectWithPlane(const QVector3D &point1, const QVector3D &point2, const QVector3D &point3, QVector3D &outNormal, QVector3D &outIntersection) const; bool computeIntersectWithPlane(const QVector3D &point, const QVector3D &normal, QVector3D &outIntersection) const; bool computeIntersectWithTriangle(const QVector3D &point1, const QVector3D &point2, const QVector3D &point3, QVector3D &outIntersection) const; bool computeIntersectWithTriangle(const QVector3D &point1, const QVector3D &point2, const QVector3D &point3, QVector3D &outNormal, QVector3D &outIntersectionPos, float &outIntersectionU, float &outIntersectionV) const; bool computeIntersectWithRectangle(const QVector3D &point1, const QVector3D &point2, const QVector3D &point3, const QVector3D &point4, QVector3D &outIntersection) const; float computeIntersectDistance(const QVector3D &intersection) const; // Circle parallel to coordinate plane bool computeIntersectWithCircle(const QVector3D &center, float fRadius, const BBPlaneName &ePlaneName, QVector3D &outIntersection) const; bool computeIntersectWithQuarterCircle(const QVector3D &center, float fRadius, const BBPlaneName &ePlaneName, QVector3D &outIntersection, const QVector3D &quadrantFlag) const; QVector3D getDirection() const { return m_Direction; } inline QVector3D getNearPoint() { return m_NearPoint; } inline QVector3D getFarPoint() { return m_FarPoint; } private: QVector3D m_NearPoint; QVector3D m_FarPoint; QVector3D m_Direction; }; #endif // BBRAY_H <|start_filename|>Code/BBearEditor/Editor/PropertyManager/BBHeadManager.h<|end_filename|> #ifndef BBHEADMANAGER_H #define BBHEADMANAGER_H #include <QWidget> class QLineEdit; class BBGameObject; class QPushButton; class BBEnumFactory; class QLabel; class BBMaterial; // manage name, class name, visibility, and so on // showed in the top of property manager class BBBaseInformationManager : public QWidget { Q_OBJECT public: BBBaseInformationManager(BBGameObject *pGameObject, QWidget *pParent = 0); ~BBBaseInformationManager(); // void rename(QString newName); private slots: virtual void changeVisibility(); // void finishRename(); signals: void visibilityChanged(BBGameObject *pGameObject, bool bVisible); // void nameChanged(GameObject *gameObject); protected: void setVisibilityButtonChecked(bool bChecked); QPushButton *m_pVisibilityButton; QLineEdit *m_pNameEdit; BBGameObject *m_pCurrentGameObject; }; // manage base information of BBGameObjectSet class BBSetBaseInformationManager : public BBBaseInformationManager { Q_OBJECT public: BBSetBaseInformationManager(BBGameObject *pCenterGameObject, const QList<BBGameObject*> &gameObjectSet, QWidget *pParent = 0); private slots: void changeVisibility() override; signals: void visibilityChanged(const QList<BBGameObject*> &gameObjectSet, bool bVisible); private: QList<BBGameObject*> m_CurrentGameObjectSet; }; class BBMaterialManager : public QWidget { Q_OBJECT public: BBMaterialManager(const QString &filePath, QWidget *pParent = nullptr); ~BBMaterialManager(); inline BBMaterial* getMaterial() { return m_pMaterial; } private slots: void changeCurrentVShader(const QString &name); void changeCurrentFShader(const QString &name); private: void setIcon(); void setShaderEnumFactory(QWidget *pParent); BBMaterial* m_pMaterial; QString m_FilePath; QLabel *m_pIcon; BBEnumFactory *m_pVShaderEnumFactory; BBEnumFactory *m_pFShaderEnumFactory; }; #endif // BBHEADMANAGER_H <|start_filename|>Code/BBearEditor/Engine/3D/Mesh/BBProcedureMesh.cpp<|end_filename|> #include "BBProcedureMesh.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BBMaterial.h" #include "Render/BBDrawCall.h" #include "Render/BBRenderPass.h" #include "Geometry/BBBoundingBox.h" BBProcedureMesh::BBProcedureMesh() : BBProcedureMesh(0, 0, 0, 0, 0, 0, 1, 1, 1) { } BBProcedureMesh::BBProcedureMesh(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz) : BBMesh(px, py, pz, rx, ry, rz, sx, sy, sz) { } void BBProcedureMesh::init(const QString &userData, BBBoundingBox3D *&pOutBoundingBox) { init1(); QList<QVector4D> positions; load(userData, positions); m_pVBO->computeTangent(m_pIndexes, m_nIndexCount); m_pVBO->computeSmoothNormal(); // create bounding box pOutBoundingBox = new BBAABBBoundingBox3D(m_Position.x(), m_Position.y(), m_Position.z(), m_Rotation.x(), m_Rotation.y(), m_Rotation.z(), m_Scale.x(), m_Scale.y(), m_Scale.z(), positions); pOutBoundingBox->init(); m_pCurrentMaterial->init("base", BB_PATH_RESOURCE_SHADER(base.vert), BB_PATH_RESOURCE_SHADER(base.frag)); // m_pCurrentMaterial->getBaseRenderPass()->setPolygonMode(GL_LINE); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_QUADS, m_nIndexCount, 0); appendDrawCall(pDrawCall); } void BBProcedureMesh::load(const QString &userData, QList<QVector4D> &outPositions) { outPositions = m_pVBO->getPositions(); } /** * @brief BBProcedureMesh::init0 A plane consists of quadrilateral primitive */ void BBProcedureMesh::init0() { m_pVBO = new BBVertexBufferObject(121); for (int i = -5; i <= 5; i++) { for (int j = -5; j <= 5; j++) { int nIndex = (i + 5) * 11 + (j + 5); m_pVBO->setPosition(nIndex, 1.0f * j, 0.0f, 1.0f * i); m_pVBO->setColor(nIndex, BBConstant::m_White); m_pVBO->setNormal(nIndex, 0.0f, 1.0f, 0.0f); } } m_nIndexCount = 400; m_pIndexes = new unsigned short[m_nIndexCount]; unsigned short *pCurrent = m_pIndexes; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { int nIndex = i * 11 + j; *(pCurrent++) = nIndex; *(pCurrent++) = nIndex + 11; *(pCurrent++) = nIndex + 12; *(pCurrent++) = nIndex + 1; } } } /** * @brief BBProcedureMesh::init1 A cube consists of quadrilateral primitive */ void BBProcedureMesh::init1() { m_pVBO = new BBVertexBufferObject(8); m_pVBO->setPosition(0, -1, 1, 1); m_pVBO->setPosition(1, -1, -1, 1); m_pVBO->setPosition(2, 1, -1, 1); m_pVBO->setPosition(3, 1, 1, 1); m_pVBO->setPosition(4, 1, -1, -1); m_pVBO->setPosition(5, 1, 1, -1); m_pVBO->setPosition(6, -1, -1, -1); m_pVBO->setPosition(7, -1, 1, -1); for (int i = 0; i < 8; i++) { m_pVBO->setColor(i, BBConstant::m_White); } m_nIndexCount = 24; unsigned short indexes[] = {0, 1, 2, 3, 3, 2, 4, 5, 5, 4, 6, 7, 7, 0, 3, 5, 7, 6, 1, 0, 6, 1, 2, 4}; m_pIndexes = new unsigned short[m_nIndexCount]; for (int i = 0; i < m_nIndexCount; i++) { m_pIndexes[i] = indexes[i]; } } <|start_filename|>Code/BBearEditor/Engine/Serializer/BBScene.pb.cc<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBScene.proto #include "BBScene.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace BBSerializer { constexpr BBScene::BBScene( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : item_() , gameobject_(){} struct BBSceneDefaultTypeInternal { constexpr BBSceneDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBSceneDefaultTypeInternal() {} union { BBScene _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBSceneDefaultTypeInternal _BBScene_default_instance_; } // namespace BBSerializer static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_BBScene_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_BBScene_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_BBScene_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_BBScene_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBScene, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBScene, item_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBScene, gameobject_), }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::BBSerializer::BBScene)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBScene_default_instance_), }; const char descriptor_table_protodef_BBScene_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\rBBScene.proto\022\014BBSerializer\032\037BBHierarc" "hyTreeWidgetItem.proto\032\022BBGameObject.pro" "to\"p\n\007BBScene\0225\n\004item\030\001 \003(\0132\'.BBSerializ" "er.BBHierarchyTreeWidgetItem\022.\n\ngameObje" "ct\030\002 \003(\0132\032.BBSerializer.BBGameObjectb\006pr" "oto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_BBScene_2eproto_deps[2] = { &::descriptor_table_BBGameObject_2eproto, &::descriptor_table_BBHierarchyTreeWidgetItem_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_BBScene_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBScene_2eproto = { false, false, 204, descriptor_table_protodef_BBScene_2eproto, "BBScene.proto", &descriptor_table_BBScene_2eproto_once, descriptor_table_BBScene_2eproto_deps, 2, 1, schemas, file_default_instances, TableStruct_BBScene_2eproto::offsets, file_level_metadata_BBScene_2eproto, file_level_enum_descriptors_BBScene_2eproto, file_level_service_descriptors_BBScene_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_BBScene_2eproto_getter() { return &descriptor_table_BBScene_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_BBScene_2eproto(&descriptor_table_BBScene_2eproto); namespace BBSerializer { // =================================================================== class BBScene::_Internal { public: }; void BBScene::clear_item() { item_.Clear(); } void BBScene::clear_gameobject() { gameobject_.Clear(); } BBScene::BBScene(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), item_(arena), gameobject_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBScene) } BBScene::BBScene(const BBScene& from) : ::PROTOBUF_NAMESPACE_ID::Message(), item_(from.item_), gameobject_(from.gameobject_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:BBSerializer.BBScene) } void BBScene::SharedCtor() { } BBScene::~BBScene() { // @@protoc_insertion_point(destructor:BBSerializer.BBScene) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBScene::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void BBScene::ArenaDtor(void* object) { BBScene* _this = reinterpret_cast< BBScene* >(object); (void)_this; } void BBScene::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBScene::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBScene::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBScene) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; item_.Clear(); gameobject_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBScene::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // repeated .BBSerializer.BBHierarchyTreeWidgetItem item = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_item(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<10>(ptr)); } else goto handle_unusual; continue; // repeated .BBSerializer.BBGameObject gameObject = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_gameobject(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<18>(ptr)); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBScene::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBScene) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .BBSerializer.BBHierarchyTreeWidgetItem item = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_item_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(1, this->_internal_item(i), target, stream); } // repeated .BBSerializer.BBGameObject gameObject = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_gameobject_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(2, this->_internal_gameobject(i), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBScene) return target; } size_t BBScene::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBScene) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .BBSerializer.BBHierarchyTreeWidgetItem item = 1; total_size += 1UL * this->_internal_item_size(); for (const auto& msg : this->item_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .BBSerializer.BBGameObject gameObject = 2; total_size += 1UL * this->_internal_gameobject_size(); for (const auto& msg : this->gameobject_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBScene::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBScene) GOOGLE_DCHECK_NE(&from, this); const BBScene* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBScene>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBScene) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBScene) MergeFrom(*source); } } void BBScene::MergeFrom(const BBScene& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBScene) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; item_.MergeFrom(from.item_); gameobject_.MergeFrom(from.gameobject_); } void BBScene::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBScene) if (&from == this) return; Clear(); MergeFrom(from); } void BBScene::CopyFrom(const BBScene& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBScene) if (&from == this) return; Clear(); MergeFrom(from); } bool BBScene::IsInitialized() const { return true; } void BBScene::InternalSwap(BBScene* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); item_.InternalSwap(&other->item_); gameobject_.InternalSwap(&other->gameobject_); } ::PROTOBUF_NAMESPACE_ID::Metadata BBScene::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBScene_2eproto_getter, &descriptor_table_BBScene_2eproto_once, file_level_metadata_BBScene_2eproto[0]); } // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::BBSerializer::BBScene* Arena::CreateMaybeMessage< ::BBSerializer::BBScene >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBScene >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> <|start_filename|>Code/BBearEditor/Engine/Render/Shader/BBShader.h<|end_filename|> #ifndef BBSHADER_H #define BBSHADER_H #include "BBBaseShader.h" class BBAttribute; class BBUniformUpdater; class BBShader : public BBBaseShader { public: BBShader(); virtual ~BBShader(); static BBShader* loadShader(const char *name, const QString &vShaderPath, const QString &fShaderPath, const QString &gShaderPath = ""); void init(const QString &vShaderPath, const QString &fShaderPath, const QString &gShaderPath = ""); inline void setShaderName(const char *name) { strcpy(m_ShaderName, name); } inline void setVShaderPath(const QString &path) { m_VShaderPath = path; } inline void setFShaderPath(const QString &path) { m_FShaderPath = path; } inline char* getShaderName() { return m_ShaderName; } inline QString getVShaderPath() { return m_VShaderPath; } inline QString getFShaderPath() { return m_FShaderPath; } private: GLuint createProgram(GLuint vShader, GLuint fShader, GLuint gShader); static QMap<std::string, BBShader*> m_CachedShaders; char m_ShaderName[64]; QString m_VShaderPath; QString m_FShaderPath; }; #endif // BBSHADER_H <|start_filename|>Code/BBearEditor/Engine/Serializer/BBCubeMap.pb.h<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBCubeMap.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_BBCubeMap_2eproto #define GOOGLE_PROTOBUF_INCLUDED_BBCubeMap_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3016000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3016000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_BBCubeMap_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_BBCubeMap_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBCubeMap_2eproto; namespace BBSerializer { class BBCubeMap; struct BBCubeMapDefaultTypeInternal; extern BBCubeMapDefaultTypeInternal _BBCubeMap_default_instance_; } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> ::BBSerializer::BBCubeMap* Arena::CreateMaybeMessage<::BBSerializer::BBCubeMap>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace BBSerializer { // =================================================================== class BBCubeMap PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:BBSerializer.BBCubeMap) */ { public: inline BBCubeMap() : BBCubeMap(nullptr) {} ~BBCubeMap() override; explicit constexpr BBCubeMap(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); BBCubeMap(const BBCubeMap& from); BBCubeMap(BBCubeMap&& from) noexcept : BBCubeMap() { *this = ::std::move(from); } inline BBCubeMap& operator=(const BBCubeMap& from) { CopyFrom(from); return *this; } inline BBCubeMap& operator=(BBCubeMap&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const BBCubeMap& default_instance() { return *internal_default_instance(); } static inline const BBCubeMap* internal_default_instance() { return reinterpret_cast<const BBCubeMap*>( &_BBCubeMap_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(BBCubeMap& a, BBCubeMap& b) { a.Swap(&b); } inline void Swap(BBCubeMap* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(BBCubeMap* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline BBCubeMap* New() const final { return CreateMaybeMessage<BBCubeMap>(nullptr); } BBCubeMap* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<BBCubeMap>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const BBCubeMap& from); void MergeFrom(const BBCubeMap& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BBCubeMap* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "BBSerializer.BBCubeMap"; } protected: explicit BBCubeMap(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kPositiveXFieldNumber = 1, kNegativeXFieldNumber = 2, kPositiveYFieldNumber = 3, kNegativeYFieldNumber = 4, kPositiveZFieldNumber = 5, kNegativeZFieldNumber = 6, }; // string positiveX = 1; bool has_positivex() const; private: bool _internal_has_positivex() const; public: void clear_positivex(); const std::string& positivex() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_positivex(ArgT0&& arg0, ArgT... args); std::string* mutable_positivex(); std::string* release_positivex(); void set_allocated_positivex(std::string* positivex); private: const std::string& _internal_positivex() const; void _internal_set_positivex(const std::string& value); std::string* _internal_mutable_positivex(); public: // string negativeX = 2; bool has_negativex() const; private: bool _internal_has_negativex() const; public: void clear_negativex(); const std::string& negativex() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_negativex(ArgT0&& arg0, ArgT... args); std::string* mutable_negativex(); std::string* release_negativex(); void set_allocated_negativex(std::string* negativex); private: const std::string& _internal_negativex() const; void _internal_set_negativex(const std::string& value); std::string* _internal_mutable_negativex(); public: // string positiveY = 3; bool has_positivey() const; private: bool _internal_has_positivey() const; public: void clear_positivey(); const std::string& positivey() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_positivey(ArgT0&& arg0, ArgT... args); std::string* mutable_positivey(); std::string* release_positivey(); void set_allocated_positivey(std::string* positivey); private: const std::string& _internal_positivey() const; void _internal_set_positivey(const std::string& value); std::string* _internal_mutable_positivey(); public: // string negativeY = 4; bool has_negativey() const; private: bool _internal_has_negativey() const; public: void clear_negativey(); const std::string& negativey() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_negativey(ArgT0&& arg0, ArgT... args); std::string* mutable_negativey(); std::string* release_negativey(); void set_allocated_negativey(std::string* negativey); private: const std::string& _internal_negativey() const; void _internal_set_negativey(const std::string& value); std::string* _internal_mutable_negativey(); public: // string positiveZ = 5; bool has_positivez() const; private: bool _internal_has_positivez() const; public: void clear_positivez(); const std::string& positivez() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_positivez(ArgT0&& arg0, ArgT... args); std::string* mutable_positivez(); std::string* release_positivez(); void set_allocated_positivez(std::string* positivez); private: const std::string& _internal_positivez() const; void _internal_set_positivez(const std::string& value); std::string* _internal_mutable_positivez(); public: // string negativeZ = 6; bool has_negativez() const; private: bool _internal_has_negativez() const; public: void clear_negativez(); const std::string& negativez() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_negativez(ArgT0&& arg0, ArgT... args); std::string* mutable_negativez(); std::string* release_negativez(); void set_allocated_negativez(std::string* negativez); private: const std::string& _internal_negativez() const; void _internal_set_negativez(const std::string& value); std::string* _internal_mutable_negativez(); public: // @@protoc_insertion_point(class_scope:BBSerializer.BBCubeMap) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr positivex_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr negativex_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr positivey_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr negativey_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr positivez_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr negativez_; friend struct ::TableStruct_BBCubeMap_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // BBCubeMap // string positiveX = 1; inline bool BBCubeMap::_internal_has_positivex() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool BBCubeMap::has_positivex() const { return _internal_has_positivex(); } inline void BBCubeMap::clear_positivex() { positivex_.ClearToEmpty(); _has_bits_[0] &= ~0x00000001u; } inline const std::string& BBCubeMap::positivex() const { // @@protoc_insertion_point(field_get:BBSerializer.BBCubeMap.positiveX) return _internal_positivex(); } template <typename ArgT0, typename... ArgT> PROTOBUF_ALWAYS_INLINE inline void BBCubeMap::set_positivex(ArgT0&& arg0, ArgT... args) { _has_bits_[0] |= 0x00000001u; positivex_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArena()); // @@protoc_insertion_point(field_set:BBSerializer.BBCubeMap.positiveX) } inline std::string* BBCubeMap::mutable_positivex() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBCubeMap.positiveX) return _internal_mutable_positivex(); } inline const std::string& BBCubeMap::_internal_positivex() const { return positivex_.Get(); } inline void BBCubeMap::_internal_set_positivex(const std::string& value) { _has_bits_[0] |= 0x00000001u; positivex_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline std::string* BBCubeMap::_internal_mutable_positivex() { _has_bits_[0] |= 0x00000001u; return positivex_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* BBCubeMap::release_positivex() { // @@protoc_insertion_point(field_release:BBSerializer.BBCubeMap.positiveX) if (!_internal_has_positivex()) { return nullptr; } _has_bits_[0] &= ~0x00000001u; return positivex_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void BBCubeMap::set_allocated_positivex(std::string* positivex) { if (positivex != nullptr) { _has_bits_[0] |= 0x00000001u; } else { _has_bits_[0] &= ~0x00000001u; } positivex_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), positivex, GetArena()); // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBCubeMap.positiveX) } // string negativeX = 2; inline bool BBCubeMap::_internal_has_negativex() const { bool value = (_has_bits_[0] & 0x00000002u) != 0; return value; } inline bool BBCubeMap::has_negativex() const { return _internal_has_negativex(); } inline void BBCubeMap::clear_negativex() { negativex_.ClearToEmpty(); _has_bits_[0] &= ~0x00000002u; } inline const std::string& BBCubeMap::negativex() const { // @@protoc_insertion_point(field_get:BBSerializer.BBCubeMap.negativeX) return _internal_negativex(); } template <typename ArgT0, typename... ArgT> PROTOBUF_ALWAYS_INLINE inline void BBCubeMap::set_negativex(ArgT0&& arg0, ArgT... args) { _has_bits_[0] |= 0x00000002u; negativex_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArena()); // @@protoc_insertion_point(field_set:BBSerializer.BBCubeMap.negativeX) } inline std::string* BBCubeMap::mutable_negativex() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBCubeMap.negativeX) return _internal_mutable_negativex(); } inline const std::string& BBCubeMap::_internal_negativex() const { return negativex_.Get(); } inline void BBCubeMap::_internal_set_negativex(const std::string& value) { _has_bits_[0] |= 0x00000002u; negativex_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline std::string* BBCubeMap::_internal_mutable_negativex() { _has_bits_[0] |= 0x00000002u; return negativex_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* BBCubeMap::release_negativex() { // @@protoc_insertion_point(field_release:BBSerializer.BBCubeMap.negativeX) if (!_internal_has_negativex()) { return nullptr; } _has_bits_[0] &= ~0x00000002u; return negativex_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void BBCubeMap::set_allocated_negativex(std::string* negativex) { if (negativex != nullptr) { _has_bits_[0] |= 0x00000002u; } else { _has_bits_[0] &= ~0x00000002u; } negativex_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), negativex, GetArena()); // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBCubeMap.negativeX) } // string positiveY = 3; inline bool BBCubeMap::_internal_has_positivey() const { bool value = (_has_bits_[0] & 0x00000004u) != 0; return value; } inline bool BBCubeMap::has_positivey() const { return _internal_has_positivey(); } inline void BBCubeMap::clear_positivey() { positivey_.ClearToEmpty(); _has_bits_[0] &= ~0x00000004u; } inline const std::string& BBCubeMap::positivey() const { // @@protoc_insertion_point(field_get:BBSerializer.BBCubeMap.positiveY) return _internal_positivey(); } template <typename ArgT0, typename... ArgT> PROTOBUF_ALWAYS_INLINE inline void BBCubeMap::set_positivey(ArgT0&& arg0, ArgT... args) { _has_bits_[0] |= 0x00000004u; positivey_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArena()); // @@protoc_insertion_point(field_set:BBSerializer.BBCubeMap.positiveY) } inline std::string* BBCubeMap::mutable_positivey() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBCubeMap.positiveY) return _internal_mutable_positivey(); } inline const std::string& BBCubeMap::_internal_positivey() const { return positivey_.Get(); } inline void BBCubeMap::_internal_set_positivey(const std::string& value) { _has_bits_[0] |= 0x00000004u; positivey_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline std::string* BBCubeMap::_internal_mutable_positivey() { _has_bits_[0] |= 0x00000004u; return positivey_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* BBCubeMap::release_positivey() { // @@protoc_insertion_point(field_release:BBSerializer.BBCubeMap.positiveY) if (!_internal_has_positivey()) { return nullptr; } _has_bits_[0] &= ~0x00000004u; return positivey_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void BBCubeMap::set_allocated_positivey(std::string* positivey) { if (positivey != nullptr) { _has_bits_[0] |= 0x00000004u; } else { _has_bits_[0] &= ~0x00000004u; } positivey_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), positivey, GetArena()); // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBCubeMap.positiveY) } // string negativeY = 4; inline bool BBCubeMap::_internal_has_negativey() const { bool value = (_has_bits_[0] & 0x00000008u) != 0; return value; } inline bool BBCubeMap::has_negativey() const { return _internal_has_negativey(); } inline void BBCubeMap::clear_negativey() { negativey_.ClearToEmpty(); _has_bits_[0] &= ~0x00000008u; } inline const std::string& BBCubeMap::negativey() const { // @@protoc_insertion_point(field_get:BBSerializer.BBCubeMap.negativeY) return _internal_negativey(); } template <typename ArgT0, typename... ArgT> PROTOBUF_ALWAYS_INLINE inline void BBCubeMap::set_negativey(ArgT0&& arg0, ArgT... args) { _has_bits_[0] |= 0x00000008u; negativey_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArena()); // @@protoc_insertion_point(field_set:BBSerializer.BBCubeMap.negativeY) } inline std::string* BBCubeMap::mutable_negativey() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBCubeMap.negativeY) return _internal_mutable_negativey(); } inline const std::string& BBCubeMap::_internal_negativey() const { return negativey_.Get(); } inline void BBCubeMap::_internal_set_negativey(const std::string& value) { _has_bits_[0] |= 0x00000008u; negativey_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline std::string* BBCubeMap::_internal_mutable_negativey() { _has_bits_[0] |= 0x00000008u; return negativey_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* BBCubeMap::release_negativey() { // @@protoc_insertion_point(field_release:BBSerializer.BBCubeMap.negativeY) if (!_internal_has_negativey()) { return nullptr; } _has_bits_[0] &= ~0x00000008u; return negativey_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void BBCubeMap::set_allocated_negativey(std::string* negativey) { if (negativey != nullptr) { _has_bits_[0] |= 0x00000008u; } else { _has_bits_[0] &= ~0x00000008u; } negativey_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), negativey, GetArena()); // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBCubeMap.negativeY) } // string positiveZ = 5; inline bool BBCubeMap::_internal_has_positivez() const { bool value = (_has_bits_[0] & 0x00000010u) != 0; return value; } inline bool BBCubeMap::has_positivez() const { return _internal_has_positivez(); } inline void BBCubeMap::clear_positivez() { positivez_.ClearToEmpty(); _has_bits_[0] &= ~0x00000010u; } inline const std::string& BBCubeMap::positivez() const { // @@protoc_insertion_point(field_get:BBSerializer.BBCubeMap.positiveZ) return _internal_positivez(); } template <typename ArgT0, typename... ArgT> PROTOBUF_ALWAYS_INLINE inline void BBCubeMap::set_positivez(ArgT0&& arg0, ArgT... args) { _has_bits_[0] |= 0x00000010u; positivez_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArena()); // @@protoc_insertion_point(field_set:BBSerializer.BBCubeMap.positiveZ) } inline std::string* BBCubeMap::mutable_positivez() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBCubeMap.positiveZ) return _internal_mutable_positivez(); } inline const std::string& BBCubeMap::_internal_positivez() const { return positivez_.Get(); } inline void BBCubeMap::_internal_set_positivez(const std::string& value) { _has_bits_[0] |= 0x00000010u; positivez_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline std::string* BBCubeMap::_internal_mutable_positivez() { _has_bits_[0] |= 0x00000010u; return positivez_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* BBCubeMap::release_positivez() { // @@protoc_insertion_point(field_release:BBSerializer.BBCubeMap.positiveZ) if (!_internal_has_positivez()) { return nullptr; } _has_bits_[0] &= ~0x00000010u; return positivez_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void BBCubeMap::set_allocated_positivez(std::string* positivez) { if (positivez != nullptr) { _has_bits_[0] |= 0x00000010u; } else { _has_bits_[0] &= ~0x00000010u; } positivez_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), positivez, GetArena()); // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBCubeMap.positiveZ) } // string negativeZ = 6; inline bool BBCubeMap::_internal_has_negativez() const { bool value = (_has_bits_[0] & 0x00000020u) != 0; return value; } inline bool BBCubeMap::has_negativez() const { return _internal_has_negativez(); } inline void BBCubeMap::clear_negativez() { negativez_.ClearToEmpty(); _has_bits_[0] &= ~0x00000020u; } inline const std::string& BBCubeMap::negativez() const { // @@protoc_insertion_point(field_get:BBSerializer.BBCubeMap.negativeZ) return _internal_negativez(); } template <typename ArgT0, typename... ArgT> PROTOBUF_ALWAYS_INLINE inline void BBCubeMap::set_negativez(ArgT0&& arg0, ArgT... args) { _has_bits_[0] |= 0x00000020u; negativez_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArena()); // @@protoc_insertion_point(field_set:BBSerializer.BBCubeMap.negativeZ) } inline std::string* BBCubeMap::mutable_negativez() { // @@protoc_insertion_point(field_mutable:BBSerializer.BBCubeMap.negativeZ) return _internal_mutable_negativez(); } inline const std::string& BBCubeMap::_internal_negativez() const { return negativez_.Get(); } inline void BBCubeMap::_internal_set_negativez(const std::string& value) { _has_bits_[0] |= 0x00000020u; negativez_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline std::string* BBCubeMap::_internal_mutable_negativez() { _has_bits_[0] |= 0x00000020u; return negativez_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* BBCubeMap::release_negativez() { // @@protoc_insertion_point(field_release:BBSerializer.BBCubeMap.negativeZ) if (!_internal_has_negativez()) { return nullptr; } _has_bits_[0] &= ~0x00000020u; return negativez_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void BBCubeMap::set_allocated_negativez(std::string* negativez) { if (negativez != nullptr) { _has_bits_[0] |= 0x00000020u; } else { _has_bits_[0] &= ~0x00000020u; } negativez_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), negativez, GetArena()); // @@protoc_insertion_point(field_set_allocated:BBSerializer.BBCubeMap.negativeZ) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_BBCubeMap_2eproto <|start_filename|>Resources/shaders/GI/FullScreenQuad_SSBO.vert<|end_filename|> #version 430 core struct Vertex { vec4 BBPosition; vec4 BBColor; vec4 BBTexcoord; vec4 BBNormal; vec4 BBTangent; vec4 BBBiTangent; }; layout (std140, binding = 0) buffer Bundle { Vertex vertexes[]; } bundle; out vec2 v2f_texcoord; void main() { v2f_texcoord = bundle.vertexes[gl_VertexID].BBTexcoord.xy; gl_Position = bundle.vertexes[gl_VertexID].BBPosition; } <|start_filename|>Resources/shaders/Shadow/VSM_ShadowMap.frag<|end_filename|> #version 430 core layout (location = 0) out vec2 FragColor; void main(void) { float depth = gl_FragCoord.z; FragColor = vec2(depth, depth * depth); } <|start_filename|>Code/BBearEditor/Engine/Physics/ClothSystem/BBClothMesh.cpp<|end_filename|> #include "BBClothMesh.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/BBMaterial.h" #include "Render/BBDrawCall.h" #include "../Body/BBClothBody.h" #include "Render/BBRenderPass.h" BBClothMesh::BBClothMesh(float fWidth, float fHeight, float fUnitStep) : BBRenderableObject() { m_fWidth = fWidth; m_fHeight = fHeight; m_fUnitStep = fUnitStep; m_nColumn = ceil(m_fWidth / m_fUnitStep) + 1; m_nRow = ceil(m_fHeight / m_fUnitStep) + 1; m_fUnitStep = m_fWidth / m_nColumn; } void BBClothMesh::init() { m_pVBO = new BBVertexBufferObject(m_nColumn * m_nRow); m_nIndexCount = (m_nColumn - 1) * (m_nRow - 1) * 6; m_pIndexes = new unsigned short[m_nIndexCount]; int nIndexesIndex = 0; for (int i = 0; i < m_nRow; i++) { for (int j = 0; j < m_nColumn; j++) { QVector3D position = QVector3D(j, i, 0) * m_fUnitStep; int nIndex = i * m_nColumn + j; m_pVBO->setPosition(nIndex, position); m_pVBO->setColor(nIndex, BBConstant::m_LightGreen); m_pVBO->setTexcoord(nIndex, 1.0f / m_fWidth * j, 1.0f / m_fHeight * i); m_pVBO->setNormal(nIndex, 0, 0, 1); m_pVBO->setTangent(nIndex, -1, 0, 0, -1); if (i < m_nRow - 1 && j < m_nColumn - 1) { m_pIndexes[nIndexesIndex++] = nIndex; m_pIndexes[nIndexesIndex++] = nIndex + 1; m_pIndexes[nIndexesIndex++] = nIndex + m_nColumn + 1; m_pIndexes[nIndexesIndex++] = nIndex; m_pIndexes[nIndexesIndex++] = nIndex + m_nColumn + 1; m_pIndexes[nIndexesIndex++] = nIndex + m_nColumn; } if (j == 0) { m_LeftVertexIndexes.push_back(nIndex); } } } m_pCurrentMaterial->init("base", BB_PATH_RESOURCE_SHADER(base.vert), BB_PATH_RESOURCE_SHADER(base.frag)); m_pCurrentMaterial->getBaseRenderPass()->setPolygonMode(GL_LINE); BBRenderableObject::init(); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO); pDrawCall->setEBO(m_pEBO, GL_TRIANGLES, m_nIndexCount, 0); appendDrawCall(pDrawCall); } void BBClothMesh::updatePhysicsCalculatedPositions(BBClothBody *pClothBody) { for (int i = 0; i < m_pVBO->getVertexCount(); i++) { m_pVBO->setPosition(i, pClothBody->getParticlePosition(i)); } m_pVBO->submitData(); } <|start_filename|>Code/BBearEditor/Engine/Base/BBGameObjectSet.cpp<|end_filename|> #include "BBGameObjectSet.h" BBGameObjectSet::BBGameObjectSet(const QList<BBGameObject*> &objects) : BBGameObjectSet(objects, QVector3D(0, 0, 0)) { // compute center of all objects QVector3D centerPos; for (int i = 0; i < m_GameObjectSet.count(); i++) { centerPos += m_GameObjectSet.at(i)->getPosition(); } centerPos /= m_GameObjectSet.count(); BBGameObject::setPosition(centerPos); } BBGameObjectSet::BBGameObjectSet(const QList<BBGameObject*> &objects, const QVector3D &centerPos) : BBGameObject(centerPos, QVector3D(0, 0, 0), QVector3D(1, 1, 1)) { m_GameObjectSet = filterSelectedObjects(objects); for (int i = 0; i < m_GameObjectSet.count(); i++) { // m_OriginalPosition is position before setRotation m_OriginalPositions.append(m_GameObjectSet.at(i)->getPosition()); m_OriginalScales.append(m_GameObjectSet.at(i)->getScale()); } } void BBGameObjectSet::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { QVector3D displacement = position - m_Position; // compute the new position of each object for (int i = 0; i < m_GameObjectSet.count(); i++) { BBGameObject *pObject = m_GameObjectSet.at(i); pObject->setPosition(pObject->getPosition() + displacement, bUpdateLocalTransform); m_OriginalPositions[i] = m_OriginalPositions[i] + displacement; } BBGameObject::setPosition(position, bUpdateLocalTransform); } void BBGameObjectSet::setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform) { BBGameObject::setRotation(nAngle, axis); // Relative to center point QMatrix4x4 matrix; matrix.translate(m_Position); matrix.rotate(m_Quaternion); matrix.scale(m_Scale); matrix.translate(-m_Position); for (int i = 0; i < m_GameObjectSet.count(); i++) { BBGameObject *pObject = m_GameObjectSet.at(i); pObject->setRotation(nAngle, axis, bUpdateLocalTransform); // change position at the same time pObject->setPosition(matrix * m_OriginalPositions.at(i), bUpdateLocalTransform); } } void BBGameObjectSet::setRotation(const QVector3D &rotation, bool bUpdateLocalTransform) { // Set the value directly for (int i = 0; i < m_GameObjectSet.count(); i++) { BBGameObject *pObject = m_GameObjectSet.at(i); pObject->setRotation(rotation, bUpdateLocalTransform); // do not change position } } void BBGameObjectSet::setScale(const QVector3D &scale, bool bUpdateLocalTransform) { BBGameObject::setScale(scale); // Relative to center point QMatrix4x4 matrix; matrix.translate(m_Position); matrix.rotate(m_Quaternion); matrix.scale(m_Scale); matrix.translate(-m_Position); for (int i = 0; i < m_GameObjectSet.count(); i++) { BBGameObject *pObject = m_GameObjectSet.at(i); pObject->setScale(scale * m_OriginalScales.at(i), bUpdateLocalTransform); // change position at the same time pObject->setPosition(matrix * m_OriginalPositions.at(i), bUpdateLocalTransform); } } QList<BBGameObject*> BBGameObjectSet::filterSelectedObjects(const QList<BBGameObject*> &gameObjects) { QList<BBGameObject*> objectSet2D; QList<BBGameObject*> objectSet3D; int count = gameObjects.count(); for (int i = 0; i < count; i++) { BBGameObject *pObject = gameObjects[i]; if (pObject->getClassName() == BB_CLASSNAME_CANVAS) { objectSet2D.append(pObject); } else { objectSet3D.append(pObject); } } // When there are UI and 3D objects at the same time, remove the UI if (objectSet3D.count() > 0) { return objectSet3D; } else { return objectSet2D; } } <|start_filename|>Code/BBearEditor/Engine/2D/BBSpriteObject2D.cpp<|end_filename|> #include "BBSpriteObject2D.h" #include "2D/BBSprite2D.h" #include "Geometry/BBBoundingBox2D.h" BBSpriteObject2D::BBSpriteObject2D(int x, int y, int nWidth, int nHeight) : BBGameObject(x, y, nWidth, nHeight) { m_pSprite2D = new BBSprite2D(x, y, nWidth, nHeight); m_pAABBBoundingBox2D = new BBAABBBoundingBox2D(x, y, nWidth, nHeight); } BBSpriteObject2D::~BBSpriteObject2D() { BB_SAFE_DELETE(m_pSprite2D); BB_SAFE_DELETE(m_pAABBBoundingBox2D); } void BBSpriteObject2D::init() { m_pSprite2D->init(); m_pAABBBoundingBox2D->init(); } void BBSpriteObject2D::render(BBCanvas *pCanvas) { m_pSprite2D->render(pCanvas); m_pAABBBoundingBox2D->render(pCanvas); } void BBSpriteObject2D::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { BBGameObject::setPosition(position, bUpdateLocalTransform); m_pSprite2D->setPosition(position, bUpdateLocalTransform); m_pAABBBoundingBox2D->setPosition(position, bUpdateLocalTransform); } void BBSpriteObject2D::setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform) { BBGameObject::setRotation(nAngle, axis, bUpdateLocalTransform); m_pSprite2D->setRotation(nAngle, axis, bUpdateLocalTransform); m_pAABBBoundingBox2D->setRotation(nAngle, axis, bUpdateLocalTransform); } void BBSpriteObject2D::setRotation(const QVector3D &rotation, bool bUpdateLocalTransform) { BBGameObject::setRotation(rotation, bUpdateLocalTransform); m_pSprite2D->setRotation(rotation, bUpdateLocalTransform); m_pAABBBoundingBox2D->setRotation(rotation, bUpdateLocalTransform); } void BBSpriteObject2D::setScale(const QVector3D &scale, bool bUpdateLocalTransform) { BBGameObject::setScale(scale, bUpdateLocalTransform); m_pSprite2D->setScale(scale, bUpdateLocalTransform); m_pAABBBoundingBox2D->setScale(scale, bUpdateLocalTransform); } <|start_filename|>Code/BBearEditor/Engine/Render/Shader/BBComputeShader.cpp<|end_filename|> #include "BBComputeShader.h" BBComputeShader::BBComputeShader() : BBShader() { } void BBComputeShader::init(const QString &shaderPath) { const char *code = nullptr; do { int nFileSize; code = BBUtils::loadFileContent(shaderPath.toStdString().c_str(), nFileSize); BB_PROCESS_ERROR(code); GLuint shader = compileShader(GL_COMPUTE_SHADER, code); BB_PROCESS_ERROR(shader); m_Program = glCreateProgram(); glAttachShader(m_Program, shader); glLinkProgram(m_Program); glDetachShader(m_Program, shader); GLint nResult; glGetProgramiv(m_Program, GL_LINK_STATUS, &nResult); if (nResult == GL_FALSE) { char szLog[1024] = {0}; GLsizei logLength = 0; glGetProgramInfoLog(m_Program, 1024, &logLength, szLog); qDebug() << "create compute program fail, log:" << szLog; glDeleteProgram(m_Program); m_Program = 0; } glDeleteShader(shader); if (m_Program != 0) { // generate attribute chain initAttributes(); initUniforms(); } } while(0); BB_SAFE_DELETE(code); } void BBComputeShader::bind(GLuint numGroupsX, GLuint numGroupsY, GLuint numGroupsZ) { glUseProgram(m_Program); glDispatchCompute(numGroupsX, numGroupsY, numGroupsZ); // sync cpu with gpu glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); } void BBComputeShader::unbind() { glUseProgram(0); } <|start_filename|>Code/BBearEditor/Engine/3D/Mesh/BBProcedureMesh.h<|end_filename|> #ifndef BBPROCEDUREMESH_H #define BBPROCEDUREMESH_H #include "BBMesh.h" class BBProcedureMesh : public BBMesh { public: BBProcedureMesh(); BBProcedureMesh(float px, float py, float pz, float rx, float ry, float rz, float sx, float sy, float sz); void init(const QString &userData, BBBoundingBox3D *&pOutBoundingBox) override; private: void load(const QString &userData, QList<QVector4D> &outPositions) override; void init0(); void init1(); }; #endif // BBPROCEDUREMESH_H
xiaoxianrouzhiyou/BBearEditor
<|start_filename|>src/arch/aarch64/concurrent_arch.asm<|end_filename|> // By <NAME> ( @mitghi ) // for AARCH64 // .text .p2align 2 .global concurrent_arch_setup_execution_context .global concurrent_arch_trampoline_to_procedure .global concurrent_arch_trampoline_to_caller .global concurrent_offsetof_procedure .global concurrent_offsetof_stack_ptr .global concurrent_offsetof_caller_return_addr concurrent_arch_setup_execution_context: ldr x6, =concurrent_offsetof_stack_ptr ldr x6, [x6] add x5, x0, x6 ldr x3, [x5] mov x2, sp mov sp, x3 ldr x6, =concurrent_offsetof_procedure ldr x6, [x6] add x5, x0, x6 ldr x4, [x5] mov x3, x4 eor x6, x6, x6 stp x0, x0, [sp, #-16]! stp x6, x6, [sp, #-16]! stp x6, x6, [sp, #-16]! stp x6, x6, [sp, #-16]! stp x6, x6, [sp, #-16]! stp x6, x6, [sp, #-16]! stp x2, x3, [sp, #-16]! stp q0, q1, [sp, #-32]! stp q2, q3, [sp, #-32]! stp q4, q5, [sp, #-32]! stp q6, q7, [sp, #-32]! stp q8, q9, [sp, #-32]! stp q10, q11, [sp, #-32]! stp q12, q13, [sp, #-32]! stp q14, q15, [sp, #-32]! stp q16, q17, [sp, #-32]! stp q18, q19, [sp, #-32]! stp q20, q21, [sp, #-32]! stp q22, q23, [sp, #-32]! stp q24, q25, [sp, #-32]! stp q26, q27, [sp, #-32]! stp q28, q29, [sp, #-32]! stp q30, q31, [sp, #-32]! ldr x6, =concurrent_offsetof_stack_ptr ldr x6, [x6] add x5, x0, x6 mov x4, sp str x4, [x5] mov sp, x2 ret concurrent_arch_trampoline_to_procedure: stp x19, x20, [sp, #-16]! stp x21, x22, [sp, #-16]! stp x23, x24, [sp, #-16]! stp x25, x26, [sp, #-16]! stp x27, x28, [sp, #-16]! stp x29, x30, [sp, #-16]! stp q0, q1, [sp, #-32]! stp q2, q3, [sp, #-32]! stp q4, q5, [sp, #-32]! stp q6, q7, [sp, #-32]! stp q8, q9, [sp, #-32]! stp q10, q11, [sp, #-32]! stp q12, q13, [sp, #-32]! stp q14, q15, [sp, #-32]! stp q16, q17, [sp, #-32]! stp q18, q19, [sp, #-32]! stp q20, q21, [sp, #-32]! stp q22, q23, [sp, #-32]! stp q24, q25, [sp, #-32]! stp q26, q27, [sp, #-32]! stp q28, q29, [sp, #-32]! stp q30, q31, [sp, #-32]! ldr x6, =concurrent_offsetof_stack_ptr ldr x6, [x6] add x5, x0, x6 ldr x3, [x5] ldr x6, =concurrent_offsetof_procedure ldr x6, [x6] add x6, x0, x6 ldr x2, [x6] mov x7, sp str x7, [x5] mov sp, x3 ldr x4, =concurrent_arch_return_at_procedure mov lr, x4 ldp q30, q31, [sp], #32 ldp q28, q29, [sp], #32 ldp q26, q27, [sp], #32 ldp q24, q25, [sp], #32 ldp q22, q23, [sp], #32 ldp q20, q21, [sp], #32 ldp q18, q19, [sp], #32 ldp q16, q17, [sp], #32 ldp q14, q15, [sp], #32 ldp q12, q13, [sp], #32 ldp q10, q11, [sp], #32 ldp q8, q9, [sp], #32 ldp q6, q7, [sp], #32 ldp q4, q5, [sp], #32 ldp q2, q3, [sp], #32 ldp q0, q1, [sp], #32 ldp x29, x3, [sp], #16 ldp x27, x28, [sp], #16 ldp x25, x26, [sp], #16 ldp x23, x24, [sp], #16 ldp x21, x22, [sp], #16 ldp x19, x20, [sp], #16 br x3 concurrent_arch_trampoline_to_caller: stp x19, x20, [sp, #-16]! stp x21, x22, [sp, #-16]! stp x23, x24, [sp, #-16]! stp x25, x26, [sp, #-16]! stp x27, x28, [sp, #-16]! stp x29, x30, [sp, #-16]! stp q0, q1, [sp, #-32]! stp q2, q3, [sp, #-32]! stp q4, q5, [sp, #-32]! stp q6, q7, [sp, #-32]! stp q8, q9, [sp, #-32]! stp q10, q11, [sp, #-32]! stp q12, q13, [sp, #-32]! stp q14, q15, [sp, #-32]! stp q16, q17, [sp, #-32]! stp q18, q19, [sp, #-32]! stp q20, q21, [sp, #-32]! stp q22, q23, [sp, #-32]! stp q24, q25, [sp, #-32]! stp q26, q27, [sp, #-32]! stp q28, q29, [sp, #-32]! stp q30, q31, [sp, #-32]! ldr x6, =concurrent_offsetof_stack_ptr ldr x6, [x6] add x5, x0, x6 ldr x3, [x5] mov x4, sp str x4, [x5] mov sp, x3 ldp q30, q31, [sp], #32 ldp q28, q29, [sp], #32 ldp q26, q27, [sp], #32 ldp q24, q25, [sp], #32 ldp q22, q23, [sp], #32 ldp q20, q21, [sp], #32 ldp q18, q19, [sp], #32 ldp q16, q17, [sp], #32 ldp q14, q15, [sp], #32 ldp q12, q13, [sp], #32 ldp q10, q11, [sp], #32 ldp q8, q9, [sp], #32 ldp q6, q7, [sp], #32 ldp q4, q5, [sp], #32 ldp q2, q3, [sp], #32 ldp q0, q1, [sp], #32 ldp x29, x30, [sp], #16 ldp x27, x28, [sp], #16 ldp x25, x26, [sp], #16 ldp x23, x24, [sp], #16 ldp x21, x22, [sp], #16 ldp x19, x20, [sp], #16 br x30 concurrent_arch_return_at_procedure: ldp x0, x1, [sp], #16 ldr x6, =concurrent_offsetof_stack_ptr ldr x6, [x6] add x5, x0, x6 ldr x3, [x5] mov sp, x3 ldp q30, q31, [sp], #32 ldp q28, q29, [sp], #32 ldp q26, q27, [sp], #32 ldp q24, q25, [sp], #32 ldp q22, q23, [sp], #32 ldp q20, q21, [sp], #32 ldp q18, q19, [sp], #32 ldp q16, q17, [sp], #32 ldp q14, q15, [sp], #32 ldp q12, q13, [sp], #32 ldp q10, q11, [sp], #32 ldp q8, q9, [sp], #32 ldp q6, q7, [sp], #32 ldp q4, q5, [sp], #32 ldp q2, q3, [sp], #32 ldp q0, q1, [sp], #32 ldp x29, x30, [sp], #16 ldp x27, x28, [sp], #16 ldp x25, x26, [sp], #16 ldp x23, x24, [sp], #16 ldp x21, x22, [sp], #16 ldp x19, x20, [sp], #16 ret .comm concurrent_offsetof_procedure,8,3 .comm concurrent_offsetof_stack_ptr,8,3 .comm concurrent_offsetof_caller_return_addr,8,3 <|start_filename|>src/arch/arm64/concurrent_arch.asm<|end_filename|> // By <NAME> ( @mitghi ) // for ARM64 // .text .p2align 2 .global _concurrent_arch_setup_execution_context .global _concurrent_arch_trampoline_to_procedure .global _concurrent_arch_trampoline_to_caller .global _concurrent_offsetof_procedure .global _concurrent_offsetof_stack_ptr .global _concurrent_offsetof_caller_return_addr _concurrent_arch_setup_execution_context: adrp x6, _concurrent_offsetof_stack_ptr@PAGE add x6, x6, _concurrent_offsetof_stack_ptr@PAGEOFF ldr x6, [x6] add x5, x0, x6 ldr x3, [x5] mov x2, sp mov sp, x3 adrp x6, _concurrent_offsetof_procedure@PAGE add x6, x6, _concurrent_offsetof_procedure@PAGEOFF ldr x6, [x6] add x5, x0, x6 ldr x4, [x5] mov x3, x4 eor x6, x6, x6 stp x0, x0, [sp, #-16]! stp x6, x6, [sp, #-16]! stp x6, x6, [sp, #-16]! stp x6, x6, [sp, #-16]! stp x6, x6, [sp, #-16]! stp x6, x6, [sp, #-16]! stp x2, x3, [sp, #-16]! stp q0, q1, [sp, #-32]! stp q2, q3, [sp, #-32]! stp q4, q5, [sp, #-32]! stp q6, q7, [sp, #-32]! stp q8, q9, [sp, #-32]! stp q10, q11, [sp, #-32]! stp q12, q13, [sp, #-32]! stp q14, q15, [sp, #-32]! stp q16, q17, [sp, #-32]! stp q18, q19, [sp, #-32]! stp q20, q21, [sp, #-32]! stp q22, q23, [sp, #-32]! stp q24, q25, [sp, #-32]! stp q26, q27, [sp, #-32]! stp q28, q29, [sp, #-32]! stp q30, q31, [sp, #-32]! adrp x6, _concurrent_offsetof_stack_ptr@PAGE add x6, x6, _concurrent_offsetof_stack_ptr@PAGEOFF ldr x6, [x6] add x5, x0, x6 mov x4, sp str x4, [x5] mov sp, x2 ret _concurrent_arch_trampoline_to_procedure: stp x19, x20, [sp, #-16]! stp x21, x22, [sp, #-16]! stp x23, x24, [sp, #-16]! stp x25, x26, [sp, #-16]! stp x27, x28, [sp, #-16]! stp x29, x30, [sp, #-16]! stp q0, q1, [sp, #-32]! stp q2, q3, [sp, #-32]! stp q4, q5, [sp, #-32]! stp q6, q7, [sp, #-32]! stp q8, q9, [sp, #-32]! stp q10, q11, [sp, #-32]! stp q12, q13, [sp, #-32]! stp q14, q15, [sp, #-32]! stp q16, q17, [sp, #-32]! stp q18, q19, [sp, #-32]! stp q20, q21, [sp, #-32]! stp q22, q23, [sp, #-32]! stp q24, q25, [sp, #-32]! stp q26, q27, [sp, #-32]! stp q28, q29, [sp, #-32]! stp q30, q31, [sp, #-32]! adrp x6, _concurrent_offsetof_stack_ptr@PAGE add x6, x6, _concurrent_offsetof_stack_ptr@PAGEOFF ldr x6, [x6] add x5, x0, x6 ldr x3, [x5] adrp x6, _concurrent_offsetof_procedure@PAGE add x6, x6, _concurrent_offsetof_procedure@PAGEOFF ldr x6, [x6] add x6, x0, x6 ldr x2, [x6] mov x7, sp str x7, [x5] mov sp, x3 adrp x4, _concurrent_arch_return_at_procedure@PAGE add x4, x4, _concurrent_arch_return_at_procedure@PAGEOFF mov lr, x4 ldp q30, q31, [sp], #32 ldp q28, q29, [sp], #32 ldp q26, q27, [sp], #32 ldp q24, q25, [sp], #32 ldp q22, q23, [sp], #32 ldp q20, q21, [sp], #32 ldp q18, q19, [sp], #32 ldp q16, q17, [sp], #32 ldp q14, q15, [sp], #32 ldp q12, q13, [sp], #32 ldp q10, q11, [sp], #32 ldp q8, q9, [sp], #32 ldp q6, q7, [sp], #32 ldp q4, q5, [sp], #32 ldp q2, q3, [sp], #32 ldp q0, q1, [sp], #32 ldp x29, x3, [sp], #16 ldp x27, x28, [sp], #16 ldp x25, x26, [sp], #16 ldp x23, x24, [sp], #16 ldp x21, x22, [sp], #16 ldp x19, x20, [sp], #16 br x3 _concurrent_arch_trampoline_to_caller: stp x19, x20, [sp, #-16]! stp x21, x22, [sp, #-16]! stp x23, x24, [sp, #-16]! stp x25, x26, [sp, #-16]! stp x27, x28, [sp, #-16]! stp x29, x30, [sp, #-16]! stp q0, q1, [sp, #-32]! stp q2, q3, [sp, #-32]! stp q4, q5, [sp, #-32]! stp q6, q7, [sp, #-32]! stp q8, q9, [sp, #-32]! stp q10, q11, [sp, #-32]! stp q12, q13, [sp, #-32]! stp q14, q15, [sp, #-32]! stp q16, q17, [sp, #-32]! stp q18, q19, [sp, #-32]! stp q20, q21, [sp, #-32]! stp q22, q23, [sp, #-32]! stp q24, q25, [sp, #-32]! stp q26, q27, [sp, #-32]! stp q28, q29, [sp, #-32]! stp q30, q31, [sp, #-32]! adrp x6, _concurrent_offsetof_stack_ptr@PAGE add x6, x6, _concurrent_offsetof_stack_ptr@PAGEOFF ldr x6, [x6] add x5, x0, x6 ldr x3, [x5] mov x4, sp str x4, [x5] mov sp, x3 ldp q30, q31, [sp], #32 ldp q28, q29, [sp], #32 ldp q26, q27, [sp], #32 ldp q24, q25, [sp], #32 ldp q22, q23, [sp], #32 ldp q20, q21, [sp], #32 ldp q18, q19, [sp], #32 ldp q16, q17, [sp], #32 ldp q14, q15, [sp], #32 ldp q12, q13, [sp], #32 ldp q10, q11, [sp], #32 ldp q8, q9, [sp], #32 ldp q6, q7, [sp], #32 ldp q4, q5, [sp], #32 ldp q2, q3, [sp], #32 ldp q0, q1, [sp], #32 ldp x29, x30, [sp], #16 ldp x27, x28, [sp], #16 ldp x25, x26, [sp], #16 ldp x23, x24, [sp], #16 ldp x21, x22, [sp], #16 ldp x19, x20, [sp], #16 br x30 _concurrent_arch_return_at_procedure: ldr x0, [sp] adrp x6, _concurrent_offsetof_stack_ptr@PAGE add x6, x6, _concurrent_offsetof_stack_ptr@PAGEOFF ldr x6, [x6] add x5, x0, x6 ldr x3, [x5] mov sp, x3 ldp q30, q31, [sp], #32 ldp q28, q29, [sp], #32 ldp q26, q27, [sp], #32 ldp q24, q25, [sp], #32 ldp q22, q23, [sp], #32 ldp q20, q21, [sp], #32 ldp q18, q19, [sp], #32 ldp q16, q17, [sp], #32 ldp q14, q15, [sp], #32 ldp q12, q13, [sp], #32 ldp q10, q11, [sp], #32 ldp q8, q9, [sp], #32 ldp q6, q7, [sp], #32 ldp q4, q5, [sp], #32 ldp q2, q3, [sp], #32 ldp q0, q1, [sp], #32 ldp x29, x30, [sp], #16 ldp x27, x28, [sp], #16 ldp x25, x26, [sp], #16 ldp x23, x24, [sp], #16 ldp x21, x22, [sp], #16 ldp x19, x20, [sp], #16 ret .comm _concurrent_offsetof_procedure,8,3 .comm _concurrent_offsetof_stack_ptr,8,3 .comm _concurrent_offsetof_caller_return_addr,8,3
mitghi/libconcurrent
<|start_filename|>Makefile<|end_filename|> build_py: docker run --rm -v $(pwd):/io konstin2/maturin:master build --cargo-extra-args="--features=python" --release --strip maturin build --cargo-extra-args="--features=python" --release --strip test: cargo test --features python_test cargo clippy --features python_test cargo fmt -- --check coverage: docker run --security-opt seccomp=unconfined -v "${PWD}:/volume" xd009642/tarpaulin bash -c "apt-get update -y && apt-get install python3-all-dev -y && cargo tarpaulin --force-clean --features python_test -v"
lv43apo91/taxonomy
<|start_filename|>Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/ExampleScenes/ExampleScripts/RecastTileUpdateHandler.cs<|end_filename|> using PF; using UnityEngine; using Mathf = UnityEngine.Mathf; using Vector3 = UnityEngine.Vector3; namespace Pathfinding { /** Helper for easier fast updates to recast graphs. * * When updating recast graphs, you might just have plonked down a few * GraphUpdateScene objects or issued a few GraphUpdateObjects to the * system. This works fine if you are only issuing a few but the problem * is that they don't have any coordination in between themselves. So if * you have 10 GraphUpdateScene objects in one tile, they will all update * that tile (10 times in total) instead of just updating it once which * is all that is required (meaning it will be 10 times slower than just * updating one tile). This script exists to help with updating only the * tiles that need updating and only updating them once instead of * multiple times. * * It is coupled with the RecastTileUpdate component, which works a bit * like the GraphUpdateScene component, just with fewer options. You can * attach the RecastTileUpdate to any GameObject to have it schedule an * update for the tile(s) that contain the GameObject. E.g if you are * creating a new building somewhere, you can attach the RecastTileUpdate * component to it to make it update the graph when it is instantiated. * * If a single tile contains multiple RecastTileUpdate components and * many try to update the graph at the same time, only one tile update * will be done, which greatly improves performance. * * If you have objects that are instantiated at roughly the same time * but not exactly the same frame, you can use the maxThrottlingDelay * field. It will delay updates up to that number of seconds to allow * more updates to be batched together. * * \note You should only have one instance of this script in the scene * if you only have a single recast graph. If you have more than one * graph you can have more than one instance of this script but you need * to manually call the SetGraph method to configure it with the correct * graph. * * \note This does not use navmesh cutting. If you only ever add * obstacles, but never add any new walkable surfaces then you might * want to use navmesh cutting instead. See \ref navmeshcutting. */ [AddComponentMenu("Pathfinding/Navmesh/RecastTileUpdateHandler")] [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_recast_tile_update_handler.php")] public class RecastTileUpdateHandler : MonoBehaviour { /** Graph that handles the updates */ RecastGraph graph; /** True for a tile if it needs updating */ bool[] dirtyTiles; /** True if any elements in dirtyTiles are true */ bool anyDirtyTiles = false; /** Earliest update request we are handling right now */ float earliestDirty = float.NegativeInfinity; /** All tile updates will be performed within (roughly) this number of seconds */ public float maxThrottlingDelay = 0.5f; public void SetGraph (RecastGraph graph) { this.graph = graph; if (graph == null) return; dirtyTiles = new bool[graph.tileXCount*graph.tileZCount]; anyDirtyTiles = false; } /** Requests an update to all tiles which touch the specified bounds */ public void ScheduleUpdate (Bounds bounds) { if (graph == null) { // If no graph has been set, use the first graph available if (AstarPath.active != null) { SetGraph(AstarPath.active.data.recastGraph); } if (graph == null) { Debug.LogError("Received tile update request (from RecastTileUpdate), but no RecastGraph could be found to handle it"); return; } } // Make sure that tiles which do not strictly // contain this bounds object but which still // might need to be updated are actually updated int voxelCharacterRadius = Mathf.CeilToInt(graph.characterRadius/graph.cellSize); int borderSize = voxelCharacterRadius + 3; // Expand borderSize voxels on each side bounds.Expand(new Vector3(borderSize, 0, borderSize)*graph.cellSize*2); var touching = graph.GetTouchingTiles(bounds); if (touching.Width * touching.Height > 0) { if (!anyDirtyTiles) { earliestDirty = Time.time; anyDirtyTiles = true; } for (int z = touching.ymin; z <= touching.ymax; z++) { for (int x = touching.xmin; x <= touching.xmax; x++) { dirtyTiles[z*graph.tileXCount + x] = true; } } } } void OnEnable () { RecastTileUpdate.OnNeedUpdates += ScheduleUpdate; } void OnDisable () { RecastTileUpdate.OnNeedUpdates -= ScheduleUpdate; } void Update () { if (anyDirtyTiles && Time.time - earliestDirty >= maxThrottlingDelay && graph != null) { UpdateDirtyTiles(); } } /** Update all dirty tiles now */ public void UpdateDirtyTiles () { if (graph == null) { new System.InvalidOperationException("No graph is set on this object"); } if (graph.tileXCount * graph.tileZCount != dirtyTiles.Length) { Debug.LogError("Graph has changed dimensions. Clearing queued graph updates and resetting."); SetGraph(graph); return; } for (int z = 0; z < graph.tileZCount; z++) { for (int x = 0; x < graph.tileXCount; x++) { if (dirtyTiles[z*graph.tileXCount + x]) { dirtyTiles[z*graph.tileXCount + x] = false; var bounds = graph.GetTileBounds(x, z); // Shrink it a bit to make sure other tiles // are not included because of rounding errors bounds.extents *= 0.5f; var guo = new GraphUpdateObject(bounds); guo.nnConstraint.graphMask = 1 << (int)graph.graphIndex; } } } anyDirtyTiles = false; } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.GridFS/GridFSDownloadOptions.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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 MongoDB.Driver.GridFS { /// <summary> /// Represents options for a GridFS download operation. /// </summary> public class GridFSDownloadOptions { // fields private bool? _checkMD5; private bool? _seekable; // properties /// <summary> /// Gets or sets a value indicating whether to check the MD5 value. /// </summary> /// <value> /// <c>true</c> if the MD5 value should be checked; otherwise, <c>false</c>. /// </value> public bool? CheckMD5 { get { return _checkMD5; } set { _checkMD5 = value; } } /// <summary> /// Gets or sets a value indicating whether the returned Stream supports seeking. /// </summary> /// <value> /// <c>true</c> if the returned Stream supports seeking; otherwise, <c>false</c>. /// </value> public bool? Seekable { get { return _seekable; } set { _seekable = value; } } } } <|start_filename|>Server/Hotfix/Module/DB/DBProxyComponentSystem.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using ETModel; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver; namespace ETHotfix { [ObjectSystem] public class DbProxyComponentSystem : AwakeSystem<DBProxyComponent> { public override void Awake(DBProxyComponent self) { self.Awake(); } } /// <summary> /// 用来与数据库操作代理 /// </summary> public static class DBProxyComponentEx { public static void Awake(this DBProxyComponent self) { StartConfig dbStartConfig = StartConfigComponent.Instance.DBConfig; self.dbAddress = dbStartConfig.GetComponent<InnerConfig>().IPEndPoint; } public static async ETTask Save(this DBProxyComponent self, ComponentWithId component) { Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress); await session.Call(new DBSaveRequest { Component = component }); } public static async ETTask SaveBatch(this DBProxyComponent self, List<ComponentWithId> components) { Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress); await session.Call(new DBSaveBatchRequest { Components = components }); } public static async ETTask Save(this DBProxyComponent self, ComponentWithId component, CancellationToken cancellationToken) { Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress); await session.Call(new DBSaveRequest { Component = component }, cancellationToken); } public static async ETVoid SaveLog(this DBProxyComponent self, ComponentWithId component) { Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress); await session.Call(new DBSaveRequest { Component = component, CollectionName = "Log" }); } public static async ETTask<T> Query<T>(this DBProxyComponent self, long id) where T: ComponentWithId { Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress); DBQueryResponse dbQueryResponse = (DBQueryResponse)await session.Call(new DBQueryRequest { CollectionName = typeof(T).Name, Id = id }); return (T)dbQueryResponse.Component; } /// <summary> /// 根据查询表达式查询 /// </summary> /// <param name="self"></param> /// <param name="exp"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static async ETTask<List<ComponentWithId>> Query<T>(this DBProxyComponent self, Expression<Func<T ,bool>> exp) where T: ComponentWithId { ExpressionFilterDefinition<T> filter = new ExpressionFilterDefinition<T>(exp); IBsonSerializerRegistry serializerRegistry = BsonSerializer.SerializerRegistry; IBsonSerializer<T> documentSerializer = serializerRegistry.GetSerializer<T>(); string json = filter.Render(documentSerializer, serializerRegistry).ToJson(); return await self.Query<T>(json); } public static async ETTask<List<ComponentWithId>> Query<T>(this DBProxyComponent self, List<long> ids) where T : ComponentWithId { Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress); DBQueryBatchResponse dbQueryBatchResponse = (DBQueryBatchResponse)await session.Call(new DBQueryBatchRequest { CollectionName = typeof(T).Name, IdList = ids }); return dbQueryBatchResponse.Components; } /// <summary> /// 根据json查询条件查询 /// </summary> /// <param name="self"></param> /// <param name="json"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static async ETTask<List<ComponentWithId>> Query<T>(this DBProxyComponent self, string json) where T : ComponentWithId { Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress); DBQueryJsonResponse dbQueryJsonResponse = (DBQueryJsonResponse)await session.Call(new DBQueryJsonRequest { CollectionName = typeof(T).Name, Json = json }); return dbQueryJsonResponse.Components; } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Examples/4.X/SimpleExamples/TwoFingers/TwoLongTapMe.cs<|end_filename|> using UnityEngine; using System.Collections; using HedgehogTeam.EasyTouch; public class TwoLongTapMe : MonoBehaviour { private TextMesh textMesh; private Color startColor; // Subscribe to events void OnEnable(){ EasyTouch.On_LongTapStart2Fingers += On_LongTapStart2Fingers; EasyTouch.On_LongTap2Fingers += On_LongTap2Fingers; EasyTouch.On_LongTapEnd2Fingers += On_LongTapEnd2Fingers; EasyTouch.On_Cancel2Fingers += On_Cancel2Fingers; } void OnDisable(){ UnsubscribeEvent(); } void OnDestroy(){ UnsubscribeEvent(); } void UnsubscribeEvent(){ EasyTouch.On_LongTapStart2Fingers -= On_LongTapStart2Fingers; EasyTouch.On_LongTap2Fingers -= On_LongTap2Fingers; EasyTouch.On_LongTapEnd2Fingers -= On_LongTapEnd2Fingers; EasyTouch.On_Cancel2Fingers -= On_Cancel2Fingers; } void Start(){ textMesh =(TextMesh) GetComponentInChildren<TextMesh>(); startColor = gameObject.GetComponent<Renderer>().material.color; } // At the long tap beginning void On_LongTapStart2Fingers( Gesture gesture){ // Verification that the action on the object if (gesture.pickedObject == gameObject){ RandomColor(); } } // During the long tap void On_LongTap2Fingers( Gesture gesture){ // Verification that the action on the object if (gesture.pickedObject == gameObject){ textMesh.text = gesture.actionTime.ToString("f2"); } } // At the long tap end void On_LongTapEnd2Fingers( Gesture gesture){ // Verification that the action on the object if (gesture.pickedObject == gameObject){ gameObject.GetComponent<Renderer>().material.color = startColor; textMesh.text="Long tap me"; } } // If the two finger gesture is finished void On_Cancel2Fingers(Gesture gesture){ On_LongTapEnd2Fingers( gesture); } void RandomColor(){ gameObject.GetComponent<Renderer>().material.color = new Color( Random.Range(0.0f,1.0f), Random.Range(0.0f,1.0f), Random.Range(0.0f,1.0f)); } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Packages/PackageAssetPostprocessor.cs<|end_filename|> using System.Linq; namespace UnityEditor.PackageManager.UI { internal class PackageAssetPostprocessor : AssetPostprocessor { static bool IsPackageJsonAsset(string path) { var pathComponents = (path ?? "").Split('/'); return pathComponents.Length == 3 && pathComponents[0] == "Packages" && pathComponents[2] == "package.json"; } static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { if (PackageCollection.Instance != null && (importedAssets.Any(IsPackageJsonAsset) || deletedAssets.Any(IsPackageJsonAsset) || movedAssets.Any(IsPackageJsonAsset))) { PackageCollection.Instance.FetchListOfflineCache(true); } } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Packages/PackageTag.cs<|end_filename|> namespace UnityEditor.PackageManager.UI { internal enum PackageTag { preview, verified, inDevelopment, local } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Configuration/ClusterBuilder.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using MongoDB.Driver.Core.Authentication; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.ConnectionPools; using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.Events.Diagnostics; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; namespace MongoDB.Driver.Core.Configuration { /// <summary> /// Represents a cluster builder. /// </summary> public class ClusterBuilder { // constants private const string __traceSourceName = "MongoDB-SDAM"; // fields private EventAggregator _eventAggregator; private ClusterSettings _clusterSettings; private ConnectionPoolSettings _connectionPoolSettings; private ConnectionSettings _connectionSettings; private SdamLoggingSettings _sdamLoggingSettings; private ServerSettings _serverSettings; private SslStreamSettings _sslStreamSettings; private Func<IStreamFactory, IStreamFactory> _streamFactoryWrapper; private TcpStreamSettings _tcpStreamSettings; // constructors /// <summary> /// Initializes a new instance of the <see cref="ClusterBuilder"/> class. /// </summary> public ClusterBuilder() { _clusterSettings = new ClusterSettings(); _sdamLoggingSettings = new SdamLoggingSettings(null); _serverSettings = new ServerSettings(); _connectionPoolSettings = new ConnectionPoolSettings(); _connectionSettings = new ConnectionSettings(); _tcpStreamSettings = new TcpStreamSettings(); _streamFactoryWrapper = inner => inner; _eventAggregator = new EventAggregator(); } // public methods /// <summary> /// Builds the cluster. /// </summary> /// <returns>A cluster.</returns> public ICluster BuildCluster() { var clusterFactory = CreateClusterFactory(); return clusterFactory.CreateCluster(); } /// <summary> /// Configures the cluster settings. /// </summary> /// <param name="configurator">The cluster settings configurator delegate.</param> /// <returns>A reconfigured cluster builder.</returns> public ClusterBuilder ConfigureCluster(Func<ClusterSettings, ClusterSettings> configurator) { Ensure.IsNotNull(configurator, nameof(configurator)); _clusterSettings = configurator(_clusterSettings); return this; } /// <summary> /// Configures the connection settings. /// </summary> /// <param name="configurator">The connection settings configurator delegate.</param> /// <returns>A reconfigured cluster builder.</returns> public ClusterBuilder ConfigureConnection(Func<ConnectionSettings, ConnectionSettings> configurator) { Ensure.IsNotNull(configurator, nameof(configurator)); _connectionSettings = configurator(_connectionSettings); return this; } /// <summary> /// Configures the connection pool settings. /// </summary> /// <param name="configurator">The connection pool settings configurator delegate.</param> /// <returns>A reconfigured cluster builder.</returns> public ClusterBuilder ConfigureConnectionPool(Func<ConnectionPoolSettings, ConnectionPoolSettings> configurator) { Ensure.IsNotNull(configurator, nameof(configurator)); _connectionPoolSettings = configurator(_connectionPoolSettings); return this; } /// <summary> /// Configures the SDAM logging settings. /// </summary> /// <param name="configurator">The SDAM logging settings configurator delegate.</param> /// <returns>A reconfigured cluster builder.</returns> public ClusterBuilder ConfigureSdamLogging(Func<SdamLoggingSettings, SdamLoggingSettings> configurator) { _sdamLoggingSettings = configurator(_sdamLoggingSettings); if (!_sdamLoggingSettings.IsLoggingEnabled) { return this; } var traceSource = new TraceSource(__traceSourceName, SourceLevels.All); traceSource.Listeners.Clear(); // remove the default listener var listener = _sdamLoggingSettings.ShouldLogToStdout ? new TextWriterTraceListener(Console.Out) : new TextWriterTraceListener(new FileStream(_sdamLoggingSettings.LogFilename, FileMode.Append)); listener.TraceOutputOptions = TraceOptions.DateTime; traceSource.Listeners.Add(listener); return this.Subscribe(new TraceSourceSdamEventSubscriber(traceSource)); } /// <summary> /// Configures the server settings. /// </summary> /// <param name="configurator">The server settings configurator delegate.</param> /// <returns>A reconfigured cluster builder.</returns> public ClusterBuilder ConfigureServer(Func<ServerSettings, ServerSettings> configurator) { _serverSettings = configurator(_serverSettings); return this; } /// <summary> /// Configures the SSL stream settings. /// </summary> /// <param name="configurator">The SSL stream settings configurator delegate.</param> /// <returns>A reconfigured cluster builder.</returns> public ClusterBuilder ConfigureSsl(Func<SslStreamSettings, SslStreamSettings> configurator) { _sslStreamSettings = configurator(_sslStreamSettings ?? new SslStreamSettings()); return this; } /// <summary> /// Configures the TCP stream settings. /// </summary> /// <param name="configurator">The TCP stream settings configurator delegate.</param> /// <returns>A reconfigured cluster builder.</returns> public ClusterBuilder ConfigureTcp(Func<TcpStreamSettings, TcpStreamSettings> configurator) { Ensure.IsNotNull(configurator, nameof(configurator)); _tcpStreamSettings = configurator(_tcpStreamSettings); return this; } /// <summary> /// Registers a stream factory wrapper. /// </summary> /// <param name="wrapper">The stream factory wrapper.</param> /// <returns>A reconfigured cluster builder.</returns> public ClusterBuilder RegisterStreamFactory(Func<IStreamFactory, IStreamFactory> wrapper) { Ensure.IsNotNull(wrapper, nameof(wrapper)); _streamFactoryWrapper = inner => wrapper(_streamFactoryWrapper(inner)); return this; } /// <summary> /// Subscribes to events of type <typeparamref name="TEvent"/>. /// </summary> /// <typeparam name="TEvent">The type of the event.</typeparam> /// <param name="handler">The handler.</param> /// <returns>A reconfigured cluster builder.</returns> public ClusterBuilder Subscribe<TEvent>(Action<TEvent> handler) { Ensure.IsNotNull(handler, nameof(handler)); _eventAggregator.Subscribe(handler); return this; } /// <summary> /// Subscribes the specified subscriber. /// </summary> /// <param name="subscriber">The subscriber.</param> /// <returns>A reconfigured cluster builder.</returns> public ClusterBuilder Subscribe(IEventSubscriber subscriber) { Ensure.IsNotNull(subscriber, nameof(subscriber)); _eventAggregator.Subscribe(subscriber); return this; } // private methods private IClusterFactory CreateClusterFactory() { var serverFactory = CreateServerFactory(); return new ClusterFactory( _clusterSettings, serverFactory, _eventAggregator); } private IConnectionPoolFactory CreateConnectionPoolFactory() { var streamFactory = CreateTcpStreamFactory(_tcpStreamSettings); var connectionFactory = new BinaryConnectionFactory( _connectionSettings, streamFactory, _eventAggregator); return new ExclusiveConnectionPoolFactory( _connectionPoolSettings, connectionFactory, _eventAggregator); } private ServerFactory CreateServerFactory() { var connectionPoolFactory = CreateConnectionPoolFactory(); var serverMonitorFactory = CreateServerMonitorFactory(); return new ServerFactory( _clusterSettings.ConnectionMode, _serverSettings, connectionPoolFactory, serverMonitorFactory, _eventAggregator); } private IServerMonitorFactory CreateServerMonitorFactory() { var serverMonitorConnectionSettings = _connectionSettings .With(authenticators: new IAuthenticator[] { }); var heartbeatConnectTimeout = _tcpStreamSettings.ConnectTimeout; if (heartbeatConnectTimeout == TimeSpan.Zero || heartbeatConnectTimeout == Timeout.InfiniteTimeSpan) { heartbeatConnectTimeout = TimeSpan.FromSeconds(30); } var heartbeatSocketTimeout = _serverSettings.HeartbeatTimeout; if (heartbeatSocketTimeout == TimeSpan.Zero || heartbeatSocketTimeout == Timeout.InfiniteTimeSpan) { heartbeatSocketTimeout = heartbeatConnectTimeout; } var serverMonitorTcpStreamSettings = new TcpStreamSettings(_tcpStreamSettings) .With( connectTimeout: heartbeatConnectTimeout, readTimeout: heartbeatSocketTimeout, writeTimeout: heartbeatSocketTimeout ); var serverMonitorStreamFactory = CreateTcpStreamFactory(serverMonitorTcpStreamSettings); var serverMonitorConnectionFactory = new BinaryConnectionFactory( serverMonitorConnectionSettings, serverMonitorStreamFactory, new EventAggregator()); return new ServerMonitorFactory( _serverSettings, serverMonitorConnectionFactory, _eventAggregator); } private IStreamFactory CreateTcpStreamFactory(TcpStreamSettings tcpStreamSettings) { var streamFactory = (IStreamFactory)new TcpStreamFactory(tcpStreamSettings); if (_sslStreamSettings != null) { streamFactory = new SslStreamFactory(_sslStreamSettings, streamFactory); } return _streamFactoryWrapper(streamFactory); } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Interfaces/IBaseOperation.cs<|end_filename|> using System; namespace UnityEditor.PackageManager.UI { internal interface IBaseOperation { event Action<Error> OnOperationError; event Action OnOperationFinalized; bool IsCompleted { get; } void Cancel(); } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Plugins/Editor/QuickEnterExitInspector.cs<|end_filename|> using UnityEngine; using System.Collections; using UnityEditor; using HedgehogTeam.EasyTouch; #if UNITY_5_3_OR_NEWER using UnityEditor.SceneManagement; #endif [CustomEditor(typeof(QuickEnterOverExist))] public class QuickEnterExitInspector : Editor { public override void OnInspectorGUI(){ QuickEnterOverExist t = (QuickEnterOverExist)target; EditorGUILayout.Space(); t.quickActionName = EditorGUILayout.TextField("Quick name",t.quickActionName); EditorGUILayout.Space(); t.isMultiTouch = EditorGUILayout.ToggleLeft("Allow multi-touches",t.isMultiTouch); t.enablePickOverUI = EditorGUILayout.ToggleLeft("Allow over UI element",t.enablePickOverUI); EditorGUILayout.Space(); serializedObject.Update(); SerializedProperty enter = serializedObject.FindProperty("onTouchEnter"); EditorGUILayout.PropertyField(enter, true, null); serializedObject.ApplyModifiedProperties(); serializedObject.Update(); SerializedProperty over = serializedObject.FindProperty("onTouchOver"); EditorGUILayout.PropertyField(over, true, null); serializedObject.ApplyModifiedProperties(); serializedObject.Update(); SerializedProperty exit = serializedObject.FindProperty("onTouchExit"); EditorGUILayout.PropertyField(exit, true, null); serializedObject.ApplyModifiedProperties(); if (GUI.changed){ EditorUtility.SetDirty(t); #if UNITY_5_3_OR_NEWER EditorSceneManager.MarkSceneDirty( EditorSceneManager.GetActiveScene()); #endif } } } <|start_filename|>Unity/Assets/ThirdParty/ILRuntime/Mono.Cecil/Mono.Cecil/ParameterDefinitionCollection.cs<|end_filename|> // // Author: // <NAME> (<EMAIL>) // // Copyright (c) 2008 - 2015 <NAME> // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using Mono.Collections.Generic; namespace Mono.Cecil { sealed class ParameterDefinitionCollection : Collection<ParameterDefinition> { readonly IMethodSignature method; internal ParameterDefinitionCollection (IMethodSignature method) { this.method = method; } internal ParameterDefinitionCollection (IMethodSignature method, int capacity) : base (capacity) { this.method = method; } protected override void OnAdd (ParameterDefinition item, int index) { item.method = method; item.index = index; } protected override void OnInsert (ParameterDefinition item, int index) { item.method = method; item.index = index; for (int i = index; i < size; i++) items [i].index = i + 1; } protected override void OnSet (ParameterDefinition item, int index) { item.method = method; item.index = index; } protected override void OnRemove (ParameterDefinition item, int index) { item.method = null; item.index = -1; for (int i = index + 1; i < size; i++) items [i].index = i - 1; } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/BulkWriteResult.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.Collections.ObjectModel; using System.Linq; #if NET452 using System.Runtime.Serialization; #endif using MongoDB.Bson; namespace MongoDB.Driver { /// <summary> /// Represents the result of a bulk write operation. /// </summary> #if NET452 [Serializable] #endif public abstract class BulkWriteResult { // fields private readonly int _requestCount; //constructors /// <summary> /// Initializes a new instance of the <see cref="BulkWriteResult"/> class. /// </summary> /// <param name="requestCount">The request count.</param> protected BulkWriteResult(int requestCount) { _requestCount = requestCount; } // properties /// <summary> /// Gets the number of documents that were deleted. /// </summary> public abstract long DeletedCount { get; } /// <summary> /// Gets the number of documents that were inserted. /// </summary> public abstract long InsertedCount { get; } /// <summary> /// Gets a value indicating whether the bulk write operation was acknowledged. /// </summary> public abstract bool IsAcknowledged { get; } /// <summary> /// Gets a value indicating whether the modified count is available. /// </summary> /// <remarks> /// The modified count is only available when all servers have been upgraded to 2.6 or above. /// </remarks> public abstract bool IsModifiedCountAvailable { get; } /// <summary> /// Gets the number of documents that were matched. /// </summary> public abstract long MatchedCount { get; } /// <summary> /// Gets the number of documents that were actually modified during an update. /// </summary> public abstract long ModifiedCount { get; } /// <summary> /// Gets the request count. /// </summary> public int RequestCount { get { return _requestCount; } } /// <summary> /// Gets a list with information about each request that resulted in an upsert. /// </summary> public abstract IReadOnlyList<BulkWriteUpsert> Upserts { get; } } /// <summary> /// Represents the result of a bulk write operation. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> #if NET452 [Serializable] #endif public abstract class BulkWriteResult<TDocument> : BulkWriteResult { // private fields private readonly IReadOnlyList<WriteModel<TDocument>> _processedRequests; // constructors /// <summary> /// Initializes a new instance of the <see cref="BulkWriteResult" /> class. /// </summary> /// <param name="requestCount">The request count.</param> /// <param name="processedRequests">The processed requests.</param> protected BulkWriteResult( int requestCount, IEnumerable<WriteModel<TDocument>> processedRequests) : base(requestCount) { _processedRequests = processedRequests.ToList(); } // public properties /// <summary> /// Gets the processed requests. /// </summary> public IReadOnlyList<WriteModel<TDocument>> ProcessedRequests { get { return _processedRequests; } } // internal static methods internal static BulkWriteResult<TDocument> FromCore(Core.Operations.BulkWriteOperationResult result) { if (result.IsAcknowledged) { return new Acknowledged( result.RequestCount, result.MatchedCount, result.DeletedCount, result.InsertedCount, result.IsModifiedCountAvailable ? (long?)result.ModifiedCount : null, result.ProcessedRequests.Select(r => WriteModel<TDocument>.FromCore(r)), result.Upserts.Select(u => BulkWriteUpsert.FromCore(u))); } return new Unacknowledged( result.RequestCount, result.ProcessedRequests.Select(r => WriteModel<TDocument>.FromCore(r))); } internal static BulkWriteResult<TDocument> FromCore(Core.Operations.BulkWriteOperationResult result, IEnumerable<WriteModel<TDocument>> requests) { if (result.IsAcknowledged) { return new Acknowledged( result.RequestCount, result.MatchedCount, result.DeletedCount, result.InsertedCount, result.IsModifiedCountAvailable ? (long?)result.ModifiedCount : null, requests, result.Upserts.Select(u => BulkWriteUpsert.FromCore(u))); } return new Unacknowledged( result.RequestCount, requests); } // nested classes /// <summary> /// Result from an acknowledged write concern. /// </summary> #if NET452 [Serializable] #endif public class Acknowledged : BulkWriteResult<TDocument> { // private fields private readonly long _deletedCount; private readonly long _insertedCount; private readonly long _matchedCount; private readonly long? _modifiedCount; private readonly IReadOnlyList<BulkWriteUpsert> _upserts; // constructors /// <summary> /// Initializes a new instance of the class. /// </summary> /// <param name="requestCount">The request count.</param> /// <param name="matchedCount">The matched count.</param> /// <param name="deletedCount">The deleted count.</param> /// <param name="insertedCount">The inserted count.</param> /// <param name="modifiedCount">The modified count.</param> /// <param name="processedRequests">The processed requests.</param> /// <param name="upserts">The upserts.</param> public Acknowledged( int requestCount, long matchedCount, long deletedCount, long insertedCount, long? modifiedCount, IEnumerable<WriteModel<TDocument>> processedRequests, IEnumerable<BulkWriteUpsert> upserts) : base(requestCount, processedRequests) { _matchedCount = matchedCount; _deletedCount = deletedCount; _insertedCount = insertedCount; _modifiedCount = modifiedCount; _upserts = upserts.ToList(); } // public properties /// <inheritdoc/> public override long DeletedCount { get { return _deletedCount; } } /// <inheritdoc/> public override long InsertedCount { get { return _insertedCount; } } /// <inheritdoc/> public override bool IsAcknowledged { get { return true; } } /// <inheritdoc/> public override bool IsModifiedCountAvailable { get { return _modifiedCount.HasValue; } } /// <inheritdoc/> public override long MatchedCount { get { return _matchedCount; } } /// <inheritdoc/> public override long ModifiedCount { get { if (!_modifiedCount.HasValue) { throw new NotSupportedException("ModifiedCount is not available."); } return _modifiedCount.Value; } } /// <inheritdoc/> public override IReadOnlyList<BulkWriteUpsert> Upserts { get { return _upserts; } } } /// <summary> /// Result from an unacknowledged write concern. /// </summary> #if NET452 [Serializable] #endif public class Unacknowledged : BulkWriteResult<TDocument> { // constructors /// <summary> /// Initializes a new instance of the class. /// </summary> /// <param name="requestCount">The request count.</param> /// <param name="processedRequests">The processed requests.</param> public Unacknowledged( int requestCount, IEnumerable<WriteModel<TDocument>> processedRequests) : base(requestCount, processedRequests) { } // public properties /// <inheritdoc/> public override long DeletedCount { get { throw new NotSupportedException("Only acknowledged writes support the DeletedCount property."); } } /// <inheritdoc/> public override long InsertedCount { get { throw new NotSupportedException("Only acknowledged writes support the InsertedCount property."); } } /// <inheritdoc/> public override bool IsAcknowledged { get { return false; } } /// <inheritdoc/> public override bool IsModifiedCountAvailable { get { throw new NotSupportedException("Only acknowledged writes support the IsModifiedCountAvailable property."); } } /// <inheritdoc/> public override long MatchedCount { get { throw new NotSupportedException("Only acknowledged writes support the MatchedCount property."); } } /// <inheritdoc/> public override long ModifiedCount { get { throw new NotSupportedException("Only acknowledged writes support the ModifiedCount property."); } } /// <inheritdoc/> public override IReadOnlyList<BulkWriteUpsert> Upserts { get { throw new NotSupportedException("Only acknowledged writes support the Upserts property."); } } } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/UI/PackageSearchToolbar.cs<|end_filename|> using System; using UnityEngine; using UnityEngine.Experimental.UIElements; namespace UnityEditor.PackageManager.UI { #if !UNITY_2018_3_OR_NEWER internal class PackageSearchToolbarFactory : UxmlFactory<PackageSearchToolbar> { protected override PackageSearchToolbar DoCreate(IUxmlAttributes bag, CreationContext cc) { return new PackageSearchToolbar(); } } #endif internal class PackageSearchToolbar : VisualElement { #if UNITY_2018_3_OR_NEWER internal new class UxmlFactory : UxmlFactory<PackageSearchToolbar> { } #endif private const string kPlaceHolder = "Search by package name, verified, preview or version number..."; public event Action OnFocusChange = delegate { }; public event Action<string> OnSearchChange = delegate { }; private string searchText; private bool showingPlaceHolder; private readonly VisualElement root; public PackageSearchToolbar() { root = Resources.GetTemplate("PackageSearchToolbar.uxml"); Add(root); root.StretchToParentSize(); SearchTextField.value = searchText; SearchTextField.maxLength = 54; SearchCancelButton.clickable.clicked += SearchCancelButtonClick; RegisterCallback<AttachToPanelEvent>(OnEnterPanel); RegisterCallback<DetachFromPanelEvent>(OnLeavePanel); searchText = PackageSearchFilter.Instance.SearchText; if (string.IsNullOrEmpty(searchText)) { showingPlaceHolder = true; SearchTextField.value = kPlaceHolder; SearchTextField.AddToClassList("placeholder"); } else { showingPlaceHolder = false; SearchTextField.value = searchText; SearchTextField.RemoveFromClassList("placeholder"); } } public void GrabFocus() { SearchTextField.Focus(); } public new void SetEnabled(bool enable) { base.SetEnabled(enable); SearchTextField.SetEnabled(enable); SearchCancelButton.SetEnabled(enable); } private void OnSearchTextFieldChange(ChangeEvent<string> evt) { if (showingPlaceHolder && evt.newValue == kPlaceHolder) return; if (!string.IsNullOrEmpty(evt.newValue)) SearchCancelButton.AddToClassList("on"); else SearchCancelButton.RemoveFromClassList("on"); searchText = evt.newValue; OnSearchChange(searchText); } private void OnSearchTextFieldFocus(FocusEvent evt) { if (showingPlaceHolder) { SearchTextField.value = string.Empty; SearchTextField.RemoveFromClassList("placeholder"); showingPlaceHolder = false; } } private void OnSearchTextFieldFocusOut(FocusOutEvent evt) { if (string.IsNullOrEmpty(searchText)) { showingPlaceHolder = true; SearchTextField.AddToClassList("placeholder"); SearchTextField.value = kPlaceHolder; } } private void SearchCancelButtonClick() { if (!string.IsNullOrEmpty(SearchTextField.value)) { SearchTextField.value = string.Empty; } showingPlaceHolder = true; SearchTextField.AddToClassList("placeholder"); SearchTextField.value = kPlaceHolder; } private void OnEnterPanel(AttachToPanelEvent evt) { SearchTextField.RegisterCallback<FocusEvent>(OnSearchTextFieldFocus); SearchTextField.RegisterCallback<FocusOutEvent>(OnSearchTextFieldFocusOut); SearchTextField.RegisterCallback<ChangeEvent<string>>(OnSearchTextFieldChange); SearchTextField.RegisterCallback<KeyDownEvent>(OnKeyDownShortcut); } private void OnLeavePanel(DetachFromPanelEvent evt) { SearchTextField.UnregisterCallback<FocusEvent>(OnSearchTextFieldFocus); SearchTextField.UnregisterCallback<FocusOutEvent>(OnSearchTextFieldFocusOut); SearchTextField.UnregisterCallback<ChangeEvent<string>>(OnSearchTextFieldChange); SearchTextField.UnregisterCallback<KeyDownEvent>(OnKeyDownShortcut); } private void OnKeyDownShortcut(KeyDownEvent evt) { if (evt.keyCode == KeyCode.Escape) { SearchCancelButtonClick(); SearchCancelButton.Focus(); evt.StopImmediatePropagation(); return; } if (evt.keyCode == KeyCode.Tab) { OnFocusChange(); evt.StopImmediatePropagation(); } } private TextField SearchTextField { get { return root.Q<TextField>("searchTextField"); } } private Button SearchCancelButton { get { return root.Q<Button>("searchCancelButton"); } } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouchControls/Examples/Version 2.X_New Features/Script/CharacterAnimationDungeon.cs<|end_filename|> using UnityEngine; using System.Collections; public class CharacterAnimationDungeon : MonoBehaviour { private CharacterController cc; private Animation anim; // Use this for initialization void Start () { cc= GetComponentInChildren<CharacterController>(); anim = GetComponentInChildren<Animation>(); } // Wait end of frame to manage charactercontroller, because gravity is managed by virtual controller void LateUpdate(){ if (cc.isGrounded && (ETCInput.GetAxis("Vertical")!=0 || ETCInput.GetAxis("Horizontal")!=0)){ anim.CrossFade("soldierRun"); } if (cc.isGrounded && ETCInput.GetAxis("Vertical")==0 && ETCInput.GetAxis("Horizontal")==0){ anim.CrossFade("soldierIdleRelaxed"); } if (!cc.isGrounded){ anim.CrossFade("soldierFalling"); } } } <|start_filename|>Unity/Assets/ThirdParty/ILRuntime/Mono.Cecil/Mono.Cecil/AssemblyInfo.cs<|end_filename|> // // Author: // <NAME> (<EMAIL>) // // Copyright (c) 2008 - 2015 <NAME> // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle (Consts.AssemblyName)] #if !NET_CORE [assembly: Guid ("fd225bb4-fa53-44b2-a6db-85f5e48dcb54")] #endif [assembly: InternalsVisibleTo ("Mono.Cecil.Pdb, PublicKey=" + Consts.PublicKey)] [assembly: InternalsVisibleTo ("Mono.Cecil.Mdb, PublicKey=" + Consts.PublicKey)] [assembly: InternalsVisibleTo ("Mono.Cecil.Rocks, PublicKey=" + Consts.PublicKey)] [assembly: InternalsVisibleTo ("Mono.Cecil.Tests, PublicKey=" + Consts.PublicKey)] <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Operations/BulkUnmixedWriteOperationEmulatorBase.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; namespace MongoDB.Driver.Core.Operations { internal abstract class BulkUnmixedWriteOperationEmulatorBase<TWriteRequest> : IExecutableInRetryableWriteContext<BulkWriteOperationResult> where TWriteRequest : WriteRequest { // fields private readonly CollectionNamespace _collectionNamespace; private bool _isOrdered = true; private int? _maxBatchCount; private int? _maxBatchLength; private readonly MessageEncoderSettings _messageEncoderSettings; private readonly List<TWriteRequest> _requests; private WriteConcern _writeConcern = WriteConcern.Acknowledged; // constructors protected BulkUnmixedWriteOperationEmulatorBase( CollectionNamespace collectionNamespace, IEnumerable<TWriteRequest> requests, MessageEncoderSettings messageEncoderSettings) : this(collectionNamespace, Ensure.IsNotNull(requests, nameof(requests)).ToList(), messageEncoderSettings) { } protected BulkUnmixedWriteOperationEmulatorBase( CollectionNamespace collectionNamespace, List<TWriteRequest> requests, MessageEncoderSettings messageEncoderSettings) { _collectionNamespace = Ensure.IsNotNull(collectionNamespace, nameof(collectionNamespace)); _requests = Ensure.IsNotNull(requests, nameof(requests)); _messageEncoderSettings = messageEncoderSettings; } // properties public CollectionNamespace CollectionNamespace { get { return _collectionNamespace; } } public int? MaxBatchCount { get { return _maxBatchCount; } set { _maxBatchCount = Ensure.IsNullOrGreaterThanZero(value, nameof(value)); } } public int? MaxBatchLength { get { return _maxBatchLength; } set { _maxBatchLength = Ensure.IsNullOrGreaterThanZero(value, nameof(value)); } } public MessageEncoderSettings MessageEncoderSettings { get { return _messageEncoderSettings; } } public bool IsOrdered { get { return _isOrdered; } set { _isOrdered = value; } } public IEnumerable<TWriteRequest> Requests { get { return _requests; } } public WriteConcern WriteConcern { get { return _writeConcern; } set { _writeConcern = Ensure.IsNotNull(value, nameof(value)); } } // public methods public BulkWriteOperationResult Execute(RetryableWriteContext context, CancellationToken cancellationToken) { var helper = new BatchHelper(this, context.Channel); foreach (var batch in helper.GetBatches()) { batch.Result = EmulateSingleRequest(context.Channel, batch.Request, batch.OriginalIndex, cancellationToken); } return helper.GetFinalResultOrThrow(); } public async Task<BulkWriteOperationResult> ExecuteAsync(RetryableWriteContext context, CancellationToken cancellationToken) { var helper = new BatchHelper(this, context.Channel); foreach (var batch in helper.GetBatches()) { batch.Result = await EmulateSingleRequestAsync(context.Channel, batch.Request, batch.OriginalIndex, cancellationToken).ConfigureAwait(false); } return helper.GetFinalResultOrThrow(); } // protected methods protected abstract WriteConcernResult ExecuteProtocol(IChannelHandle channel, TWriteRequest request, CancellationToken cancellationToken); protected abstract Task<WriteConcernResult> ExecuteProtocolAsync(IChannelHandle channel, TWriteRequest request, CancellationToken cancellationToken); // private methods private BulkWriteBatchResult EmulateSingleRequest(IChannelHandle channel, TWriteRequest request, int originalIndex, CancellationToken cancellationToken) { WriteConcernResult writeConcernResult = null; MongoWriteConcernException writeConcernException = null; try { writeConcernResult = ExecuteProtocol(channel, request, cancellationToken); } catch (MongoWriteConcernException ex) { writeConcernResult = ex.WriteConcernResult; writeConcernException = ex; } return CreateSingleRequestResult(request, originalIndex, writeConcernResult, writeConcernException); } private async Task<BulkWriteBatchResult> EmulateSingleRequestAsync(IChannelHandle channel, TWriteRequest request, int originalIndex, CancellationToken cancellationToken) { WriteConcernResult writeConcernResult = null; MongoWriteConcernException writeConcernException = null; try { writeConcernResult = await ExecuteProtocolAsync(channel, request, cancellationToken).ConfigureAwait(false); } catch (MongoWriteConcernException ex) { writeConcernResult = ex.WriteConcernResult; writeConcernException = ex; } return CreateSingleRequestResult(request, originalIndex, writeConcernResult, writeConcernException); } private BulkWriteBatchResult CreateSingleRequestResult(TWriteRequest request, int originalIndex, WriteConcernResult writeConcernResult, MongoWriteConcernException writeConcernException) { var indexMap = new IndexMap.RangeBased(0, originalIndex, 1); return BulkWriteBatchResult.Create( request, writeConcernResult, writeConcernException, indexMap); } // nested types private class BatchHelper { private readonly List<BulkWriteBatchResult> _batchResults = new List<BulkWriteBatchResult>(); private readonly IChannelHandle _channel; private bool _hasWriteErrors; private readonly BulkUnmixedWriteOperationEmulatorBase<TWriteRequest> _operation; private readonly List<TWriteRequest> _remainingRequests = new List<TWriteRequest>(); public BatchHelper(BulkUnmixedWriteOperationEmulatorBase<TWriteRequest> operation, IChannelHandle channel) { _operation = operation; _channel = channel; } public IEnumerable<Batch> GetBatches() { var originalIndex = 0; foreach (var request in _operation._requests) { if (_hasWriteErrors && _operation._isOrdered) { _remainingRequests.Add(request); continue; } var batch = new Batch { Request = request, OriginalIndex = originalIndex }; yield return batch; _batchResults.Add(batch.Result); _hasWriteErrors |= batch.Result.HasWriteErrors; originalIndex++; } } public BulkWriteOperationResult GetFinalResultOrThrow() { var combiner = new BulkWriteBatchResultCombiner(_batchResults, _operation._writeConcern.IsAcknowledged); return combiner.CreateResultOrThrowIfHasErrors(_channel.ConnectionDescription.ConnectionId, _remainingRequests); } public class Batch { public int OriginalIndex; public TWriteRequest Request; public BulkWriteBatchResult Result; } } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouchControls/Examples/Version 1.X/Button-Event-Input/ButtonUIEvent.cs<|end_filename|> using UnityEngine; using UnityEngine.UI; using System.Collections; public class ButtonUIEvent : MonoBehaviour { public Text downText; public Text pressText; public Text pressValueText; public Text upText; public void Down(){ downText.text="YES"; StartCoroutine( ClearText(downText)); } public void Up(){ upText.text="YES"; StartCoroutine( ClearText(upText)); StartCoroutine( ClearText(pressText)); StartCoroutine( ClearText(pressValueText)); } public void Press(){ pressText.text="YES"; } public void PressValue(float value){ pressValueText.text = value.ToString(); } IEnumerator ClearText(Text textToCLead){ yield return new WaitForSeconds(0.3f); textToCLead.text = ""; } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.GridFS/GridFSFindOptions.cs<|end_filename|> /* Copyright 2016-present MongoDB Inc. * * 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 MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.GridFS { /// <summary> /// Represents options for a GridFS Find operation. /// </summary> /// <typeparam name="TFileId">The type of the file identifier.</typeparam> public class GridFSFindOptions<TFileId> { // fields private int? _batchSize; private int? _limit; private TimeSpan? _maxTime; private bool? _noCursorTimeout; private int? _skip; private SortDefinition<GridFSFileInfo<TFileId>> _sort; // properties /// <summary> /// Gets or sets the batch size. /// </summary> /// <value> /// The batch size. /// </value> public int? BatchSize { get { return _batchSize; } set { _batchSize = Ensure.IsNullOrGreaterThanZero(value, nameof(value)); } } /// <summary> /// Gets or sets the maximum number of documents to return. /// </summary> /// <value> /// The maximum number of documents to return. /// </value> public int? Limit { get { return _limit; } set { _limit = value; } } /// <summary> /// Gets or sets the maximum time the server should spend on the Find. /// </summary> /// <value> /// The maximum time the server should spend on the Find. /// </value> public TimeSpan? MaxTime { get { return _maxTime; } set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); } } /// <summary> /// Gets or sets whether the cursor should not timeout. /// </summary> /// <value> /// Whether the cursor should not timeout. /// </value> public bool? NoCursorTimeout { get { return _noCursorTimeout; } set { _noCursorTimeout = value; } } /// <summary> /// Gets or sets the number of documents to skip. /// </summary> /// <value> /// The number of documents to skip. /// </value> public int? Skip { get { return _skip; } set { _skip = Ensure.IsNullOrGreaterThanOrEqualToZero(value, nameof(value)); } } /// <summary> /// Gets or sets the sort order. /// </summary> /// <value> /// The sort order. /// </value> public SortDefinition<GridFSFileInfo<TFileId>> Sort { get { return _sort; } set { _sort = value; } } } } <|start_filename|>Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/Core/RVO/RVOQuadtree.cs<|end_filename|> using UnityEngine; using Pathfinding.RVO.Sampled; namespace Pathfinding.RVO { /** Quadtree for quick nearest neighbour search of rvo agents. * \see Pathfinding.RVO.Simulator */ public class RVOQuadtree { const int LeafSize = 15; float maxRadius = 0; /** Node in a quadtree for storing RVO agents. * \see Pathfinding.GraphNode for the node class that is used for pathfinding data. */ struct Node { public int child00; public int child01; public int child10; public int child11; public Agent linkedList; public byte count; /** Maximum speed of all agents inside this node */ public float maxSpeed; public void Add (Agent agent) { agent.next = linkedList; linkedList = agent; } /** Distribute the agents in this node among the children. * Used after subdividing the node. */ public void Distribute (Node[] nodes, Rect r) { Vector2 c = r.center; while (linkedList != null) { Agent nx = linkedList.next; if (linkedList.position.x > c.x) { if (linkedList.position.y > c.y) { nodes[child11].Add(linkedList); } else { nodes[child10].Add(linkedList); } } else { if (linkedList.position.y > c.y) { nodes[child01].Add(linkedList); } else { nodes[child00].Add(linkedList); } } linkedList = nx; } count = 0; } public float CalculateMaxSpeed (Node[] nodes, int index) { if (child00 == index) { // Leaf node for (var agent = linkedList; agent != null; agent = agent.next) { maxSpeed = System.Math.Max(maxSpeed, agent.CalculatedSpeed); } } else { maxSpeed = System.Math.Max(nodes[child00].CalculateMaxSpeed(nodes, child00), nodes[child01].CalculateMaxSpeed(nodes, child01)); maxSpeed = System.Math.Max(maxSpeed, nodes[child10].CalculateMaxSpeed(nodes, child10)); maxSpeed = System.Math.Max(maxSpeed, nodes[child11].CalculateMaxSpeed(nodes, child11)); } return maxSpeed; } } Node[] nodes = new Node[42]; int filledNodes = 1; Rect bounds; /** Removes all agents from the tree */ public void Clear () { nodes[0] = new Node(); filledNodes = 1; maxRadius = 0; } public void SetBounds (Rect r) { bounds = r; } int GetNodeIndex () { if (filledNodes == nodes.Length) { var nds = new Node[nodes.Length*2]; for (int i = 0; i < nodes.Length; i++) nds[i] = nodes[i]; nodes = nds; } nodes[filledNodes] = new Node(); nodes[filledNodes].child00 = filledNodes; filledNodes++; return filledNodes-1; } /** Add a new agent to the tree. * \warning Agents must not be added multiple times to the same tree */ public void Insert (Agent agent) { int i = 0; Rect r = bounds; Vector2 p = new Vector2(agent.position.x, agent.position.y); agent.next = null; maxRadius = System.Math.Max(agent.radius, maxRadius); int depth = 0; while (true) { depth++; if (nodes[i].child00 == i) { // Leaf node. Break at depth 10 in case lots of agents ( > LeafSize ) are in the same spot if (nodes[i].count < LeafSize || depth > 10) { nodes[i].Add(agent); nodes[i].count++; break; } else { // Split Node node = nodes[i]; node.child00 = GetNodeIndex(); node.child01 = GetNodeIndex(); node.child10 = GetNodeIndex(); node.child11 = GetNodeIndex(); nodes[i] = node; nodes[i].Distribute(nodes, r); } } // Note, no else if (nodes[i].child00 != i) { // Not a leaf node Vector2 c = r.center; if (p.x > c.x) { if (p.y > c.y) { i = nodes[i].child11; r = Rect.MinMaxRect(c.x, c.y, r.xMax, r.yMax); } else { i = nodes[i].child10; r = Rect.MinMaxRect(c.x, r.yMin, r.xMax, c.y); } } else { if (p.y > c.y) { i = nodes[i].child01; r = Rect.MinMaxRect(r.xMin, c.y, c.x, r.yMax); } else { i = nodes[i].child00; r = Rect.MinMaxRect(r.xMin, r.yMin, c.x, c.y); } } } } } public void CalculateSpeeds () { nodes[0].CalculateMaxSpeed(nodes, 0); } public void Query (Vector2 p, float speed, float timeHorizon, float agentRadius, Agent agent) { new QuadtreeQuery { p = p, speed = speed, timeHorizon = timeHorizon, maxRadius = float.PositiveInfinity, agentRadius = agentRadius, agent = agent, nodes = nodes }.QueryRec(0, bounds); } struct QuadtreeQuery { public Vector2 p; public float speed, timeHorizon, agentRadius, maxRadius; public Agent agent; public Node[] nodes; public void QueryRec (int i, Rect r) { // Determine the radius that we need to search to take all agents into account // Note: the second agentRadius usage should actually be the radius of the other agents, not this agent // but for performance reasons and for simplicity we assume that agents have approximately the same radius. // Thus an agent with a very small radius may in some cases detect an agent with a very large radius too late // however this effect should be minor. var radius = System.Math.Min(System.Math.Max((nodes[i].maxSpeed + speed)*timeHorizon, agentRadius) + agentRadius, maxRadius); if (nodes[i].child00 == i) { // Leaf node for (Agent a = nodes[i].linkedList; a != null; a = a.next) { float v = agent.InsertAgentNeighbour(a, radius*radius); // Limit the search if the agent has hit the max number of nearby agents threshold if (v < maxRadius*maxRadius) { maxRadius = Mathf.Sqrt(v); } } } else { // Not a leaf node Vector2 c = r.center; if (p.x-radius < c.x) { if (p.y-radius < c.y) { QueryRec(nodes[i].child00, Rect.MinMaxRect(r.xMin, r.yMin, c.x, c.y)); radius = System.Math.Min(radius, maxRadius); } if (p.y+radius > c.y) { QueryRec(nodes[i].child01, Rect.MinMaxRect(r.xMin, c.y, c.x, r.yMax)); radius = System.Math.Min(radius, maxRadius); } } if (p.x+radius > c.x) { if (p.y-radius < c.y) { QueryRec(nodes[i].child10, Rect.MinMaxRect(c.x, r.yMin, r.xMax, c.y)); radius = System.Math.Min(radius, maxRadius); } if (p.y+radius > c.y) { QueryRec(nodes[i].child11, Rect.MinMaxRect(c.x, c.y, r.xMax, r.yMax)); } } } } } public void DebugDraw () { DebugDrawRec(0, bounds); } void DebugDrawRec (int i, Rect r) { Debug.DrawLine(new Vector3(r.xMin, 0, r.yMin), new Vector3(r.xMax, 0, r.yMin), Color.white); Debug.DrawLine(new Vector3(r.xMax, 0, r.yMin), new Vector3(r.xMax, 0, r.yMax), Color.white); Debug.DrawLine(new Vector3(r.xMax, 0, r.yMax), new Vector3(r.xMin, 0, r.yMax), Color.white); Debug.DrawLine(new Vector3(r.xMin, 0, r.yMax), new Vector3(r.xMin, 0, r.yMin), Color.white); if (nodes[i].child00 != i) { // Not a leaf node Vector2 c = r.center; DebugDrawRec(nodes[i].child11, Rect.MinMaxRect(c.x, c.y, r.xMax, r.yMax)); DebugDrawRec(nodes[i].child10, Rect.MinMaxRect(c.x, r.yMin, r.xMax, c.y)); DebugDrawRec(nodes[i].child01, Rect.MinMaxRect(r.xMin, c.y, c.x, r.yMax)); DebugDrawRec(nodes[i].child00, Rect.MinMaxRect(r.xMin, r.yMin, c.x, c.y)); } for (Agent a = nodes[i].linkedList; a != null; a = a.next) { var p = nodes[i].linkedList.position; Debug.DrawLine(new Vector3(p.x, 0, p.y)+Vector3.up, new Vector3(a.position.x, 0, a.position.y)+Vector3.up, new Color(1, 1, 0, 0.5f)); } } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Plugins/Components/EasyTouchTrigger.cs<|end_filename|> /*********************************************** EasyTouch V Copyright © 2014-2015 The Hedgehog Team http://www.thehedgehogteam.com/Forum/ <EMAIL> **********************************************/ using UnityEngine; using System.Collections; using System.Collections.Generic; namespace HedgehogTeam.EasyTouch{ [AddComponentMenu("EasyTouch/Trigger")] [System.Serializable] public class EasyTouchTrigger : MonoBehaviour { public enum ETTParameter{ None,Gesture, Finger_Id,Touch_Count, Start_Position, Position, Delta_Position, Swipe_Type, Swipe_Length, Swipe_Vector,Delta_Pinch, Twist_Anlge, ActionTime, DeltaTime, PickedObject, PickedUIElement } public enum ETTType {Object3D,UI}; [System.Serializable] public class EasyTouchReceiver{ public bool enable; public ETTType triggerType; public string name; public bool restricted; public GameObject gameObject; public bool otherReceiver; public GameObject gameObjectReceiver; public EasyTouch.EvtType eventName; public string methodName; public ETTParameter parameter; } [SerializeField] public List<EasyTouchReceiver> receivers = new List<EasyTouchReceiver>(); #region Monobehaviour Callback void Start(){ EasyTouch.SetEnableAutoSelect( true); } void OnEnable(){ SubscribeEasyTouchEvent(); } void OnDisable(){ UnsubscribeEasyTouchEvent(); } void OnDestroy(){ UnsubscribeEasyTouchEvent(); } private void SubscribeEasyTouchEvent(){ // Touch if (IsRecevier4( EasyTouch.EvtType.On_Cancel)) EasyTouch.On_Cancel += On_Cancel; if (IsRecevier4( EasyTouch.EvtType.On_TouchStart)) EasyTouch.On_TouchStart += On_TouchStart; if (IsRecevier4( EasyTouch.EvtType.On_TouchDown)) EasyTouch.On_TouchDown += On_TouchDown; if (IsRecevier4( EasyTouch.EvtType.On_TouchUp)) EasyTouch.On_TouchUp += On_TouchUp; // Tap & long tap if (IsRecevier4( EasyTouch.EvtType.On_SimpleTap)) EasyTouch.On_SimpleTap += On_SimpleTap; if (IsRecevier4( EasyTouch.EvtType.On_LongTapStart)) EasyTouch.On_LongTapStart += On_LongTapStart; if (IsRecevier4( EasyTouch.EvtType.On_LongTap)) EasyTouch.On_LongTap += On_LongTap; if (IsRecevier4( EasyTouch.EvtType.On_LongTapEnd)) EasyTouch.On_LongTapEnd += On_LongTapEnd; // Double tap if (IsRecevier4( EasyTouch.EvtType.On_DoubleTap)) EasyTouch.On_DoubleTap += On_DoubleTap; // Drag if (IsRecevier4( EasyTouch.EvtType.On_DragStart)) EasyTouch.On_DragStart += On_DragStart; if (IsRecevier4( EasyTouch.EvtType.On_Drag)) EasyTouch.On_Drag += On_Drag; if (IsRecevier4( EasyTouch.EvtType.On_DragEnd)) EasyTouch.On_DragEnd += On_DragEnd; // Swipe if (IsRecevier4( EasyTouch.EvtType.On_SwipeStart)) EasyTouch.On_SwipeStart += On_SwipeStart; if (IsRecevier4( EasyTouch.EvtType.On_Swipe)) EasyTouch.On_Swipe += On_Swipe; if (IsRecevier4( EasyTouch.EvtType.On_SwipeEnd)) EasyTouch.On_SwipeEnd += On_SwipeEnd; // Tap 2 fingers if (IsRecevier4( EasyTouch.EvtType.On_TouchStart2Fingers)) EasyTouch.On_TouchStart2Fingers += On_TouchStart2Fingers; if (IsRecevier4( EasyTouch.EvtType.On_TouchDown2Fingers)) EasyTouch.On_TouchDown2Fingers += On_TouchDown2Fingers; if (IsRecevier4( EasyTouch.EvtType.On_TouchUp2Fingers)) EasyTouch.On_TouchUp2Fingers += On_TouchUp2Fingers; // Tap & Long tap 2 fingers if (IsRecevier4( EasyTouch.EvtType.On_SimpleTap2Fingers)) EasyTouch.On_SimpleTap2Fingers+= On_SimpleTap2Fingers; if (IsRecevier4( EasyTouch.EvtType.On_LongTapStart2Fingers)) EasyTouch.On_LongTapStart2Fingers += On_LongTapStart2Fingers; if (IsRecevier4( EasyTouch.EvtType.On_LongTap2Fingers)) EasyTouch.On_LongTap2Fingers += On_LongTap2Fingers; if (IsRecevier4( EasyTouch.EvtType.On_LongTapEnd2Fingers)) EasyTouch.On_LongTapEnd2Fingers += On_LongTapEnd2Fingers; // double tap fingers if (IsRecevier4( EasyTouch.EvtType.On_DoubleTap2Fingers)) EasyTouch.On_DoubleTap2Fingers += On_DoubleTap2Fingers; // Swipe if (IsRecevier4( EasyTouch.EvtType.On_SwipeStart2Fingers)) EasyTouch.On_SwipeStart2Fingers += On_SwipeStart2Fingers; if (IsRecevier4( EasyTouch.EvtType.On_Swipe2Fingers)) EasyTouch.On_Swipe2Fingers += On_Swipe2Fingers; if (IsRecevier4( EasyTouch.EvtType.On_SwipeEnd2Fingers)) EasyTouch.On_SwipeEnd2Fingers += On_SwipeEnd2Fingers; // Drag if (IsRecevier4( EasyTouch.EvtType.On_DragStart2Fingers)) EasyTouch.On_DragStart2Fingers += On_DragStart2Fingers; if (IsRecevier4( EasyTouch.EvtType.On_Drag2Fingers)) EasyTouch.On_Drag2Fingers += On_Drag2Fingers; if (IsRecevier4( EasyTouch.EvtType.On_DragEnd2Fingers)) EasyTouch.On_DragEnd2Fingers += On_DragEnd2Fingers; // Pinch if (IsRecevier4( EasyTouch.EvtType.On_Pinch)) EasyTouch.On_Pinch += On_Pinch; if (IsRecevier4( EasyTouch.EvtType.On_PinchIn)) EasyTouch.On_PinchIn += On_PinchIn; if (IsRecevier4( EasyTouch.EvtType.On_PinchOut)) EasyTouch.On_PinchOut += On_PinchOut; if (IsRecevier4( EasyTouch.EvtType.On_PinchEnd)) EasyTouch.On_PinchEnd += On_PinchEnd; // Twist if (IsRecevier4( EasyTouch.EvtType.On_Twist)) EasyTouch.On_Twist += On_Twist; if (IsRecevier4( EasyTouch.EvtType.On_TwistEnd)) EasyTouch.On_TwistEnd += On_TwistEnd; // Unity UI if (IsRecevier4( EasyTouch.EvtType.On_OverUIElement)) EasyTouch.On_OverUIElement += On_OverUIElement; if (IsRecevier4( EasyTouch.EvtType.On_UIElementTouchUp)) EasyTouch.On_UIElementTouchUp += On_UIElementTouchUp; } private void UnsubscribeEasyTouchEvent(){ EasyTouch.On_Cancel -= On_Cancel; EasyTouch.On_TouchStart -= On_TouchStart; EasyTouch.On_TouchDown -= On_TouchDown; EasyTouch.On_TouchUp -= On_TouchUp; EasyTouch.On_SimpleTap -= On_SimpleTap; EasyTouch.On_LongTapStart -= On_LongTapStart; EasyTouch.On_LongTap -= On_LongTap; EasyTouch.On_LongTapEnd -= On_LongTapEnd; EasyTouch.On_DoubleTap -= On_DoubleTap; EasyTouch.On_DragStart -= On_DragStart; EasyTouch.On_Drag -= On_Drag; EasyTouch.On_DragEnd -= On_DragEnd; EasyTouch.On_SwipeStart -= On_SwipeStart; EasyTouch.On_Swipe -= On_Swipe; EasyTouch.On_SwipeEnd -= On_SwipeEnd; EasyTouch.On_TouchStart2Fingers -= On_TouchStart2Fingers; EasyTouch.On_TouchDown2Fingers -= On_TouchDown2Fingers; EasyTouch.On_TouchUp2Fingers -= On_TouchUp2Fingers; EasyTouch.On_SimpleTap2Fingers-= On_SimpleTap2Fingers; EasyTouch.On_LongTapStart2Fingers -= On_LongTapStart2Fingers; EasyTouch.On_LongTap2Fingers -= On_LongTap2Fingers; EasyTouch.On_LongTapEnd2Fingers -= On_LongTapEnd2Fingers; EasyTouch.On_DoubleTap2Fingers -= On_DoubleTap2Fingers; EasyTouch.On_SwipeStart2Fingers -= On_SwipeStart2Fingers; EasyTouch.On_Swipe2Fingers -= On_Swipe2Fingers; EasyTouch.On_SwipeEnd2Fingers -= On_SwipeEnd2Fingers; EasyTouch.On_DragStart2Fingers -= On_DragStart2Fingers; EasyTouch.On_Drag2Fingers -= On_Drag2Fingers; EasyTouch.On_DragEnd2Fingers -= On_DragEnd2Fingers; EasyTouch.On_Pinch -= On_Pinch; EasyTouch.On_PinchIn -= On_PinchIn; EasyTouch.On_PinchOut -= On_PinchOut; EasyTouch.On_PinchEnd -= On_PinchEnd; EasyTouch.On_Twist -= On_Twist; EasyTouch.On_TwistEnd -= On_TwistEnd; EasyTouch.On_OverUIElement += On_OverUIElement; EasyTouch.On_UIElementTouchUp += On_UIElementTouchUp; } #endregion #region One Finger EasyTouch Callback void On_TouchStart (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_TouchStart,gesture); } void On_TouchDown (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_TouchDown,gesture); } void On_TouchUp (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_TouchUp,gesture); } void On_SimpleTap (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_SimpleTap,gesture); } void On_DoubleTap (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_DoubleTap,gesture); } void On_LongTapStart (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_LongTapStart,gesture); } void On_LongTap (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_LongTap,gesture); } void On_LongTapEnd (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_LongTapEnd,gesture); } void On_SwipeStart (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_SwipeStart,gesture); } void On_Swipe (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_Swipe,gesture); } void On_SwipeEnd (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_SwipeEnd,gesture); } void On_DragStart (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_DragStart,gesture); } void On_Drag (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_Drag,gesture); } void On_DragEnd (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_DragEnd,gesture); } void On_Cancel (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_Cancel,gesture); } #endregion #region Two Finger EasyTouch Callback void On_TouchStart2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_TouchStart2Fingers,gesture); } void On_TouchDown2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_TouchDown2Fingers,gesture); } void On_TouchUp2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_TouchUp2Fingers,gesture); } void On_LongTapStart2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_LongTapStart2Fingers,gesture); } void On_LongTap2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_LongTap2Fingers,gesture); } void On_LongTapEnd2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_LongTapEnd2Fingers,gesture); } void On_DragStart2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_DragStart2Fingers,gesture); } void On_Drag2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_Drag2Fingers,gesture); } void On_DragEnd2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_DragEnd2Fingers,gesture); } void On_SwipeStart2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_SwipeStart2Fingers,gesture); } void On_Swipe2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_Swipe2Fingers,gesture); } void On_SwipeEnd2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_SwipeEnd2Fingers,gesture); } void On_Twist (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_Twist,gesture); } void On_TwistEnd (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_TwistEnd,gesture); } void On_Pinch (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_Pinch,gesture); } void On_PinchOut (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_PinchOut,gesture); } void On_PinchIn (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_PinchIn,gesture); } void On_PinchEnd (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_PinchEnd,gesture); } void On_SimpleTap2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_SimpleTap2Fingers,gesture); } void On_DoubleTap2Fingers (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_DoubleTap2Fingers,gesture); } #endregion #region UI Event void On_UIElementTouchUp (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_UIElementTouchUp,gesture); } void On_OverUIElement (Gesture gesture){ TriggerScheduler(EasyTouch.EvtType.On_OverUIElement,gesture); } #endregion #region Public Method public void AddTrigger(EasyTouch.EvtType ev){ EasyTouchReceiver r = new EasyTouchReceiver(); r.enable = true; r.restricted = true; r.eventName = ev; r.gameObject =null; r.otherReceiver = false; r.name = "New trigger"; receivers.Add( r ); if (Application.isPlaying){ UnsubscribeEasyTouchEvent(); SubscribeEasyTouchEvent(); } } public bool SetTriggerEnable(string triggerName,bool value){ EasyTouchReceiver r =GetTrigger( triggerName); if (r!=null){ r.enable = value; return true; } else{ return false; } } public bool GetTriggerEnable(string triggerName){ EasyTouchReceiver r =GetTrigger( triggerName); if (r!=null){ return r.enable; } else{ return false; } } #endregion #region Private Method private void TriggerScheduler(EasyTouch.EvtType evnt, Gesture gesture){ foreach( EasyTouchReceiver receiver in receivers){ if (receiver.enable && receiver.eventName == evnt){ if ( (receiver.restricted && ( (gesture.pickedObject == gameObject && receiver.triggerType == ETTType.Object3D ) || ( gesture.pickedUIElement == gameObject && receiver.triggerType == ETTType.UI ) )) || (!receiver.restricted && (receiver.gameObject == null || ((receiver.gameObject == gesture.pickedObject && receiver.triggerType == ETTType.Object3D ) || ( gesture.pickedUIElement == receiver.gameObject && receiver.triggerType == ETTType.UI ) ) )) ){ GameObject sender = gameObject; if (receiver.otherReceiver && receiver.gameObjectReceiver!=null){ sender = receiver.gameObjectReceiver; } switch (receiver.parameter){ case ETTParameter.None: sender.SendMessage( receiver.methodName,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.ActionTime: sender.SendMessage( receiver.methodName,gesture.actionTime,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.Delta_Pinch: sender.SendMessage( receiver.methodName,gesture.deltaPinch,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.Delta_Position: sender.SendMessage( receiver.methodName,gesture.deltaPosition,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.DeltaTime: sender.SendMessage( receiver.methodName,gesture.deltaTime,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.Finger_Id: sender.SendMessage( receiver.methodName,gesture.fingerIndex,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.Gesture: sender.SendMessage( receiver.methodName,gesture,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.PickedObject: if (gesture.pickedObject!=null){ sender.SendMessage( receiver.methodName,gesture.pickedObject,SendMessageOptions.DontRequireReceiver); } break; case ETTParameter.PickedUIElement: if (gesture.pickedUIElement!=null){ sender.SendMessage( receiver.methodName,gesture.pickedObject,SendMessageOptions.DontRequireReceiver); } break; case ETTParameter.Position: sender.SendMessage( receiver.methodName,gesture.position,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.Start_Position: sender.SendMessage( receiver.methodName,gesture.startPosition,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.Swipe_Length: sender.SendMessage( receiver.methodName,gesture.swipeLength,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.Swipe_Type: sender.SendMessage( receiver.methodName,gesture.swipe,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.Swipe_Vector: sender.SendMessage( receiver.methodName,gesture.swipeVector,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.Touch_Count: sender.SendMessage( receiver.methodName,gesture.touchCount,SendMessageOptions.DontRequireReceiver); break; case ETTParameter.Twist_Anlge: sender.SendMessage( receiver.methodName,gesture.twistAngle,SendMessageOptions.DontRequireReceiver); break; } } } } } private bool IsRecevier4(EasyTouch.EvtType evnt){ int result = receivers.FindIndex( delegate(EasyTouchTrigger.EasyTouchReceiver e){ return e.eventName == evnt; } ); if (result>-1){ return true; } else{ return false; } } private EasyTouchReceiver GetTrigger(string triggerName){ EasyTouchTrigger.EasyTouchReceiver t = receivers.Find( delegate(EasyTouchTrigger.EasyTouchReceiver n){ return n.name == triggerName; } ); return t; } #endregion } } <|start_filename|>Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/Navmesh/RelevantGraphSurface.cs<|end_filename|> using UnityEngine; namespace Pathfinding { /** Pruning of recast navmesh regions. * A RelevantGraphSurface component placed in the scene specifies that * the navmesh region it is inside should be included in the navmesh. * * \see Pathfinding.RecastGraph.relevantGraphSurfaceMode * */ [AddComponentMenu("Pathfinding/Navmesh/RelevantGraphSurface")] [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_relevant_graph_surface.php")] public class RelevantGraphSurface : VersionedMonoBehaviour { private static RelevantGraphSurface root; public float maxRange = 1; private RelevantGraphSurface prev; private RelevantGraphSurface next; private Vector3 position; public Vector3 Position { get { return position; } } public RelevantGraphSurface Next { get { return next; } } public RelevantGraphSurface Prev { get { return prev; } } public static RelevantGraphSurface Root { get { return root; } } public void UpdatePosition () { position = transform.position; } void OnEnable () { UpdatePosition(); if (root == null) { root = this; } else { next = root; root.prev = this; root = this; } } void OnDisable () { if (root == this) { root = next; if (root != null) root.prev = null; } else { if (prev != null) prev.next = next; if (next != null) next.prev = prev; } prev = null; next = null; } /** Updates the positions of all relevant graph surface components. * Required to be able to use the position property reliably. */ public static void UpdateAllPositions () { RelevantGraphSurface c = root; while (c != null) { c.UpdatePosition(); c = c.Next; } } public static void FindAllGraphSurfaces () { var srf = GameObject.FindObjectsOfType(typeof(RelevantGraphSurface)) as RelevantGraphSurface[]; for (int i = 0; i < srf.Length; i++) { srf[i].OnDisable(); srf[i].OnEnable(); } } public void OnDrawGizmos () { Gizmos.color = new Color(57/255f, 211/255f, 46/255f, 0.4f); Gizmos.DrawLine(transform.position - Vector3.up*maxRange, transform.position + Vector3.up*maxRange); } public void OnDrawGizmosSelected () { Gizmos.color = new Color(57/255f, 211/255f, 46/255f); Gizmos.DrawLine(transform.position - Vector3.up*maxRange, transform.position + Vector3.up*maxRange); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/WireProtocol/Messages/CommandMessageSection.cs<|end_filename|> /* Copyright 2018-present MongoDB Inc. * * 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 MongoDB.Bson.IO; using MongoDB.Bson.Serialization; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Core.WireProtocol.Messages { /// <summary> /// Represents the payload type. /// </summary> public enum PayloadType { /// <summary> /// Payload type 0. /// </summary> Type0 = 0, /// <summary> /// Payload type 1. /// </summary> Type1 = 1 } /// <summary> /// Represents a CommandMessage section. /// </summary> public abstract class CommandMessageSection { /// <summary> /// Gets the type of the payload. /// </summary> /// <value> /// The type of the payload. /// </value> public abstract PayloadType PayloadType { get; } } /// <summary> /// Represents a Type 0 CommandMessage section. /// </summary> /// <seealso cref="MongoDB.Driver.Core.WireProtocol.Messages.CommandMessageSection" /> public abstract class Type0CommandMessageSection : CommandMessageSection { // private fields private readonly object _document; private readonly IBsonSerializer _documentSerializer; // constructors /// <summary> /// Initializes a new instance of the <see cref="Type0CommandMessageSection{TDocument}"/> class. /// </summary> /// <param name="document">The document.</param> /// <param name="documentSerializer">The document serializer.</param> public Type0CommandMessageSection(object document, IBsonSerializer documentSerializer) { Ensure.IsNotNull((object)document, nameof(document)); _document = document; _documentSerializer = Ensure.IsNotNull(documentSerializer, nameof(documentSerializer)); } // public properties /// <summary> /// Gets the document. /// </summary> /// <value> /// The document. /// </value> public object Document => _document; /// <summary> /// Gets the document serializer. /// </summary> /// <value> /// The document serializer. /// </value> public IBsonSerializer DocumentSerializer => _documentSerializer; /// <inheritdoc /> public override PayloadType PayloadType => PayloadType.Type0; } /// <summary> /// Represents a Type 0 CommandMessage section. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> /// <seealso cref="MongoDB.Driver.Core.WireProtocol.Messages.Type0CommandMessageSection" /> public sealed class Type0CommandMessageSection<TDocument> : Type0CommandMessageSection { // private fields private readonly TDocument _document; private readonly IBsonSerializer<TDocument> _documentSerializer; // constructors /// <summary> /// Initializes a new instance of the <see cref="Type0CommandMessageSection{TDocument}"/> class. /// </summary> /// <param name="document">The document.</param> /// <param name="documentSerializer">The document serializer.</param> public Type0CommandMessageSection(TDocument document, IBsonSerializer<TDocument> documentSerializer) : base(document, documentSerializer) { Ensure.IsNotNull((object)document, nameof(document)); _document = document; _documentSerializer = Ensure.IsNotNull(documentSerializer, nameof(documentSerializer)); } // public properties /// <summary> /// Gets the document. /// </summary> /// <value> /// The document. /// </value> public new TDocument Document => _document; /// <summary> /// Gets the document serializer. /// </summary> /// <value> /// The document serializer. /// </value> public new IBsonSerializer<TDocument> DocumentSerializer => _documentSerializer; } /// <summary> /// Represents a Type 1 CommandMessage section. /// </summary> public abstract class Type1CommandMessageSection : CommandMessageSection { // private fields private readonly IBatchableSource<object> _documents; private readonly IBsonSerializer _documentSerializer; private readonly IElementNameValidator _elementNameValidator; private readonly string _identifier; private readonly int? _maxBatchCount; private readonly int? _maxDocumentSize; // constructors /// <summary> /// Initializes a new instance of the <see cref="Type1CommandMessageSection{TDocument}" /> class. /// </summary> /// <param name="identifier">The identifier.</param> /// <param name="documents">The documents.</param> /// <param name="documentSerializer">The document serializer.</param> /// <param name="elementNameValidator">The element name validator.</param> /// <param name="maxBatchCount">The maximum batch count.</param> /// <param name="maxDocumentSize">Maximum size of the document.</param> public Type1CommandMessageSection( string identifier, IBatchableSource<object> documents, IBsonSerializer documentSerializer, IElementNameValidator elementNameValidator, int? maxBatchCount, int? maxDocumentSize) { _identifier = Ensure.IsNotNull(identifier, nameof(identifier)); _documents = Ensure.IsNotNull(documents, nameof(documents)); _documentSerializer = Ensure.IsNotNull(documentSerializer, nameof(documentSerializer)); _elementNameValidator = Ensure.IsNotNull(elementNameValidator, nameof(elementNameValidator)); _maxBatchCount = Ensure.IsNullOrGreaterThanZero(maxBatchCount, nameof(maxBatchCount)); _maxDocumentSize = Ensure.IsNullOrGreaterThanZero(maxDocumentSize, nameof(maxDocumentSize)); } // public properties /// <summary> /// Gets the documents. /// </summary> /// <value> /// The documents. /// </value> public IBatchableSource<object> Documents => _documents; /// <summary> /// Gets the document serializer. /// </summary> /// <value> /// The document serializer. /// </value> public IBsonSerializer DocumentSerializer => _documentSerializer; /// <summary> /// Gets the type of the document. /// </summary> /// <value> /// The type of the document. /// </value> public abstract Type DocumentType { get; } /// <summary> /// Gets the element name validator. /// </summary> /// <value> /// The element name validator. /// </value> public IElementNameValidator ElementNameValidator => _elementNameValidator; /// <summary> /// Gets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public string Identifier => _identifier; /// <summary> /// Gets the maximum batch count. /// </summary> /// <value> /// The maximum batch count. /// </value> public int? MaxBatchCount => _maxBatchCount; /// <summary> /// Gets the maximum size of the document. /// </summary> /// <value> /// The maximum size of the document. /// </value> public int? MaxDocumentSize => _maxDocumentSize; /// <inheritdoc /> public override PayloadType PayloadType => PayloadType.Type1; } /// <summary> /// Represents a Type 1 CommandMessage section. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> /// <seealso cref="MongoDB.Driver.Core.WireProtocol.Messages.CommandMessageSection" /> public class Type1CommandMessageSection<TDocument> : Type1CommandMessageSection where TDocument : class { // private fields private readonly IBatchableSource<TDocument> _documents; private readonly IBsonSerializer<TDocument> _documentSerializer; // constructors /// <summary> /// Initializes a new instance of the <see cref="Type1CommandMessageSection{TDocument}" /> class. /// </summary> /// <param name="identifier">The identifier.</param> /// <param name="documents">The documents.</param> /// <param name="documentSerializer">The document serializer.</param> /// <param name="elementNameValidator">The element name validator.</param> /// <param name="maxBatchCount">The maximum batch count.</param> /// <param name="maxDocumentSize">Maximum size of the document.</param> public Type1CommandMessageSection( string identifier, IBatchableSource<TDocument> documents, IBsonSerializer<TDocument> documentSerializer, IElementNameValidator elementNameValidator, int? maxBatchCount, int? maxDocumentSize) : base(identifier, documents, documentSerializer, elementNameValidator, maxBatchCount, maxDocumentSize) { _documents = Ensure.IsNotNull(documents, nameof(documents)); _documentSerializer = Ensure.IsNotNull(documentSerializer, nameof(documentSerializer)); } // public properties /// <summary> /// Gets the documents. /// </summary> /// <value> /// The documents. /// </value> public new IBatchableSource<TDocument> Documents => _documents; /// <summary> /// Gets the document serializer. /// </summary> /// <value> /// The document serializer. /// </value> public new IBsonSerializer<TDocument> DocumentSerializer => _documentSerializer; /// <inheritdoc /> public override Type DocumentType => typeof(TDocument); } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Plugins/Engine/TwoFingerGesture.cs<|end_filename|> /*********************************************** EasyTouch V Copyright © 2014-2015 The Hedgehog Team http://www.thehedgehogteam.com/Forum/ <EMAIL> **********************************************/ using UnityEngine; using System.Collections; namespace HedgehogTeam.EasyTouch{ public class TwoFingerGesture{ public EasyTouch.GestureType currentGesture = EasyTouch.GestureType.None; public EasyTouch.GestureType oldGesture= EasyTouch.GestureType.None; public int finger0; public int finger1; public float startTimeAction; public float timeSinceStartAction; public Vector2 startPosition; public Vector2 position; public Vector2 deltaPosition; public Vector2 oldStartPosition; public float startDistance; public float fingerDistance; public float oldFingerDistance; public bool lockPinch=false; public bool lockTwist=true; public float lastPinch=0; public float lastTwistAngle = 0; // Game Object public GameObject pickedObject; public GameObject oldPickedObject; public Camera pickedCamera; public bool isGuiCamera; // UI public bool isOverGui; public GameObject pickedUIElement; public bool dragStart=false; public bool swipeStart=false; public bool inSingleDoubleTaps = false; public float tapCurentTime = 0; public void ClearPickedObjectData(){ pickedObject = null; oldPickedObject = null; pickedCamera = null; isGuiCamera = false; } public void ClearPickedUIData(){ isOverGui = false; pickedUIElement = null; } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/External/SemVersionExtension.cs<|end_filename|> namespace Semver { internal static class SemVersionExtension { public static string VersionOnly(this SemVersion version) { return "" + version.Major + "." + version.Minor + "." + version.Patch; } public static string ShortVersion(this SemVersion version) { return version.Major + "." + version.Minor; } } } <|start_filename|>Unity/Assets/Model/Module/Pathfinding/Recast/AstarMemory.cs<|end_filename|> using System; namespace PF { /** Various utilities for handling arrays and memory */ public static class Memory { /** Sets all values in an array to a specific value faster than a loop. * Only faster for large arrays. Slower for small ones. * Tests indicate it becomes faster somewhere when the length of the array grows above around 100. * For large arrays this can be magnitudes faster. Up to 40 times faster has been measured. * * \note Only works on primitive value types such as int, long, float, etc. * * \param array the array to fill * \param value the value to fill the array with * \param byteSize size in bytes of every element in the array. e.g 4 bytes for an int, or 8 bytes for a long. * It can be efficiently got using the sizeof built-in function. * * \code * //Set all values to 8 in the array * int[] arr = new int[20000]; * Pathfinding.Util.Memory.MemSet<int> (arr, 8, sizeof(int)); * \endcode * \see System.Buffer.BlockCopy */ public static void MemSet<T>(T[] array, T value, int byteSize) where T : struct { if (array == null) { throw new ArgumentNullException("array"); } int block = 32, index = 0; int length = Math.Min(block, array.Length); //Fill the initial array while (index < length) { array[index] = value; index++; } length = array.Length; while (index < length) { Buffer.BlockCopy(array, 0, array, index*byteSize, Math.Min(block, length-index)*byteSize); index += block; block *= 2; } } /** Sets all values in an array to a specific value faster than a loop. * Only faster for large arrays. Slower for small ones. * Tests indicate it becomes faster somewhere when the length of the array grows above around 100. * For large arrays this can be magnitudes faster. Up to 40 times faster has been measured. * * \note Only works on primitive value types such as int, long, float, etc. * * \param array the array to fill * \param value the value to fill the array with * \param byteSize size in bytes of every element in the array. e.g 4 bytes for an int, or 8 bytes for a long. * \param totalSize all indices in the range [0, totalSize-1] will be set * * It can be efficiently got using the sizeof built-in function. * * \code * //Set all values to 8 in the array * int[] arr = new int[20000]; * Pathfinding.Util.Memory.MemSet<int> (arr, 8, sizeof(int)); * \endcode * \see System.Buffer.BlockCopy */ public static void MemSet<T>(T[] array, T value, int totalSize, int byteSize) where T : struct { if (array == null) { throw new ArgumentNullException("array"); } int block = 32, index = 0; int length = Math.Min(block, totalSize); //Fill the initial array while (index < length) { array[index] = value; index++; } length = totalSize; while (index < length) { Buffer.BlockCopy(array, 0, array, index*byteSize, Math.Min(block, totalSize-index)*byteSize); index += block; block *= 2; } } /** Returns a new array with at most length \a newLength. * The array will contain a copy of all elements of \a arr up to but excluding the index newLength. */ public static T[] ShrinkArray<T>(T[] arr, int newLength) { newLength = Math.Min(newLength, arr.Length); var shrunkArr = new T[newLength]; Array.Copy(arr, shrunkArr, newLength); return shrunkArr; } /** Swaps the variables a and b */ public static void Swap<T>(ref T a, ref T b) { T tmp = a; a = b; b = tmp; } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Clusters/ElectionId.cs<|end_filename|> /* Copyright 2013-present MongoDB Inc. * * 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 MongoDB.Bson; namespace MongoDB.Driver.Core.Clusters { /// <summary> /// An election id from the server. /// </summary> public sealed class ElectionId : IEquatable<ElectionId>, IComparable<ElectionId> { private readonly ObjectId _id; /// <summary> /// Initializes a new instance of the <see cref="ElectionId"/> class. /// </summary> /// <param name="id">The identifier.</param> public ElectionId(ObjectId id) { _id = id; } /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other" /> parameter.Zero This object is equal to <paramref name="other" />. Greater than zero This object is greater than <paramref name="other" />. /// </returns> public int CompareTo(ElectionId other) { if (other == null) { return 1; } return _id.CompareTo(other._id); } /// <summary> /// Determines whether the specified <see cref="System.Object" />, is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return Equals(obj as ElectionId); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false. /// </returns> public bool Equals(ElectionId other) { return CompareTo(other) == 0; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return _id.GetHashCode(); } /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { return _id.ToString(); } } } <|start_filename|>Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/Modifiers/RadiusModifier.cs<|end_filename|> using UnityEngine; using System; using System.Collections.Generic; using PF; using Vector3 = UnityEngine.Vector3; namespace Pathfinding { /** Radius path modifier for offsetting paths. * \ingroup modifiers * * The radius modifier will offset the path to create the effect * of adjusting it to the characters radius. * It gives good results on navmeshes which have not been offset with the * character radius during scan. Especially useful when characters with different * radiuses are used on the same navmesh. It is also useful when using * rvo local avoidance with the RVONavmesh since the RVONavmesh assumes the * navmesh has not been offset with the character radius. * * This modifier assumes all paths are in the XZ plane (i.e Y axis is up). * * It is recommended to use the Funnel Modifier on the path as well. * * \shadowimage{radius_modifier.png} * * \see RVONavmesh * \see modifiers * * Also check out the howto page "Using Modifiers". * * \astarpro * * \since Added in 3.2.6 */ [AddComponentMenu("Pathfinding/Modifiers/Radius Offset")] [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_radius_modifier.php")] public class RadiusModifier : MonoModifier { #if UNITY_EDITOR [UnityEditor.MenuItem("CONTEXT/Seeker/Add Radius Modifier")] public static void AddComp (UnityEditor.MenuCommand command) { (command.context as Component).gameObject.AddComponent(typeof(RadiusModifier)); } #endif public override int Order { get { return 41; } } /** Radius of the circle segments generated. * Usually similar to the character radius. */ public float radius = 1f; /** Detail of generated circle segments. * Measured as steps per full circle. * * It is more performant to use a low value. * For movement, using a high value will barely improve path quality. */ public float detail = 10; /** Calculates inner tangents for a pair of circles. * \param p1 Position of first circle * \param p2 Position of the second circle * \param r1 Radius of the first circle * \param r2 Radius of the second circle * \param a Angle from the line joining the centers of the circles to the inner tangents. * \param sigma World angle from p1 to p2 (in XZ space) * * Add \a a to \a sigma to get the first tangent angle, subtract \a a from \a sigma to get the second tangent angle. * * \returns True on success. False when the circles are overlapping. */ bool CalculateCircleInner (Vector3 p1, Vector3 p2, float r1, float r2, out float a, out float sigma) { float dist = (p1-p2).magnitude; if (r1+r2 > dist) { a = 0; sigma = 0; return false; } a = (float)Math.Acos((r1+r2)/dist); sigma = (float)Math.Atan2(p2.z-p1.z, p2.x-p1.x); return true; } /** Calculates outer tangents for a pair of circles. * \param p1 Position of first circle * \param p2 Position of the second circle * \param r1 Radius of the first circle * \param r2 Radius of the second circle * \param a Angle from the line joining the centers of the circles to the inner tangents. * \param sigma World angle from p1 to p2 (in XZ space) * * Add \a a to \a sigma to get the first tangent angle, subtract \a a from \a sigma to get the second tangent angle. * * \returns True on success. False on failure (more specifically when |r1-r2| > |p1-p2| ) */ bool CalculateCircleOuter (Vector3 p1, Vector3 p2, float r1, float r2, out float a, out float sigma) { float dist = (p1-p2).magnitude; if (Math.Abs(r1 - r2) > dist) { a = 0; sigma = 0; return false; } a = (float)Math.Acos((r1-r2)/dist); sigma = (float)Math.Atan2(p2.z-p1.z, p2.x-p1.x); return true; } [System.Flags] enum TangentType { OuterRight = 1 << 0, InnerRightLeft = 1 << 1, InnerLeftRight = 1 << 2, OuterLeft = 1 << 3, Outer = OuterRight | OuterLeft, Inner = InnerRightLeft | InnerLeftRight } TangentType CalculateTangentType (Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4) { bool l1 = VectorMath.RightOrColinearXZ(p1, p2, p3); bool l2 = VectorMath.RightOrColinearXZ(p2, p3, p4); return (TangentType)(1 << ((l1 ? 2 : 0) + (l2 ? 1 : 0))); } TangentType CalculateTangentTypeSimple (Vector3 p1, Vector3 p2, Vector3 p3) { bool l2 = VectorMath.RightOrColinearXZ(p1, p2, p3); bool l1 = l2; return (TangentType)(1 << ((l1 ? 2 : 0) + (l2 ? 1 : 0))); } public override void Apply (Path p) { List<Vector3> vs = p.vectorPath; List<Vector3> res = Apply(vs); if (res != vs) { ListPool<Vector3>.Release(ref p.vectorPath); p.vectorPath = res; } } float[] radi = new float[10]; float[] a1 = new float[10]; float[] a2 = new float[10]; bool[] dir = new bool[10]; /** Apply this modifier on a raw Vector3 list */ public List<Vector3> Apply (List<Vector3> vs) { if (vs == null || vs.Count < 3) return vs; /** \todo Do something about these allocations */ if (radi.Length < vs.Count) { radi = new float[vs.Count]; a1 = new float[vs.Count]; a2 = new float[vs.Count]; dir = new bool[vs.Count]; } for (int i = 0; i < vs.Count; i++) { radi[i] = radius; } radi[0] = 0; radi[vs.Count-1] = 0; int count = 0; for (int i = 0; i < vs.Count-1; i++) { count++; if (count > 2*vs.Count) { Debug.LogWarning("Could not resolve radiuses, the path is too complex. Try reducing the base radius"); break; } TangentType tt; if (i == 0) { tt = CalculateTangentTypeSimple(vs[i], vs[i+1], vs[i+2]); } else if (i == vs.Count-2) { tt = CalculateTangentTypeSimple(vs[i-1], vs[i], vs[i+1]); } else { tt = CalculateTangentType(vs[i-1], vs[i], vs[i+1], vs[i+2]); } //DrawCircle (vs[i], radi[i], Color.yellow); if ((tt & TangentType.Inner) != 0) { //Angle to tangent float a; //Angle to other circle float sigma; //Calculate angles to the next circle and angles for the inner tangents if (!CalculateCircleInner(vs[i], vs[i+1], radi[i], radi[i+1], out a, out sigma)) { //Failed, try modifying radiuses float magn = (vs[i+1]-vs[i]).magnitude; radi[i] = magn*(radi[i]/(radi[i]+radi[i+1])); radi[i+1] = magn - radi[i]; radi[i] *= 0.99f; radi[i+1] *= 0.99f; i -= 2; continue; } if (tt == TangentType.InnerRightLeft) { a2[i] = sigma-a; a1[i+1] = sigma-a + (float)Math.PI; dir[i] = true; } else { a2[i] = sigma+a; a1[i+1] = sigma+a + (float)Math.PI; dir[i] = false; } } else { float sigma; float a; //Calculate angles to the next circle and angles for the outer tangents if (!CalculateCircleOuter(vs[i], vs[i+1], radi[i], radi[i+1], out a, out sigma)) { //Failed, try modifying radiuses if (i == vs.Count-2) { //The last circle has a fixed radius at 0, don't modify it radi[i] = (vs[i+1]-vs[i]).magnitude; radi[i] *= 0.99f; i -= 1; } else { if (radi[i] > radi[i+1]) { radi[i+1] = radi[i] - (vs[i+1]-vs[i]).magnitude; } else { radi[i+1] = radi[i] + (vs[i+1]-vs[i]).magnitude; } radi[i+1] *= 0.99f; } i -= 1; continue; } if (tt == TangentType.OuterRight) { a2[i] = sigma-a; a1[i+1] = sigma-a; dir[i] = true; } else { a2[i] = sigma+a; a1[i+1] = sigma+a; dir[i] = false; } } } List<Vector3> res = ListPool<Vector3>.Claim(); res.Add(vs[0]); if (detail < 1) detail = 1; float step = (float)(2*Math.PI)/detail; for (int i = 1; i < vs.Count-1; i++) { float start = a1[i]; float end = a2[i]; float rad = radi[i]; if (dir[i]) { if (end < start) end += (float)Math.PI*2; for (float t = start; t < end; t += step) { res.Add(new Vector3((float)Math.Cos(t), 0, (float)Math.Sin(t)).ToPFV3()*rad + vs[i]); } } else { if (start < end) start += (float)Math.PI*2; for (float t = start; t > end; t -= step) { res.Add(new Vector3((float)Math.Cos(t), 0, (float)Math.Sin(t)).ToPFV3()*rad + vs[i]); } } } res.Add(vs[vs.Count-1]); return res; } } } <|start_filename|>Unity/Assets/Model/Module/Demo/Player.cs<|end_filename|> namespace ETModel { public sealed class Player : Entity { public long UnitId { get; set; } public override void Dispose() { if (this.IsDisposed) { return; } base.Dispose(); } } } <|start_filename|>Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/Core/Misc/GraphEditorBase.cs<|end_filename|> using PF; namespace Pathfinding { [JsonOptIn] /** Defined here only so non-editor classes can use the #target field */ public class GraphEditorBase { /** NavGraph this editor is exposing */ public NavGraph target; } } <|start_filename|>Unity/Assets/Model/Base/IL/IDisposableAdaptor.cs<|end_filename|> using System; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; namespace ETModel { [ILAdapter] public class IDisposableClassInheritanceAdaptor : CrossBindingAdaptor { public override Type BaseCLRType { get { return typeof (IDisposable); } } public override Type AdaptorType { get { return typeof (IDisposableAdaptor); } } public override object CreateCLRInstance(ILRuntime.Runtime.Enviorment.AppDomain appdomain, ILTypeInstance instance) { return new IDisposableAdaptor(appdomain, instance); } public class IDisposableAdaptor: IDisposable, CrossBindingAdaptorType { private ILTypeInstance instance; private ILRuntime.Runtime.Enviorment.AppDomain appDomain; private IMethod iDisposable; private readonly object[] param0 = new object[0]; public IDisposableAdaptor() { } public IDisposableAdaptor(ILRuntime.Runtime.Enviorment.AppDomain appDomain, ILTypeInstance instance) { this.appDomain = appDomain; this.instance = instance; } public ILTypeInstance ILInstance { get { return instance; } } public void Dispose() { if (this.iDisposable == null) { this.iDisposable = instance.Type.GetMethod("Dispose"); } this.appDomain.Invoke(this.iDisposable, instance, this.param0); } public override string ToString() { IMethod m = this.appDomain.ObjectType.GetMethod("ToString", 0); m = instance.Type.GetVirtualMethod(m); if (m == null || m is ILMethod) { return instance.ToString(); } return instance.Type.FullName; } } } } <|start_filename|>Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/Core/astarclasses.cs<|end_filename|> using UnityEngine; using System.Collections.Generic; using PF; using Mathf = UnityEngine.Mathf; // Empty namespace declaration to avoid errors in the free version // Which does not have any classes in the RVO namespace namespace Pathfinding.RVO {} namespace Pathfinding { using Pathfinding.Util; #if UNITY_5_0 /** Used in Unity 5.0 since the HelpURLAttribute was first added in Unity 5.1 */ public class HelpURLAttribute : Attribute { } #endif [System.Serializable] /** Stores editor colors */ public class AstarColor { public Color _NodeConnection; public Color _UnwalkableNode; public Color _BoundsHandles; public Color _ConnectionLowLerp; public Color _ConnectionHighLerp; public Color _MeshEdgeColor; /** Holds user set area colors. * Use GetAreaColor to get an area color */ public Color[] _AreaColors; public static Color NodeConnection = new Color(1, 1, 1, 0.9F); public static Color UnwalkableNode = new Color(1, 0, 0, 0.5F); public static Color BoundsHandles = new Color(0.29F, 0.454F, 0.741F, 0.9F); public static Color ConnectionLowLerp = new Color(0, 1, 0, 0.5F); public static Color ConnectionHighLerp = new Color(1, 0, 0, 0.5F); public static Color MeshEdgeColor = new Color(0, 0, 0, 0.5F); /** Holds user set area colors. * Use GetAreaColor to get an area color */ private static Color[] AreaColors; /** Returns an color for an area, uses both user set ones and calculated. * If the user has set a color for the area, it is used, but otherwise the color is calculated using Mathfx.IntToColor * \see #AreaColors */ public static Color GetAreaColor (uint area) { if (AreaColors == null || area >= AreaColors.Length) { return UnityHelper.IntToColor((int)area, 1F); } return AreaColors[(int)area]; } /** Pushes all local variables out to static ones. * This is done because that makes it so much easier to access the colors during Gizmo rendering * and it has a positive performance impact as well (gizmo rendering is hot code). */ public void OnEnable () { NodeConnection = _NodeConnection; UnwalkableNode = _UnwalkableNode; BoundsHandles = _BoundsHandles; ConnectionLowLerp = _ConnectionLowLerp; ConnectionHighLerp = _ConnectionHighLerp; MeshEdgeColor = _MeshEdgeColor; AreaColors = _AreaColors; } public AstarColor () { // Set default colors _NodeConnection = new Color(1, 1, 1, 0.9F); _UnwalkableNode = new Color(1, 0, 0, 0.5F); _BoundsHandles = new Color(0.29F, 0.454F, 0.741F, 0.9F); _ConnectionLowLerp = new Color(0, 1, 0, 0.5F); _ConnectionHighLerp = new Color(1, 0, 0, 0.5F); _MeshEdgeColor = new Color(0, 0, 0, 0.5F); } } /** Progress info for e.g a progressbar. * Used by the scan functions in the project * \see #AstarPath.ScanAsync */ public struct Progress { /** Current progress as a value between 0 and 1 */ public readonly float progress; /** Description of what is currently being done */ public readonly string description; public Progress (float progress, string description) { this.progress = progress; this.description = description; } public Progress MapTo (float min, float max, string prefix = null) { return new Progress(Mathf.Lerp(min, max, progress), prefix + description); } public override string ToString () { return progress.ToString("0.0") + " " + description; } } /** Represents a collection of settings used to update nodes in a specific region of a graph. * \see AstarPath.UpdateGraphs * \see \ref graph-updates */ public class GraphUpdateObject { /** The bounds to update nodes within. * Defined in world space. */ public Bounds bounds; /** Controlls if a flood fill will be carried out after this GUO has been applied. * Disabling this can be used to gain a performance boost, but use with care. * If you are sure that a GUO will not modify walkability or connections. You can set this to false. * For example when only updating penalty values it can save processing power when setting this to false. Especially on large graphs. * \note If you set this to false, even though it does change e.g walkability, it can lead to paths returning that they failed even though there is a path, * or the try to search the whole graph for a path even though there is none, and will in the processes use wast amounts of processing power. * * If using the basic GraphUpdateObject (not a derived class), a quick way to check if it is going to need a flood fill is to check if #modifyWalkability is true or #updatePhysics is true. * */ public bool requiresFloodFill = true; /** Use physics checks to update nodes. * When updating a grid graph and this is true, the nodes' position and walkability will be updated using physics checks * with settings from "Collision Testing" and "Height Testing". * * When updating a PointGraph, setting this to true will make it re-evaluate all connections in the graph which passes through the #bounds. * This has no effect when updating GridGraphs if #modifyWalkability is turned on. * * On RecastGraphs, having this enabled will trigger a complete recalculation of all tiles intersecting the bounds. * This is quite slow (but powerful). If you only want to update e.g penalty on existing nodes, leave it disabled. */ public bool updatePhysics = true; /** Reset penalties to their initial values when updating grid graphs and #updatePhysics is true. * If you want to keep old penalties even when you update the graph you may want to disable this option. * * The images below shows two overlapping graph update objects, the right one happened to be applied before the left one. They both have updatePhysics = true and are * set to increase the penalty of the nodes by some amount. * * The first image shows the result when resetPenaltyOnPhysics is false. Both penalties are added correctly. * \shadowimage{resetPenaltyOnPhysics_False.png} * * This second image shows when resetPenaltyOnPhysics is set to true. The first GUO is applied correctly, but then the second one (the left one) is applied * and during its updating, it resets the penalties first and then adds penalty to the nodes. The result is that the penalties from both GUOs are not added together. * The green patch in at the border is there because physics recalculation (recalculation of the position of the node, checking for obstacles etc.) affects a slightly larger * area than the original GUO bounds because of the Grid Graph -> Collision Testing -> Diameter setting (it is enlarged by that value). So some extra nodes have their penalties reset. * * \shadowimage{resetPenaltyOnPhysics_True.png} */ public bool resetPenaltyOnPhysics = true; /** Update Erosion for GridGraphs. * When enabled, erosion will be recalculated for grid graphs * after the GUO has been applied. * * In the below image you can see the different effects you can get with the different values.\n * The first image shows the graph when no GUO has been applied. The blue box is not identified as an obstacle by the graph, the reason * there are unwalkable nodes around it is because there is a height difference (nodes are placed on top of the box) so erosion will be applied (an erosion value of 2 is used in this graph). * The orange box is identified as an obstacle, so the area of unwalkable nodes around it is a bit larger since both erosion and collision has made * nodes unwalkable.\n * The GUO used simply sets walkability to true, i.e making all nodes walkable. * * \shadowimage{updateErosion.png} * * When updateErosion=True, the reason the blue box still has unwalkable nodes around it is because there is still a height difference * so erosion will still be applied. The orange box on the other hand has no height difference and all nodes are set to walkable.\n * \n * When updateErosion=False, all nodes walkability are simply set to be walkable in this example. * * \see Pathfinding.GridGraph */ public bool updateErosion = true; /** NNConstraint to use. * The Pathfinding.NNConstraint.SuitableGraph function will be called on the NNConstraint to enable filtering of which graphs to update.\n * \note As the Pathfinding.NNConstraint.SuitableGraph function is A* Pathfinding Project Pro only, this variable doesn't really affect anything in the free version. * * * \astarpro */ public NNConstraint nnConstraint = NNConstraint.None; /** Penalty to add to the nodes. * A penalty of 1000 is equivalent to the cost of moving 1 world unit. */ public int addPenalty; /** If true, all nodes' \a walkable variable will be set to #setWalkability */ public bool modifyWalkability; /** If #modifyWalkability is true, the nodes' \a walkable variable will be set to this value */ public bool setWalkability; /** If true, all nodes' \a tag will be set to #setTag */ public bool modifyTag; /** If #modifyTag is true, all nodes' \a tag will be set to this value */ public int setTag; /** Track which nodes are changed and save backup data. * Used internally to revert changes if needed. */ public bool trackChangedNodes; /** Nodes which were updated by this GraphUpdateObject. * Will only be filled if #trackChangedNodes is true. * \note It might take a few frames for graph update objects to be applied. * If you need this info immediately, use #AstarPath.FlushGraphUpdates. */ public List<GraphNode> changedNodes; private List<uint> backupData; private List<Int3> backupPositionData; /** A shape can be specified if a bounds object does not give enough precision. * Note that if you set this, you should set the bounds so that it encloses the shape * because the bounds will be used as an initial fast check for which nodes that should * be updated. */ public GraphUpdateShape shape; /** Should be called on every node which is updated with this GUO before it is updated. * \param node The node to save fields for. If null, nothing will be done * \see #trackChangedNodes */ public virtual void WillUpdateNode (GraphNode node) { if (trackChangedNodes && node != null) { if (changedNodes == null) { changedNodes = ListPool<GraphNode>.Claim(); backupData = ListPool<uint>.Claim(); backupPositionData = ListPool<Int3>.Claim(); } changedNodes.Add(node); backupPositionData.Add(node.position); backupData.Add(node.Penalty); backupData.Add(node.Flags); } } /** Reverts penalties and flags (which includes walkability) on every node which was updated using this GUO. * Data for reversion is only saved if #trackChangedNodes is true. * * \note Not all data is saved. The saved data includes: penalties, walkability, tags, area, position and for grid graphs (not layered) it also includes connection data. */ public virtual void RevertFromBackup () { if (trackChangedNodes) { if (changedNodes == null) return; int counter = 0; for (int i = 0; i < changedNodes.Count; i++) { changedNodes[i].Penalty = backupData[counter]; counter++; changedNodes[i].Flags = backupData[counter]; counter++; changedNodes[i].position = backupPositionData[i]; } ListPool<GraphNode>.Release(ref changedNodes); ListPool<uint>.Release(ref backupData); ListPool<Int3>.Release(ref backupPositionData); } else { throw new System.InvalidOperationException("Changed nodes have not been tracked, cannot revert from backup. Please set trackChangedNodes to true before applying the update."); } } /** Updates the specified node using this GUO's settings */ public virtual void Apply (GraphNode node) { if (shape == null || shape.Contains(node)) { //Update penalty and walkability node.Penalty = (uint)(node.Penalty+addPenalty); if (modifyWalkability) { node.Walkable = setWalkability; } //Update tags if (modifyTag) node.Tag = (uint)setTag; } } public GraphUpdateObject () { } /** Creates a new GUO with the specified bounds */ public GraphUpdateObject (Bounds b) { bounds = b; } } public delegate void OnGraphDelegate (NavGraph graph); public delegate void OnScanDelegate (AstarPath script); /** \deprecated */ public delegate void OnScanStatus (Progress progress); } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouchControls/Plugins/Editor/ETCAreaInspector.cs<|end_filename|> using UnityEngine; using UnityEditor; #if UNITY_5_3_OR_NEWER using UnityEditor.SceneManagement; #endif using System.Collections; [CustomEditor(typeof(ETCArea))] public class ETCAreaInspector : Editor { private ETCArea.AreaPreset preset = ETCArea.AreaPreset.Choose; public override void OnInspectorGUI(){ ETCArea t = (ETCArea)target; t.show = ETCGuiTools.Toggle("Show at runtime",t.show,true); EditorGUILayout.Space(); preset = (ETCArea.AreaPreset)EditorGUILayout.EnumPopup("Preset",preset ); if (preset != ETCArea.AreaPreset.Choose){ t.ApplyPreset( preset); preset = ETCArea.AreaPreset.Choose; } if (GUI.changed){ EditorUtility.SetDirty(t); #if UNITY_5_3_OR_NEWER EditorSceneManager.MarkSceneDirty( EditorSceneManager.GetActiveScene()); #endif } } } <|start_filename|>Unity/Assets/Model/Module/AssetsBundle/AssetsBundleLoaderAsync.cs<|end_filename|> using System.IO; using System.Threading.Tasks; using UnityEngine; namespace ETModel { [ObjectSystem] public class AssetsBundleLoaderAsyncSystem : UpdateSystem<AssetsBundleLoaderAsync> { public override void Update(AssetsBundleLoaderAsync self) { self.Update(); } } public class AssetsBundleLoaderAsync : Component { private AssetBundleCreateRequest request; private ETTaskCompletionSource<AssetBundle> tcs; public void Update() { if (!this.request.isDone) { return; } ETTaskCompletionSource<AssetBundle> t = tcs; t.SetResult(this.request.assetBundle); } public override void Dispose() { if (this.IsDisposed) { return; } base.Dispose(); } public ETTask<AssetBundle> LoadAsync(string path) { this.tcs = new ETTaskCompletionSource<AssetBundle>(); this.request = AssetBundle.LoadFromFileAsync(path); return this.tcs.Task; } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/UI/PackageGroup.cs<|end_filename|> using System.Linq; using UnityEngine.Experimental.UIElements; namespace UnityEditor.PackageManager.UI { #if !UNITY_2018_3_OR_NEWER internal class PackageGroupFactory : UxmlFactory<PackageGroup> { protected override PackageGroup DoCreate(IUxmlAttributes bag, CreationContext cc) { return new PackageGroup(bag.GetPropertyString("name")); } } #endif internal class PackageGroup : VisualElement { #if UNITY_2018_3_OR_NEWER internal new class UxmlFactory : UxmlFactory<PackageGroup> { } #endif private readonly VisualElement root; internal readonly PackageGroupOrigins Origin; public PackageGroup previousGroup; public PackageGroup nextGroup; public PackageItem firstPackage; public PackageItem lastPackage; public PackageGroup() : this(string.Empty) { } public PackageGroup(string groupName) { name = groupName; root = Resources.GetTemplate("PackageGroup.uxml"); Add(root); if (string.IsNullOrEmpty(groupName) || groupName != PackageGroupOrigins.BuiltInPackages.ToString()) { HeaderTitle.text = "Packages"; Origin = PackageGroupOrigins.Packages; } else { HeaderTitle.text = "Built In Packages"; Origin = PackageGroupOrigins.BuiltInPackages; } } internal PackageItem AddPackage(Package package) { var packageItem = new PackageItem(package) {packageGroup = this}; var lastItem = List.Children().LastOrDefault() as PackageItem; if (lastItem != null) { lastItem.nextItem = packageItem; packageItem.previousItem = lastItem; packageItem.nextItem = null; } List.Add(packageItem); if (firstPackage == null) firstPackage = packageItem; lastPackage = packageItem; return packageItem; } private VisualElement List { get { return root.Q<VisualElement>("groupContainer"); } } private Label HeaderTitle { get { return root.Q<Label>("headerTitle"); } } } } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/Serialization/Serializers/EnumerableSerializerBase.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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; using System.Collections.Generic; using MongoDB.Bson.Serialization.Conventions; namespace MongoDB.Bson.Serialization.Serializers { /// <summary> /// Represents a base serializer for enumerable values. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> public abstract class EnumerableSerializerBase<TValue> : SerializerBase<TValue>, IBsonArraySerializer where TValue : class, IEnumerable { // private fields private readonly IDiscriminatorConvention _discriminatorConvention = new ScalarDiscriminatorConvention("_t"); private readonly Lazy<IBsonSerializer> _lazyItemSerializer; // constructors /// <summary> /// Initializes a new instance of the <see cref="EnumerableSerializerBase{TValue}"/> class. /// </summary> protected EnumerableSerializerBase() : this(BsonSerializer.SerializerRegistry) { } /// <summary> /// Initializes a new instance of the <see cref="EnumerableSerializerBase{TValue}"/> class. /// </summary> /// <param name="itemSerializer">The item serializer.</param> protected EnumerableSerializerBase(IBsonSerializer itemSerializer) { if (itemSerializer == null) { throw new ArgumentNullException("itemSerializer"); } _lazyItemSerializer = new Lazy<IBsonSerializer>(() => itemSerializer); } /// <summary> /// Initializes a new instance of the <see cref="EnumerableSerializerBase{TValue}" /> class. /// </summary> /// <param name="serializerRegistry">The serializer registry.</param> protected EnumerableSerializerBase(IBsonSerializerRegistry serializerRegistry) { if (serializerRegistry == null) { throw new ArgumentNullException("serializerRegistry"); } _lazyItemSerializer = new Lazy<IBsonSerializer>(() => serializerRegistry.GetSerializer(typeof(object))); } /// <summary> /// Gets the item serializer. /// </summary> /// <value> /// The item serializer. /// </value> public IBsonSerializer ItemSerializer { get { return _lazyItemSerializer.Value; } } // public methods /// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <param name="args">The deserialization args.</param> /// <returns>A deserialized value.</returns> public override TValue Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { var bsonReader = context.Reader; var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return null; case BsonType.Array: bsonReader.ReadStartArray(); var accumulator = CreateAccumulator(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var item = _lazyItemSerializer.Value.Deserialize(context); AddItem(accumulator, item); } bsonReader.ReadEndArray(); return FinalizeResult(accumulator); case BsonType.Document: var serializer = new DiscriminatedWrapperSerializer<TValue>(_discriminatorConvention, this); if (serializer.IsPositionedAtDiscriminatedWrapper(context)) { return (TValue)serializer.Deserialize(context); } else { goto default; } default: throw CreateCannotDeserializeFromBsonTypeException(bsonType); } } /// <summary> /// Tries to get the serialization info for the individual items of the array. /// </summary> /// <param name="serializationInfo">The serialization information.</param> /// <returns> /// <c>true</c> if the serialization info exists; otherwise <c>false</c>. /// </returns> public bool TryGetItemSerializationInfo(out BsonSerializationInfo serializationInfo) { var itemSerializer = _lazyItemSerializer.Value; serializationInfo = new BsonSerializationInfo(null, itemSerializer, itemSerializer.ValueType); return true; } /// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The object.</param> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TValue value) { var bsonWriter = context.Writer; if (value == null) { bsonWriter.WriteNull(); } else { var actualType = value.GetType(); if (actualType == args.NominalType || args.SerializeAsNominalType) { bsonWriter.WriteStartArray(); foreach (var item in EnumerateItemsInSerializationOrder(value)) { _lazyItemSerializer.Value.Serialize(context, item); } bsonWriter.WriteEndArray(); } else { var serializer = new DiscriminatedWrapperSerializer<TValue>(_discriminatorConvention, this); serializer.Serialize(context, value); } } } // protected methods /// <summary> /// Adds the item. /// </summary> /// <param name="accumulator">The accumulator.</param> /// <param name="item">The item.</param> protected abstract void AddItem(object accumulator, object item); /// <summary> /// Creates the accumulator. /// </summary> /// <returns>The accumulator.</returns> protected abstract object CreateAccumulator(); /// <summary> /// Enumerates the items in serialization order. /// </summary> /// <param name="value">The value.</param> /// <returns>The items.</returns> protected abstract IEnumerable EnumerateItemsInSerializationOrder(TValue value); /// <summary> /// Finalizes the result. /// </summary> /// <param name="accumulator">The accumulator.</param> /// <returns>The final result.</returns> protected abstract TValue FinalizeResult(object accumulator); } /// <summary> /// Represents a serializer for enumerable values. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TItem">The type of the items.</typeparam> public abstract class EnumerableSerializerBase<TValue, TItem> : SerializerBase<TValue>, IBsonArraySerializer where TValue : class, IEnumerable<TItem> { // private fields private readonly IDiscriminatorConvention _discriminatorConvention = new ScalarDiscriminatorConvention("_t"); private readonly Lazy<IBsonSerializer<TItem>> _lazyItemSerializer; // constructors /// <summary> /// Initializes a new instance of the <see cref="EnumerableSerializerBase{TValue, TItem}"/> class. /// </summary> protected EnumerableSerializerBase() : this(BsonSerializer.SerializerRegistry) { } /// <summary> /// Initializes a new instance of the <see cref="EnumerableSerializerBase{TValue, TItem}"/> class. /// </summary> /// <param name="itemSerializer">The item serializer.</param> protected EnumerableSerializerBase(IBsonSerializer<TItem> itemSerializer) { if (itemSerializer == null) { throw new ArgumentNullException("itemSerializer"); } _lazyItemSerializer = new Lazy<IBsonSerializer<TItem>>(() => itemSerializer); } /// <summary> /// Initializes a new instance of the <see cref="EnumerableSerializerBase{TValue, TItem}" /> class. /// </summary> /// <param name="serializerRegistry">The serializer registry.</param> protected EnumerableSerializerBase(IBsonSerializerRegistry serializerRegistry) { if (serializerRegistry == null) { throw new ArgumentNullException("serializerRegistry"); } _lazyItemSerializer = new Lazy<IBsonSerializer<TItem>>(() => serializerRegistry.GetSerializer<TItem>()); } // public properties /// <summary> /// Gets the item serializer. /// </summary> /// <value> /// The item serializer. /// </value> public IBsonSerializer<TItem> ItemSerializer { get { return _lazyItemSerializer.Value; } } // public methods /// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <param name="args">The deserialization args.</param> /// <returns>A deserialized value.</returns> public override TValue Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { var bsonReader = context.Reader; var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return null; case BsonType.Array: bsonReader.ReadStartArray(); var accumulator = CreateAccumulator(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var item = _lazyItemSerializer.Value.Deserialize(context); AddItem(accumulator, item); } bsonReader.ReadEndArray(); return FinalizeResult(accumulator); case BsonType.Document: var serializer = new DiscriminatedWrapperSerializer<TValue>(_discriminatorConvention, this); if (serializer.IsPositionedAtDiscriminatedWrapper(context)) { return (TValue)serializer.Deserialize(context); } else { goto default; } default: throw CreateCannotDeserializeFromBsonTypeException(bsonType); } } /// <summary> /// Tries to get the serialization info for the individual items of the array. /// </summary> /// <param name="serializationInfo">The serialization information.</param> /// <returns> /// The serialization info for the items. /// </returns> public bool TryGetItemSerializationInfo(out BsonSerializationInfo serializationInfo) { var serializer = _lazyItemSerializer.Value; serializationInfo = new BsonSerializationInfo(null, serializer, serializer.ValueType); return true; } /// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The object.</param> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TValue value) { var bsonWriter = context.Writer; if (value == null) { bsonWriter.WriteNull(); } else { var actualType = value.GetType(); if (actualType == args.NominalType) { bsonWriter.WriteStartArray(); foreach (var item in EnumerateItemsInSerializationOrder(value)) { _lazyItemSerializer.Value.Serialize(context, item); } bsonWriter.WriteEndArray(); } else { var serializer = new DiscriminatedWrapperSerializer<TValue>(_discriminatorConvention, this); serializer.Serialize(context, value); } } } // protected methods /// <summary> /// Adds the item. /// </summary> /// <param name="accumulator">The accumulator.</param> /// <param name="item">The item.</param> protected abstract void AddItem(object accumulator, TItem item); /// <summary> /// Creates the accumulator. /// </summary> /// <returns>The accumulator.</returns> protected abstract object CreateAccumulator(); /// <summary> /// Enumerates the items in serialization order. /// </summary> /// <param name="value">The value.</param> /// <returns>The items.</returns> protected abstract IEnumerable<TItem> EnumerateItemsInSerializationOrder(TValue value); /// <summary> /// Finalizes the result. /// </summary> /// <param name="accumulator">The accumulator.</param> /// <returns>The result.</returns> protected abstract TValue FinalizeResult(object accumulator); } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Configuration/SslStreamSettings.cs<|end_filename|> /* Copyright 2013-present MongoDB Inc. * * 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.Collections.Generic; using System.Linq; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Core.Configuration { /// <summary> /// Represents settings for an SSL stream. /// </summary> public class SslStreamSettings { // fields private readonly bool _checkCertificateRevocation; private readonly IEnumerable<X509Certificate> _clientCertificates; private readonly LocalCertificateSelectionCallback _clientCertificateSelectionCallback; private readonly SslProtocols _enabledSslProtocols; private readonly RemoteCertificateValidationCallback _serverCertificateValidationCallback; // constructors /// <summary> /// Initializes a new instance of the <see cref="SslStreamSettings"/> class. /// </summary> /// <param name="checkCertificateRevocation">Whether to check for certificate revocation.</param> /// <param name="clientCertificates">The client certificates.</param> /// <param name="clientCertificateSelectionCallback">The client certificate selection callback.</param> /// <param name="enabledProtocols">The enabled protocols.</param> /// <param name="serverCertificateValidationCallback">The server certificate validation callback.</param> public SslStreamSettings( Optional<bool> checkCertificateRevocation = default(Optional<bool>), Optional<IEnumerable<X509Certificate>> clientCertificates = default(Optional<IEnumerable<X509Certificate>>), Optional<LocalCertificateSelectionCallback> clientCertificateSelectionCallback = default(Optional<LocalCertificateSelectionCallback>), Optional<SslProtocols> enabledProtocols = default(Optional<SslProtocols>), Optional<RemoteCertificateValidationCallback> serverCertificateValidationCallback = default(Optional<RemoteCertificateValidationCallback>)) { _checkCertificateRevocation = checkCertificateRevocation.WithDefault(false); _clientCertificates = Ensure.IsNotNull(clientCertificates.WithDefault(Enumerable.Empty<X509Certificate>()), "clientCertificates").ToList(); _clientCertificateSelectionCallback = clientCertificateSelectionCallback.WithDefault(null); _enabledSslProtocols = enabledProtocols.WithDefault(SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls); _serverCertificateValidationCallback = serverCertificateValidationCallback.WithDefault(null); } // properties /// <summary> /// Gets a value indicating whether to check for certificate revocation. /// </summary> /// <value> /// <c>true</c> if certificate should be checked for revocation; otherwise, <c>false</c>. /// </value> public bool CheckCertificateRevocation { get { return _checkCertificateRevocation; } } /// <summary> /// Gets the client certificates. /// </summary> /// <value> /// The client certificates. /// </value> public IEnumerable<X509Certificate> ClientCertificates { get { return _clientCertificates; } } /// <summary> /// Gets the client certificate selection callback. /// </summary> /// <value> /// The client certificate selection callback. /// </value> public LocalCertificateSelectionCallback ClientCertificateSelectionCallback { get { return _clientCertificateSelectionCallback; } } /// <summary> /// Gets the enabled SSL protocols. /// </summary> /// <value> /// The enabled SSL protocols. /// </value> public SslProtocols EnabledSslProtocols { get { return _enabledSslProtocols; } } /// <summary> /// Gets the server certificate validation callback. /// </summary> /// <value> /// The server certificate validation callback. /// </value> public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get { return _serverCertificateValidationCallback; } } // methods /// <summary> /// Returns a new SsslStreamSettings instance with some settings changed. /// </summary> /// <param name="checkCertificateRevocation">Whether to check certificate revocation.</param> /// <param name="clientCertificates">The client certificates.</param> /// <param name="clientCertificateSelectionCallback">The client certificate selection callback.</param> /// <param name="enabledProtocols">The enabled protocols.</param> /// <param name="serverCertificateValidationCallback">The server certificate validation callback.</param> /// <returns>A new SsslStreamSettings instance.</returns> public SslStreamSettings With( Optional<bool> checkCertificateRevocation = default(Optional<bool>), Optional<IEnumerable<X509Certificate>> clientCertificates = default(Optional<IEnumerable<X509Certificate>>), Optional<LocalCertificateSelectionCallback> clientCertificateSelectionCallback = default(Optional<LocalCertificateSelectionCallback>), Optional<SslProtocols> enabledProtocols = default(Optional<SslProtocols>), Optional<RemoteCertificateValidationCallback> serverCertificateValidationCallback = default(Optional<RemoteCertificateValidationCallback>)) { return new SslStreamSettings( checkCertificateRevocation: checkCertificateRevocation.WithDefault(_checkCertificateRevocation), clientCertificates: Optional.Enumerable(clientCertificates.WithDefault(_clientCertificates)), clientCertificateSelectionCallback: clientCertificateSelectionCallback.WithDefault(_clientCertificateSelectionCallback), enabledProtocols: enabledProtocols.WithDefault(_enabledSslProtocols), serverCertificateValidationCallback: serverCertificateValidationCallback.WithDefault(_serverCertificateValidationCallback)); } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouchControls/Plugins/ETCButton.cs<|end_filename|> /*********************************************** EasyTouch Controls Copyright © 2016 The Hedgehog Team http://www.thehedgehogteam.com/Forum/ <EMAIL> **********************************************/ using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; using System.Collections; [System.Serializable] public class ETCButton : ETCBase, IPointerEnterHandler, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler { #region Unity Events [System.Serializable] public class OnDownHandler : UnityEvent{} [System.Serializable] public class OnPressedHandler : UnityEvent{} [System.Serializable] public class OnPressedValueandler : UnityEvent<float>{} [System.Serializable] public class OnUPHandler : UnityEvent{} [SerializeField] public OnDownHandler onDown; [SerializeField] public OnPressedHandler onPressed; [SerializeField] public OnPressedValueandler onPressedValue; [SerializeField] public OnUPHandler onUp; #endregion #region Members #region Public members public ETCAxis axis; public Sprite normalSprite; public Color normalColor; public Sprite pressedSprite; public Color pressedColor; #endregion #region Private members private Image cachedImage; private bool isOnPress; private GameObject previousDargObject; private bool isOnTouch; #endregion #endregion #region Constructor public ETCButton(){ axis = new ETCAxis( "Button"); _visible = true; _activated = true; isOnTouch = false; enableKeySimulation = true; axis.unityAxis = "Jump"; showPSInspector = true; showSpriteInspector = false; showBehaviourInspector = false; showEventInspector = false; } #endregion #region Monobehaviour Callback protected override void Awake (){ base.Awake (); cachedImage = GetComponent<UnityEngine.UI.Image>(); } public override void Start(){ axis.InitAxis(); base.Start(); isOnPress = false; if (allowSimulationStandalone && enableKeySimulation && !Application.isEditor){ SetVisible(visibleOnStandalone); } } protected override void UpdateControlState (){ UpdateButton(); } protected override void DoActionBeforeEndOfFrame (){ axis.DoGravity(); } #endregion #region UI Callback public void OnPointerEnter(PointerEventData eventData){ if (isSwipeIn && !isOnTouch){ if (eventData.pointerDrag != null){ if (eventData.pointerDrag.GetComponent<ETCBase>() && eventData.pointerDrag!= gameObject){ previousDargObject=eventData.pointerDrag; //ExecuteEvents.Execute<IPointerUpHandler> (previousDargObject, eventData, ExecuteEvents.pointerUpHandler); } } eventData.pointerDrag = gameObject; eventData.pointerPress = gameObject; OnPointerDown( eventData); } } public void OnPointerDown(PointerEventData eventData){ if (_activated && !isOnTouch){ pointId = eventData.pointerId; axis.ResetAxis(); axis.axisState = ETCAxis.AxisState.Down; isOnPress = false; isOnTouch = true; onDown.Invoke(); ApllyState(); axis.UpdateButton(); } } public void OnPointerUp(PointerEventData eventData){ if (pointId == eventData.pointerId){ isOnPress = false; isOnTouch = false; axis.axisState = ETCAxis.AxisState.Up; axis.axisValue = 0; onUp.Invoke(); ApllyState(); if (previousDargObject){ ExecuteEvents.Execute<IPointerUpHandler> (previousDargObject, eventData, ExecuteEvents.pointerUpHandler); previousDargObject = null; } } } public void OnPointerExit(PointerEventData eventData){ if (pointId == eventData.pointerId){ if (axis.axisState == ETCAxis.AxisState.Press && !isSwipeOut){ OnPointerUp(eventData); } } } #endregion #region Button Update private void UpdateButton(){ if (axis.axisState == ETCAxis.AxisState.Down){ isOnPress = true; axis.axisState = ETCAxis.AxisState.Press; } if (isOnPress){ axis.UpdateButton(); onPressed.Invoke(); onPressedValue.Invoke( axis.axisValue); } if (axis.axisState == ETCAxis.AxisState.Up){ isOnPress = false; axis.axisState = ETCAxis.AxisState.None; } if (enableKeySimulation && _activated && _visible && !isOnTouch){ if (Input.GetButton( axis.unityAxis)&& axis.axisState ==ETCAxis.AxisState.None ){ axis.ResetAxis(); onDown.Invoke(); axis.axisState = ETCAxis.AxisState.Down; } if (!Input.GetButton(axis.unityAxis )&& axis.axisState == ETCAxis.AxisState.Press){ axis.axisState = ETCAxis.AxisState.Up; axis.axisValue = 0; onUp.Invoke(); } axis.UpdateButton(); ApllyState(); } } #endregion #region Private Method protected override void SetVisible (bool forceUnvisible=false){ bool localVisible = _visible; if (!visible){ localVisible = visible; } GetComponent<Image>().enabled = localVisible; } private void ApllyState(){ if (cachedImage){ switch (axis.axisState){ case ETCAxis.AxisState.Down: case ETCAxis.AxisState.Press: cachedImage.sprite = pressedSprite; cachedImage.color = pressedColor; break; default: cachedImage.sprite = normalSprite; cachedImage.color = normalColor; break; } } } protected override void SetActivated(){ if (!_activated){ isOnPress = false; isOnTouch = false; axis.axisState = ETCAxis.AxisState.None; axis.axisValue = 0; ApllyState(); } } #endregion } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/UI/Common/LoadingSpinner.cs<|end_filename|> using UnityEngine; using UnityEngine.Experimental.UIElements; namespace UnityEditor.PackageManager.UI { #if !UNITY_2018_3_OR_NEWER internal class LoadingSpinnerFactory : UxmlFactory<LoadingSpinner> { protected override LoadingSpinner DoCreate(IUxmlAttributes bag, CreationContext cc) { return new LoadingSpinner(); } } #endif internal class LoadingSpinner : VisualElement { #if UNITY_2018_3_OR_NEWER internal new class UxmlFactory : UxmlFactory<LoadingSpinner, UxmlTraits> { } // This works around an issue with UXML instantiation // See https://fogbugz.unity3d.com/f/cases/1046459/ internal new class UxmlTraits : VisualElement.UxmlTraits { public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { base.Init(ve, bag, cc); UIUtils.SetElementDisplay(ve, false); } } #endif public bool InvertColor { get; set; } public bool Started { get; private set; } private int rotation; public LoadingSpinner() { InvertColor = false; Started = false; UIUtils.SetElementDisplay(this, false); } private void UpdateProgress() { if (parent == null) return; parent.transform.rotation = Quaternion.Euler(0, 0, rotation); rotation += 3; if (rotation > 360) rotation -= 360; } public void Start() { if (Started) return; // Weird hack to make sure loading spinner doesn't generate an error every frame. // Cannot put in constructor as it give really strange result. if (parent != null && parent.parent != null) parent.parent.clippingOptions = ClippingOptions.ClipAndCacheContents; rotation = 0; EditorApplication.update += UpdateProgress; Started = true; UIUtils.SetElementDisplay(this, true); } public void Stop() { if (!Started) return; EditorApplication.update -= UpdateProgress; Started = false; UIUtils.SetElementDisplay(this, false); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Bindings/CoreSessionOptions.cs<|end_filename|> /* Copyright 2018-present MongoDB Inc. * * 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 MongoDB.Driver.Core.Bindings { /// <summary> /// Core session options. /// </summary> public class CoreSessionOptions { // private fields private readonly TransactionOptions _defaultTransactionOptions; private readonly bool _isCausallyConsistent; private readonly bool _isImplicit; // constructors /// <summary> /// Initializes a new instance of the <see cref="CoreSessionOptions" /> class. /// </summary> /// <param name="isCausallyConsistent">if set to <c>true</c> this session is causally consistent]</param> /// <param name="isImplicit">if set to <c>true</c> this session is an implicit session.</param> /// <param name="defaultTransactionOptions">The default transaction options.</param> public CoreSessionOptions( bool isCausallyConsistent = false, bool isImplicit = false, TransactionOptions defaultTransactionOptions = null) { _isCausallyConsistent = isCausallyConsistent; _isImplicit = isImplicit; _defaultTransactionOptions = defaultTransactionOptions; } // public properties /// <summary> /// Gets the default transaction options. /// </summary> /// <value> /// The default transaction options. /// </value> public TransactionOptions DefaultTransactionOptions => _defaultTransactionOptions; /// <summary> /// Gets a value indicating whether this session is causally consistent. /// </summary> /// <value> /// <c>true</c> if this session is causally consistent; otherwise, <c>false</c>. /// </value> public bool IsCausallyConsistent => _isCausallyConsistent; /// <summary> /// Gets a value indicating whether this session is an implicit session. /// </summary> /// <value> /// <c>true</c> if this session is an implicit session; otherwise, <c>false</c>. /// </value> public bool IsImplicit => _isImplicit; } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Common/ApplicationUtil.cs<|end_filename|> using System.Linq; using UnityEngine; namespace UnityEditor.PackageManager.UI { class ApplicationUtil { public static bool IsPreReleaseVersion { get { var lastToken = Application.unityVersion.Split('.').LastOrDefault(); return lastToken.Contains("a") || lastToken.Contains("b"); } } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Plugins/Editor/EasyTouchTriggerInspector.cs<|end_filename|> using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using HedgehogTeam.EasyTouch; #if UNITY_5_3_OR_NEWER using UnityEditor.SceneManagement; #endif [CustomEditor(typeof(EasyTouchTrigger))] public class EasyTouchTriggerInspector : Editor { public override void OnInspectorGUI(){ EasyTouchTrigger t = (EasyTouchTrigger)target; string[] eventNames = Enum.GetNames( typeof(EasyTouch.EvtType) ) ; eventNames[0] = "Add new event"; #region Event properties GUILayout.Space(5f); for (int i=1;i<eventNames.Length;i++){ EasyTouch.EvtType ev = (EasyTouch.EvtType)Enum.Parse( typeof(EasyTouch.EvtType), eventNames[i]); int result = t.receivers.FindIndex( delegate(EasyTouchTrigger.EasyTouchReceiver e){ return e.eventName == ev; } ); if (result>-1){ TriggerInspector( ev,t); } } #endregion #region Add Event GUI.backgroundColor = Color.green; int index = EditorGUILayout.Popup("", 0, eventNames,"Button"); GUI.backgroundColor = Color.white; if (index!=0){ //AddEvent((EasyTouch.EventName)Enum.Parse( typeof(EasyTouch.EventName), eventNames[index]),t ); t.AddTrigger( (EasyTouch.EvtType)Enum.Parse( typeof(EasyTouch.EvtType), eventNames[index])); EditorPrefs.SetBool( eventNames[index], true); } #endregion if (GUI.changed){ EditorUtility.SetDirty(t); #if UNITY_5_3_OR_NEWER EditorSceneManager.MarkSceneDirty( EditorSceneManager.GetActiveScene()); #endif } } private void TriggerInspector(EasyTouch.EvtType ev, EasyTouchTrigger t){ bool folding = EditorPrefs.GetBool( ev.ToString() ); folding = HTGuiTools.BeginFoldOut( ev.ToString(),folding,false); EditorPrefs.SetBool( ev.ToString(), folding); if (folding){ HTGuiTools.BeginGroup(); int i=0; while (i<t.receivers.Count){ if (t.receivers[i].eventName == ev){ GUI.color = new Color(0.8f,0.8f,0.8f,1); HTGuiTools.BeginGroup(5); GUI.color = Color.white; EditorGUILayout.BeginHorizontal(); t.receivers[i].enable = HTGuiTools.Toggle("Enable",t.receivers[i].enable,55,true); t.receivers[i].name = EditorGUILayout.TextField("",t.receivers[i].name, GUILayout.MinWidth(130)); // Delete GUILayout.FlexibleSpace(); if (HTGuiTools.Button("X",Color.red,19)){ t.receivers[i] = null; t.receivers.RemoveAt( i ); EditorGUILayout.EndHorizontal(); return; } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); // Restriced //t.receivers[i].restricted = HTGuiTools.Toggle("Restricted to gameobject",t.receivers[i].restricted,true); t.receivers[i].triggerType = (EasyTouchTrigger.ETTType)EditorGUILayout.EnumPopup("Testing on",t.receivers[i].triggerType ); EditorGUILayout.BeginHorizontal(); t.receivers[i].restricted = EditorGUILayout.Toggle("",t.receivers[i].restricted ,(GUIStyle)"Radio" ,GUILayout.Width(15)); EditorGUILayout.LabelField("Only if on me (requiered a collider)"); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); t.receivers[i].restricted = !EditorGUILayout.Toggle("",!t.receivers[i].restricted ,(GUIStyle)"Radio",GUILayout.Width(15)); EditorGUILayout.LabelField("All the time, or other object"); EditorGUILayout.EndHorizontal(); if (!t.receivers[i].restricted){ t.receivers[i].gameObject = (GameObject)EditorGUILayout.ObjectField("Other object",t.receivers[i].gameObject,typeof(GameObject),true); } EditorGUILayout.Space(); EditorGUILayout.Space(); t.receivers[i].otherReceiver = HTGuiTools.Toggle("Other receiver",t.receivers[i].otherReceiver,true); if (t.receivers[i].otherReceiver){ t.receivers[i].gameObjectReceiver = (GameObject)EditorGUILayout.ObjectField("Receiver",t.receivers[i].gameObjectReceiver,typeof(GameObject),true); } // Method Name EditorGUILayout.BeginHorizontal(); t.receivers[i].methodName = EditorGUILayout.TextField("Method name",t.receivers[i].methodName); // Methode helper string[] mNames = null; if (!t.receivers[i].otherReceiver || (t.receivers[i].otherReceiver && t.receivers[i].gameObjectReceiver == null) ){ mNames = GetMethod( t.gameObject); } else if ( t.receivers[i].otherReceiver && t.receivers[i].gameObjectReceiver != null){ mNames = GetMethod( t.receivers[i].gameObjectReceiver); } int index = EditorGUILayout.Popup("", -1, mNames,"Button",GUILayout.Width(20)); if (index>-1){ t.receivers[i].methodName = mNames[index]; } EditorGUILayout.EndHorizontal(); // Parameter t.receivers[i].parameter = (EasyTouchTrigger.ETTParameter) EditorGUILayout.EnumPopup("Parameter to send",t.receivers[i].parameter); HTGuiTools.EndGroup(); } i++; } } else{ HTGuiTools.BeginGroup(); } HTGuiTools.EndGroup(false); if (!GUILayout.Toggle(true,"+","ObjectPickerTab")){ t.AddTrigger( ev); } GUILayout.Space(5f); } private void AddEvent(EasyTouch.EvtType ev, EasyTouchTrigger t){ EasyTouchTrigger.EasyTouchReceiver r = new EasyTouchTrigger.EasyTouchReceiver(); r.enable = true; r.restricted = true; r.eventName = ev; r.gameObject = t.gameObject; t.receivers.Add( r ); } private string[] GetMethod(GameObject obj){ List<string> methodName = new List<string>(); Component[] allComponents = obj.GetComponents<Component>(); if (allComponents.Length>0){ foreach( Component comp in allComponents){ if (comp!=null){ if (comp.GetType().IsSubclassOf( typeof(MonoBehaviour))){ MethodInfo[] methodInfos = comp.GetType().GetMethods(); foreach( MethodInfo methodInfo in methodInfos){ if ((methodInfo.DeclaringType.Namespace == null) || (!methodInfo.DeclaringType.Namespace.Contains("Unity") && !methodInfo.DeclaringType.Namespace.Contains("System"))){ if (methodInfo.IsPublic){ methodName.Add( methodInfo.Name ); } } } } } } } // return methodName.ToArray(); } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Packages/PackageInfoListExtensions.cs<|end_filename|> using System.Collections.Generic; using System.Linq; namespace UnityEditor.PackageManager.UI { internal static class PackageInfoListExtensions { public static IEnumerable<PackageInfo> ByName(this IEnumerable<PackageInfo> list, string name) { return from package in list where package.Name == name select package; } public static void SetCurrent(this IEnumerable<PackageInfo> list, bool current = true) { foreach (var package in list) { package.IsCurrent = current; } } public static void SetLatest(this IEnumerable<PackageInfo> list, bool latest = true) { foreach (var package in list) { package.IsLatest = latest; } } public static void SetGroup(this IEnumerable<PackageInfo> list, string group) { foreach (var package in list) { package.Group = group; } } } } <|start_filename|>Book/Example/Example2_1/Program.cs<|end_filename|> using System; using System.Threading; using ETModel; namespace Example2_1 { internal class Program { private static int loopCount = 0; private static void Main() { OneThreadSynchronizationContext _ = OneThreadSynchronizationContext.Instance; WaitTimeAsync(5000, WaitTimeFinishCallback); while (true) { OneThreadSynchronizationContext.Instance.Update(); Thread.Sleep(1); ++loopCount; if (loopCount % 10000 == 0) { Console.WriteLine($"loop count: {loopCount}"); } } } private static void WaitTimeAsync(int waitTime, Action action) { Thread thread = new Thread(()=>WaitTime(waitTime, action)); thread.Start(); } private static void WaitTimeFinishCallback() { Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}"); WaitTimeAsync(4000, WaitTimeFinishCallback3); } private static void WaitTimeFinishCallback3() { Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}"); WaitTimeAsync(3000, WaitTimeFinishCallback2); } private static void WaitTimeFinishCallback2() { Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}"); } /// <summary> /// 在另外的线程等待 /// </summary> private static void WaitTime(int waitTime, Action action) { Thread.Sleep(waitTime); // 将action扔回主线程执行 OneThreadSynchronizationContext.Instance.Post(o=>action(), null); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Operations/ListIndexesOperation.cs<|end_filename|> /* Copyright 2013-present MongoDB Inc. * * 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.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; namespace MongoDB.Driver.Core.Operations { /// <summary> /// Represents a list indexes operation. /// </summary> public class ListIndexesOperation : IReadOperation<IAsyncCursor<BsonDocument>> { // fields private readonly CollectionNamespace _collectionNamespace; private readonly MessageEncoderSettings _messageEncoderSettings; // constructors /// <summary> /// Initializes a new instance of the <see cref="ListIndexesOperation"/> class. /// </summary> /// <param name="collectionNamespace">The collection namespace.</param> /// <param name="messageEncoderSettings">The message encoder settings.</param> public ListIndexesOperation( CollectionNamespace collectionNamespace, MessageEncoderSettings messageEncoderSettings) { _collectionNamespace = Ensure.IsNotNull(collectionNamespace, nameof(collectionNamespace)); _messageEncoderSettings = messageEncoderSettings; } // properties /// <summary> /// Gets the collection namespace. /// </summary> /// <value> /// The collection namespace. /// </value> public CollectionNamespace CollectionNamespace { get { return _collectionNamespace; } } /// <summary> /// Gets the message encoder settings. /// </summary> /// <value> /// The message encoder settings. /// </value> public MessageEncoderSettings MessageEncoderSettings { get { return _messageEncoderSettings; } } // public methods /// <inheritdoc/> public IAsyncCursor<BsonDocument> Execute(IReadBinding binding, CancellationToken cancellationToken) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) using (var channelSource = binding.GetReadChannelSource(cancellationToken)) using (var channel = channelSource.GetChannel(cancellationToken)) using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(channel); return operation.Execute(channelBinding, cancellationToken); } } /// <inheritdoc/> public async Task<IAsyncCursor<BsonDocument>> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationToken).ConfigureAwait(false)) using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(channel); return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); } } // private methods private IReadOperation<IAsyncCursor<BsonDocument>> CreateOperation(IChannel channel) { if (Feature.ListIndexesCommand.IsSupported(channel.ConnectionDescription.ServerVersion)) { return new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); } else { return new ListIndexesUsingQueryOperation(_collectionNamespace, _messageEncoderSettings); } } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Bindings/CoreSessionHandle.cs<|end_filename|> /* Copyright 2017-present MongoDB Inc. * * 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 MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Core.Bindings { /// <summary> /// A handle to a reference counted core session. /// </summary> /// <seealso cref="MongoDB.Driver.Core.Bindings.ICoreSessionHandle" /> public sealed class CoreSessionHandle : WrappingCoreSession, ICoreSessionHandle { // private fields private readonly ReferenceCountedCoreSession _wrapped; // constructors /// <summary> /// Initializes a new instance of the <see cref="CoreSessionHandle"/> class. /// </summary> /// <param name="session">The session.</param> public CoreSessionHandle(ICoreSession session) : this(new ReferenceCountedCoreSession(Ensure.IsNotNull(session, nameof(session)))) { } /// <summary> /// Initializes a new instance of the <see cref="CoreSessionHandle"/> class. /// </summary> /// <param name="wrapped">The wrapped.</param> internal CoreSessionHandle(ReferenceCountedCoreSession wrapped) : base(Ensure.IsNotNull(wrapped, nameof(wrapped)), ownsWrapped: false) { _wrapped = wrapped; } // public methods /// <inheritdoc /> public ICoreSessionHandle Fork() { ThrowIfDisposed(); _wrapped.IncrementReferenceCount(); return new CoreSessionHandle(_wrapped); } // protected methods /// <inheritdoc /> protected override void Dispose(bool disposing) { if (disposing) { if (!IsDisposed()) { _wrapped.DecrementReferenceCount(); } } base.Dispose(disposing); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/Linq/Processors/MethodInfoMethodCallBinder.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using MongoDB.Driver.Linq.Expressions; namespace MongoDB.Driver.Linq.Processors { internal sealed class MethodInfoMethodCallBinder<TBindingContext> : IMethodCallBinder<TBindingContext> where TBindingContext : IBindingContext { private readonly Dictionary<MethodInfo, IMethodCallBinder<TBindingContext>> _binders; public MethodInfoMethodCallBinder() { _binders = new Dictionary<MethodInfo, IMethodCallBinder<TBindingContext>>(); } public Expression Bind(PipelineExpression pipeline, TBindingContext bindingContext, MethodCallExpression node, IEnumerable<Expression> arguments) { IMethodCallBinder<TBindingContext> binder; if (!TryGetMethodCallBinder(node.Method, out binder)) { return null; } return binder.Bind(pipeline, bindingContext, node, arguments); } public bool IsRegistered(MethodCallExpression node) { IMethodCallBinder<TBindingContext> binder; return TryGetMethodCallBinder(node.Method, out binder); } public void Register(IMethodCallBinder<TBindingContext> binder, IEnumerable<MethodInfo> methods) { foreach (var method in methods) { _binders[method] = binder; } } private bool TryGetMethodCallBinder(MethodInfo method, out IMethodCallBinder<TBindingContext> binder) { if (_binders.TryGetValue(method, out binder)) { return true; } var methodDefinition = MethodHelper.GetMethodDefinition(method); return _binders.TryGetValue(methodDefinition, out binder); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Operations/DeleteOpcodeOperation.cs<|end_filename|> /* Copyright 2013-present MongoDB Inc. * * 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.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; namespace MongoDB.Driver.Core.Operations { /// <summary> /// Represents a delete operation using the delete opcode. /// </summary> public class DeleteOpcodeOperation : IWriteOperation<WriteConcernResult>, IExecutableInRetryableWriteContext<WriteConcernResult> { // fields private readonly CollectionNamespace _collectionNamespace; private readonly MessageEncoderSettings _messageEncoderSettings; private readonly DeleteRequest _request; private bool _retryRequested; private WriteConcern _writeConcern = WriteConcern.Acknowledged; // constructors /// <summary> /// Initializes a new instance of the <see cref="DeleteOpcodeOperation"/> class. /// </summary> /// <param name="collectionNamespace">The collection namespace.</param> /// <param name="request">The request.</param> /// <param name="messageEncoderSettings">The message encoder settings.</param> public DeleteOpcodeOperation( CollectionNamespace collectionNamespace, DeleteRequest request, MessageEncoderSettings messageEncoderSettings) { _collectionNamespace = Ensure.IsNotNull(collectionNamespace, nameof(collectionNamespace)); _request = Ensure.IsNotNull(request, nameof(request)); _messageEncoderSettings = messageEncoderSettings; } // properties /// <summary> /// Gets the collection namespace. /// </summary> /// <value> /// The collection namespace. /// </value> public CollectionNamespace CollectionNamespace { get { return _collectionNamespace; } } /// <summary> /// Gets the request. /// </summary> /// <value> /// The request. /// </value> public DeleteRequest Request { get { return _request; } } /// <summary> /// Gets the message encoder settings. /// </summary> /// <value> /// The message encoder settings. /// </value> public MessageEncoderSettings MessageEncoderSettings { get { return _messageEncoderSettings; } } /// <summary> /// Gets or sets a value indicating whether retry is enabled for the operation. /// </summary> /// <value>A value indicating whether retry is enabled.</value> public bool RetryRequested { get { return _retryRequested; } set { _retryRequested = value; } } /// <summary> /// Gets or sets the write concern. /// </summary> /// <value> /// The write concern. /// </value> public WriteConcern WriteConcern { get { return _writeConcern; } set { _writeConcern = Ensure.IsNotNull(value, nameof(value)); } } // public methods /// <inheritdoc/> public WriteConcernResult Execute(IWriteBinding binding, CancellationToken cancellationToken) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) using (var context = RetryableWriteContext.Create(binding, false, cancellationToken)) { return Execute(context, cancellationToken); } } /// <inheritdoc/> public WriteConcernResult Execute(RetryableWriteContext context, CancellationToken cancellationToken) { Ensure.IsNotNull(context, nameof(context)); if (Feature.WriteCommands.IsSupported(context.Channel.ConnectionDescription.ServerVersion) && _writeConcern.IsAcknowledged) { var emulator = CreateEmulator(); return emulator.Execute(context, cancellationToken); } else { return ExecuteProtocol(context.Channel, cancellationToken); } } /// <inheritdoc/> public async Task<WriteConcernResult> ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) using (var context = await RetryableWriteContext.CreateAsync(binding, false, cancellationToken).ConfigureAwait(false)) { return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); } } /// <inheritdoc/> public Task<WriteConcernResult> ExecuteAsync(RetryableWriteContext context, CancellationToken cancellationToken) { Ensure.IsNotNull(context, nameof(context)); if (Feature.WriteCommands.IsSupported(context.Channel.ConnectionDescription.ServerVersion) && _writeConcern.IsAcknowledged) { var emulator = CreateEmulator(); return emulator.ExecuteAsync(context, cancellationToken); } else { return ExecuteProtocolAsync(context.Channel, cancellationToken); } } // private methods private IExecutableInRetryableWriteContext<WriteConcernResult> CreateEmulator() { return new DeleteOpcodeOperationEmulator(_collectionNamespace, _request, _messageEncoderSettings) { RetryRequested = _retryRequested, WriteConcern = _writeConcern }; } private WriteConcernResult ExecuteProtocol(IChannelHandle channel, CancellationToken cancellationToken) { if (_request.Collation != null) { throw new NotSupportedException("OP_DELETE does not support collations."); } return channel.Delete( _collectionNamespace, _request.Filter, _request.Limit != 1, _messageEncoderSettings, _writeConcern, cancellationToken); } private Task<WriteConcernResult> ExecuteProtocolAsync(IChannelHandle channel, CancellationToken cancellationToken) { if (_request.Collation != null) { throw new NotSupportedException("OP_DELETE does not support collations."); } return channel.DeleteAsync( _collectionNamespace, _request.Filter, _request.Limit != 1, _messageEncoderSettings, _writeConcern, cancellationToken); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/AggregateGraphLookupOptions.cs<|end_filename|> /* Copyright 2016-present MongoDB Inc. * * 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.Collections.Generic; using MongoDB.Bson.Serialization; namespace MongoDB.Driver { /// <summary> /// Represents options for the GraphLookup method. /// </summary> /// <typeparam name="TFrom">The type of from documents.</typeparam> /// <typeparam name="TAsElement">The type of the as field elements.</typeparam> /// <typeparam name="TOutput">The type of the output documents.</typeparam> public class AggregateGraphLookupOptions<TFrom, TAsElement, TOutput> { /// <summary> /// Gets or sets the TAsElement serialzier. /// </summary> public IBsonSerializer<TAsElement> AsElementSerializer { get; set; } /// <summary> /// Gets or sets the TFrom serializer. /// </summary> public IBsonSerializer<TFrom> FromSerializer { get; set; } /// <summary> /// Gets or sets the maximum depth. /// </summary> public int? MaxDepth { get; set; } /// <summary> /// Gets or sets the output serializer. /// </summary> public IBsonSerializer<TOutput> OutputSerializer { get; set; } /// <summary> /// Gets the filter to restrict the search with. /// </summary> public FilterDefinition<TFrom> RestrictSearchWithMatch { get; set; } } } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/ObjectModel/BsonString.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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 MongoDB.Bson.IO; namespace MongoDB.Bson { /// <summary> /// Represents a BSON string value. /// </summary> #if NET452 [Serializable] #endif public class BsonString : BsonValue, IComparable<BsonString>, IEquatable<BsonString> { // private static fields private static BsonString __emptyInstance = new BsonString(""); // private fields private readonly string _value; // constructors /// <summary> /// Initializes a new instance of the BsonString class. /// </summary> /// <param name="value">The value.</param> public BsonString(string value) { if (value == null) { throw new ArgumentNullException("value"); } _value = value; } // public static properties /// <summary> /// Gets an instance of BsonString that represents an empty string. /// </summary> public static BsonString Empty { get { return __emptyInstance; } } // public properties /// <summary> /// Gets the BsonType of this BsonValue. /// </summary> public override BsonType BsonType { get { return BsonType.String; } } /// <summary> /// Gets the BsonString as a string. /// </summary> [Obsolete("Use Value instead.")] public override object RawValue { get { return _value; } } /// <summary> /// Gets the value of this BsonString. /// </summary> public string Value { get { return _value; } } // public operators /// <summary> /// Converts a string to a BsonString. /// </summary> /// <param name="value">A string.</param> /// <returns>A BsonString.</returns> public static implicit operator BsonString(string value) { if (value != null && value.Length == 0) { return __emptyInstance; } return new BsonString(value); } /// <summary> /// Compares two BsonString values. /// </summary> /// <param name="lhs">The first BsonString.</param> /// <param name="rhs">The other BsonString.</param> /// <returns>True if the two BsonString values are not equal according to ==.</returns> public static bool operator !=(BsonString lhs, BsonString rhs) { return !(lhs == rhs); } /// <summary> /// Compares two BsonString values. /// </summary> /// <param name="lhs">The first BsonString.</param> /// <param name="rhs">The other BsonString.</param> /// <returns>True if the two BsonString values are equal according to ==.</returns> public static bool operator ==(BsonString lhs, BsonString rhs) { if (object.ReferenceEquals(lhs, null)) { return object.ReferenceEquals(rhs, null); } return lhs.Equals(rhs); } // public static methods /// <summary> /// Creates a new BsonString. /// </summary> /// <param name="value">An object to be mapped to a BsonString.</param> /// <returns>A BsonString or null.</returns> public new static BsonString Create(object value) { if (value == null) { throw new ArgumentNullException("value"); } return (BsonString)BsonTypeMapper.MapToBsonValue(value, BsonType.String); } // public methods /// <summary> /// Compares this BsonString to another BsonString. /// </summary> /// <param name="other">The other BsonString.</param> /// <returns>A 32-bit signed integer that indicates whether this BsonString is less than, equal to, or greather than the other.</returns> public int CompareTo(BsonString other) { if (other == null) { return 1; } return _value.CompareTo(other.Value); } /// <summary> /// Compares the BsonString to another BsonValue. /// </summary> /// <param name="other">The other BsonValue.</param> /// <returns>A 32-bit signed integer that indicates whether this BsonString is less than, equal to, or greather than the other BsonValue.</returns> public override int CompareTo(BsonValue other) { if (other == null) { return 1; } var otherString = other as BsonString; if (otherString != null) { return _value.CompareTo(otherString.Value); } var otherSymbol = other as BsonSymbol; if (otherSymbol != null) { return _value.CompareTo(otherSymbol.Name); } return CompareTypeTo(other); } /// <summary> /// Compares this BsonString to another BsonString. /// </summary> /// <param name="rhs">The other BsonString.</param> /// <returns>True if the two BsonString values are equal.</returns> public bool Equals(BsonString rhs) { if (object.ReferenceEquals(rhs, null) || GetType() != rhs.GetType()) { return false; } return _value == rhs._value; } /// <summary> /// Compares this BsonString to another object. /// </summary> /// <param name="obj">The other object.</param> /// <returns>True if the other object is a BsonString and equal to this one.</returns> public override bool Equals(object obj) { return Equals(obj as BsonString); // works even if obj is null or of a different type } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { // see Effective Java by <NAME> int hash = 17; hash = 37 * hash + BsonType.GetHashCode(); hash = 37 * hash + _value.GetHashCode(); return hash; } /// <summary> /// Converts this BsonValue to a Boolean (using the JavaScript definition of truthiness). /// </summary> /// <returns>A Boolean.</returns> public override bool ToBoolean() { return _value != ""; } /// <inheritdoc/> public override decimal ToDecimal() { return JsonConvert.ToDecimal(_value); } /// <inheritdoc/> public override Decimal128 ToDecimal128() { return JsonConvert.ToDecimal128(_value); } /// <summary> /// Converts this BsonValue to a Double. /// </summary> /// <returns>A Double.</returns> public override double ToDouble() { return JsonConvert.ToDouble(_value); } /// <summary> /// Converts this BsonValue to an Int32. /// </summary> /// <returns>An Int32.</returns> public override int ToInt32() { return JsonConvert.ToInt32(_value); } /// <summary> /// Converts this BsonValue to an Int64. /// </summary> /// <returns>An Int32.</returns> public override long ToInt64() { return JsonConvert.ToInt64(_value); } /// <summary> /// Returns a string representation of the value. /// </summary> /// <returns>A string representation of the value.</returns> public override string ToString() { return _value; } // protected methods /// <inheritdoc/> protected override TypeCode IConvertibleGetTypeCodeImplementation() { return TypeCode.String; } /// <inheritdoc/> protected override byte IConvertibleToByteImplementation(IFormatProvider provider) { return Convert.ToByte(_value, provider); } /// <inheritdoc/> protected override bool IConvertibleToBooleanImplementation(IFormatProvider provider) { return Convert.ToBoolean(_value, provider); } /// <inheritdoc/> protected override char IConvertibleToCharImplementation(IFormatProvider provider) { return Convert.ToChar(_value, provider); } /// <inheritdoc/> protected override DateTime IConvertibleToDateTimeImplementation(IFormatProvider provider) { return Convert.ToDateTime(_value, provider); } /// <inheritdoc/> protected override decimal IConvertibleToDecimalImplementation(IFormatProvider provider) { return Convert.ToDecimal(_value, provider); } /// <inheritdoc/> protected override double IConvertibleToDoubleImplementation(IFormatProvider provider) { return Convert.ToDouble(_value, provider); } /// <inheritdoc/> protected override short IConvertibleToInt16Implementation(IFormatProvider provider) { return Convert.ToInt16(_value, provider); } /// <inheritdoc/> protected override int IConvertibleToInt32Implementation(IFormatProvider provider) { return Convert.ToInt32(_value, provider); } /// <inheritdoc/> protected override long IConvertibleToInt64Implementation(IFormatProvider provider) { return Convert.ToInt64(_value, provider); } /// <inheritdoc/> #pragma warning disable 3002 protected override sbyte IConvertibleToSByteImplementation(IFormatProvider provider) { return Convert.ToSByte(_value, provider); } #pragma warning restore /// <inheritdoc/> protected override float IConvertibleToSingleImplementation(IFormatProvider provider) { return Convert.ToSingle(_value, provider); } /// <inheritdoc/> protected override string IConvertibleToStringImplementation(IFormatProvider provider) { return _value; } /// <inheritdoc/> #pragma warning disable 3002 protected override ushort IConvertibleToUInt16Implementation(IFormatProvider provider) { return Convert.ToUInt16(_value, provider); } #pragma warning restore /// <inheritdoc/> #pragma warning disable 3002 protected override uint IConvertibleToUInt32Implementation(IFormatProvider provider) { return Convert.ToUInt32(_value, provider); } #pragma warning restore /// <inheritdoc/> #pragma warning disable 3002 protected override ulong IConvertibleToUInt64Implementation(IFormatProvider provider) { return Convert.ToUInt64(_value, provider); } #pragma warning restore } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/Linq/Expressions/ResultOperators/AggregateResultOperator.cs<|end_filename|> /* Copyright 2016-present MongoDB Inc. * * 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.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using MongoDB.Bson.Serialization; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Linq.Expressions.ResultOperators { internal sealed class AggregateResultOperator : ResultOperator { private readonly Expression _finalizer; private readonly string _itemName; private readonly Expression _reducer; private readonly Expression _seed; private readonly IBsonSerializer _serializer; public AggregateResultOperator(Expression seed, Expression reducer, Expression finalizer, string itemName, IBsonSerializer serializer) { _seed = Ensure.IsNotNull(seed, nameof(seed)); _reducer = Ensure.IsNotNull(reducer, nameof(reducer)); _serializer = Ensure.IsNotNull(serializer, nameof(serializer)); _finalizer = finalizer; _itemName = itemName; } public Expression Finalizer { get { return _finalizer; } } public string ItemName { get { return _itemName; } } public override string Name { get { return "Aggregate"; } } public Expression Reducer { get { return _reducer; } } public Expression Seed { get { return _seed; } } public override IBsonSerializer Serializer { get { return _serializer; } } public override Type Type { get { return _serializer.ValueType; } } protected internal override ResultOperator Update(ExtensionExpressionVisitor visitor) { var seed = visitor.Visit(_seed); var reducer = visitor.Visit(_reducer); Expression finalizer = null; if (_finalizer != null) { finalizer = visitor.Visit(_finalizer); } if (seed != _seed || reducer != _reducer || finalizer != _finalizer) { return new AggregateResultOperator(seed, reducer, finalizer, _itemName, _serializer); } return this; } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/GeoJsonObjectModel/Serializers/GeoJsonGeometryCollectionSerializer.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.Collections.Generic; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; namespace MongoDB.Driver.GeoJsonObjectModel.Serializers { /// <summary> /// Represents a serializer for a GeoJsonGeometryCollection value. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> public class GeoJsonGeometryCollectionSerializer<TCoordinates> : ClassSerializerBase<GeoJsonGeometryCollection<TCoordinates>> where TCoordinates : GeoJsonCoordinates { // private constants private static class Flags { public const long Geometries = 16; } // private fields private readonly IBsonSerializer<GeoJsonGeometry<TCoordinates>> _geometrySerializer = BsonSerializer.LookupSerializer<GeoJsonGeometry<TCoordinates>>(); private readonly GeoJsonObjectSerializerHelper<TCoordinates> _helper; // constructors /// <summary> /// Initializes a new instance of the <see cref="GeoJsonGeometryCollectionSerializer{TCoordinates}"/> class. /// </summary> public GeoJsonGeometryCollectionSerializer() { _helper = new GeoJsonObjectSerializerHelper<TCoordinates> ( "GeometryCollection", new SerializerHelper.Member("geometries", Flags.Geometries) ); } // protected methods /// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <param name="args">The deserialization args.</param> /// <returns>The value.</returns> protected override GeoJsonGeometryCollection<TCoordinates> DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args) { var geoJsonObjectArgs = new GeoJsonObjectArgs<TCoordinates>(); List<GeoJsonGeometry<TCoordinates>> geometries = null; _helper.DeserializeMembers(context, (elementName, flag) => { switch (flag) { case Flags.Geometries: geometries = DeserializeGeometries(context); break; default: _helper.DeserializeBaseMember(context, elementName, flag, geoJsonObjectArgs); break; } }); return new GeoJsonGeometryCollection<TCoordinates>(geoJsonObjectArgs, geometries); } /// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The value.</param> protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, GeoJsonGeometryCollection<TCoordinates> value) { _helper.SerializeMembers(context, value, SerializeDerivedMembers); } // private methods private List<GeoJsonGeometry<TCoordinates>> DeserializeGeometries(BsonDeserializationContext context) { var bsonReader = context.Reader; bsonReader.ReadStartArray(); var geometries = new List<GeoJsonGeometry<TCoordinates>>(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var geometry = _geometrySerializer.Deserialize(context); geometries.Add(geometry); } bsonReader.ReadEndArray(); return geometries; } private void SerializeDerivedMembers(BsonSerializationContext context, GeoJsonGeometryCollection<TCoordinates> value) { SerializeGeometries(context, value.Geometries); } private void SerializeGeometries(BsonSerializationContext context, IEnumerable<GeoJsonGeometry<TCoordinates>> geometries) { var bsonWriter = context.Writer; bsonWriter.WriteName("geometries"); bsonWriter.WriteStartArray(); foreach (var geometry in geometries) { _geometrySerializer.Serialize(context, geometry); } bsonWriter.WriteEndArray(); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.GridFS/GridFSForwardOnlyUploadStream.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Operations; using MongoDB.Shared; namespace MongoDB.Driver.GridFS { internal class GridFSForwardOnlyUploadStream<TFileId> : GridFSUploadStream<TFileId> { #region static // private static fields private static readonly Task __completedTask = Task.FromResult(true); #endregion // fields private bool _aborted; private readonly List<string> _aliases; private List<byte[]> _batch; private long _batchPosition; private int _batchSize; private readonly IWriteBinding _binding; private readonly GridFSBucket<TFileId> _bucket; private readonly int _chunkSizeBytes; private bool _closed; private readonly string _contentType; private readonly bool _disableMD5; private bool _disposed; private readonly string _filename; private readonly TFileId _id; private readonly BsonValue _idAsBsonValue; private long _length; private readonly IncrementalMD5 _md5; private readonly BsonDocument _metadata; // constructors public GridFSForwardOnlyUploadStream( GridFSBucket<TFileId> bucket, IWriteBinding binding, TFileId id, string filename, BsonDocument metadata, IEnumerable<string> aliases, string contentType, int chunkSizeBytes, int batchSize, bool disableMD5) { _bucket = bucket; _binding = binding; _id = id; _filename = filename; _metadata = metadata; // can be null _aliases = aliases == null ? null : aliases.ToList(); // can be null _contentType = contentType; // can be null _chunkSizeBytes = chunkSizeBytes; _batchSize = batchSize; _batch = new List<byte[]>(); _md5 = disableMD5 ? null : IncrementalMD5.Create(); _disableMD5 = disableMD5; var idSerializer = bucket.Options.SerializerRegistry.GetSerializer<TFileId>(); var idSerializationInfo = new BsonSerializationInfo("_id", idSerializer, typeof(TFileId)); _idAsBsonValue = idSerializationInfo.SerializeValue(id); } // properties public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override TFileId Id { get { return _id; } } public override long Length { get { return _length; } } public override long Position { get { return _length; } set { throw new NotSupportedException(); } } // methods public override void Abort(CancellationToken cancellationToken = default(CancellationToken)) { if (_aborted) { return; } ThrowIfClosedOrDisposed(); _aborted = true; var operation = CreateAbortOperation(); operation.Execute(_binding, cancellationToken); } public override async Task AbortAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (_aborted) { return; } ThrowIfClosedOrDisposed(); _aborted = true; var operation = CreateAbortOperation(); await operation.ExecuteAsync(_binding, cancellationToken).ConfigureAwait(false); } public override void Close(CancellationToken cancellationToken) { try { CloseIfNotAlreadyClosed(cancellationToken); } finally { Dispose(); } } public override async Task CloseAsync(CancellationToken cancellationToken = default(CancellationToken)) { try { await CloseIfNotAlreadyClosedAsync(cancellationToken).ConfigureAwait(false); } finally { Dispose(); } } public override void Flush() { // do nothing } public override Task FlushAsync(CancellationToken cancellationToken) { // do nothing return __completedTask; } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { throw new NotSupportedException(); } public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { ThrowIfAbortedClosedOrDisposed(); while (count > 0) { var chunk = GetCurrentChunk(CancellationToken.None); var partialCount = Math.Min(count, chunk.Count); Buffer.BlockCopy(buffer, offset, chunk.Array, chunk.Offset, partialCount); offset += partialCount; count -= partialCount; _length += partialCount; } } public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { ThrowIfAbortedClosedOrDisposed(); while (count > 0) { var chunk = await GetCurrentChunkAsync(cancellationToken).ConfigureAwait(false); var partialCount = Math.Min(count, chunk.Count); Buffer.BlockCopy(buffer, offset, chunk.Array, chunk.Offset, partialCount); offset += partialCount; count -= partialCount; _length += partialCount; } } // private methods private void CloseIfNotAlreadyClosed(CancellationToken cancellationToken) { if (!_closed) { try { CloseImplementation(cancellationToken); } finally { _closed = true; } } } private async Task CloseIfNotAlreadyClosedAsync(CancellationToken cancellationToken) { if (!_closed) { try { await CloseImplementationAsync(cancellationToken).ConfigureAwait(false); } finally { _closed = true; } } } private void CloseIfNotAlreadyClosedFromDispose(bool disposing) { if (disposing) { try { CloseIfNotAlreadyClosed(CancellationToken.None); } catch { // ignore any exceptions from CloseIfNotAlreadyClosed when called from Dispose } } } private void CloseImplementation(CancellationToken cancellationToken) { if (!_aborted) { WriteFinalBatch(cancellationToken); WriteFilesCollectionDocument(cancellationToken); } } private async Task CloseImplementationAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (!_aborted) { await WriteFinalBatchAsync(cancellationToken).ConfigureAwait(false); await WriteFilesCollectionDocumentAsync(cancellationToken).ConfigureAwait(false); } } private BulkMixedWriteOperation CreateAbortOperation() { var chunksCollectionNamespace = _bucket.GetChunksCollectionNamespace(); var filter = new BsonDocument("files_id", _idAsBsonValue); var deleteRequest = new DeleteRequest(filter) { Limit = 0 }; var requests = new WriteRequest[] { deleteRequest }; var messageEncoderSettings = _bucket.GetMessageEncoderSettings(); return new BulkMixedWriteOperation(chunksCollectionNamespace, requests, messageEncoderSettings) { WriteConcern = _bucket.Options.WriteConcern }; } private BsonDocument CreateFilesCollectionDocument() { var uploadDateTime = DateTime.UtcNow; return new BsonDocument { { "_id", _idAsBsonValue }, { "length", _length }, { "chunkSize", _chunkSizeBytes }, { "uploadDate", uploadDateTime }, { "md5", () => BsonUtils.ToHexString(_md5.GetHashAndReset()), !_disableMD5 }, { "filename", _filename }, { "contentType", _contentType, _contentType != null }, { "aliases", () => new BsonArray(_aliases.Select(a => new BsonString(a))), _aliases != null }, { "metadata", _metadata, _metadata != null } }; } private IEnumerable<BsonDocument> CreateWriteBatchChunkDocuments() { var chunkDocuments = new List<BsonDocument>(); var n = (int)(_batchPosition / _chunkSizeBytes); foreach (var chunk in _batch) { var chunkDocument = new BsonDocument { { "_id", ObjectId.GenerateNewId() }, { "files_id", _idAsBsonValue }, { "n", n++ }, { "data", new BsonBinaryData(chunk, BsonBinarySubType.Binary) } }; chunkDocuments.Add(chunkDocument); _batchPosition += chunk.Length; _md5?.AppendData(chunk, 0, chunk.Length); } return chunkDocuments; } protected override void Dispose(bool disposing) { CloseIfNotAlreadyClosedFromDispose(disposing); if (!_disposed) { _disposed = true; if (disposing) { if (_md5 != null) { _md5.Dispose(); } _binding.Dispose(); } } base.Dispose(disposing); } private IMongoCollection<BsonDocument> GetChunksCollection() { return GetCollection("chunks"); } private IMongoCollection<BsonDocument> GetCollection(string suffix) { var database = _bucket.Database; var collectionName = _bucket.Options.BucketName + "." + suffix; var writeConcern = _bucket.Options.WriteConcern ?? database.Settings.WriteConcern; var settings = new MongoCollectionSettings { WriteConcern = writeConcern }; return database.GetCollection<BsonDocument>(collectionName, settings); } private ArraySegment<byte> GetCurrentChunk(CancellationToken cancellationToken) { var batchIndex = (int)((_length - _batchPosition) / _chunkSizeBytes); if (batchIndex == _batchSize) { WriteBatch(cancellationToken); _batch.Clear(); batchIndex = 0; } return GetCurrentChunkSegment(batchIndex); } private async Task<ArraySegment<byte>> GetCurrentChunkAsync(CancellationToken cancellationToken) { var batchIndex = (int)((_length - _batchPosition) / _chunkSizeBytes); if (batchIndex == _batchSize) { await WriteBatchAsync(cancellationToken).ConfigureAwait(false); _batch.Clear(); batchIndex = 0; } return GetCurrentChunkSegment(batchIndex); } private ArraySegment<byte> GetCurrentChunkSegment(int batchIndex) { if (_batch.Count <= batchIndex) { _batch.Add(new byte[_chunkSizeBytes]); } var chunk = _batch[batchIndex]; var offset = (int)(_length % _chunkSizeBytes); var count = _chunkSizeBytes - offset; return new ArraySegment<byte>(chunk, offset, count); } private IMongoCollection<BsonDocument> GetFilesCollection() { return GetCollection("files"); } private void ThrowIfAbortedClosedOrDisposed() { if (_aborted) { throw new InvalidOperationException("The upload was aborted."); } ThrowIfClosedOrDisposed(); } private void ThrowIfClosedOrDisposed() { if (_closed) { throw new InvalidOperationException("The stream is closed."); } ThrowIfDisposed(); } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } } private void TruncateFinalChunk() { var finalChunkSize = (int)(_length % _chunkSizeBytes); if (finalChunkSize > 0) { var finalChunk = _batch[_batch.Count - 1]; if (finalChunk.Length != finalChunkSize) { var truncatedFinalChunk = new byte[finalChunkSize]; Buffer.BlockCopy(finalChunk, 0, truncatedFinalChunk, 0, finalChunkSize); _batch[_batch.Count - 1] = truncatedFinalChunk; } } } private void WriteBatch(CancellationToken cancellationToken) { var chunksCollection = GetChunksCollection(); var chunkDocuments = CreateWriteBatchChunkDocuments(); chunksCollection.InsertMany(chunkDocuments, cancellationToken: cancellationToken); _batch.Clear(); } private async Task WriteBatchAsync(CancellationToken cancellationToken) { var chunksCollection = GetChunksCollection(); var chunkDocuments = CreateWriteBatchChunkDocuments(); await chunksCollection.InsertManyAsync(chunkDocuments, cancellationToken: cancellationToken).ConfigureAwait(false); _batch.Clear(); } private void WriteFilesCollectionDocument(CancellationToken cancellationToken) { var filesCollection = GetFilesCollection(); var filesCollectionDocument = CreateFilesCollectionDocument(); filesCollection.InsertOne(filesCollectionDocument, cancellationToken: cancellationToken); } private async Task WriteFilesCollectionDocumentAsync(CancellationToken cancellationToken) { var filesCollection = GetFilesCollection(); var filesCollectionDocument = CreateFilesCollectionDocument(); await filesCollection.InsertOneAsync(filesCollectionDocument, cancellationToken: cancellationToken).ConfigureAwait(false); } private void WriteFinalBatch(CancellationToken cancellationToken) { if (_batch.Count > 0) { TruncateFinalChunk(); WriteBatch(cancellationToken); } } private async Task WriteFinalBatchAsync(CancellationToken cancellationToken) { if (_batch.Count > 0) { TruncateFinalChunk(); await WriteBatchAsync(cancellationToken).ConfigureAwait(false); } } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Packages/PackageListExtensions.cs<|end_filename|> using System.Collections.Generic; using System.Linq; namespace UnityEditor.PackageManager.UI { internal static class PackageListExtensions { public static IEnumerable<Package> Current(this IEnumerable<Package> list) { return (from package in list where package.Current != null select package); } } } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Shared/CanonicalEquatableDerivedClass.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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; namespace MongoDB.Shared { internal class CanonicalEquatableDerivedClass : CanonicalEquatableClass, IEquatable<CanonicalEquatableDerivedClass> { // private fields private int _z; // constructors /// <summary> /// Initializes a new instance of the <see cref="CanonicalEquatableDerivedClass"/> class. /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="z">The z.</param> public CanonicalEquatableDerivedClass(int x, int y, int z) : base(x, y) { _z = z; } // base class defines == and != // public methods /// <summary> /// Determines whether the specified <see cref="CanonicalEquatableDerivedClass" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="CanonicalEquatableDerivedClass" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="CanonicalEquatableDerivedClass" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(CanonicalEquatableDerivedClass obj) { return Equals((object)obj); } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { // base class checks for obj == null and correct type if (!base.Equals(obj)) { return false; } var rhs = (CanonicalEquatableDerivedClass)obj; return // be sure z implements ==, otherwise use Equals _z == rhs._z; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { // use hash code of base class as seed to Hasher return new Hasher(base.GetHashCode()) .Hash(_z) .GetHashCode(); } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Tests/Editor/Services/Mock/MockListOperation.cs<|end_filename|> using System; using System.Collections.Generic; namespace UnityEditor.PackageManager.UI.Tests { internal class MockListOperation : MockOperation, IListOperation { public new event Action<Error> OnOperationError = delegate { }; public new event Action OnOperationFinalized = delegate { }; public bool OfflineMode { get; set; } public MockListOperation(MockOperationFactory factory) : base(factory) { } public void GetPackageListAsync(Action<IEnumerable<PackageInfo>> doneCallbackAction, Action<Error> errorCallbackAction = null) { if (ForceError != null) { if (errorCallbackAction != null) errorCallbackAction(ForceError); IsCompleted = true; OnOperationError(ForceError); } else { if (doneCallbackAction != null) doneCallbackAction(Factory.Packages); IsCompleted = true; } OnOperationFinalized(); } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Plugins/Editor/QuickTouchInspector.cs<|end_filename|> using UnityEngine; using System.Collections; using UnityEditor; using HedgehogTeam.EasyTouch; #if UNITY_5_3_OR_NEWER using UnityEditor.SceneManagement; #endif [CustomEditor(typeof(QuickTouch))] public class QuickTouchInspector : Editor { public override void OnInspectorGUI(){ QuickTouch t = (QuickTouch)target; EditorGUILayout.Space(); t.quickActionName = EditorGUILayout.TextField("Name",t.quickActionName); EditorGUILayout.Space(); t.is2Finger = EditorGUILayout.Toggle("2 fingers gesture",t.is2Finger); t.actionTriggering = (QuickTouch.ActionTriggering)EditorGUILayout.EnumPopup("Action triggering",t.actionTriggering); EditorGUILayout.Space(); if (!t.is2Finger){ t.isMultiTouch = EditorGUILayout.ToggleLeft("Allow multi-touch",t.isMultiTouch); } t.enablePickOverUI = EditorGUILayout.ToggleLeft("Allow over UI Element",t.enablePickOverUI); serializedObject.Update(); SerializedProperty touch = serializedObject.FindProperty("onTouch"); EditorGUILayout.PropertyField(touch, true, null); serializedObject.ApplyModifiedProperties(); if (t.actionTriggering == QuickTouch.ActionTriggering.Up){ touch = serializedObject.FindProperty("onTouchNotOverMe"); EditorGUILayout.PropertyField(touch, true, null); serializedObject.ApplyModifiedProperties(); } if (GUI.changed){ EditorUtility.SetDirty(t); #if UNITY_5_3_OR_NEWER EditorSceneManager.MarkSceneDirty( EditorSceneManager.GetActiveScene()); #endif } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/MongoException.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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 MongoDB.Driver.Core.Misc; #if NET452 using System.Runtime.Serialization; #endif namespace MongoDB.Driver { /// <summary> /// Represents a MongoDB exception. /// </summary> #if NET452 [Serializable] #endif public class MongoException : Exception { // private fields private readonly List<string> _errorLabels = new List<string>(); // constructors /// <summary> /// Initializes a new instance of the <see cref="MongoException"/> class. /// </summary> /// <param name="message">The error message.</param> public MongoException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="MongoException"/> class. /// </summary> /// <param name="message">The error message.</param> /// <param name="innerException">The inner exception.</param> public MongoException(string message, Exception innerException) : base(message, innerException) { } #if NET452 /// <summary> /// Initializes a new instance of the <see cref="MongoException"/> class. /// </summary> /// <param name="info">The SerializationInfo.</param> /// <param name="context">The StreamingContext.</param> public MongoException(SerializationInfo info, StreamingContext context) : base(info, context) { _errorLabels = (List<string>)info.GetValue(nameof(_errorLabels), typeof(List<String>)); } #endif // public properties /// <summary> /// Gets the error labels. /// </summary> /// <value> /// The error labels. /// </value> public IReadOnlyList<string> ErrorLabels => _errorLabels; // public methods /// <summary> /// Adds an error label. /// </summary> /// <param name="errorLabel">The error label.</param> public void AddErrorLabel(string errorLabel) { Ensure.IsNotNull(errorLabel, nameof(errorLabel)); if (!_errorLabels.Contains(errorLabel)) { _errorLabels.Add(errorLabel); } } /// <summary> /// Determines whether the exception has some error label. /// </summary> /// <param name="errorLabel">The error label.</param> /// <returns> /// <c>true</c> if the exception has some error label; otherwise, <c>false</c>. /// </returns> public bool HasErrorLabel(string errorLabel) { return _errorLabels.Contains(errorLabel); } /// <summary> /// Removes the error label. /// </summary> /// <param name="errorLabel">The error label.</param> public void RemoveErrorLabel(string errorLabel) { _errorLabels.Remove(errorLabel); } #if NET452 /// <inheritdoc/> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(_errorLabels), _errorLabels); } #endif } } <|start_filename|>Unity/Assets/Model/Module/Pathfinding/Recast/AstarDeserializer.cs<|end_filename|> using System; using System.Collections.Generic; namespace PF { public static class AstarDeserializer { /** Deserializes graphs from the specified byte array. * An error will be logged if deserialization fails. */ public static NavGraph[] DeserializeGraphs (byte[] bytes) { NavGraph[] graphs = { new RecastGraph() }; DeserializeGraphsAdditive(graphs, bytes); return graphs; } /** Deserializes graphs from the specified byte array additively. * An error will be logged if deserialization fails. * This function will add loaded graphs to the current ones. */ public static void DeserializeGraphsAdditive (NavGraph[] graphs, byte[] bytes) { try { if (bytes != null) { var sr = new AstarSerializer(); if (sr.OpenDeserialize(bytes)) { DeserializeGraphsPartAdditive(graphs, sr); sr.CloseDeserialize(); } else { throw new Exception("Invalid data file (cannot read zip).\nThe data is either corrupt or it was saved using a 3.0.x or earlier version of the system"); } } else { throw new System.ArgumentNullException("bytes"); } //AstarPath.active.VerifyIntegrity(); } catch (System.Exception e) { #if !SERVER UnityEngine.Debug.LogError("Caught exception while deserializing data.\n"+e); #endif throw; } } /** Helper function for deserializing graphs */ public static void DeserializeGraphsPartAdditive (NavGraph[] graphs, AstarSerializer sr) { if (graphs == null) graphs = new NavGraph[0]; var gr = new List<NavGraph>(graphs); // Set an offset so that the deserializer will load // the graphs with the correct graph indexes sr.SetGraphIndexOffset(gr.Count); gr.AddRange(sr.DeserializeGraphs()); graphs = gr.ToArray(); sr.DeserializeEditorSettingsCompatibility(); sr.DeserializeExtraInfo(); //Assign correct graph indices. for (int i = 0; i < graphs.Length; i++) { if (graphs[i] == null) continue; graphs[i].GetNodes(node => node.GraphIndex = (uint)i); } for (int i = 0; i < graphs.Length; i++) { for (int j = i+1; j < graphs.Length; j++) { if (graphs[i] != null && graphs[j] != null && graphs[i].guid == graphs[j].guid) { #if !SERVER UnityEngine.Debug.LogWarning("Guid Conflict when importing graphs additively. Imported graph will get a new Guid.\nThis message is (relatively) harmless."); #endif graphs[i].guid = Guid.NewGuid(); break; } } } } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Tests/Editor/Services/Packages/PackageCollectionTests.cs<|end_filename|> using System; using System.Collections.Generic; using NUnit.Framework; namespace UnityEditor.PackageManager.UI.Tests { internal class PackageCollectionTests : PackageBaseTests { private Action<PackageFilter> OnFilterChangeEvent; private Action<IEnumerable<Package>> OnPackagesChangeEvent; [SetUp] public void Setup() { PackageCollection.Instance.SetFilter(PackageFilter.Local); } [TearDown] public void TearDown() { PackageCollection.Instance.OnFilterChanged -= OnFilterChangeEvent; PackageCollection.Instance.OnPackagesChanged -= OnPackagesChangeEvent; } [Test] public void Constructor_Instance_FilterIsLocal() { Assert.AreEqual(PackageFilter.Local, PackageCollection.Instance.Filter); } [Test] public void SetFilter_WhenFilterChange_FilterChangeEventIsPropagated() { var wasCalled = false; OnFilterChangeEvent = filter => { wasCalled = true; }; PackageCollection.Instance.OnFilterChanged += OnFilterChangeEvent; PackageCollection.Instance.SetFilter(PackageFilter.All, false); Assert.IsTrue(wasCalled); } [Test] public void SetFilter_WhenNoFilterChange_FilterChangeEventIsNotPropagated() { var wasCalled = false; OnFilterChangeEvent = filter => { wasCalled = true; }; PackageCollection.Instance.OnFilterChanged += OnFilterChangeEvent; PackageCollection.Instance.SetFilter(PackageFilter.Local, false); Assert.IsFalse(wasCalled); } [Test] public void SetFilter_WhenFilterChange_FilterIsChanged() { PackageCollection.Instance.SetFilter(PackageFilter.All, false); Assert.AreEqual(PackageFilter.All, PackageCollection.Instance.Filter); } [Test] public void SetFilter_WhenNoFilterChangeRefresh_PackagesChangeEventIsNotPropagated() { var wasCalled = false; OnPackagesChangeEvent = packages => { wasCalled = true; }; PackageCollection.Instance.OnPackagesChanged += OnPackagesChangeEvent; PackageCollection.Instance.SetFilter(PackageFilter.Local); Assert.IsFalse(wasCalled); } [Test] public void SetFilter_WhenFilterChangeNoRefresh_PackagesChangeEventIsNotPropagated() { var wasCalled = false; OnPackagesChangeEvent = packages => { wasCalled = true; }; PackageCollection.Instance.OnPackagesChanged += OnPackagesChangeEvent; PackageCollection.Instance.SetFilter(PackageFilter.All, false); Assert.IsFalse(wasCalled); } [Test] public void SetFilter_WhenNoFilterChangeNoRefresh_PackagesChangeEventIsNotPropagated() { var wasCalled = false; OnPackagesChangeEvent = packages => { wasCalled = true; }; PackageCollection.Instance.OnPackagesChanged += OnPackagesChangeEvent; PackageCollection.Instance.SetFilter(PackageFilter.Local, false); Assert.IsFalse(wasCalled); } [Test] public void FetchListCache_PackagesChangeEventIsPropagated() { var wasCalled = false; OnPackagesChangeEvent = packages => { wasCalled = true; }; PackageCollection.Instance.OnPackagesChanged += OnPackagesChangeEvent; Factory.Packages = PackageSets.Instance.Many(5); PackageCollection.Instance.FetchListCache(true); Assert.IsTrue(wasCalled); } [Test] public void FetchListOfflineCache_PackagesChangeEventIsPropagated() { var wasCalled = false; OnPackagesChangeEvent = packages => { wasCalled = true; }; PackageCollection.Instance.OnPackagesChanged += OnPackagesChangeEvent; Factory.Packages = PackageSets.Instance.Many(5); PackageCollection.Instance.FetchListOfflineCache(true); Assert.IsTrue(wasCalled); } [Test] public void FetchSearchCache_PackagesChangeEventIsPropagated() { var wasCalled = false; OnPackagesChangeEvent = packages => { wasCalled = true; }; PackageCollection.Instance.OnPackagesChanged += OnPackagesChangeEvent; Factory.SearchOperation = new MockSearchOperation(Factory, PackageSets.Instance.Many(5)); PackageCollection.Instance.FetchSearchCache(true); Assert.IsTrue(wasCalled); } } } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/Serialization/Serializers/DateTimeSerializer.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.Globalization; using System.IO; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Options; namespace MongoDB.Bson.Serialization.Serializers { /// <summary> /// Represents a serializer for DateTimes. /// </summary> public class DateTimeSerializer : StructSerializerBase<DateTime>, IRepresentationConfigurable<DateTimeSerializer> { // private constants private static class Flags { public const long DateTime = 1; public const long Ticks = 2; } // private static fields private static readonly DateTimeSerializer __dateOnlyInstance = new DateTimeSerializer(true); private static readonly DateTimeSerializer __localInstance = new DateTimeSerializer(DateTimeKind.Local); private static readonly DateTimeSerializer __utcInstance = new DateTimeSerializer(DateTimeKind.Utc); // private fields private readonly bool _dateOnly; private readonly SerializerHelper _helper; private readonly Int64Serializer _int64Serializer = new Int64Serializer(); private readonly DateTimeKind _kind; private readonly BsonType _representation; // constructors /// <summary> /// Initializes a new instance of the <see cref="DateTimeSerializer"/> class. /// </summary> public DateTimeSerializer() : this(DateTimeKind.Utc, BsonType.DateTime) { } /// <summary> /// Initializes a new instance of the <see cref="DateTimeSerializer"/> class. /// </summary> /// <param name="dateOnly">if set to <c>true</c> [date only].</param> public DateTimeSerializer(bool dateOnly) : this(dateOnly, BsonType.DateTime) { } /// <summary> /// Initializes a new instance of the <see cref="DateTimeSerializer"/> class. /// </summary> /// <param name="dateOnly">if set to <c>true</c> [date only].</param> /// <param name="representation">The representation.</param> public DateTimeSerializer(bool dateOnly, BsonType representation) : this(dateOnly, DateTimeKind.Utc, representation) { } /// <summary> /// Initializes a new instance of the <see cref="DateTimeSerializer"/> class. /// </summary> /// <param name="representation">The representation.</param> public DateTimeSerializer(BsonType representation) : this(DateTimeKind.Utc, representation) { } /// <summary> /// Initializes a new instance of the <see cref="DateTimeSerializer"/> class. /// </summary> /// <param name="kind">The kind.</param> public DateTimeSerializer(DateTimeKind kind) : this(kind, BsonType.DateTime) { } /// <summary> /// Initializes a new instance of the <see cref="DateTimeSerializer"/> class. /// </summary> /// <param name="kind">The kind.</param> /// <param name="representation">The representation.</param> public DateTimeSerializer(DateTimeKind kind, BsonType representation) : this(false, kind, representation) { } private DateTimeSerializer(bool dateOnly, DateTimeKind kind, BsonType representation) { switch (representation) { case BsonType.DateTime: case BsonType.Document: case BsonType.Int64: case BsonType.String: break; default: var message = string.Format("{0} is not a valid representation for a DateTimeSerializer.", representation); throw new ArgumentException(message); } _dateOnly = dateOnly; _kind = kind; _representation = representation; _helper = new SerializerHelper ( new SerializerHelper.Member("DateTime", Flags.DateTime), new SerializerHelper.Member("Ticks", Flags.Ticks) ); } // public static properties /// <summary> /// Gets an instance of DateTimeSerializer with DateOnly=true. /// </summary> public static DateTimeSerializer DateOnlyInstance { get { return __dateOnlyInstance; } } /// <summary> /// Gets an instance of DateTimeSerializer with Kind=Local. /// </summary> public static DateTimeSerializer LocalInstance { get { return __localInstance; } } /// <summary> /// Gets an instance of DateTimeSerializer with Kind=Utc. /// </summary> public static DateTimeSerializer UtcInstance { get { return __utcInstance; } } // public properties /// <summary> /// Gets whether this DateTime consists of a Date only. /// </summary> public bool DateOnly { get { return _dateOnly; } } /// <summary> /// Gets the DateTimeKind (Local, Unspecified or Utc). /// </summary> public DateTimeKind Kind { get { return _kind; } } /// <summary> /// Gets the external representation. /// </summary> /// <value> /// The representation. /// </value> public BsonType Representation { get { return _representation; } } // public methods /// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <param name="args">The deserialization args.</param> /// <returns>A deserialized value.</returns> public override DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { var bsonReader = context.Reader; DateTime value; var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.DateTime: // use an intermediate BsonDateTime so MinValue and MaxValue are handled correctly value = new BsonDateTime(bsonReader.ReadDateTime()).ToUniversalTime(); break; case BsonType.Document: value = default(DateTime); _helper.DeserializeMembers(context, (elementName, flag) => { switch (flag) { case Flags.DateTime: bsonReader.SkipValue(); break; // ignore value (use Ticks instead) case Flags.Ticks: value = new DateTime(_int64Serializer.Deserialize(context), DateTimeKind.Utc); break; } }); break; case BsonType.Int64: value = DateTime.SpecifyKind(new DateTime(bsonReader.ReadInt64()), DateTimeKind.Utc); break; case BsonType.String: if (_dateOnly) { value = DateTime.SpecifyKind(DateTime.ParseExact(bsonReader.ReadString(), "yyyy-MM-dd", null), DateTimeKind.Utc); } else { value = JsonConvert.ToDateTime(bsonReader.ReadString()); } break; default: throw CreateCannotDeserializeFromBsonTypeException(bsonType); } if (_dateOnly) { if (value.TimeOfDay != TimeSpan.Zero) { throw new FormatException("TimeOfDay component for DateOnly DateTime value is not zero."); } value = DateTime.SpecifyKind(value, _kind); // not ToLocalTime or ToUniversalTime! } else { switch (_kind) { case DateTimeKind.Local: case DateTimeKind.Unspecified: value = DateTime.SpecifyKind(BsonUtils.ToLocalTime(value), _kind); break; case DateTimeKind.Utc: value = BsonUtils.ToUniversalTime(value); break; } } return value; } /// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The object.</param> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTime value) { var bsonWriter = context.Writer; DateTime utcDateTime; if (_dateOnly) { if (value.TimeOfDay != TimeSpan.Zero) { throw new BsonSerializationException("TimeOfDay component is not zero."); } utcDateTime = DateTime.SpecifyKind(value, DateTimeKind.Utc); // not ToLocalTime } else { utcDateTime = BsonUtils.ToUniversalTime(value); } var millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(utcDateTime); switch (_representation) { case BsonType.DateTime: bsonWriter.WriteDateTime(millisecondsSinceEpoch); break; case BsonType.Document: bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("DateTime", millisecondsSinceEpoch); bsonWriter.WriteInt64("Ticks", utcDateTime.Ticks); bsonWriter.WriteEndDocument(); break; case BsonType.Int64: bsonWriter.WriteInt64(utcDateTime.Ticks); break; case BsonType.String: if (_dateOnly) { bsonWriter.WriteString(value.ToString("yyyy-MM-dd")); } else { if (value == DateTime.MinValue || value == DateTime.MaxValue) { // serialize MinValue and MaxValue as Unspecified so we do NOT get the time zone offset value = DateTime.SpecifyKind(value, DateTimeKind.Unspecified); } else if (value.Kind == DateTimeKind.Unspecified) { // serialize Unspecified as Local se we get the time zone offset value = DateTime.SpecifyKind(value, DateTimeKind.Local); } bsonWriter.WriteString(JsonConvert.ToString(value)); } break; default: var message = string.Format("'{0}' is not a valid DateTime representation.", _representation); throw new BsonSerializationException(message); } } /// <summary> /// Returns a serializer that has been reconfigured with the specified dateOnly value. /// </summary> /// <param name="dateOnly">if set to <c>true</c> the values will be required to be Date's only (zero time component).</param> /// <returns> /// The reconfigured serializer. /// </returns> public DateTimeSerializer WithDateOnly(bool dateOnly) { if (dateOnly == _dateOnly) { return this; } else { return new DateTimeSerializer(dateOnly, _representation); } } /// <summary> /// Returns a serializer that has been reconfigured with the specified dateOnly value and representation. /// </summary> /// <param name="dateOnly">if set to <c>true</c> the values will be required to be Date's only (zero time component).</param> /// <param name="representation">The representation.</param> /// <returns> /// The reconfigured serializer. /// </returns> public DateTimeSerializer WithDateOnly(bool dateOnly, BsonType representation) { if (dateOnly == _dateOnly && representation == _representation) { return this; } else { return new DateTimeSerializer(dateOnly, representation); } } /// <summary> /// Returns a serializer that has been reconfigured with the specified DateTimeKind value. /// </summary> /// <param name="kind">The DateTimeKind.</param> /// <returns> /// The reconfigured serializer. /// </returns> public DateTimeSerializer WithKind(DateTimeKind kind) { if (kind == _kind && _dateOnly == false) { return this; } else { return new DateTimeSerializer(kind, _representation); } } /// <summary> /// Returns a serializer that has been reconfigured with the specified DateTimeKind value and representation. /// </summary> /// <param name="kind">The DateTimeKind.</param> /// <param name="representation">The representation.</param> /// <returns> /// The reconfigured serializer. /// </returns> public DateTimeSerializer WithKind(DateTimeKind kind, BsonType representation) { if (kind == _kind && representation == _representation && _dateOnly == false) { return this; } else { return new DateTimeSerializer(kind, representation); } } /// <summary> /// Returns a serializer that has been reconfigured with the specified representation. /// </summary> /// <param name="representation">The representation.</param> /// <returns>The reconfigured serializer.</returns> public DateTimeSerializer WithRepresentation(BsonType representation) { if (representation == _representation) { return this; } else { if (_dateOnly) { return new DateTimeSerializer(_dateOnly, representation); } else { return new DateTimeSerializer(_kind, representation); } } } // explicit interface implementations IBsonSerializer IRepresentationConfigurable.WithRepresentation(BsonType representation) { return WithRepresentation(representation); } } } <|start_filename|>Unity/Assets/ThirdParty/ILRuntime/Mono.Cecil/Mono.Cecil/MemberDefinitionCollection.cs<|end_filename|> // // Author: // <NAME> (<EMAIL>) // // Copyright (c) 2008 - 2015 <NAME> // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using Mono.Collections.Generic; namespace Mono.Cecil { sealed class MemberDefinitionCollection<T> : Collection<T> where T : IMemberDefinition { TypeDefinition container; internal MemberDefinitionCollection (TypeDefinition container) { this.container = container; } internal MemberDefinitionCollection (TypeDefinition container, int capacity) : base (capacity) { this.container = container; } protected override void OnAdd (T item, int index) { Attach (item); } protected sealed override void OnSet (T item, int index) { Attach (item); } protected sealed override void OnInsert (T item, int index) { Attach (item); } protected sealed override void OnRemove (T item, int index) { Detach (item); } protected sealed override void OnClear () { foreach (var definition in this) Detach (definition); } void Attach (T element) { if (element.DeclaringType == container) return; if (element.DeclaringType != null) throw new ArgumentException ("Member already attached"); element.DeclaringType = this.container; } static void Detach (T element) { element.DeclaringType = null; } } } <|start_filename|>Unity/Assets/Editor/AstarPathfindingProject/RVOSquareObstacleEditor.cs<|end_filename|> using UnityEditor; using Pathfinding.RVO; namespace Pathfinding { [CustomEditor(typeof(RVOSquareObstacle))] [CanEditMultipleObjects] public class RVOSquareObstacleEditor : Editor { public override void OnInspectorGUI () { DrawDefaultInspector(); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Events/Diagnostics/TraceSourceSdamEventSubscriber.cs<|end_filename|> /* Copyright 2018–present MongoDB Inc. * * 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.Diagnostics; using System.Reflection; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Core.Events.Diagnostics { /// <summary> /// An event subscriber that writes SDAM events to a trace source. /// </summary> public sealed class TraceSourceSdamEventSubscriber : IEventSubscriber { private readonly TraceSource _traceSource; private readonly ReflectionEventSubscriber _subscriber; /// <summary> /// Initializes a new instance of the <see cref="TraceSourceSdamEventSubscriber"/> class. /// </summary> /// <param name="traceSource">The trace source.</param> public TraceSourceSdamEventSubscriber(TraceSource traceSource) { _traceSource = Ensure.IsNotNull(traceSource, nameof(traceSource)); _subscriber = new ReflectionEventSubscriber(this, bindingFlags: BindingFlags.Instance | BindingFlags.NonPublic); } /// <inheritdoc /> public bool TryGetEventHandler<TEvent>(out Action<TEvent> handler) { return _subscriber.TryGetEventHandler(out handler); } // Clusters private void Handle(ClusterOpeningEvent @event) { Info(TraceSourceEventHelper.ClusterIdBase, "{0}: opening.", TraceSourceEventHelper.Label(@event.ClusterId)); } private void Handle(ClusterOpenedEvent @event) { Debug(TraceSourceEventHelper.ClusterIdBase + 1, "{0}: opened in {1}ms.", TraceSourceEventHelper.Label(@event.ClusterId), @event.Duration.TotalMilliseconds); } private void Handle(ClusterClosingEvent @event) { Debug(TraceSourceEventHelper.ClusterIdBase + 2, "{0}: closing.", TraceSourceEventHelper.Label(@event.ClusterId)); } private void Handle(ClusterClosedEvent @event) { Info(TraceSourceEventHelper.ClusterIdBase + 3, "{0}: closed in {1}ms.", TraceSourceEventHelper.Label(@event.ClusterId), @event.Duration.TotalMilliseconds); } private void Handle(ClusterAddingServerEvent @event) { Info(TraceSourceEventHelper.ClusterIdBase + 4, "{0}: adding server at endpoint {1}.", TraceSourceEventHelper.Label(@event.ClusterId), TraceSourceEventHelper.Format(@event.EndPoint)); } private void Handle(ClusterAddedServerEvent @event) { Debug(TraceSourceEventHelper.ClusterIdBase + 5, "{0}: added server {1} in {2}ms.", TraceSourceEventHelper.Label(@event.ServerId.ClusterId), TraceSourceEventHelper.Format(@event.ServerId), @event.Duration.TotalMilliseconds); } private void Handle(ClusterRemovingServerEvent @event) { Debug(TraceSourceEventHelper.ClusterIdBase + 6, "{0}: removing server {1}. Reason: {2}", TraceSourceEventHelper.Label(@event.ServerId.ClusterId), TraceSourceEventHelper.Format(@event.ServerId), @event.Reason); } private void Handle(ClusterRemovedServerEvent @event) { Info(TraceSourceEventHelper.ClusterIdBase + 7, "{0}: removed server {1} in {2}ms. Reason: {3}", TraceSourceEventHelper.Label(@event.ServerId.ClusterId), TraceSourceEventHelper.Format(@event.ServerId), @event.Duration.TotalMilliseconds, @event.Reason); } private void Handle(ClusterDescriptionChangedEvent @event) { Info(TraceSourceEventHelper.ClusterIdBase + 8, "{0}: {1}", TraceSourceEventHelper.Label(@event.OldDescription.ClusterId), @event.NewDescription); } private void Handle(SdamInformationEvent @event) { Info(TraceSourceEventHelper.ClusterIdBase + 9, "{0}", @event); } // Servers private void Handle(ServerOpeningEvent @event) { Info(TraceSourceEventHelper.ServerIdBase, "{0}: opening.", TraceSourceEventHelper.Label(@event.ServerId)); } private void Handle(ServerOpenedEvent @event) { Debug(TraceSourceEventHelper.ServerIdBase + 1, "{0}: opened in {1}ms.", TraceSourceEventHelper.Label(@event.ServerId), @event.Duration.TotalMilliseconds); } private void Handle(ServerClosingEvent @event) { Debug(TraceSourceEventHelper.ServerIdBase + 2, "{0}: closing.", TraceSourceEventHelper.Label(@event.ServerId)); } private void Handle(ServerClosedEvent @event) { Info(TraceSourceEventHelper.ServerIdBase + 3, "{0}: closed in {1}ms.", TraceSourceEventHelper.Label(@event.ServerId), @event.Duration.TotalMilliseconds); } private void Handle(ServerHeartbeatStartedEvent @event) { Debug(TraceSourceEventHelper.ServerIdBase + 4, "{0}: sending heartbeat.", TraceSourceEventHelper.Label(@event.ConnectionId)); } private void Handle(ServerHeartbeatSucceededEvent @event) { Debug(TraceSourceEventHelper.ServerIdBase + 5, "{0}: sent heartbeat in {1}ms.", TraceSourceEventHelper.Label(@event.ConnectionId), @event.Duration.TotalMilliseconds); } private void Handle(ServerHeartbeatFailedEvent @event) { Error(TraceSourceEventHelper.ServerIdBase + 6, @event.Exception, "{0}: error sending heartbeat.", TraceSourceEventHelper.Label(@event.ConnectionId)); } private void Handle(ServerDescriptionChangedEvent @event) { Debug(TraceSourceEventHelper.ServerIdBase + 7, "{0}: {1}", TraceSourceEventHelper.Label(@event.OldDescription.ServerId), @event.NewDescription); } private void Debug(int id, string message, params object[] args) { _traceSource.TraceEvent(TraceEventType.Verbose, id, message, args); } private void Info(int id, string message, params object[] args) { _traceSource.TraceEvent(TraceEventType.Information, id, message, args); } private void Error(int id, Exception ex, string message, params object[] args) { _traceSource.TraceEvent( TraceEventType.Error, id, message + Environment.NewLine + ex.ToString(), args); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/GeoJsonObjectModel/Serializers/GeoJsonCoordinatesSerializer.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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 MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; namespace MongoDB.Driver.GeoJsonObjectModel.Serializers { /// <summary> /// Represents a serializer for a GeoJsonCoordinates value. /// </summary> public class GeoJsonCoordinatesSerializer : ClassSerializerBase<GeoJsonCoordinates> { // protected methods /// <summary> /// Gets the actual type. /// </summary> /// <param name="context">The context.</param> /// <returns>The actual type.</returns> protected override Type GetActualType(BsonDeserializationContext context) { throw new NotSupportedException("There is no way to determine the actual type of a GeoJsonCoordinates. Use a concrete subclass instead."); } } } <|start_filename|>Server/Model/Module/Actor/ActorMessageSender.cs<|end_filename|> using System.Net; namespace ETModel { // 知道对方的instanceId,使用这个类发actor消息 public struct ActorMessageSender { // actor的地址 public IPEndPoint Address { get; } public long ActorId { get; } public ActorMessageSender(long actorId, IPEndPoint address) { this.ActorId = actorId; this.Address = address; } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/WireProtocol/Messages/Encoders/BinaryEncoders/ReplyMessageBinaryEncoder.cs<|end_filename|> /* Copyright 2013-present MongoDB Inc. * * 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; using System.Linq; using System.Text; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Core.WireProtocol.Messages.Encoders.BinaryEncoders { /// <summary> /// Represents a binary encoder for a Reply message. /// </summary> /// <typeparam name="TDocument">The type of the documents.</typeparam> public class ReplyMessageBinaryEncoder<TDocument> : MessageBinaryEncoderBase, IMessageEncoder { // fields private readonly IBsonSerializer<TDocument> _serializer; // constructors /// <summary> /// Initializes a new instance of the <see cref="ReplyMessageBinaryEncoder{TDocument}"/> class. /// </summary> /// <param name="stream">The stream.</param> /// <param name="encoderSettings">The encoder settings.</param> /// <param name="serializer">The serializer.</param> public ReplyMessageBinaryEncoder(Stream stream, MessageEncoderSettings encoderSettings, IBsonSerializer<TDocument> serializer) : base(stream, encoderSettings) { _serializer = Ensure.IsNotNull(serializer, nameof(serializer)); } // methods /// <summary> /// Reads the message. /// </summary> /// <returns>A message.</returns> public ReplyMessage<TDocument> ReadMessage() { var binaryReader = CreateBinaryReader(); var stream = binaryReader.BsonStream; stream.ReadInt32(); // messageSize var requestId = stream.ReadInt32(); var responseTo = stream.ReadInt32(); stream.ReadInt32(); // opcode var flags = (ResponseFlags)stream.ReadInt32(); var cursorId = stream.ReadInt64(); var startingFrom = stream.ReadInt32(); var numberReturned = stream.ReadInt32(); List<TDocument> documents = null; BsonDocument queryFailureDocument = null; var awaitCapable = (flags & ResponseFlags.AwaitCapable) == ResponseFlags.AwaitCapable; var cursorNotFound = (flags & ResponseFlags.CursorNotFound) == ResponseFlags.CursorNotFound; var queryFailure = (flags & ResponseFlags.QueryFailure) == ResponseFlags.QueryFailure; if (queryFailure) { var context = BsonDeserializationContext.CreateRoot(binaryReader); queryFailureDocument = BsonDocumentSerializer.Instance.Deserialize(context); } else { documents = new List<TDocument>(); for (var i = 0; i < numberReturned; i++) { var allowDuplicateElementNames = typeof(TDocument) == typeof(BsonDocument); var context = BsonDeserializationContext.CreateRoot(binaryReader, builder => { builder.AllowDuplicateElementNames = allowDuplicateElementNames; }); documents.Add(_serializer.Deserialize(context)); } } return new ReplyMessage<TDocument>( awaitCapable, cursorId, cursorNotFound, documents, numberReturned, queryFailure, queryFailureDocument, requestId, responseTo, _serializer, startingFrom); } /// <summary> /// Writes the message. /// </summary> /// <param name="message">The message.</param> public void WriteMessage(ReplyMessage<TDocument> message) { Ensure.IsNotNull(message, nameof(message)); var binaryWriter = CreateBinaryWriter(); var stream = binaryWriter.BsonStream; var startPosition = stream.Position; stream.WriteInt32(0); // messageSize stream.WriteInt32(message.RequestId); stream.WriteInt32(message.ResponseTo); stream.WriteInt32((int)Opcode.Reply); var flags = ResponseFlags.None; if (message.AwaitCapable) { flags |= ResponseFlags.AwaitCapable; } if (message.QueryFailure) { flags |= ResponseFlags.QueryFailure; } if (message.CursorNotFound) { flags |= ResponseFlags.CursorNotFound; } stream.WriteInt32((int)flags); stream.WriteInt64(message.CursorId); stream.WriteInt32(message.StartingFrom); stream.WriteInt32(message.NumberReturned); if (message.QueryFailure) { var context = BsonSerializationContext.CreateRoot(binaryWriter); _serializer.Serialize(context, message.QueryFailureDocument); } else { foreach (var doc in message.Documents) { var context = BsonSerializationContext.CreateRoot(binaryWriter); _serializer.Serialize(context, doc); } } stream.BackpatchSize(startPosition); } // explicit interface implementations MongoDBMessage IMessageEncoder.ReadMessage() { return ReadMessage(); } void IMessageEncoder.WriteMessage(MongoDBMessage message) { WriteMessage((ReplyMessage<TDocument>)message); } // nested types [Flags] private enum ResponseFlags { None = 0, CursorNotFound = 1, QueryFailure = 2, AwaitCapable = 8 } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Packages/PackageError.cs<|end_filename|> using System; namespace UnityEditor.PackageManager.UI { [Serializable] internal class PackageError { public string PackageName; public Error Error; public PackageError(string packageName, Error error) { PackageName = packageName; Error = error; } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Bindings/NonDisposingCoreSessionHandle.cs<|end_filename|> /* Copyright 2018-present MongoDB Inc. * * 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 MongoDB.Driver.Core.Bindings { /// <summary> /// A handle to a core session that should not be disposed when the handle is disposed. /// </summary> /// <seealso cref="MongoDB.Driver.Core.Bindings.ICoreSessionHandle" /> internal sealed class NonDisposingCoreSessionHandle : WrappingCoreSession, ICoreSessionHandle { // private fields private readonly ICoreSession _wrapped; // constructors /// <summary> /// Initializes a new instance of the <see cref="NonDisposingCoreSessionHandle" /> class. /// </summary> /// <param name="wrapped">The wrapped session.</param> public NonDisposingCoreSessionHandle(ICoreSession wrapped) : base(wrapped, ownsWrapped: false) { _wrapped = wrapped; } // public methods /// <inheritdoc /> public ICoreSessionHandle Fork() { ThrowIfDisposed(); return new NonDisposingCoreSessionHandle(_wrapped); } // protected methods /// <inheritdoc /> protected override void Dispose(bool disposing) { base.Dispose(disposing); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Connections/ConnectionInitializer.cs<|end_filename|> /* Copyright 2013-present MongoDB Inc. * * 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.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver.Core.Authentication; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.WireProtocol; namespace MongoDB.Driver.Core.Connections { /// <summary> /// Represents a connection initializer (opens and authenticates connections). /// </summary> internal class ConnectionInitializer : IConnectionInitializer { private readonly BsonDocument _clientDocument; public ConnectionInitializer(string applicationName) { _clientDocument = ClientDocumentHelper.CreateClientDocument(applicationName); } public ConnectionDescription InitializeConnection(IConnection connection, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); var isMasterCommand = CreateInitialIsMasterCommand(connection.Settings.Authenticators); var isMasterProtocol = IsMasterHelper.CreateProtocol(isMasterCommand); var isMasterResult = IsMasterHelper.GetResult(connection, isMasterProtocol, cancellationToken); var buildInfoProtocol = CreateBuildInfoProtocol(); var buildInfoResult = new BuildInfoResult(buildInfoProtocol.Execute(connection, cancellationToken)); var description = new ConnectionDescription(connection.ConnectionId, isMasterResult, buildInfoResult); AuthenticationHelper.Authenticate(connection, description, cancellationToken); try { var getLastErrorProtocol = CreateGetLastErrorProtocol(); var getLastErrorResult = getLastErrorProtocol.Execute(connection, cancellationToken); description = UpdateConnectionIdWithServerValue(description, getLastErrorResult); } catch { // if we couldn't get the server's connection id, so be it. } return description; } public async Task<ConnectionDescription> InitializeConnectionAsync(IConnection connection, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); var isMasterCommand = CreateInitialIsMasterCommand(connection.Settings.Authenticators); var isMasterProtocol = IsMasterHelper.CreateProtocol(isMasterCommand); var isMasterResult = await IsMasterHelper.GetResultAsync(connection, isMasterProtocol, cancellationToken).ConfigureAwait(false); var buildInfoProtocol = CreateBuildInfoProtocol(); var buildInfoResult = new BuildInfoResult(await buildInfoProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false)); var description = new ConnectionDescription(connection.ConnectionId, isMasterResult, buildInfoResult); await AuthenticationHelper.AuthenticateAsync(connection, description, cancellationToken).ConfigureAwait(false); try { var getLastErrorProtocol = CreateGetLastErrorProtocol(); var getLastErrorResult = await getLastErrorProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false); description = UpdateConnectionIdWithServerValue(description, getLastErrorResult); } catch { // if we couldn't get the server's connection id, so be it. } return description; } // private methods private CommandWireProtocol<BsonDocument> CreateBuildInfoProtocol() { var buildInfoCommand = new BsonDocument("buildInfo", 1); var buildInfoProtocol = new CommandWireProtocol<BsonDocument>( databaseNamespace: DatabaseNamespace.Admin, command: buildInfoCommand, slaveOk: true, resultSerializer: BsonDocumentSerializer.Instance, messageEncoderSettings: null); return buildInfoProtocol; } private CommandWireProtocol<BsonDocument> CreateGetLastErrorProtocol() { var getLastErrorCommand = new BsonDocument("getLastError", 1); var getLastErrorProtocol = new CommandWireProtocol<BsonDocument>( databaseNamespace: DatabaseNamespace.Admin, command: getLastErrorCommand, slaveOk: true, resultSerializer: BsonDocumentSerializer.Instance, messageEncoderSettings: null); return getLastErrorProtocol; } private BsonDocument CreateInitialIsMasterCommand(IReadOnlyList<IAuthenticator> authenticators) { var command = IsMasterHelper.CreateCommand(); IsMasterHelper.AddClientDocumentToCommand(command, _clientDocument); return IsMasterHelper.CustomizeCommand(command, authenticators); } private ConnectionDescription UpdateConnectionIdWithServerValue(ConnectionDescription description, BsonDocument getLastErrorResult) { BsonValue connectionIdBsonValue; if (getLastErrorResult.TryGetValue("connectionId", out connectionIdBsonValue)) { var connectionId = description.ConnectionId.WithServerValue(connectionIdBsonValue.ToInt32()); description = description.WithConnectionId(connectionId); } return description; } } } <|start_filename|>Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/Core/RVO/RVOCoreObstacle.cs<|end_filename|> using UnityEngine; namespace Pathfinding.RVO { /** One vertex in an obstacle. * This is a linked list and one vertex can therefore be used to reference the whole obstacle * \astarpro */ public class ObstacleVertex { public bool ignore; /** Position of the vertex */ public Vector3 position; public Vector2 dir; /** Height of the obstacle in this vertex */ public float height; /** Collision layer for this obstacle */ public RVOLayer layer = RVOLayer.DefaultObstacle; /** Next vertex in the obstacle */ public ObstacleVertex next; /** Previous vertex in the obstacle */ public ObstacleVertex prev; } } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/Serialization/IBsonSerializerRegistry.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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; namespace MongoDB.Bson.Serialization { /// <summary> /// A serializer registry. /// </summary> public interface IBsonSerializerRegistry { /// <summary> /// Gets the serializer for the specified <paramref name="type"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The serializer.</returns> IBsonSerializer GetSerializer(Type type); /// <summary> /// Gets the serializer for the specified <typeparamref name="T"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <returns>The serializer.</returns> IBsonSerializer<T> GetSerializer<T>(); } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/MongoClientSettings.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading; using MongoDB.Bson; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Misc; using MongoDB.Shared; namespace MongoDB.Driver { /// <summary> /// The settings for a MongoDB client. /// </summary> public class MongoClientSettings : IEquatable<MongoClientSettings>, IInheritableMongoClientSettings { // private fields private string _applicationName; private Action<ClusterBuilder> _clusterConfigurator; private ConnectionMode _connectionMode; private TimeSpan _connectTimeout; private MongoCredentialStore _credentials; private GuidRepresentation _guidRepresentation; private TimeSpan _heartbeatInterval; private TimeSpan _heartbeatTimeout; private bool _ipv6; private TimeSpan _localThreshold; private TimeSpan _maxConnectionIdleTime; private TimeSpan _maxConnectionLifeTime; private int _maxConnectionPoolSize; private int _minConnectionPoolSize; private ReadConcern _readConcern; private UTF8Encoding _readEncoding; private ReadPreference _readPreference; private string _replicaSetName; private bool _retryWrites; private string _sdamLogFilename; private List<MongoServerAddress> _servers; private TimeSpan _serverSelectionTimeout; private TimeSpan _socketTimeout; private SslSettings _sslSettings; private bool _useSsl; private bool _verifySslCertificate; private int _waitQueueSize; private TimeSpan _waitQueueTimeout; private WriteConcern _writeConcern; private UTF8Encoding _writeEncoding; // the following fields are set when Freeze is called private bool _isFrozen; private int _frozenHashCode; private string _frozenStringRepresentation; // constructors /// <summary> /// Creates a new instance of MongoClientSettings. Usually you would use a connection string instead. /// </summary> public MongoClientSettings() { _applicationName = null; _connectionMode = ConnectionMode.Automatic; _connectTimeout = MongoDefaults.ConnectTimeout; _credentials = new MongoCredentialStore(new MongoCredential[0]); _guidRepresentation = MongoDefaults.GuidRepresentation; _heartbeatInterval = ServerSettings.DefaultHeartbeatInterval; _heartbeatTimeout = ServerSettings.DefaultHeartbeatTimeout; _ipv6 = false; _localThreshold = MongoDefaults.LocalThreshold; _maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime; _maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime; _maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize; _minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize; _readConcern = ReadConcern.Default; _readEncoding = null; _readPreference = ReadPreference.Primary; _replicaSetName = null; _retryWrites = false; _sdamLogFilename = null; _servers = new List<MongoServerAddress> { new MongoServerAddress("localhost") }; _serverSelectionTimeout = MongoDefaults.ServerSelectionTimeout; _socketTimeout = MongoDefaults.SocketTimeout; _sslSettings = null; _useSsl = false; _verifySslCertificate = true; _waitQueueSize = MongoDefaults.ComputedWaitQueueSize; _waitQueueTimeout = MongoDefaults.WaitQueueTimeout; _writeConcern = WriteConcern.Acknowledged; _writeEncoding = null; } // public properties /// <summary> /// Gets or sets the application name. /// </summary> public string ApplicationName { get { return _applicationName; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _applicationName = ApplicationNameHelper.EnsureApplicationNameIsValid(value, nameof(value)); } } /// <summary> /// Gets or sets the cluster configurator. /// </summary> public Action<ClusterBuilder> ClusterConfigurator { get { return _clusterConfigurator; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _clusterConfigurator = value; } } /// <summary> /// Gets or sets the connection mode. /// </summary> public ConnectionMode ConnectionMode { get { return _connectionMode; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _connectionMode = value; } } /// <summary> /// Gets or sets the connect timeout. /// </summary> public TimeSpan ConnectTimeout { get { return _connectTimeout; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _connectTimeout = value; } } /// <summary> /// Gets or sets the credential. /// </summary> public MongoCredential Credential { get { return _credentials.SingleOrDefault(); } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } if (value == null) { _credentials = new MongoCredentialStore(Enumerable.Empty<MongoCredential>()); } else { _credentials = new MongoCredentialStore(new[] { value }); } } } /// <summary> /// Gets or sets the credentials. /// </summary> [Obsolete("Use Credential instead. Using multiple credentials is deprecated.")] public IEnumerable<MongoCredential> Credentials { get { return _credentials; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } if (value == null) { throw new ArgumentNullException("value"); } _credentials = new MongoCredentialStore(value); } } /// <summary> /// Gets or sets the representation to use for Guids. /// </summary> public GuidRepresentation GuidRepresentation { get { return _guidRepresentation; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _guidRepresentation = value; } } /// <summary> /// Gets a value indicating whether the settings have been frozen to prevent further changes. /// </summary> public bool IsFrozen { get { return _isFrozen; } } /// <summary> /// Gets or sets the heartbeat interval. /// </summary> public TimeSpan HeartbeatInterval { get { return _heartbeatInterval; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _heartbeatInterval = Ensure.IsGreaterThanZero(value, nameof(value)); } } /// <summary> /// Gets or sets the heartbeat timeout. /// </summary> public TimeSpan HeartbeatTimeout { get { return _heartbeatTimeout; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _heartbeatTimeout = Ensure.IsInfiniteOrGreaterThanZero(value, nameof(value)); } } /// <summary> /// Gets or sets a value indicating whether to use IPv6. /// </summary> public bool IPv6 { get { return _ipv6; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _ipv6 = value; } } /// <summary> /// Gets or sets the local threshold. /// </summary> public TimeSpan LocalThreshold { get { return _localThreshold; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _localThreshold = value; } } /// <summary> /// Gets or sets the max connection idle time. /// </summary> public TimeSpan MaxConnectionIdleTime { get { return _maxConnectionIdleTime; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _maxConnectionIdleTime = value; } } /// <summary> /// Gets or sets the max connection life time. /// </summary> public TimeSpan MaxConnectionLifeTime { get { return _maxConnectionLifeTime; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _maxConnectionLifeTime = value; } } /// <summary> /// Gets or sets the max connection pool size. /// </summary> public int MaxConnectionPoolSize { get { return _maxConnectionPoolSize; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _maxConnectionPoolSize = value; } } /// <summary> /// Gets or sets the min connection pool size. /// </summary> public int MinConnectionPoolSize { get { return _minConnectionPoolSize; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _minConnectionPoolSize = value; } } /// <summary> /// Gets or sets the read concern. /// </summary> public ReadConcern ReadConcern { get { return _readConcern; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _readConcern = Ensure.IsNotNull(value, nameof(value)); } } /// <summary> /// Gets or sets the Read Encoding. /// </summary> public UTF8Encoding ReadEncoding { get { return _readEncoding; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _readEncoding = value; } } /// <summary> /// Gets or sets the read preferences. /// </summary> public ReadPreference ReadPreference { get { return _readPreference; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } if (value == null) { throw new ArgumentNullException("value"); } _readPreference = value; } } /// <summary> /// Gets or sets the name of the replica set. /// </summary> public string ReplicaSetName { get { return _replicaSetName; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _replicaSetName = value; } } /// <summary> /// Gets or sets whether to retry writes. /// </summary> public bool RetryWrites { get { return _retryWrites; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _retryWrites = value; } } /// <summary> /// Gets or set the name of the SDAM log file. Null turns logging off. stdout will log to console. /// </summary> public string SdamLogFilename { get { return _sdamLogFilename; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _sdamLogFilename = value; } } /// <summary> /// Gets or sets the address of the server (see also Servers if using more than one address). /// </summary> public MongoServerAddress Server { get { return _servers.Single(); } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } if (value == null) { throw new ArgumentNullException("value"); } _servers = new List<MongoServerAddress> { value }; } } /// <summary> /// Gets or sets the list of server addresses (see also Server if using only one address). /// </summary> public IEnumerable<MongoServerAddress> Servers { get { return new ReadOnlyCollection<MongoServerAddress>(_servers); } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } if (value == null) { throw new ArgumentNullException("value"); } _servers = new List<MongoServerAddress>(value); } } /// <summary> /// Gets or sets the server selection timeout. /// </summary> public TimeSpan ServerSelectionTimeout { get { return _serverSelectionTimeout; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _serverSelectionTimeout = value; } } /// <summary> /// Gets or sets the socket timeout. /// </summary> public TimeSpan SocketTimeout { get { return _socketTimeout; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _socketTimeout = value; } } /// <summary> /// Gets or sets the SSL settings. /// </summary> public SslSettings SslSettings { get { return _sslSettings; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _sslSettings = value; } } /// <summary> /// Gets or sets a value indicating whether to use SSL. /// </summary> public bool UseSsl { get { return _useSsl; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _useSsl = value; } } /// <summary> /// Gets or sets a value indicating whether to verify an SSL certificate. /// </summary> public bool VerifySslCertificate { get { return _verifySslCertificate; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _verifySslCertificate = value; } } /// <summary> /// Gets or sets the wait queue size. /// </summary> public int WaitQueueSize { get { return _waitQueueSize; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _waitQueueSize = value; } } /// <summary> /// Gets or sets the wait queue timeout. /// </summary> public TimeSpan WaitQueueTimeout { get { return _waitQueueTimeout; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _waitQueueTimeout = value; } } /// <summary> /// Gets or sets the WriteConcern to use. /// </summary> public WriteConcern WriteConcern { get { return _writeConcern; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } if (value == null) { throw new ArgumentNullException("value"); } _writeConcern = value; } } /// <summary> /// Gets or sets the Write Encoding. /// </summary> public UTF8Encoding WriteEncoding { get { return _writeEncoding; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } _writeEncoding = value; } } // public operators /// <summary> /// Determines whether two <see cref="MongoClientSettings"/> instances are equal. /// </summary> /// <param name="lhs">The LHS.</param> /// <param name="rhs">The RHS.</param> /// <returns> /// <c>true</c> if the left hand side is equal to the right hand side; otherwise, <c>false</c>. /// </returns> public static bool operator ==(MongoClientSettings lhs, MongoClientSettings rhs) { return object.Equals(lhs, rhs); // handles lhs == null correctly } /// <summary> /// Determines whether two <see cref="MongoClientSettings"/> instances are not equal. /// </summary> /// <param name="lhs">The LHS.</param> /// <param name="rhs">The RHS.</param> /// <returns> /// <c>true</c> if the left hand side is not equal to the right hand side; otherwise, <c>false</c>. /// </returns> public static bool operator !=(MongoClientSettings lhs, MongoClientSettings rhs) { return !(lhs == rhs); } // public static methods /// <summary> /// Gets a MongoClientSettings object intialized with values from a connection string. /// </summary> /// <param name="connectionString">The connection string.</param> /// <returns>A MongoClientSettings.</returns> public static MongoClientSettings FromConnectionString(string connectionString) { return FromUrl(new MongoUrl(connectionString)); } /// <summary> /// Gets a MongoClientSettings object intialized with values from a MongoURL. /// </summary> /// <param name="url">The MongoURL.</param> /// <returns>A MongoClientSettings.</returns> public static MongoClientSettings FromUrl(MongoUrl url) { if (url.Scheme == ConnectionStringScheme.MongoDBPlusSrv) { url = url.Resolve(); } var credential = url.GetCredential(); var clientSettings = new MongoClientSettings(); clientSettings.ApplicationName = url.ApplicationName; clientSettings.ConnectionMode = url.ConnectionMode; clientSettings.ConnectTimeout = url.ConnectTimeout; if (credential != null) { foreach (var property in url.AuthenticationMechanismProperties) { if (property.Key.Equals("CANONICALIZE_HOST_NAME", StringComparison.OrdinalIgnoreCase)) { credential = credential.WithMechanismProperty(property.Key, bool.Parse(property.Value)); } else { credential = credential.WithMechanismProperty(property.Key, property.Value); } } clientSettings.Credential = credential; } clientSettings.GuidRepresentation = url.GuidRepresentation; clientSettings.HeartbeatInterval = url.HeartbeatInterval; clientSettings.HeartbeatTimeout = url.HeartbeatTimeout; clientSettings.IPv6 = url.IPv6; clientSettings.MaxConnectionIdleTime = url.MaxConnectionIdleTime; clientSettings.MaxConnectionLifeTime = url.MaxConnectionLifeTime; clientSettings.MaxConnectionPoolSize = url.MaxConnectionPoolSize; clientSettings.MinConnectionPoolSize = url.MinConnectionPoolSize; clientSettings.ReadConcern = new ReadConcern(url.ReadConcernLevel); clientSettings.ReadEncoding = null; // ReadEncoding must be provided in code clientSettings.ReadPreference = (url.ReadPreference == null) ? ReadPreference.Primary : url.ReadPreference; clientSettings.ReplicaSetName = url.ReplicaSetName; clientSettings.RetryWrites = url.RetryWrites.GetValueOrDefault(false); clientSettings.LocalThreshold = url.LocalThreshold; clientSettings.Servers = new List<MongoServerAddress>(url.Servers); clientSettings.ServerSelectionTimeout = url.ServerSelectionTimeout; clientSettings.SocketTimeout = url.SocketTimeout; clientSettings.SslSettings = null; // SSL settings must be provided in code clientSettings.UseSsl = url.UseSsl; clientSettings.VerifySslCertificate = url.VerifySslCertificate; clientSettings.WaitQueueSize = url.ComputedWaitQueueSize; clientSettings.WaitQueueTimeout = url.WaitQueueTimeout; clientSettings.WriteConcern = url.GetWriteConcern(true); // WriteConcern is enabled by default for MongoClient clientSettings.WriteEncoding = null; // WriteEncoding must be provided in code return clientSettings; } // public methods /// <summary> /// Creates a clone of the settings. /// </summary> /// <returns>A clone of the settings.</returns> public MongoClientSettings Clone() { var clone = new MongoClientSettings(); clone._applicationName = _applicationName; clone._clusterConfigurator = _clusterConfigurator; clone._connectionMode = _connectionMode; clone._connectTimeout = _connectTimeout; clone._credentials = _credentials; clone._guidRepresentation = _guidRepresentation; clone._heartbeatInterval = _heartbeatInterval; clone._heartbeatTimeout = _heartbeatTimeout; clone._ipv6 = _ipv6; clone._maxConnectionIdleTime = _maxConnectionIdleTime; clone._maxConnectionLifeTime = _maxConnectionLifeTime; clone._maxConnectionPoolSize = _maxConnectionPoolSize; clone._minConnectionPoolSize = _minConnectionPoolSize; clone._readConcern = _readConcern; clone._readEncoding = _readEncoding; clone._readPreference = _readPreference; clone._replicaSetName = _replicaSetName; clone._retryWrites = _retryWrites; clone._localThreshold = _localThreshold; clone._sdamLogFilename = _sdamLogFilename; clone._servers = new List<MongoServerAddress>(_servers); clone._serverSelectionTimeout = _serverSelectionTimeout; clone._socketTimeout = _socketTimeout; clone._sslSettings = (_sslSettings == null) ? null : _sslSettings.Clone(); clone._useSsl = _useSsl; clone._verifySslCertificate = _verifySslCertificate; clone._waitQueueSize = _waitQueueSize; clone._waitQueueTimeout = _waitQueueTimeout; clone._writeConcern = _writeConcern; clone._writeEncoding = _writeEncoding; return clone; } /// <summary> /// Determines whether the specified <see cref="MongoClientSettings" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="MongoClientSettings" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="MongoClientSettings" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(MongoClientSettings obj) { return Equals((object)obj); // handles obj == null correctly } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (object.ReferenceEquals(obj, null) || GetType() != obj.GetType()) { return false; } var rhs = (MongoClientSettings)obj; return _applicationName == rhs._applicationName && object.ReferenceEquals(_clusterConfigurator, rhs._clusterConfigurator) && _connectionMode == rhs._connectionMode && _connectTimeout == rhs._connectTimeout && _credentials == rhs._credentials && _guidRepresentation == rhs._guidRepresentation && _heartbeatInterval == rhs._heartbeatInterval && _heartbeatTimeout == rhs._heartbeatTimeout && _ipv6 == rhs._ipv6 && _maxConnectionIdleTime == rhs._maxConnectionIdleTime && _maxConnectionLifeTime == rhs._maxConnectionLifeTime && _maxConnectionPoolSize == rhs._maxConnectionPoolSize && _minConnectionPoolSize == rhs._minConnectionPoolSize && object.Equals(_readEncoding, rhs._readEncoding) && object.Equals(_readConcern, rhs._readConcern) && _readPreference == rhs._readPreference && _replicaSetName == rhs._replicaSetName && _retryWrites == rhs._retryWrites && _localThreshold == rhs._localThreshold && _sdamLogFilename == rhs._sdamLogFilename && _servers.SequenceEqual(rhs._servers) && _serverSelectionTimeout == rhs._serverSelectionTimeout && _socketTimeout == rhs._socketTimeout && _sslSettings == rhs._sslSettings && _useSsl == rhs._useSsl && _verifySslCertificate == rhs._verifySslCertificate && _waitQueueSize == rhs._waitQueueSize && _waitQueueTimeout == rhs._waitQueueTimeout && _writeConcern == rhs._writeConcern && object.Equals(_writeEncoding, rhs._writeEncoding); } /// <summary> /// Freezes the settings. /// </summary> /// <returns>The frozen settings.</returns> public MongoClientSettings Freeze() { if (!_isFrozen) { _frozenHashCode = GetHashCode(); _frozenStringRepresentation = ToString(); _isFrozen = true; } return this; } /// <summary> /// Returns a frozen copy of the settings. /// </summary> /// <returns>A frozen copy of the settings.</returns> public MongoClientSettings FrozenCopy() { if (_isFrozen) { return this; } else { return Clone().Freeze(); } } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { if (_isFrozen) { return _frozenHashCode; } return new Hasher() .Hash(_applicationName) .Hash(_clusterConfigurator) .Hash(_connectionMode) .Hash(_connectTimeout) .Hash(_credentials) .Hash(_guidRepresentation) .Hash(_heartbeatInterval) .Hash(_heartbeatTimeout) .Hash(_ipv6) .Hash(_maxConnectionIdleTime) .Hash(_maxConnectionLifeTime) .Hash(_maxConnectionPoolSize) .Hash(_minConnectionPoolSize) .Hash(_readConcern) .Hash(_readEncoding) .Hash(_readPreference) .Hash(_replicaSetName) .Hash(_retryWrites) .Hash(_localThreshold) .Hash(_sdamLogFilename) .HashElements(_servers) .Hash(_serverSelectionTimeout) .Hash(_socketTimeout) .Hash(_sslSettings) .Hash(_useSsl) .Hash(_verifySslCertificate) .Hash(_waitQueueSize) .Hash(_waitQueueTimeout) .Hash(_writeConcern) .Hash(_writeEncoding) .GetHashCode(); } /// <summary> /// Returns a string representation of the settings. /// </summary> /// <returns>A string representation of the settings.</returns> public override string ToString() { if (_isFrozen) { return _frozenStringRepresentation; } var sb = new StringBuilder(); if (_applicationName != null) { sb.AppendFormat("ApplicationName={0};", _applicationName); } sb.AppendFormat("ConnectionMode={0};", _connectionMode); sb.AppendFormat("ConnectTimeout={0};", _connectTimeout); sb.AppendFormat("Credentials={{{0}}};", _credentials); sb.AppendFormat("GuidRepresentation={0};", _guidRepresentation); sb.AppendFormat("HeartbeatInterval={0};", _heartbeatInterval); sb.AppendFormat("HeartbeatTimeout={0};", _heartbeatTimeout); sb.AppendFormat("IPv6={0};", _ipv6); sb.AppendFormat("MaxConnectionIdleTime={0};", _maxConnectionIdleTime); sb.AppendFormat("MaxConnectionLifeTime={0};", _maxConnectionLifeTime); sb.AppendFormat("MaxConnectionPoolSize={0};", _maxConnectionPoolSize); sb.AppendFormat("MinConnectionPoolSize={0};", _minConnectionPoolSize); if (_readEncoding != null) { sb.Append("ReadEncoding=UTF8Encoding;"); } sb.AppendFormat("ReadConcern={0};", _readConcern); sb.AppendFormat("ReadPreference={0};", _readPreference); sb.AppendFormat("ReplicaSetName={0};", _replicaSetName); sb.AppendFormat("RetryWrites={0}", _retryWrites); sb.AppendFormat("LocalThreshold={0};", _localThreshold); if (_sdamLogFilename != null) { sb.AppendFormat("SDAMLogFileName={0};", _sdamLogFilename); } sb.AppendFormat("Servers={0};", string.Join(",", _servers.Select(s => s.ToString()).ToArray())); sb.AppendFormat("ServerSelectionTimeout={0};", _serverSelectionTimeout); sb.AppendFormat("SocketTimeout={0};", _socketTimeout); if (_sslSettings != null) { sb.AppendFormat("SslSettings={0};", _sslSettings); } sb.AppendFormat("Ssl={0};", _useSsl); sb.AppendFormat("SslVerifyCertificate={0};", _verifySslCertificate); sb.AppendFormat("WaitQueueSize={0};", _waitQueueSize); sb.AppendFormat("WaitQueueTimeout={0}", _waitQueueTimeout); sb.AppendFormat("WriteConcern={0};", _writeConcern); if (_writeEncoding != null) { sb.Append("WriteEncoding=UTF8Encoding;"); } return sb.ToString(); } // internal methods internal ClusterKey ToClusterKey() { return new ClusterKey( _applicationName, _clusterConfigurator, _connectionMode, _connectTimeout, _credentials.ToList(), _heartbeatInterval, _heartbeatTimeout, _ipv6, _localThreshold, _maxConnectionIdleTime, _maxConnectionLifeTime, _maxConnectionPoolSize, _minConnectionPoolSize, _replicaSetName, _sdamLogFilename, _servers.ToList(), _serverSelectionTimeout, _socketTimeout, _sslSettings, _useSsl, _verifySslCertificate, _waitQueueSize, _waitQueueTimeout); } } } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/Serialization/Serializers/ByteArraySerializer.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.Globalization; using System.Text; namespace MongoDB.Bson.Serialization.Serializers { /// <summary> /// Represents a serializer for ByteArrays. /// </summary> public class ByteArraySerializer : SealedClassSerializerBase<byte[]>, IRepresentationConfigurable<ByteArraySerializer> { // private fields private readonly BsonType _representation; // constructors /// <summary> /// Initializes a new instance of the <see cref="ByteArraySerializer"/> class. /// </summary> public ByteArraySerializer() : this(BsonType.Binary) { } /// <summary> /// Initializes a new instance of the <see cref="ByteArraySerializer"/> class. /// </summary> /// <param name="representation">The representation.</param> public ByteArraySerializer(BsonType representation) { switch (representation) { case BsonType.Binary: case BsonType.String: break; default: var message = string.Format("{0} is not a valid representation for a ByteArraySerializer.", representation); throw new ArgumentException(message); } _representation = representation; } // public properties /// <summary> /// Gets the representation. /// </summary> /// <value> /// The representation. /// </value> public BsonType Representation { get { return _representation; } } // public methods #pragma warning disable 618 // about obsolete BsonBinarySubType.OldBinary /// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <param name="args">The deserialization args.</param> /// <returns>A deserialized value.</returns> protected override byte[] DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args) { var bsonReader = context.Reader; BsonType bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Binary: return bsonReader.ReadBytes(); case BsonType.String: var s = bsonReader.ReadString(); if ((s.Length % 2) != 0) { s = "0" + s; // prepend a zero to make length even } var bytes = new byte[s.Length / 2]; for (int i = 0; i < s.Length; i += 2) { var hex = s.Substring(i, 2); var b = byte.Parse(hex, NumberStyles.HexNumber); bytes[i / 2] = b; } return bytes; default: throw CreateCannotDeserializeFromBsonTypeException(bsonType); } } #pragma warning restore 618 /// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The object.</param> protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, byte[] value) { var bsonWriter = context.Writer; switch (_representation) { case BsonType.Binary: bsonWriter.WriteBytes(value); break; case BsonType.String: bsonWriter.WriteString(BsonUtils.ToHexString(value)); break; default: var message = string.Format("'{0}' is not a valid Byte[] representation.", _representation); throw new BsonSerializationException(message); } } /// <summary> /// Returns a serializer that has been reconfigured with the specified representation. /// </summary> /// <param name="representation">The representation.</param> /// <returns>The reconfigured serializer.</returns> public ByteArraySerializer WithRepresentation(BsonType representation) { if (representation == _representation) { return this; } else { return new ByteArraySerializer(representation); } } // explicit interface implementations IBsonSerializer IRepresentationConfigurable.WithRepresentation(BsonType representation) { return WithRepresentation(representation); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/WireProtocol/Messages/CommandRequestMessage.cs<|end_filename|> /* Copyright 2018-present MongoDB Inc. * * 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.Linq; using System.Text; using System.Threading.Tasks; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; namespace MongoDB.Driver.Core.WireProtocol.Messages { /// <summary> /// Represents a command request message. /// </summary> /// <seealso cref="MongoDB.Driver.Core.WireProtocol.Messages.RequestMessage" /> public class CommandRequestMessage : RequestMessage { // private fields private readonly CommandMessage _wrappedMessage; // constructors /// <summary> /// Initializes a new instance of the <see cref="CommandRequestMessage" /> class. /// </summary> /// <param name="wrappedMessage">The wrapped message.</param> /// <param name="shouldBeSent">The should be sent.</param> public CommandRequestMessage(CommandMessage wrappedMessage, Func<bool> shouldBeSent) : base(Ensure.IsNotNull(wrappedMessage, nameof(wrappedMessage)).RequestId, shouldBeSent) { _wrappedMessage = Ensure.IsNotNull(wrappedMessage, nameof(wrappedMessage)); } // public properties /// <inheritdoc /> public override MongoDBMessageType MessageType => _wrappedMessage.MessageType; /// <summary> /// Gets the wrapped message. /// </summary> /// <value> /// The wrapped message. /// </value> public CommandMessage WrappedMessage => _wrappedMessage; // public methods /// <inheritdoc /> public override IMessageEncoder GetEncoder(IMessageEncoderFactory encoderFactory) { return encoderFactory.GetCommandRequestMessageEncoder(); } } } <|start_filename|>Unity/Assets/Model/Module/Message/Network/KCP/Kcp.cs<|end_filename|> using System; using System.Runtime.InteropServices; namespace ETModel { public delegate int KcpOutput(IntPtr buf, int len, IntPtr kcp, IntPtr user); public class Kcp { #if UNITY_IPHONE && !UNITY_EDITOR const string KcpDLL = "__Internal"; #else const string KcpDLL = "kcp"; #endif [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern uint ikcp_check(IntPtr kcp, uint current); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern IntPtr ikcp_create(uint conv, IntPtr user); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern void ikcp_flush(IntPtr kcp); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern uint ikcp_getconv(IntPtr ptr); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern int ikcp_input(IntPtr kcp, byte[] data, int offset, int size); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern int ikcp_nodelay(IntPtr kcp, int nodelay, int interval, int resend, int nc); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern int ikcp_peeksize(IntPtr kcp); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern int ikcp_recv(IntPtr kcp, byte[] buffer, int len); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern void ikcp_release(IntPtr kcp); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern int ikcp_send(IntPtr kcp, byte[] buffer, int len); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern void ikcp_setminrto(IntPtr ptr, int minrto); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern int ikcp_setmtu(IntPtr kcp, int mtu); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern void ikcp_setoutput(IntPtr kcp, KcpOutput output); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern void ikcp_update(IntPtr kcp, uint current); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern int ikcp_waitsnd(IntPtr kcp); [DllImport(KcpDLL, CallingConvention=CallingConvention.Cdecl)] private static extern int ikcp_wndsize(IntPtr kcp, int sndwnd, int rcvwnd); public static uint KcpCheck(IntPtr kcp, uint current) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } return ikcp_check(kcp, current); } public static IntPtr KcpCreate(uint conv, IntPtr user) { return ikcp_create(conv, user); } public static void KcpFlush(IntPtr kcp) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } ikcp_flush(kcp); } public static uint KcpGetconv(IntPtr ptr) { if (ptr == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } return ikcp_getconv(ptr); } public static int KcpInput(IntPtr kcp, byte[] data, int offset, int size) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } return ikcp_input(kcp, data, offset, size); } public static int KcpNodelay(IntPtr kcp, int nodelay, int interval, int resend, int nc) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } return ikcp_nodelay(kcp, nodelay, interval, resend, nc); } public static int KcpPeeksize(IntPtr kcp) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } return ikcp_peeksize(kcp); } public static int KcpRecv(IntPtr kcp, byte[] buffer, int len) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } return ikcp_recv(kcp, buffer, len); } public static void KcpRelease(IntPtr kcp) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } ikcp_release(kcp); } public static int KcpSend(IntPtr kcp, byte[] buffer, int len) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } return ikcp_send(kcp, buffer, len); } public static void KcpSetminrto(IntPtr kcp, int minrto) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } ikcp_setminrto(kcp, minrto); } public static int KcpSetmtu(IntPtr kcp, int mtu) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } return ikcp_setmtu(kcp, mtu); } public static void KcpSetoutput(IntPtr kcp, KcpOutput output) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } ikcp_setoutput(kcp, output); } public static void KcpUpdate(IntPtr kcp, uint current) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } ikcp_update(kcp, current); } public static int KcpWaitsnd(IntPtr kcp) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } return ikcp_waitsnd(kcp); } public static int KcpWndsize(IntPtr kcp, int sndwnd, int rcvwnd) { if (kcp == IntPtr.Zero) { throw new Exception($"kcp error, kcp point is zero"); } return ikcp_wndsize(kcp, sndwnd, rcvwnd); } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Examples/4.X/SimpleExamples/MultiFinger/FingerTouch.cs<|end_filename|> using UnityEngine; using System.Collections; using HedgehogTeam.EasyTouch; public class FingerTouch : MonoBehaviour { private TextMesh textMesh; public Vector3 deltaPosition = Vector2.zero; public int fingerId=-1; void OnEnable(){ EasyTouch.On_TouchStart += On_TouchStart; EasyTouch.On_TouchUp += On_TouchUp; EasyTouch.On_Swipe += On_Swipe; EasyTouch.On_Drag += On_Drag; EasyTouch.On_DoubleTap += On_DoubleTap; textMesh =(TextMesh) GetComponentInChildren<TextMesh>(); } void OnDestroy(){ EasyTouch.On_TouchStart -= On_TouchStart; EasyTouch.On_TouchUp -= On_TouchUp; EasyTouch.On_Swipe -= On_Swipe; EasyTouch.On_Drag -= On_Drag; EasyTouch.On_DoubleTap -= On_DoubleTap; } void On_Drag (Gesture gesture) { if ( gesture.pickedObject.transform.IsChildOf(gameObject.transform) && fingerId == gesture.fingerIndex){ Vector3 position = gesture.GetTouchToWorldPoint(gesture.pickedObject.transform.position); transform.position = position - deltaPosition; } } void On_Swipe (Gesture gesture) { if (fingerId == gesture.fingerIndex){ Vector3 position = gesture.GetTouchToWorldPoint(transform.position); transform.position = position - deltaPosition; } } void On_TouchStart (Gesture gesture) { if (gesture.pickedObject!=null && gesture.pickedObject.transform.IsChildOf(gameObject.transform)){ fingerId = gesture.fingerIndex; textMesh.text = fingerId.ToString(); Vector3 position = gesture.GetTouchToWorldPoint(gesture.pickedObject.transform.position); deltaPosition = position - transform.position; } } void On_TouchUp (Gesture gesture) { if (gesture.fingerIndex == fingerId){ fingerId = -1; textMesh.text=""; } } public void InitTouch(int ind){ fingerId = ind; textMesh.text = fingerId.ToString(); } void On_DoubleTap (Gesture gesture) { if (gesture.pickedObject!=null && gesture.pickedObject.transform.IsChildOf(gameObject.transform)){ DestroyImmediate( transform.gameObject ); } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/UI/PackageManagerToolbar.cs<|end_filename|> using System.Linq; using UnityEngine; using UnityEngine.Experimental.UIElements; namespace UnityEditor.PackageManager.UI { #if !UNITY_2018_3_OR_NEWER internal class PackageManangerToolbarFactory : UxmlFactory<PackageManagerToolbar> { protected override PackageManagerToolbar DoCreate(IUxmlAttributes bag, CreationContext cc) { return new PackageManagerToolbar(); } } #endif internal class PackageManagerToolbar : VisualElement { #if UNITY_2018_3_OR_NEWER internal new class UxmlFactory : UxmlFactory<PackageManagerToolbar> { } #endif private readonly VisualElement root; [SerializeField] private PackageFilter selectedFilter = PackageFilter.All; public PackageManagerToolbar() { root = Resources.GetTemplate("PackageManagerToolbar.uxml"); Add(root); root.StretchToParentSize(); SetFilter(PackageCollection.Instance.Filter); RegisterCallback<AttachToPanelEvent>(OnEnterPanel); RegisterCallback<DetachFromPanelEvent>(OnLeavePanel); } public void GrabFocus() { SearchToolbar.GrabFocus(); } public new void SetEnabled(bool enable) { base.SetEnabled(enable); FilterButton.SetEnabled(enable); AdvancedButton.SetEnabled(enable); SearchToolbar.SetEnabled(enable); } private static string GetFilterDisplayName(PackageFilter filter) { switch (filter) { case PackageFilter.All: return "All packages"; case PackageFilter.Local: return "In Project"; case PackageFilter.Modules: return "Built-in packages"; case PackageFilter.None: return "None"; default: return filter.ToString(); } } private void SetFilter(object obj) { var previouSelectedFilter = selectedFilter; selectedFilter = (PackageFilter) obj; FilterButton.text = string.Format("{0} ▾", GetFilterDisplayName(selectedFilter)); if (selectedFilter != previouSelectedFilter) PackageCollection.Instance.SetFilter(selectedFilter); } private void OnFilterButtonMouseDown(MouseDownEvent evt) { if (evt.propagationPhase != PropagationPhase.AtTarget) return; var menu = new GenericMenu(); menu.AddItem(new GUIContent(GetFilterDisplayName(PackageFilter.All)), selectedFilter == PackageFilter.All, SetFilter, PackageFilter.All); menu.AddItem(new GUIContent(GetFilterDisplayName(PackageFilter.Local)), selectedFilter == PackageFilter.Local, SetFilter, PackageFilter.Local); menu.AddSeparator(""); menu.AddItem(new GUIContent(GetFilterDisplayName(PackageFilter.Modules)), selectedFilter == PackageFilter.Modules, SetFilter, PackageFilter.Modules); var menuPosition = new Vector2(FilterButton.layout.xMin, FilterButton.layout.center.y); menuPosition = this.LocalToWorld(menuPosition); var menuRect = new Rect(menuPosition, Vector2.zero); menu.DropDown(menuRect); } private void OnAdvancedButtonMouseDown(MouseDownEvent evt) { if (evt.propagationPhase != PropagationPhase.AtTarget) return; var menu = new GenericMenu(); menu.AddItem(new GUIContent("Show preview packages"), PackageManagerPrefs.ShowPreviewPackages, TogglePreviewPackages); //menu.AddItem(new GUIContent("Reset to defaults"), false, ResetToDefaultsClick); var menuPosition = new Vector2(AdvancedButton.layout.xMax + 30, AdvancedButton.layout.center.y); menuPosition = this.LocalToWorld(menuPosition); var menuRect = new Rect(menuPosition, Vector2.zero); menu.DropDown(menuRect); } private static void TogglePreviewPackages() { var showPreviewPackages = PackageManagerPrefs.ShowPreviewPackages; if (!showPreviewPackages && PackageManagerPrefs.ShowPreviewPackagesWarning) { const string message = "Preview packages are not verified with Unity, may be unstable, and are unsupported in production. Are you sure you want to show preview packages?"; if (!EditorUtility.DisplayDialog("Unity Package Manager", message, "Yes", "No")) return; PackageManagerPrefs.ShowPreviewPackagesWarning = false; } PackageManagerPrefs.ShowPreviewPackages = !showPreviewPackages; PackageCollection.Instance.UpdatePackageCollection(true); } private void ResetToDefaultsClick() { if (!EditorUtility.DisplayDialog("Unity Package Manager", "Operation will reset all your packages to Editor defaults. Do you want to continue?", "Yes", "No")) return; // Registered on callback AssemblyReloadEvents.beforeAssemblyReload += PackageManagerWindow.ShowPackageManagerWindow; Client.ResetToEditorDefaults(); var windows = UnityEngine.Resources.FindObjectsOfTypeAll<PackageManagerWindow>(); if (windows.Length > 0) { windows[0].Close(); } } private void OnEnterPanel(AttachToPanelEvent evt) { FilterButton.RegisterCallback<MouseDownEvent>(OnFilterButtonMouseDown); AdvancedButton.RegisterCallback<MouseDownEvent>(OnAdvancedButtonMouseDown); } private void OnLeavePanel(DetachFromPanelEvent evt) { FilterButton.UnregisterCallback<MouseDownEvent>(OnFilterButtonMouseDown); AdvancedButton.UnregisterCallback<MouseDownEvent>(OnAdvancedButtonMouseDown); } private Label FilterButton { get { return root.Q<Label>("toolbarFilterButton"); } } private Label AdvancedButton { get { return root.Q<Label>("toolbarAdvancedButton"); } } internal PackageSearchToolbar SearchToolbar { get { return root.Q<PackageSearchToolbar>("toolbarSearch"); } } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/GeoJsonObjectModel/Serializers/GeoJsonCoordinateReferenceSystemSerializer.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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 MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; namespace MongoDB.Driver.GeoJsonObjectModel.Serializers { /// <summary> /// Represents a serializer for a GeoJsonCoordinateReferenceSystem value. /// </summary> public class GeoJsonCoordinateReferenceSystemSerializer : ClassSerializerBase<GeoJsonCoordinateReferenceSystem> { // protected methods /// <summary> /// Gets the actual type. /// </summary> /// <param name="context">The context.</param> /// <returns>The actual type.</returns> protected override Type GetActualType(BsonDeserializationContext context) { var bsonReader = context.Reader; var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); if (bsonReader.FindElement("type")) { var type = bsonReader.ReadString(); bsonReader.ReturnToBookmark(bookmark); switch (type) { case "link": return typeof(GeoJsonLinkedCoordinateReferenceSystem); case "name": return typeof(GeoJsonNamedCoordinateReferenceSystem); default: var message = string.Format("The type field of the GeoJsonCoordinateReferenceSystem is not valid: '{0}'.", type); throw new FormatException(message); } } else { throw new FormatException("GeoJsonCoordinateReferenceSystem object is missing the type field."); } } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Authentication/SaslMapParser.cs<|end_filename|> /* Copyright 2018–present MongoDB Inc. * * 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.Collections.Generic; using System.IO; using System.Text; namespace MongoDB.Driver.Core.Authentication { /// <summary> /// Per RFC5802: https://tools.ietf.org/html/rfc5802 /// "SCRAM is a SASL mechanism whose client response and server challenge /// messages are text-based messages containing one or more attribute- /// value pairs separated by commas. Each attribute has a one-letter /// name." /// </summary> internal static class SaslMapParser { private const int EOF = -1; public static IDictionary<char, string> Parse(string text) { IDictionary<char, string> dict = new Dictionary<char, string>(); using (var reader = new StringReader(text)) { while (reader.Peek() != EOF) { dict.Add(ReadKeyValue(reader)); if (reader.Peek() == ',') { Read(reader, ','); } } } return dict; } private static KeyValuePair<char, string> ReadKeyValue(TextReader reader) { var key = ReadKey(reader); Read(reader, '='); var value = ReadValue(reader); return new KeyValuePair<char, string>(key, value); } private static char ReadKey(TextReader reader) { // keys are of length 1. return (char)reader.Read(); } private static void Read(TextReader reader, char expected) { var ch = (char)reader.Read(); if (ch != expected) { throw new IOException(string.Format("Expected {0} but found {1}.", expected, ch)); } } private static string ReadValue(TextReader reader) { var sb = new StringBuilder(); var ch = reader.Peek(); while (ch != ',' && ch != EOF) { sb.Append((char)reader.Read()); ch = reader.Peek(); } return sb.ToString(); } } } <|start_filename|>Unity/Assets/Editor/ComponentViewEditor/Entity/SerializationTypeExtension.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace ETEditor { public static class SerializationTypeExtension { private static readonly Dictionary<string, string> _builtInTypesToString = new Dictionary<string, string>() { { "System.Boolean", "bool" }, { "System.Byte", "byte" }, { "System.SByte", "sbyte" }, { "System.Char", "char" }, { "System.Decimal", "decimal" }, { "System.Double", "double" }, { "System.Single", "float" }, { "System.Int32", "int" }, { "System.UInt32", "uint" }, { "System.Int64", "long" }, { "System.UInt64", "ulong" }, { "System.Object", "object" }, { "System.Int16", "short" }, { "System.UInt16", "ushort" }, { "System.String", "string" }, { "System.Void", "void" } }; private static readonly Dictionary<string, string> _builtInTypeStrings = new Dictionary<string, string>() { { "bool", "System.Boolean" }, { "byte", "System.Byte" }, { "sbyte", "System.SByte" }, { "char", "System.Char" }, { "decimal", "System.Decimal" }, { "double", "System.Double" }, { "float", "System.Single" }, { "int", "System.Int32" }, { "uint", "System.UInt32" }, { "long", "System.Int64" }, { "ulong", "System.UInt64" }, { "object", "System.Object" }, { "short", "System.Int16" }, { "ushort", "System.UInt16" }, { "string", "System.String" }, { "void", "System.Void" } }; public static string ToCompilableString(this Type type) { if (SerializationTypeExtension._builtInTypesToString.ContainsKey(type.FullName)) return SerializationTypeExtension._builtInTypesToString[type.FullName]; if (type.IsGenericType) { string str1 = type.FullName.Split('`')[0]; string[] array = ((IEnumerable<Type>) type.GetGenericArguments()) .Select<Type, string>((Func<Type, string>) (argType => argType.ToCompilableString())).ToArray<string>(); string str2 = "<"; string str3 = string.Join(", ", array); string str4 = ">"; return str1 + str2 + str3 + str4; } if (type.IsArray) return type.GetElementType().ToCompilableString() + "[" + new string(',', type.GetArrayRank() - 1) + "]"; if (type.IsNested) return type.FullName.Replace('+', '.'); return type.FullName; } public static Type ToType(this string typeString) { string typeString1 = SerializationTypeExtension.generateTypeString(typeString); Type type1 = Type.GetType(typeString1); if (type1 != null) return type1; foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { Type type2 = assembly.GetType(typeString1); if (type2 != null) return type2; } return (Type) null; } public static string ShortTypeName(this string fullTypeName) { string[] strArray = fullTypeName.Split('.'); return strArray[strArray.Length - 1]; } public static string RemoveDots(this string fullTypeName) { return fullTypeName.Replace(".", string.Empty); } private static string generateTypeString(string typeString) { if (SerializationTypeExtension._builtInTypeStrings.ContainsKey(typeString)) { typeString = SerializationTypeExtension._builtInTypeStrings[typeString]; } else { typeString = SerializationTypeExtension.generateGenericArguments(typeString); typeString = SerializationTypeExtension.generateArray(typeString); } return typeString; } private static string generateGenericArguments(string typeString) { string[] separator = new string[1] { ", " }; typeString = Regex.Replace(typeString, "<(?<arg>.*)>", (MatchEvaluator) (m => { string typeString1 = SerializationTypeExtension.generateTypeString(m.Groups["arg"].Value); return "`" + (object) typeString1.Split(separator, StringSplitOptions.None).Length + "[" + typeString1 + "]"; })); return typeString; } private static string generateArray(string typeString) { typeString = Regex.Replace(typeString, "(?<type>[^\\[]*)(?<rank>\\[,*\\])", (MatchEvaluator) (m => SerializationTypeExtension.generateTypeString(m.Groups["type"].Value) + m.Groups["rank"].Value)); return typeString; } } } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/Serialization/Serializers/DiscriminatedInterfaceSerializer.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.Reflection; using MongoDB.Bson.Serialization.Conventions; namespace MongoDB.Bson.Serialization.Serializers { /// <summary> /// Represents a serializer for Interfaces. /// </summary> /// <typeparam name="TInterface">The type of the interface.</typeparam> public class DiscriminatedInterfaceSerializer<TInterface> : SerializerBase<TInterface> // where TInterface is an interface { // private fields private readonly Type _interfaceType; private readonly IDiscriminatorConvention _discriminatorConvention; private readonly IBsonSerializer<object> _objectSerializer; // constructors /// <summary> /// Initializes a new instance of the <see cref="DiscriminatedInterfaceSerializer{TInterface}" /> class. /// </summary> public DiscriminatedInterfaceSerializer() : this(BsonSerializer.LookupDiscriminatorConvention(typeof(TInterface))) { } /// <summary> /// Initializes a new instance of the <see cref="DiscriminatedInterfaceSerializer{TInterface}" /> class. /// </summary> /// <param name="discriminatorConvention">The discriminator convention.</param> /// <exception cref="System.ArgumentException">interfaceType</exception> /// <exception cref="System.ArgumentNullException">interfaceType</exception> public DiscriminatedInterfaceSerializer(IDiscriminatorConvention discriminatorConvention) { var interfaceTypeInfo = typeof(TInterface).GetTypeInfo(); if (!interfaceTypeInfo.IsInterface) { var message = string.Format("{0} is not an interface.", typeof(TInterface).FullName); throw new ArgumentException(message, "<TInterface>"); } _interfaceType = typeof(TInterface); _discriminatorConvention = discriminatorConvention; _objectSerializer = new ObjectSerializer(_discriminatorConvention); } // public methods /// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <param name="args">The deserialization args.</param> /// <returns>A deserialized value.</returns> /// <exception cref="System.FormatException"></exception> public override TInterface Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { var bsonReader = context.Reader; if (bsonReader.GetCurrentBsonType() == BsonType.Null) { bsonReader.ReadNull(); return default(TInterface); } else { var actualType = _discriminatorConvention.GetActualType(bsonReader, typeof(TInterface)); if (actualType == _interfaceType) { var message = string.Format("Unable to determine actual type of object to deserialize for interface type {0}.", _interfaceType.FullName); throw new FormatException(message); } var serializer = BsonSerializer.LookupSerializer(actualType); return (TInterface)serializer.Deserialize(context, args); } } /// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The document.</param> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TInterface value) { var bsonWriter = context.Writer; if (value == null) { bsonWriter.WriteNull(); } else { args.NominalType = typeof(object); _objectSerializer.Serialize(context, args, value); } } } } <|start_filename|>Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/ExampleScenes/Example3_Recast_Navmesh1/MecanimBridge.cs<|end_filename|> using UnityEngine; namespace Pathfinding.Examples { using Pathfinding.Util; /** Example of how to use Mecanim with the included movement scripts. * * This script will use Mecanim to apply root motion to move the character * instead of allowing the movement script to do the movement. * * It assumes that the Mecanim controller uses 3 input variables * - \a InputMagnitude which is simply 1 when the character should be moving and 0 when it should stop. * - \a X which is component of the desired movement direction along the left/right axis. * - \a Y which is component of the desired movement direction along the forward/backward axis. * * It works with AIPath and RichAI. * * \see #Pathfinding.IAstarAI * \see #Pathfinding.AIPath * \see #Pathfinding.RichAI */ [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_examples_1_1_mecanim_bridge.php")] public class MecanimBridge : VersionedMonoBehaviour { public float velocitySmoothing = 1; /** Cached reference to the movement script */ IAstarAI ai; /** Cached Animator component */ Animator anim; /** Cached Transform component */ Transform tr; Vector3 smoothedVelocity; /** Position of the left and right feet during the previous frame */ Vector3[] prevFootPos = new Vector3[2]; /** Cached reference to the left and right feet */ Transform[] footTransforms; protected override void Awake () { base.Awake(); ai = GetComponent<IAstarAI>(); anim = GetComponent<Animator>(); tr = transform; // Find the feet of the character footTransforms = new [] { anim.GetBoneTransform(HumanBodyBones.LeftFoot), anim.GetBoneTransform(HumanBodyBones.RightFoot) }; } /** Update is called once per frame */ void Update () { var aiBase = ai as AIBase; aiBase.canMove = false; // aiBase.updatePosition = false; // aiBase.updateRotation = false; } /** Calculate position of the currently grounded foot */ Vector3 CalculateBlendPoint () { // Fall back to rotating around the transform position if no feet could be found if (footTransforms[0] == null || footTransforms[1] == null) return tr.position; var leftFootPos = footTransforms[0].position; var rightFootPos = footTransforms[1].position; // This is the same calculation that Unity uses for // Animator.pivotWeight and Animator.pivotPosition // but those properties do not work for all animations apparently. var footVelocity1 = (leftFootPos - prevFootPos[0]) / Time.deltaTime; var footVelocity2 = (rightFootPos - prevFootPos[1]) / Time.deltaTime; float denominator = footVelocity1.magnitude + footVelocity2.magnitude; var pivotWeight = denominator > 0 ? footVelocity1.magnitude / denominator : 0.5f; prevFootPos[0] = leftFootPos; prevFootPos[1] = rightFootPos; var pivotPosition = Vector3.Lerp(leftFootPos, rightFootPos, pivotWeight); return pivotPosition; } void OnAnimatorMove () { Vector3 nextPosition; Quaternion nextRotation; ai.MovementUpdate(Time.deltaTime, out nextPosition, out nextRotation); //var desiredVelocity = (ai.steeringTarget - tr.position).normalized * 2;//ai.desiredVelocity; var desiredVelocity = ai.desiredVelocity; var desiredVelocityWithoutGrav = desiredVelocity; desiredVelocityWithoutGrav.y = 0; anim.SetFloat("InputMagnitude", ai.reachedEndOfPath || desiredVelocityWithoutGrav.magnitude < 0.1f ? 0f : 1f); // Calculate the desired velocity relative to the character (+Z = forward, +X = right) var localDesiredVelocity = tr.InverseTransformDirection(desiredVelocityWithoutGrav); smoothedVelocity = Vector3.Lerp(smoothedVelocity, localDesiredVelocity, velocitySmoothing > 0 ? Time.deltaTime / velocitySmoothing : 1); if (smoothedVelocity.magnitude < 0.4f) { smoothedVelocity = smoothedVelocity.normalized * 0.4f; } anim.SetFloat("X", smoothedVelocity.x); anim.SetFloat("Y", smoothedVelocity.z); // Calculate how much the agent should rotate during this frame var newRot = RotateTowards(desiredVelocityWithoutGrav, Time.deltaTime * (ai as AIPath).rotationSpeed); // Rotate the character around the currently grounded foot to prevent foot sliding nextPosition = ai.position; nextRotation = ai.rotation; nextPosition = RotatePointAround(nextPosition, CalculateBlendPoint(), newRot * Quaternion.Inverse(nextRotation)); nextRotation = newRot; // Apply rotational root motion nextRotation = anim.deltaRotation * nextRotation; // Use gravity from the movement script, not from animation var deltaPos = anim.deltaPosition; deltaPos.y = desiredVelocity.y * Time.deltaTime; nextPosition += deltaPos; // Call the movement script to perform the final movement ai.FinalizeMovement(nextPosition, nextRotation); } static Vector3 RotatePointAround (Vector3 point, Vector3 around, Quaternion rotation) { return rotation * (point - around) + around; } /** Calculates a rotation closer to the desired direction. * \param direction Direction in the movement plane to rotate toward. * \param maxDegrees Maximum number of degrees to rotate this frame. * \returns The new rotation for the character */ protected virtual Quaternion RotateTowards (Vector3 direction, float maxDegrees) { if (direction != Vector3.zero) { Quaternion targetRotation = Quaternion.LookRotation(direction); return Quaternion.RotateTowards(tr.rotation, targetRotation, maxDegrees); } else { return tr.rotation; } } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Plugins/Components/QuickBase.cs<|end_filename|> /*********************************************** EasyTouch V Copyright © 2014-2015 The Hedgehog Team http://www.thehedgehogteam.com/Forum/ <EMAIL> **********************************************/ using UnityEngine; using System.Collections; namespace HedgehogTeam.EasyTouch{ public class QuickBase : MonoBehaviour { #region enumeration protected enum GameObjectType { Auto,Obj_3D,Obj_2D,UI}; public enum DirectAction {None,Rotate, RotateLocal,Translate, TranslateLocal, Scale}; public enum AffectedAxesAction {X,Y,Z,XY,XZ,YZ,XYZ}; #endregion #region Members public string quickActionName; // Touch management public bool isMultiTouch = false; public bool is2Finger = false; public bool isOnTouch=false; public bool enablePickOverUI = false; public bool resetPhysic = false; // simple Action public DirectAction directAction; public AffectedAxesAction axesAction; public float sensibility = 1; public CharacterController directCharacterController; public bool inverseAxisValue = false; protected Rigidbody cachedRigidBody; protected bool isKinematic; protected Rigidbody2D cachedRigidBody2D; protected bool isKinematic2D; // internal management protected GameObjectType realType; protected int fingerIndex =-1; #endregion #region Monobehavior Callback void Awake(){ cachedRigidBody = GetComponent<Rigidbody>(); if (cachedRigidBody){ isKinematic = cachedRigidBody.isKinematic; } cachedRigidBody2D = GetComponent<Rigidbody2D>(); if (cachedRigidBody2D){ isKinematic2D = cachedRigidBody2D.isKinematic; } } public virtual void Start(){ EasyTouch.SetEnableAutoSelect( true); realType = GameObjectType.Obj_3D; if (GetComponent<Collider>()){ realType = GameObjectType.Obj_3D; } else if (GetComponent<Collider2D>()){ realType = GameObjectType.Obj_2D; } else if (GetComponent<CanvasRenderer>()){ realType = GameObjectType.UI; } switch (realType){ case GameObjectType.Obj_3D: LayerMask mask = EasyTouch.Get3DPickableLayer(); mask = mask | 1<<gameObject.layer; EasyTouch.Set3DPickableLayer( mask); break; //2D case GameObjectType.Obj_2D: EasyTouch.SetEnable2DCollider( true); mask = EasyTouch.Get2DPickableLayer(); mask = mask | 1<<gameObject.layer; EasyTouch.Set2DPickableLayer( mask); break; // UI case GameObjectType.UI: EasyTouch.instance.enableUIMode = true; EasyTouch.SetUICompatibily( false); break; } if (enablePickOverUI){ EasyTouch.instance.enableUIMode = true; EasyTouch.SetUICompatibily( false); } } public virtual void OnEnable(){ //QuickTouchManager.instance.RegisterQuickAction( this); } public virtual void OnDisable(){ //if (QuickTouchManager._instance){ // QuickTouchManager.instance.UnregisterQuickAction( this); //} } #endregion #region Protected Methods protected Vector3 GetInfluencedAxis(){ Vector3 axis = Vector3.zero; switch(axesAction){ case AffectedAxesAction.X: axis = new Vector3(1,0,0); break; case AffectedAxesAction.Y: axis = new Vector3(0,1,0); break; case AffectedAxesAction.Z: axis = new Vector3(0,0,1); break; case AffectedAxesAction.XY: axis = new Vector3(1,1,0); break; case AffectedAxesAction.XYZ: axis = new Vector3(1,1,1); break; case AffectedAxesAction.XZ: axis = new Vector3(1,0,1); break; case AffectedAxesAction.YZ: axis = new Vector3(0,1,1); break; } return axis; } protected void DoDirectAction(float value){ Vector3 localAxis = GetInfluencedAxis(); switch ( directAction){ // Rotate case DirectAction.Rotate: transform.Rotate( localAxis * value, Space.World); break; // Rotate Local case DirectAction.RotateLocal: transform.Rotate( localAxis * value,Space.Self); break; // Translate case DirectAction.Translate: if ( directCharacterController==null){ transform.Translate(localAxis * value,Space.World); } else{ Vector3 direction = localAxis * value; directCharacterController.Move( direction ); } break; // Translate local case DirectAction.TranslateLocal: if ( directCharacterController==null){ transform.Translate(localAxis * value,Space.Self); } else{ Vector3 direction = directCharacterController.transform.TransformDirection(localAxis) * value; directCharacterController.Move( direction ); } break; // Scale case DirectAction.Scale: transform.localScale += localAxis * value; break; /* // Force case DirectAction.Force: if (directRigidBody!=null){ directRigidBody.AddForce( localAxis * axisValue * speed); } break; // Relative force case DirectAction.RelativeForce: if (directRigidBody!=null){ directRigidBody.AddRelativeForce( localAxis * axisValue * speed); } break; // Torque case DirectAction.Torque: if (directRigidBody!=null){ directRigidBody.AddTorque(localAxis * axisValue * speed); } break; // Relative torque case DirectAction.RelativeTorque: if (directRigidBody!=null){ directRigidBody.AddRelativeTorque(localAxis * axisValue * speed); } break;*/ } } #endregion #region Public Methods public void EnabledQuickComponent(string quickActionName){ QuickBase[] quickBases = GetComponents<QuickBase>(); foreach( QuickBase qb in quickBases){ if (qb.quickActionName == quickActionName){ qb.enabled = true; } } } public void DisabledQuickComponent(string quickActionName){ QuickBase[] quickBases = GetComponents<QuickBase>(); foreach( QuickBase qb in quickBases){ if (qb.quickActionName == quickActionName){ qb.enabled = false; } } } public void DisabledAllSwipeExcepted(string quickActionName){ QuickSwipe[] swipes = FindObjectsOfType(typeof(QuickSwipe)) as QuickSwipe[]; foreach( QuickSwipe swipe in swipes){ if (swipe.quickActionName != quickActionName || ( swipe.quickActionName == quickActionName && swipe.gameObject != gameObject)){ swipe.enabled = false; } } } #endregion } } <|start_filename|>Server/Hotfix/Module/Demo/C2G_EnterMapHandler.cs<|end_filename|> using System; using System.Net; using ETModel; namespace ETHotfix { [MessageHandler(AppType.Gate)] public class C2G_EnterMapHandler : AMRpcHandler<C2G_EnterMap, G2C_EnterMap> { protected override async ETTask Run(Session session, C2G_EnterMap request, G2C_EnterMap response, Action reply) { Player player = session.GetComponent<SessionPlayerComponent>().Player; // 在map服务器上创建战斗Unit IPEndPoint mapAddress = StartConfigComponent.Instance.MapConfigs[0].GetComponent<InnerConfig>().IPEndPoint; Session mapSession = Game.Scene.GetComponent<NetInnerComponent>().Get(mapAddress); M2G_CreateUnit createUnit = (M2G_CreateUnit)await mapSession.Call(new G2M_CreateUnit() { PlayerId = player.Id, GateSessionId = session.InstanceId }); player.UnitId = createUnit.UnitId; response.UnitId = createUnit.UnitId; reply(); } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Packages/PackageGroupOrigins.cs<|end_filename|> namespace UnityEditor.PackageManager.UI { internal enum PackageGroupOrigins { Packages, BuiltInPackages } } <|start_filename|>Book/Example/Example2_2/Program.cs<|end_filename|> using System; using System.Threading; using System.Threading.Tasks; using ETModel; namespace Example2_2 { class Program { private static int loopCount = 0; static void Main(string[] args) { OneThreadSynchronizationContext _ = OneThreadSynchronizationContext.Instance; Console.WriteLine($"主线程: {Thread.CurrentThread.ManagedThreadId}"); Crontine(); while (true) { OneThreadSynchronizationContext.Instance.Update(); Thread.Sleep(1); ++loopCount; if (loopCount % 10000 == 0) { Console.WriteLine($"loop count: {loopCount}"); } } } private static async void Crontine() { await WaitTimeAsync(5000); Console.WriteLine($"当前线程: {Thread.CurrentThread.ManagedThreadId}, WaitTimeAsync finsih loopCount的值是: {loopCount}"); await WaitTimeAsync(4000); Console.WriteLine($"当前线程: {Thread.CurrentThread.ManagedThreadId}, WaitTimeAsync finsih loopCount的值是: {loopCount}"); await WaitTimeAsync(3000); Console.WriteLine($"当前线程: {Thread.CurrentThread.ManagedThreadId}, WaitTimeAsync finsih loopCount的值是: {loopCount}"); } private static Task WaitTimeAsync(int waitTime) { TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); Thread thread = new Thread(()=>WaitTime(waitTime, tcs)); thread.Start(); return tcs.Task; } /// <summary> /// 在另外的线程等待 /// </summary> private static void WaitTime(int waitTime, TaskCompletionSource<bool> tcs) { Thread.Sleep(waitTime); // 将tcs扔回主线程执行 OneThreadSynchronizationContext.Instance.Post(o=>tcs.SetResult(true), null); } } } <|start_filename|>Unity/Assets/ThirdParty/ILRuntime/Mono.Cecil/Mono.Cecil/GenericInstanceType.cs<|end_filename|> // // Author: // <NAME> (<EMAIL>) // // Copyright (c) 2008 - 2015 <NAME> // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Text; using Mono.Collections.Generic; using MD = Mono.Cecil.Metadata; namespace Mono.Cecil { public sealed class GenericInstanceType : TypeSpecification, IGenericInstance, IGenericContext { Collection<TypeReference> arguments; public bool HasGenericArguments { get { return !arguments.IsNullOrEmpty (); } } public Collection<TypeReference> GenericArguments { get { return arguments ?? (arguments = new Collection<TypeReference> ()); } } public override TypeReference DeclaringType { get { return ElementType.DeclaringType; } set { throw new NotSupportedException (); } } public override string FullName { get { var name = new StringBuilder (); name.Append (base.FullName); this.GenericInstanceFullName (name); return name.ToString (); } } public override bool IsGenericInstance { get { return true; } } public override bool ContainsGenericParameter { get { return this.ContainsGenericParameter () || base.ContainsGenericParameter; } } IGenericParameterProvider IGenericContext.Type { get { return ElementType; } } public GenericInstanceType (TypeReference type) : base (type) { base.IsValueType = type.IsValueType; this.etype = MD.ElementType.GenericInst; } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Packages/PackageSearchFilter.cs<|end_filename|> using System; namespace UnityEditor.PackageManager.UI { [Serializable] internal class PackageSearchFilter { private static PackageSearchFilter instance = new PackageSearchFilter(); public static PackageSearchFilter Instance { get { return instance; } } public string SearchText { get; set; } public static void InitInstance(ref PackageSearchFilter value) { if (value == null) // UI window opened value = instance; else // Domain reload instance = value; } public void ResetSearch() { SearchText = string.Empty; } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/PasswordEvidence.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.Linq; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Driver.Core.Misc; using MongoDB.Shared; namespace MongoDB.Driver { /// <summary> /// Evidence of a MongoIdentity via a shared secret. /// </summary> public sealed class PasswordEvidence : MongoIdentityEvidence { // private fields private readonly SecureString _securePassword; // constructors /// <summary> /// Initializes a new instance of the <see cref="PasswordEvidence" /> class. /// Less secure when used in conjunction with SCRAM-SHA-256, due to the need to store the password in a managed /// string in order to SaslPrep it. /// See <a href="https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst#scram-sha-256">Driver Authentication: SCRAM-SHA-256</a> /// for additional details. /// </summary> /// <param name="password">The password.</param> public PasswordEvidence(SecureString password) { Ensure.IsNotNull(password, nameof(password)); _securePassword = password.Copy(); _securePassword.MakeReadOnly(); } /// <summary> /// Initializes a new instance of the <see cref="PasswordEvidence" /> class. /// </summary> /// <param name="password">The password.</param> public PasswordEvidence(string password) { Ensure.IsNotNull(password, nameof(password)); _securePassword = CreateSecureString(password); } // public properties /// <summary> /// Gets the password. /// </summary> public SecureString SecurePassword { get { return _securePassword; } } // public methods /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="rhs">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object rhs) { if (object.ReferenceEquals(rhs, null) || GetType() != rhs.GetType()) { return false; } using (var lhsDecryptedPassword = new DecryptedSecureString(_securePassword)) using (var rhsDecryptedPassword = new DecryptedSecureString(((PasswordEvidence)rhs)._securePassword)) { return lhsDecryptedPassword.GetChars().SequenceEqual(rhsDecryptedPassword.GetChars()); } } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { using (var decryptedPassword = new DecryptedSecureString(_securePassword)) { return new Hasher().HashStructElements(decryptedPassword.GetChars()).GetHashCode(); } } // internal methods /// <summary> /// Computes the MONGODB-CR password digest. /// </summary> /// <param name="username">The username.</param> /// <returns>The MONGODB-CR password digest.</returns> [Obsolete("MONGODB-CR was replaced by SCRAM-SHA-1 in MongoDB 3.0, and is now deprecated.")] internal string ComputeMongoCRPasswordDigest(string username) { using (var md5 = MD5.Create()) using (var decryptedPassword = new DecryptedSecureString(_securePassword)) { var encoding = Utf8Encodings.Strict; var prefixBytes = encoding.GetBytes(username + ":mongo:"); var hash = ComputeHash(md5, prefixBytes, decryptedPassword.GetUtf8Bytes()); return BsonUtils.ToHexString(hash); } } // private static methods private static SecureString CreateSecureString(string value) { var secureString = new SecureString(); foreach (var c in value) { secureString.AppendChar(c); } secureString.MakeReadOnly(); return secureString; } private static byte[] ComputeHash(HashAlgorithm algorithm, byte[] prefixBytes, byte[] passwordBytes) { var buffer = new byte[prefixBytes.Length + passwordBytes.Length]; var bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { Buffer.BlockCopy(prefixBytes, 0, buffer, 0, prefixBytes.Length); Buffer.BlockCopy(passwordBytes, 0, buffer, prefixBytes.Length, passwordBytes.Length); return algorithm.ComputeHash(buffer); } finally { Array.Clear(buffer, 0, buffer.Length); bufferHandle.Free(); } } } } <|start_filename|>Server/Model/Module/ActorLocation/ActorLocationSenderComponent.cs<|end_filename|> using System; using System.Collections.Generic; namespace ETModel { public class ActorLocationSenderComponent: Component { public readonly Dictionary<long, ActorLocationSender> ActorLocationSenders = new Dictionary<long, ActorLocationSender>(); public override void Dispose() { if (this.IsDisposed) { return; } base.Dispose(); foreach (ActorLocationSender actorLocationSender in this.ActorLocationSenders.Values) { actorLocationSender.Dispose(); } this.ActorLocationSenders.Clear(); } public ActorLocationSender Get(long id) { if (id == 0) { throw new Exception($"actor id is 0"); } if (this.ActorLocationSenders.TryGetValue(id, out ActorLocationSender actorLocationSender)) { return actorLocationSender; } actorLocationSender = ComponentFactory.CreateWithId<ActorLocationSender>(id); actorLocationSender.Parent = this; this.ActorLocationSenders[id] = actorLocationSender; return actorLocationSender; } public void Remove(long id) { if (!this.ActorLocationSenders.TryGetValue(id, out ActorLocationSender actorMessageSender)) { return; } this.ActorLocationSenders.Remove(id); actorMessageSender.Dispose(); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/Linq/FieldExpressionFlattener.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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.Linq.Expressions; using MongoDB.Driver.Linq.Expressions; namespace MongoDB.Driver.Linq { internal class FieldExpressionFlattener : ExtensionExpressionVisitor { public static Expression FlattenFields(Expression node) { var visitor = new FieldExpressionFlattener(); return visitor.Visit(node); } public FieldExpressionFlattener() { } protected internal override Expression VisitArrayIndex(ArrayIndexExpression node) { var field = Visit(node.Array) as IFieldExpression; if (field != null) { var constantIndex = node.Index as ConstantExpression; if (constantIndex == null) { throw new NotSupportedException($"Only a constant index is supported in the expression {node}."); } var index = constantIndex.Value.ToString(); if (index == "-1") { // We've treated -1 as meaning $ operator. We can't break this now, // so, specifically when we are flattening fields names, this is // how we'll continue to treat -1. index = "$"; } return new FieldExpression( field.AppendFieldName(index), node.Serializer); } return node; } protected internal override Expression VisitDocumentWrappedField(FieldAsDocumentExpression node) { var field = Visit(node.Document) as IFieldExpression; if (field != null) { return new FieldExpression( node.PrependFieldName(field.FieldName), node.Serializer); } return node; } protected internal override Expression VisitField(FieldExpression node) { var document = Visit(node.Document) as IFieldExpression; if (document != null) { return new FieldExpression( node.PrependFieldName(document.FieldName), node.Serializer, node.Original); } return node; } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Upm/UpmBaseOperation.cs<|end_filename|> using System; using System.Globalization; using System.Collections.Generic; using System.Linq; using Semver; using UnityEngine; using UnityEditor.PackageManager.Requests; namespace UnityEditor.PackageManager.UI { internal abstract class UpmBaseOperation : IBaseOperation { public static string GroupName(PackageSource origin) { var group = PackageGroupOrigins.Packages.ToString(); if (origin == PackageSource.BuiltIn) group = PackageGroupOrigins.BuiltInPackages.ToString(); return group; } protected static IEnumerable<PackageInfo> FromUpmPackageInfo(PackageManager.PackageInfo info, bool isCurrent=true) { var packages = new List<PackageInfo>(); var displayName = info.displayName; if (string.IsNullOrEmpty(displayName)) { displayName = info.name.Replace("com.unity.modules.", ""); displayName = displayName.Replace("com.unity.", ""); displayName = new CultureInfo("en-US").TextInfo.ToTitleCase(displayName); } string author = info.author.name; if (string.IsNullOrEmpty(info.author.name) && info.name.StartsWith("com.unity.")) author = "Unity Technologies Inc."; var lastCompatible = info.versions.latestCompatible; var versions = new List<string>(); versions.AddRange(info.versions.compatible); if (versions.FindIndex(version => version == info.version) == -1) { versions.Add(info.version); versions.Sort((left, right) => { if (left == null || right == null) return 0; SemVersion leftVersion = left; SemVersion righVersion = right; return leftVersion.CompareByPrecedence(righVersion); }); SemVersion packageVersion = info.version; if (!string.IsNullOrEmpty(lastCompatible)) { SemVersion lastCompatibleVersion = string.IsNullOrEmpty(lastCompatible) ? (SemVersion) null : lastCompatible; if (packageVersion != null && string.IsNullOrEmpty(packageVersion.Prerelease) && packageVersion.CompareByPrecedence(lastCompatibleVersion) > 0) lastCompatible = info.version; } else { if (packageVersion != null && string.IsNullOrEmpty(packageVersion.Prerelease)) lastCompatible = info.version; } } foreach(var version in versions) { var isVersionCurrent = version == info.version && isCurrent; var isBuiltIn = info.source == PackageSource.BuiltIn; var isVerified = string.IsNullOrEmpty(SemVersion.Parse(version).Prerelease) && version == info.versions.recommended; var state = (isBuiltIn || info.version == lastCompatible || !isCurrent ) ? PackageState.UpToDate : PackageState.Outdated; // Happens mostly when using a package that hasn't been in production yet. if (info.versions.all.Length <= 0) state = PackageState.UpToDate; if (info.errors.Length > 0) state = PackageState.Error; var packageInfo = new PackageInfo { Name = info.name, DisplayName = displayName, PackageId = version == info.version ? info.packageId : null, Version = version, Description = info.description, Category = info.category, IsCurrent = isVersionCurrent, IsLatest = version == lastCompatible, IsVerified = isVerified, Errors = info.errors.ToList(), Group = GroupName(info.source), State = state, Origin = isBuiltIn || isVersionCurrent ? info.source : PackageSource.Registry, Author = author, Info = info }; packages.Add(packageInfo); } return packages; } public static event Action<UpmBaseOperation> OnOperationStart = delegate { }; public event Action<Error> OnOperationError = delegate { }; public event Action OnOperationFinalized = delegate { }; public Error ForceError { get; set; } // Allow external component to force an error on the requests (eg: testing) public Error Error { get; protected set; } // Keep last error public bool IsCompleted { get; private set; } protected abstract Request CreateRequest(); [SerializeField] protected Request CurrentRequest; public readonly ThreadedDelay Delay = new ThreadedDelay(); protected abstract void ProcessData(); protected void Start() { Error = null; OnOperationStart(this); Delay.Start(); if (TryForcedError()) return; EditorApplication.update += Progress; } // Common progress code for all classes private void Progress() { if (!Delay.IsDone) return; // Create the request after the delay if (CurrentRequest == null) { CurrentRequest = CreateRequest(); } // Since CurrentRequest's error property is private, we need to simulate // an error instead of just setting it. if (TryForcedError()) return; if (CurrentRequest.IsCompleted) { if (CurrentRequest.Status == StatusCode.Success) OnDone(); else if (CurrentRequest.Status >= StatusCode.Failure) OnError(CurrentRequest.Error); else Debug.LogError("Unsupported progress state " + CurrentRequest.Status); } } private void OnError(Error error) { try { Error = error; var message = "Cannot perform upm operation."; if (error != null) message = "Cannot perform upm operation: " + Error.message + " [" + Error.errorCode + "]"; Debug.LogError(message); OnOperationError(Error); } catch (Exception exception) { Debug.LogError("Package Manager Window had an error while reporting an error in an operation: " + exception); } FinalizeOperation(); } private void OnDone() { try { ProcessData(); } catch (Exception error) { Debug.LogError("Package Manager Window had an error while completing an operation: " + error); } FinalizeOperation(); } private void FinalizeOperation() { EditorApplication.update -= Progress; OnOperationFinalized(); IsCompleted = true; } public void Cancel() { EditorApplication.update -= Progress; OnOperationError = delegate { }; OnOperationFinalized = delegate { }; IsCompleted = true; } private bool TryForcedError() { if (ForceError != null) { OnError(ForceError); return true; } return false; } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Plugins/Components/QuickDrag.cs<|end_filename|> /*********************************************** EasyTouch V Copyright © 2014-2015 The Hedgehog Team http://www.thehedgehogteam.com/Forum/ <EMAIL> **********************************************/ using UnityEngine; using System.Collections; using UnityEngine.Events; using UnityEngine.EventSystems; using HedgehogTeam.EasyTouch; namespace HedgehogTeam.EasyTouch{ [AddComponentMenu("EasyTouch/Quick Drag")] public class QuickDrag: QuickBase { #region Events [System.Serializable] public class OnDragStart : UnityEvent<Gesture>{} [System.Serializable] public class OnDrag : UnityEvent<Gesture>{} [System.Serializable] public class OnDragEnd : UnityEvent<Gesture>{} [SerializeField] public OnDragStart onDragStart; [SerializeField] public OnDrag onDrag; [SerializeField] public OnDragEnd onDragEnd; #endregion #region Members public bool isStopOncollisionEnter = false; private Vector3 deltaPosition; private bool isOnDrag = false; private Gesture lastGesture; #endregion #region Monobehaviour CallBack public QuickDrag(){ quickActionName = "QuickDrag"+ System.Guid.NewGuid().ToString().Substring(0,7); axesAction = AffectedAxesAction.XY; } public override void OnEnable(){ base.OnEnable(); EasyTouch.On_TouchStart += On_TouchStart; EasyTouch.On_TouchDown += On_TouchDown; EasyTouch.On_TouchUp += On_TouchUp; EasyTouch.On_Drag += On_Drag; EasyTouch.On_DragStart += On_DragStart; EasyTouch.On_DragEnd += On_DragEnd; } public override void OnDisable(){ base.OnDisable(); UnsubscribeEvent(); } void OnDestroy(){ UnsubscribeEvent(); } void UnsubscribeEvent(){ EasyTouch.On_TouchStart -= On_TouchStart; EasyTouch.On_TouchDown -= On_TouchDown; EasyTouch.On_TouchUp -= On_TouchUp; EasyTouch.On_Drag -= On_Drag; EasyTouch.On_DragStart -= On_DragStart; EasyTouch.On_DragEnd -= On_DragEnd; } void OnCollisionEnter(){ if (isStopOncollisionEnter && isOnDrag){ StopDrag(); } } #endregion #region EasyTouch Event void On_TouchStart (Gesture gesture){ if ( realType == GameObjectType.UI){ if (gesture.isOverGui ){ if ((gesture.pickedUIElement == gameObject || gesture.pickedUIElement.transform.IsChildOf( transform)) && fingerIndex==-1){ fingerIndex = gesture.fingerIndex; transform.SetAsLastSibling(); onDragStart.Invoke(gesture); isOnDrag = true; } } } } void On_TouchDown (Gesture gesture){ if (isOnDrag && fingerIndex == gesture.fingerIndex && realType == GameObjectType.UI){ if (gesture.isOverGui ){ if ((gesture.pickedUIElement == gameObject || gesture.pickedUIElement.transform.IsChildOf( transform)) ){ transform.position += (Vector3)gesture.deltaPosition; if (gesture.deltaPosition != Vector2.zero){ onDrag.Invoke(gesture); } lastGesture = gesture; } } } } void On_TouchUp (Gesture gesture){ if (fingerIndex == gesture.fingerIndex && realType == GameObjectType.UI){ lastGesture = gesture; StopDrag(); } } // At the drag beginning void On_DragStart( Gesture gesture){ if (realType != GameObjectType.UI){ if ((!enablePickOverUI && gesture.pickedUIElement == null) || enablePickOverUI){ if (gesture.pickedObject == gameObject && !isOnDrag){ isOnDrag = true; fingerIndex = gesture.fingerIndex; // the world coordinate from touch Vector3 position = gesture.GetTouchToWorldPoint(gesture.pickedObject.transform.position); deltaPosition = position - transform.position; // if (resetPhysic){ if (cachedRigidBody){ cachedRigidBody.isKinematic = true; } if (cachedRigidBody2D){ cachedRigidBody2D.isKinematic = true; } } onDragStart.Invoke(gesture); } } } } // During the drag void On_Drag(Gesture gesture){ if (fingerIndex == gesture.fingerIndex){ if (realType == GameObjectType.Obj_2D || realType == GameObjectType.Obj_3D){ // Verification that the action on the object if (gesture.pickedObject == gameObject && fingerIndex == gesture.fingerIndex){ // the world coordinate from touch Vector3 position = gesture.GetTouchToWorldPoint(gesture.pickedObject.transform.position)-deltaPosition; transform.position = GetPositionAxes( position); if (gesture.deltaPosition != Vector2.zero){ onDrag.Invoke(gesture); } lastGesture = gesture; } } } } // End of drag void On_DragEnd(Gesture gesture){ if (fingerIndex == gesture.fingerIndex){ lastGesture = gesture; StopDrag(); } } #endregion #region Private Method private Vector3 GetPositionAxes(Vector3 position){ Vector3 axes = position; switch (axesAction){ case AffectedAxesAction.X: axes = new Vector3(position.x,transform.position.y,transform.position.z); break; case AffectedAxesAction.Y: axes = new Vector3(transform.position.x,position.y,transform.position.z); break; case AffectedAxesAction.Z: axes = new Vector3(transform.position.x,transform.position.y,position.z); break; case AffectedAxesAction.XY: axes = new Vector3(position.x,position.y,transform.position.z); break; case AffectedAxesAction.XZ: axes = new Vector3(position.x,transform.position.y,position.z); break; case AffectedAxesAction.YZ: axes = new Vector3(transform.position.x,position.y,position.z); break; } return axes; } #endregion #region Public Method public void StopDrag(){ fingerIndex = -1; if (resetPhysic){ if (cachedRigidBody){ cachedRigidBody.isKinematic = isKinematic; } if (cachedRigidBody2D){ cachedRigidBody2D.isKinematic = isKinematic2D; } } isOnDrag = false; onDragEnd.Invoke(lastGesture); } #endregion } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/ServerErrorCode.cs<|end_filename|> /* Copyright 2018-present MongoDB Inc. * * 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 MongoDB.Driver { internal enum ServerErrorCode { // this is not a complete list, more will be added as needed // see: https://github.com/mongodb/mongo/blob/master/src/mongo/base/error_codes.err CappedPositionLost = 136, CursorKilled = 237, ElectionInProgress = 216, ExceededTimeLimit = 50, HostNotFound = 7, HostUnreachable = 6, Interrupted = 11601, InterruptedAtShutdown = 11600, InterruptedDueToReplStateChange = 11602, NetworkTimeout = 89, NotMaster = 10107, NotMasterNoSlaveOk = 13435, NotMasterOrSecondary = 13436, PrimarySteppedDown = 189, RetryChangeStream = 234, ShutdownInProgress = 91, SocketException = 9001, UnknownReplWriteConcern = 79, UnsatisfiableWriteConcern = 100, WriteConcernFailed = 64 } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Tests/Editor/Services/Packages/PackageSearchTests.cs<|end_filename|> using System.Collections.Generic; using NUnit.Framework; namespace UnityEditor.PackageManager.UI.Tests { internal class PackageSearchTests : PackageBaseTests { private const string kName = "Test-Package"; private const string kCurrentVersion = "3.0.0"; private const string kPrerelease = "preview"; private const string kUpperPrerelease = "PREVIEW"; private const string kMixedPrerelease = "pReViEw"; private Package testPackage; [SetUp] public void Setup() { testPackage = new Package(kName, new List<PackageInfo> { PackageSets.Instance.Single(PackageSource.Registry, kName, kCurrentVersion + "-" + kPrerelease, true, true) }); } [TestCase(null)] [TestCase("")] [TestCase("\t")] [TestCase(" ")] [TestCase(" ")] public void MatchCriteria_NullOrEmptyCriteria_ReturnsTrue(string criteria) { Assert.IsTrue(PackageFiltering.FilterByText(testPackage, criteria)); } [TestCaseSource("GetAllPartialName")] public void MatchCriteria_CriteriaMatchDisplayNamePartially_ReturnsTrue(string criteria) { Assert.IsTrue(PackageFiltering.FilterByText(testPackage, criteria)); } [TestCaseSource("GetAllPartialVersions")] public void MatchCriteria_CriteriaMatchCurrentVersion_ReturnsTrue(string criteria) { Assert.IsTrue(PackageFiltering.FilterByText(testPackage, criteria)); } [TestCase(kPrerelease)] [TestCase(kUpperPrerelease)] [TestCase(kMixedPrerelease)] public void MatchCriteria_CriteriaMatchCurrentVersionPreRelease_ReturnsTrue(string criteria) { Assert.IsTrue(PackageFiltering.FilterByText(testPackage, criteria)); } [TestCase("p")] [TestCase("pr")] [TestCase("pre")] [TestCase("prev")] [TestCase("view")] [TestCase("vie")] [TestCase("vi")] public void MatchCriteria_CriteriaPartialMatchCurrentVersionPreRelease_ReturnsTrue(string criteria) { Assert.IsTrue(PackageFiltering.FilterByText(testPackage, criteria)); } [TestCase("-p")] [TestCase("-pr")] [TestCase("-pre")] [TestCase("-prev")] [TestCase("-previ")] [TestCase("-previe")] [TestCase("-preview")] public void MatchCriteria_CriteriaPartialMatchCurrentVersionPreReleaseLeadingDash_ReturnsTrue(string criteria) { Assert.IsTrue(PackageFiltering.FilterByText(testPackage, criteria)); } [TestCase("veri")] [TestCase("verif")] [TestCase("verifie")] [TestCase("verified")] [TestCase("erified")] [TestCase("rified")] [TestCase("ified")] public void MatchCriteria_CriteriaPartialMatchVerified_ReturnsTrue(string criteria) { Assert.IsTrue(PackageFiltering.FilterByText(testPackage, criteria)); } [TestCase("Test Package")] [TestCase("Test -Package")] [TestCase("Test - Package")] [TestCase("Test- Package")] [TestCase("NotFound")] [TestCase("1.0.0-preview")] [TestCase("5.0.0")] [TestCase("beta")] [TestCase("previewed")] [TestCase("verify")] [TestCase("experimental")] public void MatchCriteria_CriteriaDoesntMatch_ReturnsFalse(string criteria) { Assert.IsFalse(PackageFiltering.FilterByText(testPackage, criteria)); } private static IEnumerable<string> GetAllPartialVersions() { var versions = new List<string>(); for (var i = 1; i <= kCurrentVersion.Length; i++) { versions.Add(kCurrentVersion.Substring(0, i)); } return versions; } private static IEnumerable<string> GetAllPartial(string str) { var names = new List<string>(); for (var i = 0; i < str.Length; i++) { var s1 = str.Substring(0, i + 1); var s2 = str.Substring(i, str.Length - i); names.Add(s1); names.Add(s1.ToLower()); names.Add(s1.ToUpper()); names.Add(" " + s1); names.Add(s1 + " "); names.Add(" " + s1 + " "); names.Add(s2); names.Add(s2.ToLower()); names.Add(s2.ToUpper()); names.Add(" " + s2); names.Add(s2 + " "); names.Add(" " + s2 + " "); } return names; } private static IEnumerable<string> GetAllPartialName() { return GetAllPartial(kName); } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Common/Resources.cs<|end_filename|> using UnityEngine.Experimental.UIElements; namespace UnityEditor.PackageManager.UI { internal static class Resources { private static string TemplateRoot { get { return PackageManagerWindow.ResourcesPath + "Templates"; } } private static string TemplatePath(string filename) { return string.Format("{0}/{1}", TemplateRoot, filename); } public static VisualElement GetTemplate(string templateFilename) { return AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(TemplatePath(templateFilename)).CloneTree(null); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/AggregateOptions.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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 MongoDB.Bson; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver { /// <summary> /// Options for an aggregate operation. /// </summary> public class AggregateOptions { // fields private bool? _allowDiskUse; private int? _batchSize; private bool? _bypassDocumentValidation; private Collation _collation; private string _comment; private BsonValue _hint; private TimeSpan? _maxAwaitTime; private TimeSpan? _maxTime; private ExpressionTranslationOptions _translationOptions; private bool? _useCursor; // properties /// <summary> /// Gets or sets a value indicating whether to allow disk use. /// </summary> public bool? AllowDiskUse { get { return _allowDiskUse; } set { _allowDiskUse = value; } } /// <summary> /// Gets or sets the size of a batch. /// </summary> public int? BatchSize { get { return _batchSize; } set { _batchSize = Ensure.IsNullOrGreaterThanOrEqualToZero(value, nameof(value)); } } /// <summary> /// Gets or sets a value indicating whether to bypass document validation. /// </summary> public bool? BypassDocumentValidation { get { return _bypassDocumentValidation; } set { _bypassDocumentValidation = value; } } /// <summary> /// Gets or sets the collation. /// </summary> public Collation Collation { get { return _collation; } set { _collation = value; } } /// <summary> /// Gets or sets the comment. /// </summary> public string Comment { get { return _comment; } set { _comment = value; } } /// <summary> /// Gets or sets the hint. This must either be a BsonString representing the index name or a BsonDocument representing the key pattern of the index. /// </summary> public BsonValue Hint { get { return _hint; } set { _hint = value; } } /// <summary> /// Gets or sets the maximum await time. /// </summary> public TimeSpan? MaxAwaitTime { get { return _maxAwaitTime; } set { _maxAwaitTime = value; } } /// <summary> /// Gets or sets the maximum time. /// </summary> public TimeSpan? MaxTime { get { return _maxTime; } set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); } } /// <summary> /// Gets or sets the translation options. /// </summary> public ExpressionTranslationOptions TranslationOptions { get { return _translationOptions; } set { _translationOptions = value; } } /// <summary> /// Gets or sets a value indicating whether to use a cursor. /// </summary> public bool? UseCursor { get { return _useCursor; } set { _useCursor = value; } } } } <|start_filename|>Server/Hotfix/Module/Actor/MailboxGateSessionHandler.cs<|end_filename|> using System; using ETModel; namespace ETHotfix { /// <summary> /// gate session类型的Mailbox,收到的actor消息直接转发给客户端 /// </summary> [MailboxHandler(AppType.Gate, MailboxType.GateSession)] public class MailboxGateSessionHandler : IMailboxHandler { public async ETTask Handle(Session session, Entity entity, object actorMessage) { try { IActorMessage iActorMessage = actorMessage as IActorMessage; // 发送给客户端 Session clientSession = entity as Session; iActorMessage.ActorId = 0; clientSession.Send(iActorMessage); await ETTask.CompletedTask; } catch (Exception e) { Log.Error(e); } } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/ReturnDocument.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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; namespace MongoDB.Driver { /// <summary> /// Which version of the document to return when executing a FindAndModify command. /// </summary> public enum ReturnDocument { /// <summary> /// Return the document before the modification. /// </summary> Before, /// <summary> /// Return the document after the modification. /// </summary> After } internal static class ReturnDocumentExtensions { public static Core.Operations.ReturnDocument ToCore(this ReturnDocument returnDocument) { switch (returnDocument) { case ReturnDocument.Before: return Core.Operations.ReturnDocument.Before; case ReturnDocument.After: return Core.Operations.ReturnDocument.After; default: throw new ArgumentException("Unrecognized ReturnDocument.", "returnDocument"); } } } } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/Serialization/Serializers/ElementAppendingSerializer.cs<|end_filename|> /* Copyright 2017-present MongoDB Inc. * * 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.Linq; using MongoDB.Bson.IO; namespace MongoDB.Bson.Serialization.Serializers { /// <summary> /// A serializer that serializes a document and appends elements to the end of it. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> /// <seealso cref="MongoDB.Bson.Serialization.IBsonSerializer{TDocument}" /> public class ElementAppendingSerializer<TDocument> : IBsonSerializer<TDocument> { // private fields private readonly IBsonSerializer<TDocument> _documentSerializer; private readonly List<BsonElement> _elements; private readonly Action<BsonWriterSettings> _writerSettingsConfigurator; // constructors /// <summary> /// Initializes a new instance of the <see cref="ElementAppendingSerializer{TDocument}" /> class. /// </summary> /// <param name="documentSerializer">The document serializer.</param> /// <param name="elements">The elements to append.</param> /// <param name="writerSettingsConfigurator">The writer settings configurator.</param> public ElementAppendingSerializer( IBsonSerializer<TDocument> documentSerializer, IEnumerable<BsonElement> elements, Action<BsonWriterSettings> writerSettingsConfigurator = null) { if (documentSerializer == null) { throw new ArgumentNullException(nameof(documentSerializer)); } if (elements == null) { throw new ArgumentNullException(nameof(elements)); } _documentSerializer = documentSerializer; _elements = elements.ToList(); _writerSettingsConfigurator = writerSettingsConfigurator; // can be null } // public properties /// <inheritdoc /> public Type ValueType => typeof(TDocument); // public methods /// <inheritdoc /> public TDocument Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { throw new NotSupportedException(); } object IBsonSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { throw new NotSupportedException(); } /// <inheritdoc /> public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TDocument value) { var writer = context.Writer; var elementAppendingWriter = new ElementAppendingBsonWriter(writer, _elements, _writerSettingsConfigurator); var elementAppendingContext = BsonSerializationContext.CreateRoot(elementAppendingWriter, builder => ConfigureElementAppendingContext(builder, context)); _documentSerializer.Serialize(elementAppendingContext, args, value); } void IBsonSerializer.Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value) { Serialize(context, args, (TDocument)value); } // private methods private void ConfigureElementAppendingContext(BsonSerializationContext.Builder builder, BsonSerializationContext originalContext) { builder.IsDynamicType = originalContext.IsDynamicType; } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Upm/UpmListOperation.cs<|end_filename|> using System; using System.Collections.Generic; using UnityEngine; using UnityEditor.PackageManager.Requests; namespace UnityEditor.PackageManager.UI { internal class UpmListOperation : UpmBaseOperation, IListOperation { [SerializeField] private Action<IEnumerable<PackageInfo>> _doneCallbackAction; public UpmListOperation(bool offlineMode) : base() { OfflineMode = offlineMode; } public bool OfflineMode { get; set; } public void GetPackageListAsync(Action<IEnumerable<PackageInfo>> doneCallbackAction, Action<Error> errorCallbackAction = null) { this._doneCallbackAction = doneCallbackAction; OnOperationError += errorCallbackAction; Start(); } protected override Request CreateRequest() { return Client.List(OfflineMode); } protected override void ProcessData() { var request = CurrentRequest as ListRequest; var packages = new List<PackageInfo>(); foreach (var upmPackage in request.Result) { var packageInfos = FromUpmPackageInfo(upmPackage); packages.AddRange(packageInfos); } _doneCallbackAction(packages); } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Tests/Editor/Services/Mock/MockSearchOperation.cs<|end_filename|> using System; using System.Collections.Generic; namespace UnityEditor.PackageManager.UI.Tests { internal class MockSearchOperation : MockOperation, ISearchOperation { public new event Action<Error> OnOperationError = delegate { }; public new event Action OnOperationFinalized = delegate { }; public IEnumerable<PackageInfo> Packages { get; set; } public MockSearchOperation(MockOperationFactory factory, IEnumerable<PackageInfo> packages) : base(factory) { Packages = packages; } public void GetAllPackageAsync(Action<IEnumerable<PackageInfo>> doneCallbackAction = null, Action<Error> errorCallbackAction = null) { if (ForceError != null) { if (errorCallbackAction != null) errorCallbackAction(ForceError); IsCompleted = true; OnOperationError(ForceError); } else { if (doneCallbackAction != null) doneCallbackAction(Packages); IsCompleted = true; } OnOperationFinalized(); } } } <|start_filename|>Unity/Assets/Editor/ComponentViewEditor/TypeDrawerAttribute.cs<|end_filename|> using System; namespace ETEditor { public class TypeDrawerAttribute: Attribute { } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/TransactionOptions.cs<|end_filename|> /* Copyright 2018-present MongoDB Inc. * * 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.Linq; using System.Text; using System.Threading.Tasks; using MongoDB.Bson; namespace MongoDB.Driver { /// <summary> /// Transaction options. /// </summary> public class TransactionOptions { // private fields private readonly ReadConcern _readConcern; private readonly ReadPreference _readPreference; private readonly WriteConcern _writeConcern; // public constructors /// <summary> /// Initializes a new instance of the <see cref="TransactionOptions" /> class. /// </summary> /// <param name="readConcern">The read concern.</param> /// <param name="readPreference">The read preference.</param> /// <param name="writeConcern">The write concern.</param> public TransactionOptions( Optional<ReadConcern> readConcern = default(Optional<ReadConcern>), Optional<ReadPreference> readPreference = default(Optional<ReadPreference>), Optional<WriteConcern> writeConcern = default(Optional<WriteConcern>)) { _readConcern = readConcern.WithDefault(null); _readPreference = readPreference.WithDefault(null); _writeConcern = writeConcern.WithDefault(null); } // public properties /// <summary> /// Gets the read concern. /// </summary> /// <value> /// The read concern. /// </value> public ReadConcern ReadConcern => _readConcern; /// <summary> /// Gets the read preference. /// </summary> /// <value> /// The read preference. /// </value> public ReadPreference ReadPreference => _readPreference; /// <summary> /// Gets the write concern. /// </summary> /// <value> /// The write concern. /// </value> public WriteConcern WriteConcern => _writeConcern; // public methods /// <summary> /// Returns a new TransactionOptions with some values changed. /// </summary> /// <param name="readConcern">The new read concern.</param> /// <param name="readPreference">The read preference.</param> /// <param name="writeConcern">The new write concern.</param> /// <returns> /// The new TransactionOptions. /// </returns> public TransactionOptions With( Optional<ReadConcern> readConcern = default(Optional<ReadConcern>), Optional<ReadPreference> readPreference = default(Optional<ReadPreference>), Optional<WriteConcern> writeConcern = default(Optional<WriteConcern>)) { return new TransactionOptions( readConcern: readConcern.WithDefault(_readConcern), readPreference: readPreference.WithDefault(_readPreference), writeConcern: writeConcern.WithDefault(_writeConcern)); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Misc/SizeLimitingBatchableSourceSerializer.cs<|end_filename|> /* Copyright 2017-present MongoDB Inc. * * 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 MongoDB.Bson.IO; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; namespace MongoDB.Driver.Core.Misc { /// <summary> /// A serializer for BatchableSource that serializes as much of the BatchableSource as fits in the max batch count and size. /// </summary> /// <typeparam name="TItem">The type of the items.</typeparam> public class SizeLimitingBatchableSourceSerializer<TItem> : SerializerBase<BatchableSource<TItem>> { // private fields private readonly IElementNameValidator _itemElementNameValidator; private readonly IBsonSerializer<TItem> _itemSerializer; private readonly int _maxBatchCount; private readonly int _maxBatchSize; private readonly int _maxItemSize; // constructors /// <summary> /// Initializes a new instance of the <see cref="SizeLimitingBatchableSourceSerializer{TItem}" /> class. /// </summary> /// <param name="itemSerializer">The item serializer.</param> /// <param name="itemElementNameValidator">The item element name validator.</param> /// <param name="maxBatchCount">The maximum batch count.</param> /// <param name="maxItemSize">The maximum size of a serialized item.</param> /// <param name="maxBatchSize">The maximum size of the batch.</param> public SizeLimitingBatchableSourceSerializer( IBsonSerializer<TItem> itemSerializer, IElementNameValidator itemElementNameValidator, int maxBatchCount, int maxItemSize, int maxBatchSize) { _itemSerializer = Ensure.IsNotNull(itemSerializer, nameof(itemSerializer)); _itemElementNameValidator = Ensure.IsNotNull(itemElementNameValidator, nameof(itemElementNameValidator)); _maxBatchCount = Ensure.IsGreaterThanZero(maxBatchCount, nameof(maxBatchCount)); _maxItemSize = Ensure.IsGreaterThanZero(maxItemSize, nameof(maxItemSize)); _maxBatchSize = Ensure.IsGreaterThanZero(maxBatchSize, nameof(maxBatchSize)); } // public methods /// <inheritdoc /> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, BatchableSource<TItem> value) { Ensure.IsNotNull(value, nameof(value)); var writer = context.Writer; while (writer is WrappingBsonWriter) { writer = ((WrappingBsonWriter)writer).Wrapped; } var binaryWriter = writer as BsonBinaryWriter; var startPosition = binaryWriter?.Position; writer.PushSettings(s => { var bs = s as BsonBinaryWriterSettings; if (bs != null) { bs.MaxDocumentSize = _maxItemSize; } }); writer.PushElementNameValidator(_itemElementNameValidator); try { var batchCount = Math.Min(value.Count, _maxBatchCount); if (batchCount != value.Count && !value.CanBeSplit) { throw new ArgumentException("Batch is too large."); } for (var i = 0; i < batchCount; i++) { var itemPosition = binaryWriter?.Position; var item = value.Items[value.Offset + i]; _itemSerializer.Serialize(context, args, item); // always process at least one item if (i > 0) { var batchSize = binaryWriter?.Position - startPosition; if (batchSize > _maxBatchSize) { if (value.CanBeSplit) { binaryWriter.BaseStream.Position = itemPosition.Value; // remove the last item binaryWriter.BaseStream.SetLength(itemPosition.Value); value.SetProcessedCount(i); return; } else { throw new ArgumentException("Batch is too large."); } } } } value.SetProcessedCount(batchCount); } finally { writer.PopElementNameValidator(); writer.PopSettings(); } } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Packages/PackageState.cs<|end_filename|> namespace UnityEditor.PackageManager.UI { internal enum PackageState { UpToDate, Outdated, InProgress, Error } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Plugins/Editor/QuickPinchInspector.cs<|end_filename|> using UnityEngine; using System.Collections; using UnityEditor; using HedgehogTeam.EasyTouch; #if UNITY_5_3_OR_NEWER using UnityEditor.SceneManagement; #endif [CustomEditor(typeof(QuickPinch))] public class QuickPinchInspector : Editor { public override void OnInspectorGUI(){ QuickPinch t = (QuickPinch)target; EditorGUILayout.Space(); t.quickActionName = EditorGUILayout.TextField("Quick name",t.quickActionName); EditorGUILayout.Space(); t.isGestureOnMe = EditorGUILayout.ToggleLeft("Gesture over me", t.isGestureOnMe); t.enablePickOverUI = EditorGUILayout.ToggleLeft("Allow over UI Element",t.enablePickOverUI); EditorGUILayout.Space(); t.actionTriggering = (QuickPinch.ActionTiggering)EditorGUILayout.EnumPopup("Triggering",t.actionTriggering); t.pinchDirection = (QuickPinch.ActionPinchDirection)EditorGUILayout.EnumPopup("Pinch direction",t.pinchDirection); //t.rotationDirection = (QuickTwist.ActionRotationDirection)EditorGUILayout.EnumPopup("Twist direction",t.rotationDirection); EditorGUILayout.Space(); if (t.actionTriggering == QuickPinch.ActionTiggering.InProgress){ t.enableSimpleAction = EditorGUILayout.Toggle("Enable simple action",t.enableSimpleAction); if (t.enableSimpleAction){ EditorGUI.indentLevel++; t.directAction = (QuickSwipe.DirectAction) EditorGUILayout.EnumPopup("Action",t.directAction); t.axesAction = (QuickSwipe.AffectedAxesAction)EditorGUILayout.EnumPopup("Affected axes",t.axesAction); t.sensibility = EditorGUILayout.FloatField("Sensibility",t.sensibility); t.inverseAxisValue = EditorGUILayout.Toggle("Inverse axis",t.inverseAxisValue); EditorGUI.indentLevel--; } } EditorGUILayout.Space(); serializedObject.Update(); SerializedProperty pinchAction = serializedObject.FindProperty("onPinchAction"); EditorGUILayout.PropertyField(pinchAction, true, null); serializedObject.ApplyModifiedProperties(); if (GUI.changed){ EditorUtility.SetDirty(t); #if UNITY_5_3_OR_NEWER EditorSceneManager.MarkSceneDirty( EditorSceneManager.GetActiveScene()); #endif } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Plugins/Editor/EasyTouchMenu.cs<|end_filename|> using UnityEngine; using UnityEditor; using System.Collections; using UnityEngine.EventSystems; using HedgehogTeam.EasyTouch; public static class EasyTouchMenu{ [MenuItem ("GameObject/EasyTouch/EasyTouch", false, 0)] static void AddEasyTouch(){ Selection.activeObject = EasyTouch.instance.gameObject; } } /* [MenuItem ("Window/GameAnalytics/Folder Structure/Revert to original", false, 601)] static void RevertFolders () { if (!Directory.Exists(Application.dataPath + "/Plugins/GameAnalytics/")) { Debug.LogWarning("Folder structure incompatible, are you already using original folder structure, or have you manually changed the folder structure?"); return; } if (!Directory.Exists(Application.dataPath + "/GameAnalytics/")) AssetDatabase.CreateFolder("Assets", "GameAnalytics"); if (!Directory.Exists(Application.dataPath + "/GameAnalytics/Plugins")) AssetDatabase.CreateFolder("Assets/GameAnalytics", "Plugins"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/Android", "Assets/GameAnalytics/Plugins/Android"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/Components", "Assets/GameAnalytics/Plugins/Components"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/Examples", "Assets/GameAnalytics/Plugins/Examples"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/Framework", "Assets/GameAnalytics/Plugins/Framework"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/iOS", "Assets/GameAnalytics/Plugins/iOS"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/Playmaker", "Assets/GameAnalytics/Plugins/Playmaker"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/WebPlayer", "Assets/GameAnalytics/Plugins/WebPlayer"); AssetDatabase.MoveAsset("Assets/Editor/GameAnalytics", "Assets/GameAnalytics/Editor"); AssetDatabase.DeleteAsset("Assets/Plugins/GameAnalytics"); AssetDatabase.DeleteAsset("Assets/Editor/GameAnalytics"); Debug.Log("Project must be reloaded when reverting folder structure."); EditorApplication.OpenProject(Application.dataPath.Remove(Application.dataPath.Length - "Assets".Length, "Assets".Length)); } */ /* #if true #endif*/ /* [MenuItem ("Window/Easy Touch/Folder Structure/Switch to JS", false, 100)] static void JsFolders(){ // EasyTouch is here if (!Directory.Exists(Application.dataPath + "/EasyTouchBundle/EasyTouch/Plugins/")){ Debug.LogWarning("Folder structure incompatible, did you already switch to JS folder structure, or have you manually changed the folder structure?"); return; } // Create Structure if (!Directory.Exists(Application.dataPath + "/Plugins/")) AssetDatabase.CreateFolder("Assets", "Plugins"); if (!Directory.Exists(Application.dataPath + "/Plugins/EasyTouch")) AssetDatabase.CreateFolder("Assets/Plugins", "EasyTouch"); AssetDatabase.MoveAsset("Assets/EasyTouchBundle/EasyTouch/Plugins/Components","Assets/Plugins/EasyTouch/Components"); AssetDatabase.MoveAsset("Assets/EasyTouchBundle/EasyTouch/Plugins/Engine","Assets/Plugins/EasyTouch/Engine"); // Refresh database AssetDatabase.Refresh(); } [MenuItem ("Window/EasyTouch/Folder Structure/Revert to original", false, 200)] static void CFolders(){ if (!Directory.Exists(Application.dataPath + "/Plugins/EasyTouch/")){ Debug.LogWarning("Folder structure incompatible, are you already using original folder structure, or have you manually changed the folder structure?"); return; } AssetDatabase.MoveAsset("Assets/Plugins/EasyTouch/Components","Assets/EasyTouchBundle/EasyTouch/Plugins/Components"); AssetDatabase.MoveAsset("Assets/Plugins/EasyTouch/Engine","Assets/EasyTouchBundle/EasyTouch/Plugins/Engine"); AssetDatabase.DeleteAsset("Assets/Plugins/EasyTouch"); Debug.Log("Project must be reloaded when reverting folder structure."); EditorApplication.OpenProject(Application.dataPath.Remove(Application.dataPath.Length - "Assets".Length, "Assets".Length)); }*/ <|start_filename|>Unity/Assets/Model/Module/Pathfinding/Recast/TriangleMeshNode.cs<|end_filename|> using UnityEngine; namespace PF { /** Interface for something that holds a triangle based navmesh */ public interface INavmeshHolder : ITransformedGraph, INavmesh { /** Position of vertex number i in the world */ Int3 GetVertex (int i); /** Position of vertex number i in coordinates local to the graph. * The up direction is always the +Y axis for these coordinates. */ Int3 GetVertexInGraphSpace (int i); int GetVertexArrayIndex (int index); /** Transforms coordinates from graph space to world space */ void GetTileCoordinates (int tileIndex, out int x, out int z); } /** Node represented by a triangle */ public class TriangleMeshNode : MeshNode { /** Internal vertex index for the first vertex */ public int v0; /** Internal vertex index for the second vertex */ public int v1; /** Internal vertex index for the third vertex */ public int v2; /** Holds INavmeshHolder references for all graph indices to be able to access them in a performant manner */ protected static INavmeshHolder[] _navmeshHolders = new INavmeshHolder[0]; /** Used for synchronised access to the #_navmeshHolders array */ protected static readonly System.Object lockObject = new System.Object(); public static INavmeshHolder GetNavmeshHolder (uint graphIndex) { return _navmeshHolders[(int)graphIndex]; } /** Sets the internal navmesh holder for a given graph index. * \warning Internal method */ public static void SetNavmeshHolder (int graphIndex, INavmeshHolder graph) { // We need to lock to make sure that // the resize operation is thread safe lock (lockObject) { if (graphIndex >= _navmeshHolders.Length) { var gg = new INavmeshHolder[graphIndex+1]; _navmeshHolders.CopyTo(gg, 0); _navmeshHolders = gg; } _navmeshHolders[graphIndex] = graph; } } /** Set the position of this node to the average of its 3 vertices */ public void UpdatePositionFromVertices () { Int3 a, b, c; GetVertices(out a, out b, out c); position = (a + b + c) * 0.333333f; } /** Return a number identifying a vertex. * This number does not necessarily need to be a index in an array but two different vertices (in the same graph) should * not have the same vertex numbers. */ public int GetVertexIndex (int i) { return i == 0 ? v0 : (i == 1 ? v1 : v2); } /** Return a number specifying an index in the source vertex array. * The vertex array can for example be contained in a recast tile, or be a navmesh graph, that is graph dependant. * This is slower than GetVertexIndex, if you only need to compare vertices, use GetVertexIndex. */ public int GetVertexArrayIndex (int i) { return GetNavmeshHolder(GraphIndex).GetVertexArrayIndex(i == 0 ? v0 : (i == 1 ? v1 : v2)); } /** Returns all 3 vertices of this node in world space */ public void GetVertices (out Int3 v0, out Int3 v1, out Int3 v2) { // Get the object holding the vertex data for this node // This is usually a graph or a recast graph tile var holder = GetNavmeshHolder(GraphIndex); v0 = holder.GetVertex(this.v0); v1 = holder.GetVertex(this.v1); v2 = holder.GetVertex(this.v2); } /** Returns all 3 vertices of this node in graph space */ public void GetVerticesInGraphSpace (out Int3 v0, out Int3 v1, out Int3 v2) { // Get the object holding the vertex data for this node // This is usually a graph or a recast graph tile var holder = GetNavmeshHolder(GraphIndex); v0 = holder.GetVertexInGraphSpace(this.v0); v1 = holder.GetVertexInGraphSpace(this.v1); v2 = holder.GetVertexInGraphSpace(this.v2); } public override Int3 GetVertex (int i) { return GetNavmeshHolder(GraphIndex).GetVertex(GetVertexIndex(i)); } public Int3 GetVertexInGraphSpace (int i) { return GetNavmeshHolder(GraphIndex).GetVertexInGraphSpace(GetVertexIndex(i)); } public override int GetVertexCount () { // A triangle has 3 vertices return 3; } public override Vector3 ClosestPointOnNode (Vector3 p) { Int3 a, b, c; GetVertices(out a, out b, out c); return Polygon.ClosestPointOnTriangle((Vector3)a, (Vector3)b, (Vector3)c, p); } /** Closest point on the node when seen from above. * This method is mostly for internal use as the #Pathfinding.NavmeshBase.Linecast methods use it. * * - The returned point is the closest one on the node to \a p when seen from above (relative to the graph). * This is important mostly for sloped surfaces. * - The returned point is an Int3 point in graph space. * - It is guaranteed to be inside the node, so if you call #ContainsPointInGraphSpace with the return value from this method the result is guaranteed to be true. * * This method is slower than e.g #ClosestPointOnNode or #ClosestPointOnNodeXZ. * However they do not have the same guarantees as this method has. */ internal Int3 ClosestPointOnNodeXZInGraphSpace (Vector3 p) { // Get the vertices that make up the triangle Int3 a, b, c; GetVerticesInGraphSpace(out a, out b, out c); // Convert p to graph space p = GetNavmeshHolder(GraphIndex).transform.InverseTransform(p); // Find the closest point on the triangle to p when looking at the triangle from above (relative to the graph) var closest = Polygon.ClosestPointOnTriangleXZ((Vector3)a, (Vector3)b, (Vector3)c, p); // Make sure the point is actually inside the node var i3closest = (Int3)closest; if (ContainsPointInGraphSpace(i3closest)) { // Common case return i3closest; } else { // Annoying... // The closest point when converted from floating point coordinates to integer coordinates // is not actually inside the node. It needs to be inside the node for some methods // (like for example Linecast) to work properly. // Try the 8 integer coordinates around the closest point // and check if any one of them are completely inside the node. // This will most likely succeed as it should be very close. for (int dx = -1; dx <= 1; dx++) { for (int dz = -1; dz <= 1; dz++) { if ((dx != 0 || dz != 0)) { var candidate = new Int3(i3closest.x + dx, i3closest.y, i3closest.z + dz); if (ContainsPointInGraphSpace(candidate)) return candidate; } } } // Happens veery rarely. // Pick the closest vertex of the triangle. // The vertex is guaranteed to be inside the triangle. var da = (a - i3closest).sqrMagnitudeLong; var db = (b - i3closest).sqrMagnitudeLong; var dc = (c - i3closest).sqrMagnitudeLong; return da < db ? (da < dc ? a : c) : (db < dc ? b : c); } } public override Vector3 ClosestPointOnNodeXZ (Vector3 p) { // Get all 3 vertices for this node Int3 tp1, tp2, tp3; GetVertices(out tp1, out tp2, out tp3); return Polygon.ClosestPointOnTriangleXZ((Vector3)tp1, (Vector3)tp2, (Vector3)tp3, p); } public override bool ContainsPoint (Vector3 p) { return ContainsPointInGraphSpace((Int3)GetNavmeshHolder(GraphIndex).transform.InverseTransform(p)); } public override bool ContainsPointInGraphSpace (Int3 p) { // Get all 3 vertices for this node Int3 a, b, c; GetVerticesInGraphSpace(out a, out b, out c); if ((long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z) > 0) return false; if ((long)(c.x - b.x) * (long)(p.z - b.z) - (long)(p.x - b.x) * (long)(c.z - b.z) > 0) return false; if ((long)(a.x - c.x) * (long)(p.z - c.z) - (long)(p.x - c.x) * (long)(a.z - c.z) > 0) return false; return true; // Equivalent code, but the above code is faster //return Polygon.IsClockwiseMargin (a,b, p) && Polygon.IsClockwiseMargin (b,c, p) && Polygon.IsClockwiseMargin (c,a, p); //return Polygon.ContainsPoint(g.GetVertex(v0),g.GetVertex(v1),g.GetVertex(v2),p); } public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { pathNode.UpdateG(path); handler.heap.Add(pathNode); if (connections == null) return; for (int i = 0; i < connections.Length; i++) { GraphNode other = connections[i].node; PathNode otherPN = handler.GetPathNode(other); if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG(path, otherPN, handler); } } public override void Open (Path path, PathNode pathNode, PathHandler handler) { if (connections == null) return; // Flag2 indicates if this node needs special treatment // with regard to connection costs bool flag2 = pathNode.flag2; // Loop through all connections for (int i = connections.Length-1; i >= 0; i--) { var conn = connections[i]; var other = conn.node; // Make sure we can traverse the neighbour if (path.CanTraverse(conn.node)) { PathNode pathOther = handler.GetPathNode(conn.node); // Fast path out, worth it for triangle mesh nodes since they usually have degree 2 or 3 if (pathOther == pathNode.parent) { continue; } uint cost = conn.cost; if (flag2 || pathOther.flag2) { // Get special connection cost from the path // This is used by the start and end nodes cost = path.GetConnectionSpecialCost(this, conn.node, cost); } // Test if we have seen the other node before if (pathOther.pathID != handler.PathID) { // We have not seen the other node before // So the path from the start through this node to the other node // must be the shortest one so far // Might not be assigned pathOther.node = conn.node; pathOther.parent = pathNode; pathOther.pathID = handler.PathID; pathOther.cost = cost; pathOther.H = path.CalculateHScore(other); pathOther.UpdateG(path); handler.heap.Add(pathOther); } else { // If not we can test if the path from this node to the other one is a better one than the one already used if (pathNode.G + cost + path.GetTraversalCost(other) < pathOther.G) { pathOther.cost = cost; pathOther.parent = pathNode; other.UpdateRecursiveG(path, pathOther, handler); } } } } } /** Returns the edge which is shared with \a other. * If no edge is shared, -1 is returned. * If there is a connection with the other node, but the connection is not marked as using a particular edge of the shape of the node * then 0xFF will be returned. * * The vertices in the edge can be retrieved using * \code * var edge = node.SharedEdge(other); * var a = node.GetVertex(edge); * var b = node.GetVertex((edge+1) % node.GetVertexCount()); * \endcode * * \see #GetPortal which also handles edges that are shared over tile borders and some types of node links */ public int SharedEdge (GraphNode other) { var edge = -1; for (int i = 0; i < connections.Length; i++) { if (connections[i].node == other) edge = connections[i].shapeEdge; } return edge; } public override bool GetPortal (GraphNode toNode, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards) { int aIndex, bIndex; return GetPortal(toNode, left, right, backwards, out aIndex, out bIndex); } public bool GetPortal (GraphNode toNode, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards, out int aIndex, out int bIndex) { aIndex = -1; bIndex = -1; //If the nodes are in different graphs, this function has no idea on how to find a shared edge. if (backwards || toNode.GraphIndex != GraphIndex) return false; // Since the nodes are in the same graph, they are both TriangleMeshNodes // So we don't need to care about other types of nodes var toTriNode = toNode as TriangleMeshNode; var edge = SharedEdge(toTriNode); // A connection was found, but it specifically didn't use an edge if (edge == 0xFF) return false; // No connection was found between the nodes // Check if there is a node link that connects them if (edge == -1) { return false; } aIndex = edge; bIndex = (edge + 1) % GetVertexCount(); // Get the vertices of the shared edge for the first node Int3 v1a = GetVertex(edge); Int3 v1b = GetVertex((edge+1) % GetVertexCount()); // Get tile indices int tileIndex1 = (GetVertexIndex(0) >> NavmeshBase.TileIndexOffset) & NavmeshBase.TileIndexMask; int tileIndex2 = (toTriNode.GetVertexIndex(0) >> NavmeshBase.TileIndexOffset) & NavmeshBase.TileIndexMask; if (tileIndex1 != tileIndex2) { // When the nodes are in different tiles, the edges might not be completely identical // so another technique is needed. // Get the tile coordinates, from them we can figure out which edge is going to be shared int x1, x2, z1, z2, coord; INavmeshHolder nm = GetNavmeshHolder(GraphIndex); nm.GetTileCoordinates(tileIndex1, out x1, out z1); nm.GetTileCoordinates(tileIndex2, out x2, out z2); if (System.Math.Abs(x1-x2) == 1) coord = 2; else if (System.Math.Abs(z1-z2) == 1) coord = 0; else return false; // Tiles are not adjacent. This is likely a custom connection between two nodes. var otherEdge = toTriNode.SharedEdge(this); // A connection was found, but it specifically didn't use an edge. This is odd since the connection in the other direction did use an edge if (otherEdge == 0xFF) throw new System.Exception("Connection used edge in one direction, but not in the other direction. Has the wrong overload of AddConnection been used?"); // If it is -1 then it must be a one-way connection. Fall back to using the whole edge if (otherEdge != -1) { // When the nodes are in different tiles, they might not share exactly the same edge // so we clamp the portal to the segment of the edges which they both have. int mincoord = System.Math.Min(v1a[coord], v1b[coord]); int maxcoord = System.Math.Max(v1a[coord], v1b[coord]); // Get the vertices of the shared edge for the second node Int3 v2a = toTriNode.GetVertex(otherEdge); Int3 v2b = toTriNode.GetVertex((otherEdge+1) % toTriNode.GetVertexCount()); mincoord = System.Math.Max(mincoord, System.Math.Min(v2a[coord], v2b[coord])); maxcoord = System.Math.Min(maxcoord, System.Math.Max(v2a[coord], v2b[coord])); if (v1a[coord] < v1b[coord]) { v1a[coord] = mincoord; v1b[coord] = maxcoord; } else { v1a[coord] = maxcoord; v1b[coord] = mincoord; } } } if (left != null) { // All triangles should be laid out in clockwise order so v1b is the rightmost vertex (seen from this node) left.Add((Vector3)v1a); right.Add((Vector3)v1b); } return true; } /** \todo This is the area in XZ space, use full 3D space for higher correctness maybe? */ public override float SurfaceArea () { var holder = GetNavmeshHolder(GraphIndex); return System.Math.Abs(VectorMath.SignedTriangleAreaTimes2XZ(holder.GetVertex(v0), holder.GetVertex(v1), holder.GetVertex(v2))) * 0.5f; } public override void SerializeNode (GraphSerializationContext ctx) { base.SerializeNode(ctx); ctx.writer.Write(v0); ctx.writer.Write(v1); ctx.writer.Write(v2); } public override void DeserializeNode (GraphSerializationContext ctx) { base.DeserializeNode(ctx); v0 = ctx.reader.ReadInt32(); v1 = ctx.reader.ReadInt32(); v2 = ctx.reader.ReadInt32(); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Clusters/MultiServerCluster.cs<|end_filename|> /* Copyright 2013-present MongoDB Inc. * * 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.Diagnostics; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver.Core.Async; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.Events.Diagnostics; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; namespace MongoDB.Driver.Core.Clusters { /// <summary> /// Represents a multi server cluster. /// </summary> internal sealed class MultiServerCluster : Cluster { // fields private readonly CancellationTokenSource _monitorServersCancellationTokenSource; private volatile ElectionInfo _maxElectionInfo; private volatile string _replicaSetName; private readonly AsyncQueue<ServerDescriptionChangedEventArgs> _serverDescriptionChangedQueue; private readonly List<IClusterableServer> _servers; private readonly object _serversLock = new object(); private readonly InterlockedInt32 _state; private readonly Action<ClusterClosingEvent> _closingEventHandler; private readonly Action<ClusterClosedEvent> _closedEventHandler; private readonly Action<ClusterOpeningEvent> _openingEventHandler; private readonly Action<ClusterOpenedEvent> _openedEventHandler; private readonly Action<ClusterAddingServerEvent> _addingServerEventHandler; private readonly Action<ClusterAddedServerEvent> _addedServerEventHandler; private readonly Action<ClusterRemovingServerEvent> _removingServerEventHandler; private readonly Action<ClusterRemovedServerEvent> _removedServerEventHandler; private readonly Action<SdamInformationEvent> _sdamInformationEventHandler; // constructors public MultiServerCluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber) : base(settings, serverFactory, eventSubscriber) { Ensure.IsGreaterThanZero(settings.EndPoints.Count, "settings.EndPoints.Count"); if (settings.ConnectionMode == ClusterConnectionMode.Standalone) { throw new ArgumentException("ClusterConnectionMode.StandAlone is not supported for a MultiServerCluster."); } if (settings.ConnectionMode == ClusterConnectionMode.Direct) { throw new ArgumentException("ClusterConnectionMode.Direct is not supported for a MultiServerCluster."); } _monitorServersCancellationTokenSource = new CancellationTokenSource(); _serverDescriptionChangedQueue = new AsyncQueue<ServerDescriptionChangedEventArgs>(); _servers = new List<IClusterableServer>(); _state = new InterlockedInt32(State.Initial); _replicaSetName = settings.ReplicaSetName; eventSubscriber.TryGetEventHandler(out _closingEventHandler); eventSubscriber.TryGetEventHandler(out _closedEventHandler); eventSubscriber.TryGetEventHandler(out _openingEventHandler); eventSubscriber.TryGetEventHandler(out _openedEventHandler); eventSubscriber.TryGetEventHandler(out _addingServerEventHandler); eventSubscriber.TryGetEventHandler(out _addedServerEventHandler); eventSubscriber.TryGetEventHandler(out _removingServerEventHandler); eventSubscriber.TryGetEventHandler(out _removedServerEventHandler); eventSubscriber.TryGetEventHandler(out _sdamInformationEventHandler); } // methods protected override void Dispose(bool disposing) { Stopwatch stopwatch = null; if (_state.TryChange(State.Disposed)) { if (disposing) { if (_closingEventHandler != null) { _closingEventHandler(new ClusterClosingEvent(ClusterId)); } stopwatch = Stopwatch.StartNew(); _monitorServersCancellationTokenSource.Cancel(); _monitorServersCancellationTokenSource.Dispose(); var clusterDescription = Description; lock (_serversLock) { foreach (var server in _servers.ToList()) { RemoveServer(clusterDescription, server.EndPoint, "The cluster is closing."); } } stopwatch.Stop(); } } base.Dispose(disposing); if (stopwatch != null && _closedEventHandler != null) { _closedEventHandler(new ClusterClosedEvent(ClusterId, stopwatch.Elapsed)); } } public override void Initialize() { base.Initialize(); if (_state.TryChange(State.Initial, State.Open)) { if (_openingEventHandler != null) { _openingEventHandler(new ClusterOpeningEvent(ClusterId, Settings)); } var stopwatch = Stopwatch.StartNew(); MonitorServersAsync().ConfigureAwait(false); // We lock here even though AddServer locks. Monitors // are re-entrant such that this won't cause problems, // but could prevent issues of conflicting reports // from servers that are quick to respond. var clusterDescription = Description.WithType(Settings.ConnectionMode.ToClusterType()); var newServers = new List<IClusterableServer>(); lock (_serversLock) { foreach (var endPoint in Settings.EndPoints) { clusterDescription = EnsureServer(clusterDescription, endPoint, newServers); } } stopwatch.Stop(); UpdateClusterDescription(clusterDescription); foreach (var server in newServers) { server.Initialize(); } if (_openedEventHandler != null) { _openedEventHandler(new ClusterOpenedEvent(ClusterId, Settings, stopwatch.Elapsed)); } } } private bool IsServerValidForCluster(ClusterType clusterType, ClusterConnectionMode connectionMode, ServerType serverType) { switch (clusterType) { case ClusterType.ReplicaSet: return serverType.IsReplicaSetMember(); case ClusterType.Sharded: return serverType == ServerType.ShardRouter; case ClusterType.Unknown: switch (connectionMode) { case ClusterConnectionMode.Automatic: return serverType.IsReplicaSetMember() || serverType == ServerType.ShardRouter; default: throw new MongoInternalException("Unexpected connection mode."); } default: throw new MongoInternalException("Unexpected cluster type."); } } protected override void RequestHeartbeat() { List<IClusterableServer> servers; lock (_serversLock) { servers = _servers.ToList(); } foreach (var server in servers) { if (server.IsInitialized) { try { server.RequestHeartbeat(); } catch (ObjectDisposedException) { // There is a possible race condition here // due to the fact that we are working // with the server outside of the lock, // meaning another thread could remove // the server and dispose of it before // we invoke the method. } } } } private async Task MonitorServersAsync() { var monitorServersCancellationToken = _monitorServersCancellationTokenSource.Token; while (!monitorServersCancellationToken.IsCancellationRequested) { try { var eventArgs = await _serverDescriptionChangedQueue.DequeueAsync(monitorServersCancellationToken).ConfigureAwait(false); // TODO: add timeout and cancellationToken to DequeueAsync ProcessServerDescriptionChanged(eventArgs); } catch (OperationCanceledException) when (monitorServersCancellationToken.IsCancellationRequested) { // ignore OperationCanceledException when monitor servers cancellation is requested } catch (Exception unexpectedException) { // if we catch an exception here it's because of a bug in the driver var handler = _sdamInformationEventHandler; if (handler != null) { try { handler.Invoke(new SdamInformationEvent(() => string.Format( "Unexpected exception in MultiServerCluster.MonitorServersAsync: {0}", unexpectedException.ToString()))); } catch { // ignore any exceptions thrown by the handler (note: event handlers aren't supposed to throw exceptions) } } // TODO: should we reset the cluster state in some way? (the state is undefined since an unexpected exception was thrown) } } } private void ServerDescriptionChangedHandler(object sender, ServerDescriptionChangedEventArgs args) { _serverDescriptionChangedQueue.Enqueue(args); } private void ProcessServerDescriptionChanged(ServerDescriptionChangedEventArgs args) { var newServerDescription = args.NewServerDescription; var newClusterDescription = Description; if (!_servers.Any(x => EndPointHelper.Equals(x.EndPoint, newServerDescription.EndPoint))) { return; } var newServers = new List<IClusterableServer>(); if (newServerDescription.State == ServerState.Disconnected) { newClusterDescription = newClusterDescription.WithServerDescription(newServerDescription); } else { if (IsServerValidForCluster(newClusterDescription.Type, Settings.ConnectionMode, newServerDescription.Type)) { if (newClusterDescription.Type == ClusterType.Unknown) { newClusterDescription = newClusterDescription.WithType(newServerDescription.Type.ToClusterType()); } switch (newClusterDescription.Type) { case ClusterType.ReplicaSet: newClusterDescription = ProcessReplicaSetChange(newClusterDescription, args, newServers); break; case ClusterType.Sharded: newClusterDescription = ProcessShardedChange(newClusterDescription, args); break; default: throw new MongoInternalException("Unexpected cluster type."); } } else { newClusterDescription = newClusterDescription.WithoutServerDescription(newServerDescription.EndPoint); } } UpdateClusterDescription(newClusterDescription); foreach (var server in newServers) { server.Initialize(); } } private ClusterDescription ProcessReplicaSetChange(ClusterDescription clusterDescription, ServerDescriptionChangedEventArgs args, List<IClusterableServer> newServers) { if (!args.NewServerDescription.Type.IsReplicaSetMember()) { return RemoveServer(clusterDescription, args.NewServerDescription.EndPoint, string.Format("Server is a {0}, not a replica set member.", args.NewServerDescription.Type)); } if (args.NewServerDescription.Type == ServerType.ReplicaSetGhost) { return clusterDescription.WithServerDescription(args.NewServerDescription); } if (_replicaSetName == null) { _replicaSetName = args.NewServerDescription.ReplicaSetConfig.Name; } if (_replicaSetName != args.NewServerDescription.ReplicaSetConfig.Name) { return RemoveServer(clusterDescription, args.NewServerDescription.EndPoint, string.Format("Server was a member of the '{0}' replica set, but should be '{1}'.", args.NewServerDescription.ReplicaSetConfig.Name, _replicaSetName)); } clusterDescription = clusterDescription.WithServerDescription(args.NewServerDescription); clusterDescription = EnsureServers(clusterDescription, args.NewServerDescription, newServers); if (args.NewServerDescription.CanonicalEndPoint != null && !EndPointHelper.Equals(args.NewServerDescription.CanonicalEndPoint, args.NewServerDescription.EndPoint)) { return RemoveServer(clusterDescription, args.NewServerDescription.EndPoint, "CanonicalEndPoint is different than seed list EndPoint."); } if (args.NewServerDescription.Type == ServerType.ReplicaSetPrimary) { if (args.NewServerDescription.ReplicaSetConfig.Version != null) { bool isCurrentPrimaryStale = true; if (_maxElectionInfo != null) { isCurrentPrimaryStale = _maxElectionInfo.IsStale(args.NewServerDescription.ReplicaSetConfig.Version.Value, args.NewServerDescription.ElectionId); var isReportedPrimaryStale = _maxElectionInfo.IsFresher( args.NewServerDescription.ReplicaSetConfig.Version.Value, args.NewServerDescription.ElectionId); if (isReportedPrimaryStale && args.NewServerDescription.ElectionId != null) { // we only invalidate the "newly" reported stale primary if electionId was used. lock (_serversLock) { var server = _servers.SingleOrDefault(x => EndPointHelper.Equals(args.NewServerDescription.EndPoint, x.EndPoint)); server.Invalidate(); _sdamInformationEventHandler?.Invoke(new SdamInformationEvent(() => string.Format( @"Invalidating server: Setting ServerType to ""Unknown"" for {0} because it " + @"claimed to be the replica set primary for replica set ""{1}"" but sent a " + @"(setVersion, electionId) tuple of ({2}, {3}) that was less than than the " + @"largest tuple seen, (maxSetVersion, maxElectionId), of ({4}, {5}).", args.NewServerDescription.EndPoint, args.NewServerDescription.ReplicaSetConfig.Name, args.NewServerDescription.ReplicaSetConfig.Version, args.NewServerDescription.ElectionId, _maxElectionInfo.SetVersion, _maxElectionInfo.ElectionId))); return clusterDescription.WithServerDescription( new ServerDescription(server.ServerId, server.EndPoint)); } } } if (isCurrentPrimaryStale) { if (_maxElectionInfo == null) { _sdamInformationEventHandler?.Invoke(new SdamInformationEvent(() => string.Format( @"Initializing (maxSetVersion, maxElectionId): Saving tuple " + @"(setVersion, electionId) of ({0}, {1}) as (maxSetVersion, maxElectionId) for " + @"replica set ""{2}"" because replica set primary {3} sent ({0}, {1}), the first " + @"(setVersion, electionId) tuple ever seen for replica set ""{4}"".", args.NewServerDescription.ReplicaSetConfig.Version, args.NewServerDescription.ElectionId, args.NewServerDescription.ReplicaSetConfig.Name, args.NewServerDescription.EndPoint, args.NewServerDescription.ReplicaSetConfig.Name))); } else { if (_maxElectionInfo.SetVersion < args.NewServerDescription.ReplicaSetConfig.Version.Value) { _sdamInformationEventHandler?.Invoke(new SdamInformationEvent(() => string.Format( @"Updating stale setVersion: Updating the current " + @"(maxSetVersion, maxElectionId) tuple from ({0}, {1}) to ({2}, {3}) for " + @"replica set ""{4}"" because replica set primary {5} sent ({6}, {7})—a larger " + @"(setVersion, electionId) tuple then the saved tuple, ({0}, {1}).", _maxElectionInfo.SetVersion, _maxElectionInfo.ElectionId, args.NewServerDescription.ReplicaSetConfig.Version, args.NewServerDescription.ElectionId, args.NewServerDescription.ReplicaSetConfig.Name, args.NewServerDescription.EndPoint, args.NewServerDescription.ReplicaSetConfig.Version, args.NewServerDescription.ElectionId))) ; } else // current primary is stale & setVersion is not stale ⇒ the electionId must be stale { _sdamInformationEventHandler?.Invoke(new SdamInformationEvent(() => string.Format( @"Updating stale electionId: Updating the current " + @"(maxSetVersion, maxElectionId) tuple from ({0}, {1}) to ({2}, {3}) for " + @"replica set ""{4}"" because replica set primary {5} sent ({6}, {7})—" + @"a larger (setVersion, electionId) tuple than the saved tuple, ({0}, {1}).", _maxElectionInfo.SetVersion, _maxElectionInfo.ElectionId, args.NewServerDescription.ReplicaSetConfig.Version, args.NewServerDescription.ElectionId, args.NewServerDescription.ReplicaSetConfig.Name, args.NewServerDescription.EndPoint, args.NewServerDescription.ReplicaSetConfig.Version, args.NewServerDescription.ElectionId))); } } _maxElectionInfo = new ElectionInfo( args.NewServerDescription.ReplicaSetConfig.Version.Value, args.NewServerDescription.ElectionId); } } var currentPrimaryEndPoints = clusterDescription.Servers .Where(x => x.Type == ServerType.ReplicaSetPrimary) .Where(x => !EndPointHelper.Equals(x.EndPoint, args.NewServerDescription.EndPoint)) .Select(x => x.EndPoint) .ToList(); if (currentPrimaryEndPoints.Count > 0) { lock (_serversLock) { var currentPrimaries = _servers.Where(x => EndPointHelper.Contains(currentPrimaryEndPoints, x.EndPoint)); foreach (var currentPrimary in currentPrimaries) { // kick off the server to invalidate itself currentPrimary.Invalidate(); // set it to disconnected in the cluster clusterDescription = clusterDescription.WithServerDescription( new ServerDescription(currentPrimary.ServerId, currentPrimary.EndPoint)); } } } } return clusterDescription; } private ClusterDescription ProcessShardedChange(ClusterDescription clusterDescription, ServerDescriptionChangedEventArgs args) { if (args.NewServerDescription.Type != ServerType.ShardRouter) { return RemoveServer(clusterDescription, args.NewServerDescription.EndPoint, "Server is not a shard router."); } return clusterDescription.WithServerDescription(args.NewServerDescription); } private ClusterDescription EnsureServer(ClusterDescription clusterDescription, EndPoint endPoint, List<IClusterableServer> newServers) { if (_state.Value == State.Disposed) { return clusterDescription; } IClusterableServer server; Stopwatch stopwatch = new Stopwatch(); lock (_serversLock) { if (_servers.Any(n => EndPointHelper.Equals(n.EndPoint, endPoint))) { return clusterDescription; } if (_addingServerEventHandler != null) { _addingServerEventHandler(new ClusterAddingServerEvent(ClusterId, endPoint)); } stopwatch.Start(); server = CreateServer(endPoint); server.DescriptionChanged += ServerDescriptionChangedHandler; _servers.Add(server); newServers.Add(server); } clusterDescription = clusterDescription.WithServerDescription(server.Description); stopwatch.Stop(); if (_addedServerEventHandler != null) { _addedServerEventHandler(new ClusterAddedServerEvent(server.ServerId, stopwatch.Elapsed)); } return clusterDescription; } private ClusterDescription EnsureServers(ClusterDescription clusterDescription, ServerDescription serverDescription, List<IClusterableServer> newServers) { if (serverDescription.Type == ServerType.ReplicaSetPrimary || !clusterDescription.Servers.Any(x => x.Type == ServerType.ReplicaSetPrimary)) { foreach (var endPoint in serverDescription.ReplicaSetConfig.Members) { clusterDescription = EnsureServer(clusterDescription, endPoint, newServers); } } if (serverDescription.Type == ServerType.ReplicaSetPrimary) { var requiredEndPoints = serverDescription.ReplicaSetConfig.Members; var extraEndPoints = clusterDescription.Servers.Where(x => !EndPointHelper.Contains(requiredEndPoints, x.EndPoint)).Select(x => x.EndPoint); foreach (var endPoint in extraEndPoints) { clusterDescription = RemoveServer(clusterDescription, endPoint, "Server is not in the host list of the primary."); } } return clusterDescription; } private ClusterDescription RemoveServer(ClusterDescription clusterDescription, EndPoint endPoint, string reason) { IClusterableServer server; var stopwatch = new Stopwatch(); lock (_serversLock) { server = _servers.SingleOrDefault(x => EndPointHelper.Equals(x.EndPoint, endPoint)); if (server == null) { return clusterDescription; } if (_removingServerEventHandler != null) { _removingServerEventHandler(new ClusterRemovingServerEvent(server.ServerId, reason)); } stopwatch.Start(); _servers.Remove(server); } server.DescriptionChanged -= ServerDescriptionChangedHandler; server.Dispose(); stopwatch.Stop(); if (_removedServerEventHandler != null) { _removedServerEventHandler(new ClusterRemovedServerEvent(server.ServerId, reason, stopwatch.Elapsed)); } return clusterDescription.WithoutServerDescription(endPoint); } protected override bool TryGetServer(EndPoint endPoint, out IClusterableServer server) { lock (_serversLock) { server = _servers.FirstOrDefault(s => EndPointHelper.Equals(s.EndPoint, endPoint)); return server != null; } } private void ThrowIfDisposed() { if (_state.Value == State.Disposed) { throw new ObjectDisposedException(GetType().Name); } } // nested classes private static class State { public const int Initial = 0; public const int Open = 1; public const int Disposed = 2; } private class ElectionInfo { private readonly int _setVersion; private readonly ElectionId _electionId; public ElectionInfo(int setVersion, ElectionId electionId) { _setVersion = setVersion; _electionId = electionId; } public int SetVersion => _setVersion; public ElectionId ElectionId => _electionId; public bool IsFresher(int setVersion, ElectionId electionId) { return _setVersion > setVersion || _setVersion == setVersion && _electionId != null && _electionId.CompareTo(electionId) > 0; } public bool IsStale(int setVersion, ElectionId electionId) { if (_setVersion < setVersion) { return true; } if (_setVersion > setVersion) { return false; } // Now it must be that _setVersion == setVersion if (_electionId == null) { return true; } return _electionId.CompareTo(electionId) < 0; /* above is equivalent to: * return * _setVersion < setVersion * || _setVersion == setVersion && (_electionId == null || _electionId.CompareTo(electionId) < 0); */ } } } } <|start_filename|>Unity/Assets/Model/Base/Object/ISerializeToEntity.cs<|end_filename|> namespace ETModel { public interface ISerializeToEntity { } } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/Serialization/Conventions/NamedExtraElementsMemberConvention.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.Linq; using System.Reflection; namespace MongoDB.Bson.Serialization.Conventions { /// <summary> /// A convention that finds the extra elements member by name (and that is also of type <see cref="BsonDocument"/> or <see cref="IDictionary{String, Object}"/>). /// </summary> public class NamedExtraElementsMemberConvention : ConventionBase, IClassMapConvention { // private fields private readonly IEnumerable<string> _names; private readonly MemberTypes _memberTypes; private readonly BindingFlags _bindingFlags; // constructors /// <summary> /// Initializes a new instance of the NamedExtraElementsMemberConvention class. /// </summary> /// <param name="name">The name of the extra elements member.</param> public NamedExtraElementsMemberConvention(string name) : this(new [] { name }) { } /// <summary> /// Initializes a new instance of the <see cref="NamedExtraElementsMemberConvention" /> class. /// </summary> /// <param name="names">The names.</param> public NamedExtraElementsMemberConvention(IEnumerable<string> names) : this(names, BindingFlags.Instance | BindingFlags.Public) { } /// <summary> /// Initializes a new instance of the <see cref="NamedExtraElementsMemberConvention" /> class. /// </summary> /// <param name="names">The names.</param> /// <param name="memberTypes">The member types.</param> public NamedExtraElementsMemberConvention(IEnumerable<string> names, MemberTypes memberTypes) : this(names, memberTypes, BindingFlags.Instance | BindingFlags.Public) { } /// <summary> /// Initializes a new instance of the <see cref="NamedExtraElementsMemberConvention" /> class. /// </summary> /// <param name="names">The names.</param> /// <param name="bindingFlags">The binding flags.</param> public NamedExtraElementsMemberConvention(IEnumerable<string> names, BindingFlags bindingFlags) : this(names, MemberTypes.Field | MemberTypes.Property, bindingFlags) { } /// <summary> /// Initializes a new instance of the <see cref="NamedExtraElementsMemberConvention" /> class. /// </summary> /// <param name="names">The names.</param> /// <param name="memberTypes">The member types.</param> /// <param name="bindingFlags">The binding flags.</param> /// <exception cref="System.ArgumentNullException"></exception> public NamedExtraElementsMemberConvention(IEnumerable<string> names, MemberTypes memberTypes, BindingFlags bindingFlags) { if (names == null) { throw new ArgumentNullException("names"); } _names = names; _memberTypes = memberTypes; _bindingFlags = bindingFlags | BindingFlags.DeclaredOnly; } // public methods /// <summary> /// Applies a modification to the class map. /// </summary> /// <param name="classMap">The class map.</param> public void Apply(BsonClassMap classMap) { var classTypeInfo = classMap.ClassType.GetTypeInfo(); foreach (var name in _names) { var member = classTypeInfo.GetMember(name, _memberTypes, _bindingFlags).SingleOrDefault(); if (member != null) { Type memberType = null; var fieldInfo = member as FieldInfo; if (fieldInfo != null) { memberType = fieldInfo.FieldType; } else { var propertyInfo = member as PropertyInfo; if (propertyInfo != null) { memberType = propertyInfo.PropertyType; } } if (memberType != null && (memberType == typeof(BsonDocument) || typeof(IDictionary<string, object>).GetTypeInfo().IsAssignableFrom(memberType))) { classMap.MapExtraElementsMember(member); return; } } } } } } <|start_filename|>Unity/Assets/ThirdParty/ILRuntime/Mono.Cecil/Mono.Cecil/GenericParameterAttributes.cs<|end_filename|> // // Author: // <NAME> (<EMAIL>) // // Copyright (c) 2008 - 2015 <NAME> // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; namespace Mono.Cecil { [Flags] public enum GenericParameterAttributes : ushort { VarianceMask = 0x0003, NonVariant = 0x0000, Covariant = 0x0001, Contravariant = 0x0002, SpecialConstraintMask = 0x001c, ReferenceTypeConstraint = 0x0004, NotNullableValueTypeConstraint = 0x0008, DefaultConstructorConstraint = 0x0010 } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/Linq/MongoQueryableImpl.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Linq { internal sealed class MongoQueryableImpl<TInput, TOutput> : IOrderedMongoQueryable<TOutput> { private readonly IMongoQueryProvider _queryProvider; private readonly Expression _expression; public MongoQueryableImpl(IMongoQueryProvider queryProvider) { _queryProvider = Ensure.IsNotNull(queryProvider, nameof(queryProvider)); _expression = Expression.Constant(this, typeof(IMongoQueryable<TOutput>)); } public MongoQueryableImpl(IMongoQueryProvider queryProvider, Expression expression) { _queryProvider = Ensure.IsNotNull(queryProvider, nameof(queryProvider)); _expression = Ensure.IsNotNull(expression, nameof(expression)); } public Type ElementType { get { return typeof(TOutput); } } public Expression Expression { get { return _expression; } } public IQueryProvider Provider { get { return _queryProvider; } } public IEnumerator<TOutput> GetEnumerator() { var results = (IEnumerable<TOutput>)_queryProvider.Execute(_expression); return results.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public QueryableExecutionModel GetExecutionModel() { return _queryProvider.GetExecutionModel(_expression); } public IAsyncCursor<TOutput> ToCursor(CancellationToken cancellationToken) { var model = _queryProvider.GetExecutionModel(_expression); var mongoQueryProvider = (MongoQueryProviderImpl<TInput>)_queryProvider; return (IAsyncCursor<TOutput>)mongoQueryProvider.ExecuteModel(model); } public Task<IAsyncCursor<TOutput>> ToCursorAsync(CancellationToken cancellationToken) { return _queryProvider.ExecuteAsync<IAsyncCursor<TOutput>>(_expression, cancellationToken); } public override string ToString() { var pipeline = GetExecutionModel(); return pipeline.ToString(); } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouchControls/Plugins/ETCInput.cs<|end_filename|> /*********************************************** EasyTouch Controls Copyright © 2016 The Hedgehog Team http://www.thehedgehogteam.com/Forum/ <EMAIL> **********************************************/ using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; using UnityEngine.Events; using UnityEngine.EventSystems; //ETCSingleton<ETCInput> public class ETCInput : MonoBehaviour{ public static ETCInput _instance = null; public static ETCInput instance{ get{ if( !_instance ){ // check if an ObjectPoolManager is already available in the scene graph _instance = FindObjectOfType( typeof( ETCInput ) ) as ETCInput; // nope, create a new one if( !_instance ){ GameObject obj = new GameObject( "InputManager" ); _instance = obj.AddComponent<ETCInput>(); } } return _instance; } } private Dictionary<string,ETCAxis> axes = new Dictionary<string,ETCAxis>(); private Dictionary<string, ETCBase> controls = new Dictionary<string, ETCBase>(); private static ETCBase control; private static ETCAxis axis; #region Control public void RegisterControl(ETCBase ctrl){ if (controls.ContainsKey( ctrl.name)){ Debug.LogWarning("ETCInput control : " + ctrl.name + " already exists"); } else{ controls.Add( ctrl.name, ctrl); if (ctrl.GetType() == typeof(ETCJoystick) ){ RegisterAxis( (ctrl as ETCJoystick).axisX ); RegisterAxis( (ctrl as ETCJoystick).axisY ); } else if (ctrl.GetType() == typeof(ETCTouchPad) ){ RegisterAxis( (ctrl as ETCTouchPad).axisX ); RegisterAxis( (ctrl as ETCTouchPad).axisY ); } else if (ctrl.GetType() == typeof(ETCDPad) ){ RegisterAxis( (ctrl as ETCDPad).axisX ); RegisterAxis( (ctrl as ETCDPad).axisY ); } else if (ctrl.GetType() == typeof(ETCButton)){ RegisterAxis( (ctrl as ETCButton).axis ); } } } public void UnRegisterControl(ETCBase ctrl){ if (controls.ContainsKey( ctrl.name) && ctrl.enabled ){ controls.Remove( ctrl.name); if (ctrl.GetType() == typeof(ETCJoystick) ){ UnRegisterAxis( (ctrl as ETCJoystick).axisX ); UnRegisterAxis( (ctrl as ETCJoystick).axisY ); } else if (ctrl.GetType() == typeof(ETCTouchPad) ){ UnRegisterAxis( (ctrl as ETCTouchPad).axisX ); UnRegisterAxis( (ctrl as ETCTouchPad).axisY ); } else if (ctrl.GetType() == typeof(ETCDPad) ){ UnRegisterAxis( (ctrl as ETCDPad).axisX ); UnRegisterAxis( (ctrl as ETCDPad).axisY ); } else if (ctrl.GetType() == typeof(ETCButton)){ UnRegisterAxis( (ctrl as ETCButton).axis ); } } } public void Create(){ } public static void Register(ETCBase ctrl){ ETCInput.instance.RegisterControl( ctrl); } public static void UnRegister(ETCBase ctrl){ ETCInput.instance.UnRegisterControl( ctrl); } public static void SetControlVisible(string ctrlName,bool value){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ control.visible = value; } else{ Debug.LogWarning("ETCInput : " + ctrlName + " doesn't exist"); } } public static bool GetControlVisible(string ctrlName){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ return control.visible; } else{ Debug.LogWarning("ETCInput : " + ctrlName + " doesn't exist"); return false; } } public static void SetControlActivated(string ctrlName,bool value){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ control.activated = value; } else{ Debug.LogWarning("ETCInput : " + ctrlName + " doesn't exist"); } } public static bool GetControlActivated(string ctrlName){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ return control.activated; } else{ Debug.LogWarning("ETCInput : " + ctrlName + " doesn't exist"); return false; } } public static void SetControlSwipeIn(string ctrlName,bool value){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ control.isSwipeIn = value; } else{ Debug.LogWarning("ETCInput : " + ctrlName + " doesn't exist"); } } public static bool GetControlSwipeIn(string ctrlName){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ return control.isSwipeIn; } else{ Debug.LogWarning("ETCInput : " + ctrlName + " doesn't exist"); return false; } } public static void SetControlSwipeOut(string ctrlName,bool value){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ control.isSwipeOut = value; } else{ Debug.LogWarning("ETCInput : " + ctrlName + " doesn't exist"); } } public static bool GetControlSwipeOut(string ctrlName,bool value){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ return control.isSwipeOut ; } else{ Debug.LogWarning("ETCInput : " + ctrlName + " doesn't exist"); return false; } } public static void SetDPadAxesCount(string ctrlName, ETCBase.DPadAxis value){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ control.dPadAxisCount = value; } else{ Debug.LogWarning("ETCInput : " + ctrlName + " doesn't exist"); } } public static ETCBase.DPadAxis GetDPadAxesCount(string ctrlName){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ return control.dPadAxisCount; } else{ Debug.LogWarning("ETCInput : " + ctrlName + " doesn't exist"); return ETCBase.DPadAxis.Two_Axis; } } #endregion #region New 2.0 // Control public static ETCJoystick GetControlJoystick(string ctrlName){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ if (control.GetType() == typeof(ETCJoystick)){ ETCJoystick tmpJoy = (ETCJoystick)control; return tmpJoy; } } return null; } public static ETCDPad GetControlDPad(string ctrlName){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ if (control.GetType() == typeof(ETCDPad)){ ETCDPad tmpctrl = (ETCDPad)control; return tmpctrl; } } return null; } public static ETCTouchPad GetControlTouchPad(string ctrlName){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ if (control.GetType() == typeof(ETCTouchPad)){ ETCTouchPad tmpctrl = (ETCTouchPad)control; return tmpctrl; } } return null; } public static ETCButton GetControlButton(string ctrlName){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ if (control.GetType() == typeof(ETCJoystick)){ ETCButton tmpctrl = (ETCButton)control; return tmpctrl; } } return null; } //Image public static void SetControlSprite(string ctrlName,Sprite spr,Color color = default(Color)){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ Image img = control.GetComponent<Image>(); if (img){ img.sprite = spr; img.color = color; } } } public static void SetJoystickThumbSprite(string ctrlName,Sprite spr,Color color = default(Color)){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ if (control.GetType() == typeof(ETCJoystick)){ ETCJoystick tmpJoy = (ETCJoystick)control; if (tmpJoy){ Image img = tmpJoy.thumb.GetComponent<Image>(); if (img){ img.sprite = spr; img.color = color; } } } } } public static void SetButtonSprite(string ctrlName, Sprite sprNormal,Sprite sprPress,Color color = default(Color)){ if (ETCInput.instance.controls.TryGetValue( ctrlName, out control)){ ETCButton btn = control.GetComponent<ETCButton>(); btn.normalSprite = sprNormal; btn.normalColor = color; btn.pressedColor = color; btn.pressedSprite = sprPress; SetControlSprite( ctrlName,sprNormal,color); } } // Axes public static void SetAxisSpeed(string axisName, float speed){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.speed = speed; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static void SetAxisGravity(string axisName, float gravity){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.gravity = gravity; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static void SetTurnMoveSpeed(string ctrlName, float speed){ ETCJoystick joy = GetControlJoystick( ctrlName); if (joy){ joy.tmSpeed = speed; } } #endregion #region Axes public static void ResetAxis(string axisName ){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.axisValue = 0; axis.axisSpeedValue =0; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static void SetAxisEnabled(string axisName,bool value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.enable = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static bool GetAxisEnabled(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.enable; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return false; } } public static void SetAxisInverted(string axisName, bool value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.invertedAxis = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static bool GetAxisInverted(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.invertedAxis; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return false; } } public static void SetAxisDeadValue(string axisName, float value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.deadValue = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static float GetAxisDeadValue(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.deadValue; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return -1; } } public static void SetAxisSensitivity(string axisName, float value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.speed = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static float GetAxisSensitivity(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.speed; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return -1; } } public static void SetAxisThreshold(string axisName, float value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.axisThreshold = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static float GetAxisThreshold(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.axisThreshold; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return -1; } } public static void SetAxisInertia(string axisName, bool value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.isEnertia = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static bool GetAxisInertia(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.isEnertia; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return false; } } public static void SetAxisInertiaSpeed(string axisName, float value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.inertia = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static float GetAxisInertiaSpeed(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.inertia; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return -1; } } public static void SetAxisInertiaThreshold( string axisName, float value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.inertiaThreshold = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static float GetAxisInertiaThreshold( string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.inertiaThreshold; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return -1; } } public static void SetAxisAutoStabilization( string axisName, bool value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.isAutoStab = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static bool GetAxisAutoStabilization(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.isAutoStab; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return false; } } public static void SetAxisAutoStabilizationSpeed( string axisName, float value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.autoStabSpeed = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static float GetAxisAutoStabilizationSpeed(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.autoStabSpeed; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return -1; } } public static void SetAxisAutoStabilizationThreshold( string axisName, float value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.autoStabThreshold = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static float GetAxisAutoStabilizationThreshold(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.autoStabThreshold; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return -1; } } public static void SetAxisClampRotation(string axisName, bool value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.isClampRotation = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static bool GetAxisClampRotation(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.isClampRotation; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return false; } } public static void SetAxisClampRotationValue(string axisName, float min, float max){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.minAngle = min; axis.maxAngle = max; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static void SetAxisClampRotationMinValue(string axisName, float value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.minAngle = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static void SetAxisClampRotationMaxValue(string axisName, float value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.maxAngle = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static float GetAxisClampRotationMinValue(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.minAngle; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return -1; } } public static float GetAxisClampRotationMaxValue(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.maxAngle; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return -1; } } public static void SetAxisDirecTransform(string axisName, Transform value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.directTransform = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static Transform GetAxisDirectTransform( string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.directTransform; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return null; } } public static void SetAxisDirectAction(string axisName, ETCAxis.DirectAction value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.directAction = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static ETCAxis.DirectAction GetAxisDirectAction(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.directAction; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return ETCAxis.DirectAction.Rotate; } } public static void SetAxisAffectedAxis(string axisName, ETCAxis.AxisInfluenced value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.axisInfluenced = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static ETCAxis.AxisInfluenced GetAxisAffectedAxis(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.axisInfluenced; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return ETCAxis.AxisInfluenced.X; } } public static void SetAxisOverTime(string axisName, bool value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.isValueOverTime = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static bool GetAxisOverTime(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.isValueOverTime; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return false; } } public static void SetAxisOverTimeStep(string axisName, float value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.overTimeStep = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static float GetAxisOverTimeStep(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.overTimeStep; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return -1; } } public static void SetAxisOverTimeMaxValue(string axisName, float value){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ axis.maxOverTimeValue = value; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); } } public static float GetAxisOverTimeMaxValue(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.maxOverTimeValue; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return -1; } } public static float GetAxis(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.axisValue; } else{ Debug.LogWarning("ETCInput : " + axisName + " doesn't exist"); return 0; } } public static float GetAxisSpeed(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ return axis.axisSpeedValue; } else{ Debug.LogWarning(axisName + " doesn't exist"); return 0; } } public static bool GetAxisDownUp(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ if (axis.axisState == ETCAxis.AxisState.DownUp){ return true; } else{ return false; } } else{ Debug.LogWarning(axisName + " doesn't exist"); return false; } } public static bool GetAxisDownDown(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ if (axis.axisState == ETCAxis.AxisState.DownDown){ return true; } else{ return false; } } else{ Debug.LogWarning(axisName + " doesn't exist"); return false; } } public static bool GetAxisDownRight(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ if (axis.axisState == ETCAxis.AxisState.DownRight){ return true; } else{ return false; } } else{ Debug.LogWarning(axisName + " doesn't exist"); return false; } } public static bool GetAxisDownLeft(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ if (axis.axisState == ETCAxis.AxisState.DownLeft){ return true; } else{ return false; } } else{ Debug.LogWarning(axisName + " doesn't exist"); return false; } } public static bool GetAxisPressedUp(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ if (axis.axisState == ETCAxis.AxisState.PressUp){ return true; } else{ return false; } } else{ Debug.LogWarning(axisName + " doesn't exist"); return false; } } public static bool GetAxisPressedDown(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ if (axis.axisState == ETCAxis.AxisState.PressDown){ return true; } else{ return false; } } else{ Debug.LogWarning(axisName + " doesn't exist"); return false; } } public static bool GetAxisPressedRight(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ if (axis.axisState == ETCAxis.AxisState.PressRight){ return true; } else{ return false; } } else{ Debug.LogWarning(axisName + " doesn't exist"); return false; } } public static bool GetAxisPressedLeft(string axisName){ if (ETCInput.instance.axes.TryGetValue( axisName, out axis)){ if (axis.axisState == ETCAxis.AxisState.PressLeft){ return true; } else{ return false; } } else{ Debug.LogWarning(axisName + " doesn't exist"); return false; } } public static bool GetButtonDown(string buttonName){ if (ETCInput.instance.axes.TryGetValue( buttonName, out axis)){ if (axis.axisState == ETCAxis.AxisState.Down ){ return true; } else{ return false; } } else{ Debug.LogWarning(buttonName + " doesn't exist"); return false; } } public static bool GetButton(string buttonName){ if (ETCInput.instance.axes.TryGetValue( buttonName, out axis)){ if (axis.axisState == ETCAxis.AxisState.Down || axis.axisState == ETCAxis.AxisState.Press){ return true; } else{ return false; } } else{ Debug.LogWarning(buttonName + " doesn't exist"); return false; } } public static bool GetButtonUp(string buttonName){ if (ETCInput.instance.axes.TryGetValue( buttonName, out axis)){ if (axis.axisState == ETCAxis.AxisState.Up ){ return true; } else{ return false; } } else{ Debug.LogWarning(buttonName + " doesn't exist"); return false; } } public static float GetButtonValue(string buttonName){ if (ETCInput.instance.axes.TryGetValue( buttonName, out axis)){ return axis.axisValue; } else{ Debug.LogWarning(buttonName + " doesn't exist"); return -1; } } #endregion #region private Method private void RegisterAxis(ETCAxis axis){ if (ETCInput.instance.axes.ContainsKey( axis.name)){ Debug.LogWarning("ETCInput axis : " + axis.name + " already exists"); } else{ axes.Add( axis.name,axis); } } private void UnRegisterAxis(ETCAxis axis){ if (ETCInput.instance.axes.ContainsKey( axis.name)){ axes.Remove( axis.name); } } #endregion } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/IO/BsonReader.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.IO; using System.Linq; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; namespace MongoDB.Bson.IO { /// <summary> /// Represents a BSON reader for some external format (see subclasses). /// </summary> public abstract class BsonReader : IBsonReader { // private fields private bool _disposed = false; private BsonReaderSettings _settings; private BsonReaderState _state; private BsonType _currentBsonType; private string _currentName; // constructors /// <summary> /// Initializes a new instance of the BsonReader class. /// </summary> /// <param name="settings">The reader settings.</param> protected BsonReader(BsonReaderSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } _settings = settings.FrozenCopy(); _state = BsonReaderState.Initial; } // public properties /// <summary> /// Gets the current BsonType. /// </summary> public BsonType CurrentBsonType { get { return _currentBsonType; } protected set { _currentBsonType = value; } } /// <summary> /// Gets the settings of the reader. /// </summary> public BsonReaderSettings Settings { get { return _settings; } } /// <summary> /// Gets the current state of the reader. /// </summary> public BsonReaderState State { get { return _state; } protected set { _state = value; } } // protected properties /// <summary> /// Gets the current name. /// </summary> protected string CurrentName { get { return _currentName; } set { _currentName = value; } } /// <summary> /// Gets whether the BsonReader has been disposed. /// </summary> protected bool Disposed { get { return _disposed; } } // public methods /// <summary> /// Closes the reader. /// </summary> public abstract void Close(); /// <summary> /// Disposes of any resources used by the reader. /// </summary> public void Dispose() { if (!_disposed) { Dispose(true); _disposed = true; } } /// <summary> /// Gets a bookmark to the reader's current position and state. /// </summary> /// <returns>A bookmark.</returns> public abstract BsonReaderBookmark GetBookmark(); /// <summary> /// Gets the current BsonType (calls ReadBsonType if necessary). /// </summary> /// <returns>The current BsonType.</returns> public BsonType GetCurrentBsonType() { if (_state == BsonReaderState.Initial || _state == BsonReaderState.ScopeDocument || _state == BsonReaderState.Type) { ReadBsonType(); } if (_state != BsonReaderState.Value) { ThrowInvalidState("GetCurrentBsonType", BsonReaderState.Value); } return _currentBsonType; } /// <summary> /// Determines whether this reader is at end of file. /// </summary> /// <returns> /// Whether this reader is at end of file. /// </returns> public abstract bool IsAtEndOfFile(); /// <summary> /// Reads BSON binary data from the reader. /// </summary> /// <returns>A BsonBinaryData.</returns> public abstract BsonBinaryData ReadBinaryData(); /// <summary> /// Reads a BSON boolean from the reader. /// </summary> /// <returns>A Boolean.</returns> public abstract bool ReadBoolean(); /// <summary> /// Reads a BsonType from the reader. /// </summary> /// <returns>A BsonType.</returns> public abstract BsonType ReadBsonType(); /// <summary> /// Reads BSON binary data from the reader. /// </summary> /// <returns>A byte array.</returns> public abstract byte[] ReadBytes(); /// <summary> /// Reads a BSON DateTime from the reader. /// </summary> /// <returns>The number of milliseconds since the Unix epoch.</returns> public abstract long ReadDateTime(); /// <inheritdoc /> public abstract Decimal128 ReadDecimal128(); /// <summary> /// Reads a BSON Double from the reader. /// </summary> /// <returns>A Double.</returns> public abstract double ReadDouble(); /// <summary> /// Reads the end of a BSON array from the reader. /// </summary> public abstract void ReadEndArray(); /// <summary> /// Reads the end of a BSON document from the reader. /// </summary> public abstract void ReadEndDocument(); /// <summary> /// Reads a BSON Int32 from the reader. /// </summary> /// <returns>An Int32.</returns> public abstract int ReadInt32(); /// <summary> /// Reads a BSON Int64 from the reader. /// </summary> /// <returns>An Int64.</returns> public abstract long ReadInt64(); /// <summary> /// Reads a BSON JavaScript from the reader. /// </summary> /// <returns>A string.</returns> public abstract string ReadJavaScript(); /// <summary> /// Reads a BSON JavaScript with scope from the reader (call ReadStartDocument next to read the scope). /// </summary> /// <returns>A string.</returns> public abstract string ReadJavaScriptWithScope(); /// <summary> /// Reads a BSON MaxKey from the reader. /// </summary> public abstract void ReadMaxKey(); /// <summary> /// Reads a BSON MinKey from the reader. /// </summary> public abstract void ReadMinKey(); /// <summary> /// Reads the name of an element from the reader. /// </summary> /// <returns>The name of the element.</returns> public virtual string ReadName() { return ReadName(Utf8NameDecoder.Instance); } /// <summary> /// Reads the name of an element from the reader (using the provided name decoder). /// </summary> /// <param name="nameDecoder">The name decoder.</param> /// <returns> /// The name of the element. /// </returns> public abstract string ReadName(INameDecoder nameDecoder); /// <summary> /// Reads a BSON null from the reader. /// </summary> public abstract void ReadNull(); /// <summary> /// Reads a BSON ObjectId from the reader. /// </summary> /// <returns>An ObjectId.</returns> public abstract ObjectId ReadObjectId(); /// <summary> /// Reads a raw BSON array. /// </summary> /// <returns>The raw BSON array.</returns> public virtual IByteBuffer ReadRawBsonArray() { // overridden in BsonBinaryReader to read the raw bytes from the stream // for all other streams, deserialize the array and reserialize it using a BsonBinaryWriter to get the raw bytes var deserializationContext = BsonDeserializationContext.CreateRoot(this); var array = BsonArraySerializer.Instance.Deserialize(deserializationContext); using (var memoryStream = new MemoryStream()) using (var bsonWriter = new BsonBinaryWriter(memoryStream, BsonBinaryWriterSettings.Defaults)) { var serializationContext = BsonSerializationContext.CreateRoot(bsonWriter); bsonWriter.WriteStartDocument(); var startPosition = memoryStream.Position + 3; // just past BsonType, "x" and null byte bsonWriter.WriteName("x"); BsonArraySerializer.Instance.Serialize(serializationContext, array); var endPosition = memoryStream.Position; bsonWriter.WriteEndDocument(); byte[] memoryStreamBuffer; #if NETSTANDARD1_5 || NETSTANDARD1_6 memoryStreamBuffer = memoryStream.ToArray(); #else memoryStreamBuffer = memoryStream.GetBuffer(); #endif var buffer = new ByteArrayBuffer(memoryStreamBuffer, (int)memoryStream.Length, isReadOnly: true); return new ByteBufferSlice(buffer, (int)startPosition, (int)(endPosition - startPosition)); } } /// <summary> /// Reads a raw BSON document. /// </summary> /// <returns>The raw BSON document.</returns> public virtual IByteBuffer ReadRawBsonDocument() { // overridden in BsonBinaryReader to read the raw bytes from the stream // for all other streams, deserialize the document and use ToBson to get the raw bytes var deserializationContext = BsonDeserializationContext.CreateRoot(this); var document = BsonDocumentSerializer.Instance.Deserialize(deserializationContext); var bytes = document.ToBson(); return new ByteArrayBuffer(bytes, isReadOnly: true); } /// <summary> /// Reads a BSON regular expression from the reader. /// </summary> /// <returns>A BsonRegularExpression.</returns> public abstract BsonRegularExpression ReadRegularExpression(); /// <summary> /// Reads the start of a BSON array. /// </summary> public abstract void ReadStartArray(); /// <summary> /// Reads the start of a BSON document. /// </summary> public abstract void ReadStartDocument(); /// <summary> /// Reads a BSON string from the reader. /// </summary> /// <returns>A String.</returns> public abstract string ReadString(); /// <summary> /// Reads a BSON symbol from the reader. /// </summary> /// <returns>A string.</returns> public abstract string ReadSymbol(); /// <summary> /// Reads a BSON timestamp from the reader. /// </summary> /// <returns>The combined timestamp/increment.</returns> public abstract long ReadTimestamp(); /// <summary> /// Reads a BSON undefined from the reader. /// </summary> public abstract void ReadUndefined(); /// <summary> /// Returns the reader to previously bookmarked position and state. /// </summary> /// <param name="bookmark">The bookmark.</param> public abstract void ReturnToBookmark(BsonReaderBookmark bookmark); /// <summary> /// Skips the name (reader must be positioned on a name). /// </summary> public abstract void SkipName(); /// <summary> /// Skips the value (reader must be positioned on a value). /// </summary> public abstract void SkipValue(); // protected methods /// <summary> /// Disposes of any resources used by the reader. /// </summary> /// <param name="disposing">True if called from Dispose.</param> protected virtual void Dispose(bool disposing) { } /// <summary> /// Throws an InvalidOperationException when the method called is not valid for the current ContextType. /// </summary> /// <param name="methodName">The name of the method.</param> /// <param name="actualContextType">The actual ContextType.</param> /// <param name="validContextTypes">The valid ContextTypes.</param> protected void ThrowInvalidContextType( string methodName, ContextType actualContextType, params ContextType[] validContextTypes) { var validContextTypesString = string.Join(" or ", validContextTypes.Select(c => c.ToString()).ToArray()); var message = string.Format( "{0} can only be called when ContextType is {1}, not when ContextType is {2}.", methodName, validContextTypesString, actualContextType); throw new InvalidOperationException(message); } /// <summary> /// Throws an InvalidOperationException when the method called is not valid for the current state. /// </summary> /// <param name="methodName">The name of the method.</param> /// <param name="validStates">The valid states.</param> protected void ThrowInvalidState(string methodName, params BsonReaderState[] validStates) { var validStatesString = string.Join(" or ", validStates.Select(s => s.ToString()).ToArray()); var message = string.Format( "{0} can only be called when State is {1}, not when State is {2}.", methodName, validStatesString, _state); throw new InvalidOperationException(message); } /// <summary> /// Throws an ObjectDisposedException. /// </summary> protected void ThrowObjectDisposedException() { throw new ObjectDisposedException(this.GetType().Name); } /// <summary> /// Verifies the current state and BsonType of the reader. /// </summary> /// <param name="methodName">The name of the method calling this one.</param> /// <param name="requiredBsonType">The required BSON type.</param> protected void VerifyBsonType(string methodName, BsonType requiredBsonType) { if (_state == BsonReaderState.Initial || _state == BsonReaderState.ScopeDocument || _state == BsonReaderState.Type) { ReadBsonType(); } if (_state == BsonReaderState.Name) { // ignore name SkipName(); } if (_state != BsonReaderState.Value) { ThrowInvalidState(methodName, BsonReaderState.Value); } if (_currentBsonType != requiredBsonType) { var message = string.Format( "{0} can only be called when CurrentBsonType is {1}, not when CurrentBsonType is {2}.", methodName, requiredBsonType, _currentBsonType); throw new InvalidOperationException(message); } } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/Linq/Processors/Transformers/SelectSelectCombiningTransformer.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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.Linq; using System.Linq.Expressions; using MongoDB.Driver.Linq.Expressions; namespace MongoDB.Driver.Linq.Processors.Transformers { internal sealed class SelectSelectCombiningTransformer : IExpressionTransformer<MethodCallExpression> { private readonly ExpressionType[] _supportedNodeTypes = new[] { ExpressionType.Call }; public ExpressionType[] SupportedNodeTypes { get { return _supportedNodeTypes; } } public Expression Transform(MethodCallExpression node) { if (!ExpressionHelper.IsLinqMethod(node, "Select") || !ExpressionHelper.IsLambda(node.Arguments[1], 1)) { return node; } var call = node.Arguments[0] as MethodCallExpression; if (call == null || !ExpressionHelper.IsLinqMethod(call, "Select") || !ExpressionHelper.IsLambda(call.Arguments[1], 1)) { return node; } var innerLambda = ExpressionHelper.GetLambda(call.Arguments[1]); var outerLambda = ExpressionHelper.GetLambda(node.Arguments[1]); var sourceType = innerLambda.Parameters[0].Type; var resultType = outerLambda.Body.Type; var innerSelector = innerLambda.Body; var outerSelector = outerLambda.Body; var selector = ExpressionReplacer.Replace(outerSelector, outerLambda.Parameters[0], innerSelector); return Expression.Call( typeof(Enumerable), "Select", new[] { sourceType, resultType }, call.Arguments[0], Expression.Lambda( typeof(Func<,>).MakeGenericType(sourceType, resultType), selector, innerLambda.Parameters[0])); } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Examples/4.X/UnityUI/UICompatibility/UIWindow.cs<|end_filename|> using UnityEngine; using UnityEngine.EventSystems; using HedgehogTeam.EasyTouch; public class UIWindow : MonoBehaviour, IDragHandler, IPointerDownHandler{ public void OnDrag (PointerEventData eventData){ transform.position += (Vector3)eventData.delta; } public void OnPointerDown (PointerEventData eventData){ transform.SetAsLastSibling(); } } <|start_filename|>Unity/Assets/Model/ILBinding/ETModel_Session_Binding.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class ETModel_Session_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(ETModel.Session); args = new Type[]{typeof(ETModel.IRequest)}; method = type.GetMethod("Call", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Call_0); args = new Type[]{typeof(ETModel.IMessage)}; method = type.GetMethod("Send", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Send_1); args = new Type[]{}; method = type.GetMethod("get_Error", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_Error_2); args = new Type[]{}; method = type.GetMethod("get_Network", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_Network_3); args = new Type[]{typeof(System.UInt16), typeof(System.Object)}; method = type.GetMethod("Send", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Send_4); } static StackObject* Call_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ETModel.IRequest @request = (ETModel.IRequest)typeof(ETModel.IRequest).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); ETModel.Session instance_of_this_method = (ETModel.Session)typeof(ETModel.Session).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.Call(@request); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* Send_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ETModel.IMessage @message = (ETModel.IMessage)typeof(ETModel.IMessage).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); ETModel.Session instance_of_this_method = (ETModel.Session)typeof(ETModel.Session).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.Send(@message); return __ret; } static StackObject* get_Error_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ETModel.Session instance_of_this_method = (ETModel.Session)typeof(ETModel.Session).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.Error; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method; return __ret + 1; } static StackObject* get_Network_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ETModel.Session instance_of_this_method = (ETModel.Session)typeof(ETModel.Session).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.Network; object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* Send_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Object @message = (System.Object)typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.UInt16 @opcode = (ushort)ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 3); ETModel.Session instance_of_this_method = (ETModel.Session)typeof(ETModel.Session).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.Send(@opcode, @message); return __ret; } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/GeoJsonObjectModel/GeoJson.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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 MongoDB.Bson; namespace MongoDB.Driver.GeoJsonObjectModel { /// <summary> /// A static class containing helper methods to create GeoJson objects. /// </summary> public static class GeoJson { // public static methods /// <summary> /// Creates a GeoJson bounding box. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="min">The min.</param> /// <param name="max">The max.</param> /// <returns>A GeoJson bounding box.</returns> public static GeoJsonBoundingBox<TCoordinates> BoundingBox<TCoordinates>(TCoordinates min, TCoordinates max) where TCoordinates : GeoJsonCoordinates { return new GeoJsonBoundingBox<TCoordinates>(min, max); } /// <summary> /// Creates a GeoJson Feature object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="geometry">The geometry.</param> /// <returns>A GeoJson Feature object.</returns> public static GeoJsonFeature<TCoordinates> Feature<TCoordinates>(GeoJsonGeometry<TCoordinates> geometry) where TCoordinates : GeoJsonCoordinates { return new GeoJsonFeature<TCoordinates>(geometry); } /// <summary> /// Creates a GeoJson Feature object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="args">The additional args.</param> /// <param name="geometry">The geometry.</param> /// <returns>A GeoJson Feature object.</returns> public static GeoJsonFeature<TCoordinates> Feature<TCoordinates>(GeoJsonFeatureArgs<TCoordinates> args, GeoJsonGeometry<TCoordinates> geometry) where TCoordinates : GeoJsonCoordinates { return new GeoJsonFeature<TCoordinates>(args, geometry); } /// <summary> /// Creates a GeoJson FeatureCollection object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="args">The additional args.</param> /// <param name="features">The features.</param> /// <returns>A GeoJson FeatureCollection object.</returns> public static GeoJsonFeatureCollection<TCoordinates> FeatureCollection<TCoordinates>(GeoJsonObjectArgs<TCoordinates> args, params GeoJsonFeature<TCoordinates>[] features) where TCoordinates : GeoJsonCoordinates { return new GeoJsonFeatureCollection<TCoordinates>(args, features); } /// <summary> /// Creates a GeoJson FeatureCollection object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="features">The features.</param> /// <returns>A GeoJson FeatureCollection object.</returns> public static GeoJsonFeatureCollection<TCoordinates> FeatureCollection<TCoordinates>(params GeoJsonFeature<TCoordinates>[] features) where TCoordinates : GeoJsonCoordinates { return new GeoJsonFeatureCollection<TCoordinates>(features); } /// <summary> /// Creates a GeoJson 2D geographic position (longitude, latitude). /// </summary> /// <param name="longitude">The longitude.</param> /// <param name="latitude">The latitude.</param> /// <returns>A GeoJson 2D geographic position.</returns> public static GeoJson2DGeographicCoordinates Geographic(double longitude, double latitude) { return new GeoJson2DGeographicCoordinates(longitude, latitude); } /// <summary> /// Creates a GeoJson 3D geographic position (longitude, latitude, altitude). /// </summary> /// <param name="longitude">The longitude.</param> /// <param name="latitude">The latitude.</param> /// <param name="altitude">The altitude.</param> /// <returns>A GeoJson 3D geographic position.</returns> public static GeoJson3DGeographicCoordinates Geographic(double longitude, double latitude, double altitude) { return new GeoJson3DGeographicCoordinates(longitude, latitude, altitude); } /// <summary> /// Creates a GeoJson GeometryCollection object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="args">The additional args.</param> /// <param name="geometries">The geometries.</param> /// <returns>A GeoJson GeometryCollection object.</returns> public static GeoJsonGeometryCollection<TCoordinates> GeometryCollection<TCoordinates>(GeoJsonObjectArgs<TCoordinates> args, params GeoJsonGeometry<TCoordinates>[] geometries) where TCoordinates : GeoJsonCoordinates { return new GeoJsonGeometryCollection<TCoordinates>(args, geometries); } /// <summary> /// Creates a GeoJson GeometryCollection object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="geometries">The geometries.</param> /// <returns>A GeoJson GeometryCollection object.</returns> public static GeoJsonGeometryCollection<TCoordinates> GeometryCollection<TCoordinates>(params GeoJsonGeometry<TCoordinates>[] geometries) where TCoordinates : GeoJsonCoordinates { return new GeoJsonGeometryCollection<TCoordinates>(geometries); } /// <summary> /// Creates the coordinates of a GeoJson linear ring. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="positions">The positions.</param> /// <returns>The coordinates of a GeoJson linear ring.</returns> public static GeoJsonLinearRingCoordinates<TCoordinates> LinearRingCoordinates<TCoordinates>(params TCoordinates[] positions) where TCoordinates : GeoJsonCoordinates { return new GeoJsonLinearRingCoordinates<TCoordinates>(positions); } /// <summary> /// Creates a GeoJson LineString object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="args">The additional args.</param> /// <param name="positions">The positions.</param> /// <returns>A GeoJson LineString object.</returns> public static GeoJsonLineString<TCoordinates> LineString<TCoordinates>(GeoJsonObjectArgs<TCoordinates> args, params TCoordinates[] positions) where TCoordinates : GeoJsonCoordinates { var coordinates = new GeoJsonLineStringCoordinates<TCoordinates>(positions); return new GeoJsonLineString<TCoordinates>(args, coordinates); } /// <summary> /// Creates a GeoJson LineString object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="positions">The positions.</param> /// <returns>A GeoJson LineString object.</returns> public static GeoJsonLineString<TCoordinates> LineString<TCoordinates>(params TCoordinates[] positions) where TCoordinates : GeoJsonCoordinates { var coordinates = new GeoJsonLineStringCoordinates<TCoordinates>(positions); return new GeoJsonLineString<TCoordinates>(coordinates); } /// <summary> /// Creates the coordinates of a GeoJson LineString. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="positions">The positions.</param> /// <returns>The coordinates of a GeoJson LineString.</returns> public static GeoJsonLineStringCoordinates<TCoordinates> LineStringCoordinates<TCoordinates>(params TCoordinates[] positions) where TCoordinates : GeoJsonCoordinates { return new GeoJsonLineStringCoordinates<TCoordinates>(positions); } /// <summary> /// Creates a GeoJson MultiLineString object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="args">The additional args.</param> /// <param name="lineStrings">The line strings.</param> /// <returns>A GeoJson MultiLineString object.</returns> public static GeoJsonMultiLineString<TCoordinates> MultiLineString<TCoordinates>(GeoJsonObjectArgs<TCoordinates> args, params GeoJsonLineStringCoordinates<TCoordinates>[] lineStrings) where TCoordinates : GeoJsonCoordinates { var coordinates = new GeoJsonMultiLineStringCoordinates<TCoordinates>(lineStrings); return new GeoJsonMultiLineString<TCoordinates>(args, coordinates); } /// <summary> /// Creates a GeoJson MultiLineString object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="lineStrings">The line strings.</param> /// <returns>A GeoJson MultiLineString object.</returns> public static GeoJsonMultiLineString<TCoordinates> MultiLineString<TCoordinates>(params GeoJsonLineStringCoordinates<TCoordinates>[] lineStrings) where TCoordinates : GeoJsonCoordinates { var coordinates = new GeoJsonMultiLineStringCoordinates<TCoordinates>(lineStrings); return new GeoJsonMultiLineString<TCoordinates>(coordinates); } /// <summary> /// Creates a GeoJson MultiPoint object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="args">The additional args.</param> /// <param name="positions">The positions.</param> /// <returns>A GeoJson MultiPoint object.</returns> public static GeoJsonMultiPoint<TCoordinates> MultiPoint<TCoordinates>(GeoJsonObjectArgs<TCoordinates> args, params TCoordinates[] positions) where TCoordinates : GeoJsonCoordinates { var coordinates = new GeoJsonMultiPointCoordinates<TCoordinates>(positions); return new GeoJsonMultiPoint<TCoordinates>(args, coordinates); } /// <summary> /// Creates a GeoJson MultiPoint object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="positions">The positions.</param> /// <returns>A GeoJson MultiPoint object.</returns> public static GeoJsonMultiPoint<TCoordinates> MultiPoint<TCoordinates>(params TCoordinates[] positions) where TCoordinates : GeoJsonCoordinates { var coordinates = new GeoJsonMultiPointCoordinates<TCoordinates>(positions); return new GeoJsonMultiPoint<TCoordinates>(coordinates); } /// <summary> /// Creates a GeoJson MultiPolygon object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="args">The additional args.</param> /// <param name="polygons">The polygons.</param> /// <returns>A GeoJson MultiPolygon object.</returns> public static GeoJsonMultiPolygon<TCoordinates> MultiPolygon<TCoordinates>(GeoJsonObjectArgs<TCoordinates> args, params GeoJsonPolygonCoordinates<TCoordinates>[] polygons) where TCoordinates : GeoJsonCoordinates { var coordinates = new GeoJsonMultiPolygonCoordinates<TCoordinates>(polygons); return new GeoJsonMultiPolygon<TCoordinates>(args, coordinates); } /// <summary> /// Creates a GeoJson MultiPolygon object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="polygons">The polygons.</param> /// <returns>A GeoJson MultiPolygon object.</returns> public static GeoJsonMultiPolygon<TCoordinates> MultiPolygon<TCoordinates>(params GeoJsonPolygonCoordinates<TCoordinates>[] polygons) where TCoordinates : GeoJsonCoordinates { var coordinates = new GeoJsonMultiPolygonCoordinates<TCoordinates>(polygons); return new GeoJsonMultiPolygon<TCoordinates>(coordinates); } /// <summary> /// Creates a GeoJson Point object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="args">The additional args.</param> /// <param name="coordinates">The coordinates.</param> /// <returns>A GeoJson Point object.</returns> public static GeoJsonPoint<TCoordinates> Point<TCoordinates>(GeoJsonObjectArgs<TCoordinates> args, TCoordinates coordinates) where TCoordinates : GeoJsonCoordinates { return new GeoJsonPoint<TCoordinates>(args, coordinates); } /// <summary> /// Creates a GeoJson Point object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="coordinates">The coordinates.</param> /// <returns>A GeoJson Point object.</returns> public static GeoJsonPoint<TCoordinates> Point<TCoordinates>(TCoordinates coordinates) where TCoordinates : GeoJsonCoordinates { return new GeoJsonPoint<TCoordinates>(coordinates); } /// <summary> /// Creates a GeoJson Polygon object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="args">The additional args.</param> /// <param name="positions">The positions.</param> /// <returns>A GeoJson Polygon object.</returns> public static GeoJsonPolygon<TCoordinates> Polygon<TCoordinates>(GeoJsonObjectArgs<TCoordinates> args, params TCoordinates[] positions) where TCoordinates : GeoJsonCoordinates { var exterior = new GeoJsonLinearRingCoordinates<TCoordinates>(positions); var coordinates = new GeoJsonPolygonCoordinates<TCoordinates>(exterior); return new GeoJsonPolygon<TCoordinates>(args, coordinates); } /// <summary> /// Creates a GeoJson Polygon object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="args">The additional args.</param> /// <param name="coordinates">The coordinates.</param> /// <returns>A GeoJson Polygon object.</returns> public static GeoJsonPolygon<TCoordinates> Polygon<TCoordinates>(GeoJsonObjectArgs<TCoordinates> args, GeoJsonPolygonCoordinates<TCoordinates> coordinates) where TCoordinates : GeoJsonCoordinates { return new GeoJsonPolygon<TCoordinates>(args, coordinates); } /// <summary> /// Creates a GeoJson Polygon object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="coordinates">The coordinates.</param> /// <returns>A GeoJson Polygon object.</returns> public static GeoJsonPolygon<TCoordinates> Polygon<TCoordinates>(GeoJsonPolygonCoordinates<TCoordinates> coordinates) where TCoordinates : GeoJsonCoordinates { return new GeoJsonPolygon<TCoordinates>(coordinates); } /// <summary> /// Creates a GeoJson Polygon object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="positions">The positions.</param> /// <returns>A GeoJson Polygon object.</returns> public static GeoJsonPolygon<TCoordinates> Polygon<TCoordinates>(params TCoordinates[] positions) where TCoordinates : GeoJsonCoordinates { var exterior = new GeoJsonLinearRingCoordinates<TCoordinates>(positions); var coordinates = new GeoJsonPolygonCoordinates<TCoordinates>(exterior); return new GeoJsonPolygon<TCoordinates>(coordinates); } /// <summary> /// Creates the coordinates of a GeoJson Polygon object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="positions">The positions.</param> /// <returns>The coordinates of a GeoJson Polygon object.</returns> public static GeoJsonPolygonCoordinates<TCoordinates> PolygonCoordinates<TCoordinates>(params TCoordinates[] positions) where TCoordinates : GeoJsonCoordinates { var exterior = new GeoJsonLinearRingCoordinates<TCoordinates>(positions); return new GeoJsonPolygonCoordinates<TCoordinates>(exterior); } /// <summary> /// Creates the coordinates of a GeoJson Polygon object. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> /// <param name="exterior">The exterior.</param> /// <param name="holes">The holes.</param> /// <returns>The coordinates of a GeoJson Polygon object.</returns> public static GeoJsonPolygonCoordinates<TCoordinates> PolygonCoordinates<TCoordinates>(GeoJsonLinearRingCoordinates<TCoordinates> exterior, params GeoJsonLinearRingCoordinates<TCoordinates>[] holes) where TCoordinates : GeoJsonCoordinates { return new GeoJsonPolygonCoordinates<TCoordinates>(exterior, holes); } /// <summary> /// Creates a GeoJson 2D position (x, y). /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <returns>A GeoJson 2D position.</returns> public static GeoJson2DCoordinates Position(double x, double y) { return new GeoJson2DCoordinates(x, y); } /// <summary> /// Creates a GeoJson 3D position (x, y, z). /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="z">The z.</param> /// <returns>A GeoJson 3D position.</returns> public static GeoJson3DCoordinates Position(double x, double y, double z) { return new GeoJson3DCoordinates(x, y, z); } /// <summary> /// Creates a GeoJson 2D projected position (easting, northing). /// </summary> /// <param name="easting">The easting.</param> /// <param name="northing">The northing.</param> /// <returns>A GeoJson 2D projected position.</returns> public static GeoJson2DProjectedCoordinates Projected(double easting, double northing) { return new GeoJson2DProjectedCoordinates(easting, northing); } /// <summary> /// Creates a GeoJson 3D projected position (easting, northing, altitude). /// </summary> /// <param name="easting">The easting.</param> /// <param name="northing">The northing.</param> /// <param name="altitude">The altitude.</param> /// <returns>A GeoJson 3D projected position.</returns> public static GeoJson3DProjectedCoordinates Projected(double easting, double northing, double altitude) { return new GeoJson3DProjectedCoordinates(easting, northing, altitude); } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/OperationFactory.cs<|end_filename|> namespace UnityEditor.PackageManager.UI { internal static class OperationFactory { private static IOperationFactory _instance; public static IOperationFactory Instance { get { if (_instance == null) _instance = new UpmOperationFactory (); return _instance; } internal set { _instance = value; } } internal static void Reset() { _instance = null; } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Upm/UpmSearchOperation.cs<|end_filename|> using System; using System.Collections.Generic; using UnityEngine; using UnityEditor.PackageManager.Requests; namespace UnityEditor.PackageManager.UI { internal class UpmSearchOperation : UpmBaseOperation, ISearchOperation { [SerializeField] private Action<IEnumerable<PackageInfo>> _doneCallbackAction; public void GetAllPackageAsync(Action<IEnumerable<PackageInfo>> doneCallbackAction = null, Action<Error> errorCallbackAction = null) { _doneCallbackAction = doneCallbackAction; OnOperationError += errorCallbackAction; Start(); } protected override Request CreateRequest() { return Client.SearchAll(); } protected override void ProcessData() { var request = CurrentRequest as SearchRequest; var packages = new List<PackageInfo>(); foreach (var upmPackage in request.Result) { var packageInfos = FromUpmPackageInfo(upmPackage, false); packages.AddRange(packageInfos); } _doneCallbackAction(packages); } } } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/Serialization/Serializers/EnumerableInterfaceImplementerSerializer.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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; using System.Collections.Generic; using System.Reflection; namespace MongoDB.Bson.Serialization.Serializers { /// <summary> /// Represents a serializer for a class that implements IEnumerable. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> public class EnumerableInterfaceImplementerSerializer<TValue> : EnumerableInterfaceImplementerSerializerBase<TValue>, IChildSerializerConfigurable where TValue : class, IList, new() { // constructors /// <summary> /// Initializes a new instance of the <see cref="EnumerableInterfaceImplementerSerializer{TValue}"/> class. /// </summary> public EnumerableInterfaceImplementerSerializer() { } /// <summary> /// Initializes a new instance of the <see cref="EnumerableInterfaceImplementerSerializer{TValue}"/> class. /// </summary> /// <param name="itemSerializer">The item serializer.</param> public EnumerableInterfaceImplementerSerializer(IBsonSerializer itemSerializer) : base(itemSerializer) { } /// <summary> /// Initializes a new instance of the <see cref="EnumerableInterfaceImplementerSerializer{TValue}" /> class. /// </summary> /// <param name="serializerRegistry"></param> public EnumerableInterfaceImplementerSerializer(IBsonSerializerRegistry serializerRegistry) : base(serializerRegistry) { } // public methods /// <summary> /// Returns a serializer that has been reconfigured with the specified item serializer. /// </summary> /// <param name="itemSerializer">The item serializer.</param> /// <returns>The reconfigured serializer.</returns> public EnumerableInterfaceImplementerSerializer<TValue> WithItemSerializer(IBsonSerializer itemSerializer) { return new EnumerableInterfaceImplementerSerializer<TValue>(itemSerializer); } // protected methods /// <summary> /// Creates the accumulator. /// </summary> /// <returns>The accumulator.</returns> protected override object CreateAccumulator() { return new TValue(); } // explicit interface implementations IBsonSerializer IChildSerializerConfigurable.ChildSerializer { get { return ItemSerializer; } } IBsonSerializer IChildSerializerConfigurable.WithChildSerializer(IBsonSerializer childSerializer) { return WithItemSerializer(childSerializer); } } /// <summary> /// Represents a serializer for a class that implementes <see cref="IEnumerable{TItem}"/>. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TItem">The type of the item.</typeparam> public class EnumerableInterfaceImplementerSerializer<TValue, TItem> : EnumerableInterfaceImplementerSerializerBase<TValue, TItem>, IChildSerializerConfigurable where TValue : class, IEnumerable<TItem> { // constructors /// <summary> /// Initializes a new instance of the <see cref="EnumerableInterfaceImplementerSerializer{TValue, TItem}"/> class. /// </summary> public EnumerableInterfaceImplementerSerializer() { } /// <summary> /// Initializes a new instance of the <see cref="EnumerableInterfaceImplementerSerializer{TValue, TItem}"/> class. /// </summary> /// <param name="itemSerializer">The item serializer.</param> public EnumerableInterfaceImplementerSerializer(IBsonSerializer<TItem> itemSerializer) : base(itemSerializer) { } /// <summary> /// Initializes a new instance of the <see cref="EnumerableInterfaceImplementerSerializer{TValue, TItem}" /> class. /// </summary> /// <param name="serializerRegistry">The serializer registry.</param> public EnumerableInterfaceImplementerSerializer(IBsonSerializerRegistry serializerRegistry) : base(serializerRegistry) { } // public methods /// <summary> /// Returns a serializer that has been reconfigured with the specified item serializer. /// </summary> /// <param name="itemSerializer">The item serializer.</param> /// <returns>The reconfigured serializer.</returns> public EnumerableInterfaceImplementerSerializer<TValue, TItem> WithItemSerializer(IBsonSerializer<TItem> itemSerializer) { return new EnumerableInterfaceImplementerSerializer<TValue, TItem>(itemSerializer); } // protected methods /// <summary> /// Creates the accumulator. /// </summary> /// <returns>The accumulator.</returns> protected override object CreateAccumulator() { return new List<TItem>(); } /// <summary> /// Finalizes the result. /// </summary> /// <param name="accumulator">The accumulator.</param> /// <returns>The final result.</returns> protected override TValue FinalizeResult(object accumulator) { // find and call a constructor that we can pass the accumulator to var accumulatorType = accumulator.GetType(); foreach (var constructorInfo in typeof(TValue).GetTypeInfo().GetConstructors()) { var parameterInfos = constructorInfo.GetParameters(); if (parameterInfos.Length == 1 && parameterInfos[0].ParameterType.GetTypeInfo().IsAssignableFrom(accumulatorType)) { return (TValue)constructorInfo.Invoke(new object[] { accumulator }); } } // otherwise try to find a no-argument constructor and an Add method var valueTypeInfo = typeof(TValue).GetTypeInfo(); var noArgumentConstructorInfo = valueTypeInfo.GetConstructor(new Type[] { }); var addMethodInfo = typeof(TValue).GetTypeInfo().GetMethod("Add", new Type[] { typeof(TItem) }); if (noArgumentConstructorInfo != null && addMethodInfo != null) { var value = (TValue)noArgumentConstructorInfo.Invoke(new Type[] { }); foreach (var item in (IEnumerable<TItem>)accumulator) { addMethodInfo.Invoke(value, new object[] { item }); } return value; } var message = string.Format("Type '{0}' does not have a suitable constructor or Add method.", typeof(TValue).FullName); throw new BsonSerializationException(message); } // explicit interface implementations IBsonSerializer IChildSerializerConfigurable.ChildSerializer { get { return ItemSerializer; } } IBsonSerializer IChildSerializerConfigurable.WithChildSerializer(IBsonSerializer childSerializer) { return WithItemSerializer((IBsonSerializer<TItem>)childSerializer); } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Interfaces/IOperationFactory.cs<|end_filename|> namespace UnityEditor.PackageManager.UI { /// <summary> /// This is the Interface we will use to create the facade we need for testing. /// In the case of the Fake factory, we can create fake operations with doctored data we use for our tests. /// </summary> internal interface IOperationFactory { IListOperation CreateListOperation(bool offlineMode = false); ISearchOperation CreateSearchOperation(); IAddOperation CreateAddOperation(); IRemoveOperation CreateRemoveOperation(); } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/Linq/Processors/Pipeline/MethodCallBinders/JoinBinder.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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.Linq; using System.Linq.Expressions; using System.Reflection; using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver.Linq.Expressions; using MongoDB.Driver.Support; namespace MongoDB.Driver.Linq.Processors.Pipeline.MethodCallBinders { internal sealed class JoinBinder : IMethodCallBinder<PipelineBindingContext> { public static IEnumerable<MethodInfo> GetSupportedMethods() { yield return MethodHelper.GetMethodDefinition(() => Enumerable.Join<object, object, object, object>(null, null, null, null, null)); yield return MethodHelper.GetMethodDefinition(() => Queryable.Join<object, object, object, object>(null, null, null, null, null)); yield return MethodHelper.GetMethodDefinition(() => Enumerable.GroupJoin<object, object, object, object>(null, null, null, null, null)); yield return MethodHelper.GetMethodDefinition(() => Queryable.GroupJoin<object, object, object, object>(null, null, null, null, null)); } public Expression Bind(PipelineExpression pipeline, PipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable<Expression> arguments) { var args = arguments.ToList(); var joined = bindingContext.Bind(args[0]) as CollectionExpression; if (joined == null) { throw new NotSupportedException("The joined collection cannot have any qualifiers."); } var sourceKeySelectorLambda = ExpressionHelper.GetLambda(args[1]); bindingContext.AddExpressionMapping(sourceKeySelectorLambda.Parameters[0], pipeline.Projector); var sourceKeySelector = bindingContext.Bind(sourceKeySelectorLambda.Body) as IFieldExpression; if (sourceKeySelector == null) { var message = string.Format("Unable to determine the serialization information for the outer key selector in the tree: {0}", node.ToString()); throw new NotSupportedException(message); } var joinedArraySerializer = joined.Serializer as IBsonArraySerializer; BsonSerializationInfo joinedItemSerializationInfo; if (joinedArraySerializer == null || !joinedArraySerializer.TryGetItemSerializationInfo(out joinedItemSerializationInfo)) { var message = string.Format("Unable to determine the serialization information for the inner collection: {0}", node.ToString()); throw new NotSupportedException(message); } var joinedKeySelectorLambda = ExpressionHelper.GetLambda(args[2]); var joinedDocument = new DocumentExpression(joinedItemSerializationInfo.Serializer); bindingContext.AddExpressionMapping(joinedKeySelectorLambda.Parameters[0], joinedDocument); var joinedKeySelector = bindingContext.Bind(joinedKeySelectorLambda.Body) as IFieldExpression; if (joinedKeySelector == null) { var message = string.Format("Unable to determine the serialization information for the inner key selector in the tree: {0}", node.ToString()); throw new NotSupportedException(message); } var resultSelectorLambda = ExpressionHelper.GetLambda(args[3]); var sourceSerializer = pipeline.Projector.Serializer; var joinedSerializer = node.Method.Name == "GroupJoin" ? joined.Serializer : joinedItemSerializationInfo.Serializer; var sourceDocument = new DocumentExpression(sourceSerializer); var joinedField = new FieldExpression( resultSelectorLambda.Parameters[1].Name, joinedSerializer); bindingContext.AddExpressionMapping( resultSelectorLambda.Parameters[0], sourceDocument); bindingContext.AddExpressionMapping( resultSelectorLambda.Parameters[1], joinedField); var resultSelector = bindingContext.Bind(resultSelectorLambda.Body); Expression source; if (node.Method.Name == "GroupJoin") { source = new GroupJoinExpression( node.Type, pipeline.Source, joined, (Expression)sourceKeySelector, (Expression)joinedKeySelector, resultSelectorLambda.Parameters[1].Name); } else { source = new JoinExpression( node.Type, pipeline.Source, joined, (Expression)sourceKeySelector, (Expression)joinedKeySelector, resultSelectorLambda.Parameters[1].Name); } SerializationExpression projector; var newResultSelector = resultSelector as NewExpression; if (newResultSelector != null && newResultSelector.Arguments[0] == sourceDocument && newResultSelector.Arguments[1] == joinedField) { Func<object, object, object> creator = (s, j) => Activator.CreateInstance(resultSelector.Type, s, j); var serializer = (IBsonSerializer)Activator.CreateInstance( typeof(JoinSerializer<>).MakeGenericType(resultSelector.Type), sourceSerializer, newResultSelector.Members[0].Name, joinedSerializer, newResultSelector.Members[1].Name, resultSelectorLambda.Parameters[1].Name, creator); projector = new DocumentExpression(serializer); } else { projector = bindingContext.BindProjector(ref resultSelector); source = new SelectExpression( source, "__i", // since this is a top-level pipeline, this doesn't matter resultSelector); } return new PipelineExpression( source, projector); } } } <|start_filename|>Unity/Assets/Model/Component/Config/InnerConfig.cs<|end_filename|> using System.Net; using MongoDB.Bson.Serialization.Attributes; namespace ETModel { [BsonIgnoreExtraElements] public class InnerConfig: AConfigComponent { [BsonIgnore] public IPEndPoint IPEndPoint { get; private set; } public string Address { get; set; } public override void EndInit() { this.IPEndPoint = NetworkHelper.ToIPEndPoint(this.Address); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Operations/EvalOperation.cs<|end_filename|> /* Copyright 2013-present MongoDB Inc. * * 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.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; using MongoDB.Shared; namespace MongoDB.Driver.Core.Operations { /// <summary> /// Represents an eval operation. /// </summary> public class EvalOperation : IWriteOperation<BsonValue> { // fields private IEnumerable<BsonValue> _args; private readonly DatabaseNamespace _databaseNamespace; private readonly BsonJavaScript _function; private TimeSpan? _maxTime; private readonly MessageEncoderSettings _messageEncoderSettings; private bool? _noLock; // constructors /// <summary> /// Initializes a new instance of the <see cref="EvalOperation"/> class. /// </summary> /// <param name="databaseNamespace">The database namespace.</param> /// <param name="function">The JavaScript function.</param> /// <param name="messageEncoderSettings">The message encoder settings.</param> public EvalOperation( DatabaseNamespace databaseNamespace, BsonJavaScript function, MessageEncoderSettings messageEncoderSettings) { _databaseNamespace = Ensure.IsNotNull(databaseNamespace, nameof(databaseNamespace)); _function = Ensure.IsNotNull(function, nameof(function)); _messageEncoderSettings = messageEncoderSettings; } // properties /// <summary> /// Gets or sets the arguments to the JavaScript function. /// </summary> /// <value> /// The arguments to the JavaScript function. /// </value> public IEnumerable<BsonValue> Args { get { return _args; } set { _args = value; } } /// <summary> /// Gets the database namespace. /// </summary> /// <value> /// The database namespace. /// </value> public DatabaseNamespace DatabaseNamespace { get { return _databaseNamespace; } } /// <summary> /// Gets the JavaScript function. /// </summary> /// <value> /// The JavaScript function. /// </value> public BsonJavaScript Function { get { return _function; } } /// <summary> /// Gets or sets the maximum time the server should spend on this operation. /// </summary> /// <value> /// The maximum time the server should spend on this operation. /// </value> public TimeSpan? MaxTime { get { return _maxTime; } set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); } } /// <summary> /// Gets the message encoder settings. /// </summary> /// <value> /// The message encoder settings. /// </value> public MessageEncoderSettings MessageEncoderSettings { get { return _messageEncoderSettings; } } /// <summary> /// Gets or sets a value indicating whether the server should not take a global write lock before evaluating the JavaScript function. /// </summary> /// <value> /// A value indicating whether the server should not take a global write lock before evaluating the JavaScript function. /// </value> public bool? NoLock { get { return _noLock; } set { _noLock = value; } } // public methods /// <inheritdoc/> public BsonValue Execute(IWriteBinding binding, CancellationToken cancellationToken) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); var result = operation.Execute(binding, cancellationToken); return result["retval"]; } /// <inheritdoc/> public async Task<BsonValue> ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); var result = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); return result["retval"]; } // private methods internal BsonDocument CreateCommand() { return new BsonDocument { { "$eval", _function }, { "args", () => new BsonArray(_args), _args != null }, { "nolock", () => _noLock.Value, _noLock.HasValue }, { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue } }; } private WriteCommandOperation<BsonDocument> CreateOperation() { var command = CreateCommand(); return new WriteCommandOperation<BsonDocument>(_databaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings); } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouchControls/Examples/Version 1.X/ControlEventInput/ControlUIInput.cs<|end_filename|> using UnityEngine; using UnityEngine.UI; using System.Collections; public class ControlUIInput : MonoBehaviour { public Text getAxisText; public Text getAxisSpeedText; public Text getAxisYText; public Text getAxisYSpeedText; public Text downRightText; public Text downDownText; public Text downLeftText; public Text downUpText; public Text rightText; public Text downText; public Text leftText; public Text upText; void Update () { getAxisText.text = ETCInput.GetAxis("Horizontal").ToString("f2"); getAxisSpeedText.text = ETCInput.GetAxisSpeed("Horizontal").ToString("f2"); getAxisYText.text = ETCInput.GetAxis("Vertical").ToString("f2"); getAxisYSpeedText.text = ETCInput.GetAxisSpeed("Vertical").ToString("f2"); if (ETCInput.GetAxisDownRight("Horizontal")){ downRightText.text = "YES"; StartCoroutine( ClearText(downRightText)); } if (ETCInput.GetAxisDownDown("Vertical")){ downDownText.text = "YES"; StartCoroutine( ClearText(downDownText)); } if (ETCInput.GetAxisDownLeft("Horizontal")){ downLeftText.text = "YES"; StartCoroutine( ClearText(downLeftText)); } if (ETCInput.GetAxisDownUp("Vertical")){ downUpText.text = "YES"; StartCoroutine( ClearText(downUpText)); } if (ETCInput.GetAxisPressedRight("Horizontal")){ rightText.text ="YES"; } else{ rightText.text =""; } if (ETCInput.GetAxisPressedDown("Vertical")){ downText.text ="YES"; } else{ downText.text =""; } if (ETCInput.GetAxisPressedLeft("Horizontal")){ leftText.text ="Yes"; } else{ leftText.text =""; } if (ETCInput.GetAxisPressedUp("Vertical")){ upText.text ="YES"; } else{ upText.text =""; } } IEnumerator ClearText(Text textToCLead){ yield return new WaitForSeconds(0.3f); textToCLead.text = ""; } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.GridFS/GridFSFileInfo.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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.Linq; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.GridFS { /// <summary> /// Represents information about a stored GridFS file (backed by a files collection document). /// </summary> /// <typeparam name="TFileId">The type of the file identifier.</typeparam> [BsonSerializer(typeof(GridFSFileInfoSerializer<>))] public sealed class GridFSFileInfo<TFileId> : BsonDocumentBackedClass { // constructors /// <summary> /// Initializes a new instance of the <see cref="GridFSFileInfo" /> class. /// </summary> /// <param name="backingDocument">The backing document.</param> /// <param name="fileInfoSerializer">The fileInfo serializer.</param> public GridFSFileInfo(BsonDocument backingDocument, IGridFSFileInfoSerializer<TFileId> fileInfoSerializer) : base(backingDocument, fileInfoSerializer) { } // public properties /// <summary> /// Gets the aliases. /// </summary> /// <value> /// The aliases. /// </value> [Obsolete("Place aliases inside metadata instead.")] public IEnumerable<string> Aliases { get { return GetValue<string[]>("Aliases", null); } } /// <summary> /// Gets the backing document. /// </summary> /// <value> /// The backing document. /// </value> new public BsonDocument BackingDocument { get { return base.BackingDocument; } } /// <summary> /// Gets the size of a chunk. /// </summary> /// <value> /// The size of a chunk. /// </value> public int ChunkSizeBytes { get { return GetValue<int>("ChunkSizeBytes"); } } /// <summary> /// Gets the type of the content. /// </summary> /// <value> /// The type of the content. /// </value> [Obsolete("Place contentType inside metadata instead.")] public string ContentType { get { return GetValue<string>("ContentType", null); } } /// <summary> /// Gets the filename. /// </summary> /// <value> /// The filename. /// </value> public string Filename { get { return GetValue<string>("Filename"); } } /// <summary> /// Gets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public TFileId Id { get { return GetValue<TFileId>("Id"); } } // public properties /// <summary> /// Gets the length. /// </summary> /// <value> /// The length. /// </value> public long Length { get { return GetValue<long>("Length"); } } /// <summary> /// Gets the MD5 checksum. /// </summary> /// <value> /// The MD5 checksum. /// </value> public string MD5 { get { return GetValue<string>("MD5", null); } } /// <summary> /// Gets the metadata. /// </summary> /// <value> /// The metadata. /// </value> public BsonDocument Metadata { get { return GetValue<BsonDocument>("Metadata", null); } } /// <summary> /// Gets the upload date time. /// </summary> /// <value> /// The upload date time. /// </value> public DateTime UploadDateTime { get { return GetValue<DateTime>("UploadDateTime"); } } } } <|start_filename|>Server/Hotfix/Module/DB/DBQueryBatchRequestHandler.cs<|end_filename|> using System; using ETModel; namespace ETHotfix { [MessageHandler(AppType.DB)] public class DBQueryBatchRequestHandler : AMRpcHandler<DBQueryBatchRequest, DBQueryBatchResponse> { protected override async ETTask Run(Session session, DBQueryBatchRequest request, DBQueryBatchResponse response, Action reply) { DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>(); response.Components = await dbComponent.GetBatch(request.CollectionName, request.IdList); reply(); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.GridFS/GridFSFileInfoSerializerCompat.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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 MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; namespace MongoDB.Driver.GridFS { /// <summary> /// Represents a serializer for GridFSFileInfo. /// </summary> public class GridFSFileInfoSerializer : BsonDocumentBackedClassSerializer<GridFSFileInfo> { private static readonly GridFSFileInfoSerializer __instance = new GridFSFileInfoSerializer(); /// <summary> /// Gets the pre-created instance. /// </summary> public static GridFSFileInfoSerializer Instance { get { return __instance; } } /// <summary> /// Initializes a new instance of the <see cref="GridFSFileInfoSerializer" /> class. /// </summary> public GridFSFileInfoSerializer() { RegisterMember("Aliases", "aliases", new ArraySerializer<string>()); RegisterMember("ChunkSizeBytes", "chunkSize", new Int32Serializer()); RegisterMember("ContentType", "contentType", new StringSerializer()); RegisterMember("Filename", "filename", new StringSerializer()); RegisterMember("IdAsBsonValue", "_id", BsonValueSerializer.Instance); RegisterMember("Length", "length", new Int64Serializer()); RegisterMember("MD5", "md5", new StringSerializer()); RegisterMember("Metadata", "metadata", BsonDocumentSerializer.Instance); RegisterMember("UploadDateTime", "uploadDate", new DateTimeSerializer()); } /// <inheritdoc/> protected override GridFSFileInfo CreateInstance(BsonDocument backingDocument) { return new GridFSFileInfo(backingDocument); } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Examples/4.X/AdvancedExamples/AutoSelect/MultiLayerTouch.cs<|end_filename|> using UnityEngine; using UnityEngine.UI; using System.Collections; using HedgehogTeam.EasyTouch; public class MultiLayerTouch : MonoBehaviour { public Text label; public Text label2; void OnEnable(){ EasyTouch.On_TouchDown += On_TouchDown; EasyTouch.On_TouchUp += On_TouchUp; } void OnDestroy(){ EasyTouch.On_TouchDown -= On_TouchDown; EasyTouch.On_TouchUp -= On_TouchUp; } void On_TouchDown (Gesture gesture) { if (gesture.pickedObject!=null){ if (!EasyTouch.GetAutoUpdatePickedObject()){ label.text = "Picked object from event : " + gesture.pickedObject.name + " : " + gesture.position; } else{ label.text = "Picked object from event : " + gesture.pickedObject.name + " : " + gesture.position; } } else{ if (!EasyTouch.GetAutoUpdatePickedObject()){ label.text = "Picked object from event : none"; } else{ label.text = "Picked object from event : none"; } } label2.text = ""; if (!EasyTouch.GetAutoUpdatePickedObject()){ GameObject tmp = gesture.GetCurrentPickedObject(); if (tmp != null){ label2.text = "Picked object from GetCurrentPickedObject : " + tmp.name ; } else{ label2.text = "Picked object from GetCurrentPickedObject : none"; } } } void On_TouchUp (Gesture gesture) { label.text=""; label2.text=""; } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/UI/Common/PopupField.cs<|end_filename|> using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.UIElements; namespace UnityEditor.PackageManager.UI { #if UNITY_2018_3_OR_NEWER internal class PopupField<T> : Experimental.UIElements.PopupField<T> { private Func<T, string> m_Callback; public override T value { get { return base.value; } set { base.value = value; if (m_Callback != null) m_TextElement.text = m_Callback(m_Value); else m_TextElement.text = m_Value.ToString(); } } /// <summary> /// Callback that will return the string to be set in the field's label. /// </summary> /// <param name="callback"></param> public void SetLabelCallback(Func<T, string> callback) { m_Callback = callback; } public PopupField(List<T> choices, T defaultValue) : base(choices, defaultValue) { } public PopupField(List<T> choices, int defaultIndex) : base(choices, defaultIndex) { } } #else internal class PopupField<T> : BaseTextElement, INotifyValueChanged<T> { private readonly List<T> m_PossibleValues; private Func<T, string> m_Callback; private EventCallback<ChangeEvent<T>> m_valueCallback; private T m_Value; public T value { get { return m_Value; } set { if (EqualityComparer<T>.Default.Equals(m_Value, value)) return; if (!m_PossibleValues.Contains(value)) throw new ArgumentException(string.Format("Value {0} is not present in the list of possible values", value)); m_Value = value; m_Index = m_PossibleValues.IndexOf(m_Value); if (m_Callback != null) text = m_Callback(m_Value); else text = m_Value.ToString(); #if UNITY_2018_3_OR_NEWER MarkDirtyRepaint(); #else Dirty(ChangeType.Repaint); #endif } } private int m_Index = -1; public int index { get { return m_Index; } set { if (value != m_Index) { if (value >= m_PossibleValues.Count || value < 0) throw new ArgumentException(string.Format("Index {0} is beyond the scope of possible value", value)); m_Index = value; this.value = m_PossibleValues[m_Index]; } } } /// <summary> /// Callback that will return the string to be set in the field's label. /// </summary> /// <param name="callback"></param> public void SetLabelCallback(Func<T, string> callback) { m_Callback = callback; } private PopupField(List<T> possibleValues) { if (possibleValues == null) throw new ArgumentNullException("possibleValues can't be null"); m_PossibleValues = possibleValues; AddToClassList("popupField"); } public PopupField(List<T> possibleValues, T defaultValue) : this(possibleValues) { if (defaultValue == null) throw new ArgumentNullException("defaultValue can't be null"); if (!m_PossibleValues.Contains(defaultValue)) throw new ArgumentException(string.Format("Default value {0} is not present in the list of possible values", defaultValue)); // note: idx will be set when setting value value = defaultValue; } public PopupField(List<T> possibleValues, int defaultIndex) : this(possibleValues) { if (defaultIndex >= m_PossibleValues.Count || defaultIndex < 0) throw new ArgumentException(string.Format("Default Index {0} is beyond the scope of possible value", value)); // note: value will be set when setting idx index = defaultIndex; } public void SetValueAndNotify(T newValue) { if (!EqualityComparer<T>.Default.Equals(newValue, value)) { using (ChangeEvent<T> evt = ChangeEvent<T>.GetPooled(value, newValue)) { value = newValue; if (m_valueCallback != null) m_valueCallback(evt); } } } public void OnValueChanged(EventCallback<ChangeEvent<T>> callback) { m_valueCallback = callback; RegisterCallback(callback); } protected override void ExecuteDefaultAction(EventBase evt) { base.ExecuteDefaultAction(evt); if (evt.GetEventTypeId() == MouseDownEvent.TypeId()) OnMouseDown(); } private void OnMouseDown() { var menu = new GenericMenu(); foreach (T item in m_PossibleValues) { bool isSelected = EqualityComparer<T>.Default.Equals(item, value); menu.AddItem(new GUIContent(item.ToString()), isSelected, () => ChangeValueFromMenu(item)); } var menuPosition = new Vector2(0.0f, layout.height); menuPosition = this.LocalToWorld(menuPosition); var menuRect = new Rect(menuPosition, Vector2.zero); menu.DropDown(menuRect); } private void ChangeValueFromMenu(T menuItem) { SetValueAndNotify(menuItem); } } #endif } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Operations/OperationClock.cs<|end_filename|> /* Copyright 2017-present MongoDB Inc. * * 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 MongoDB.Bson; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Core.Operations { /// <summary> /// An operation clock. /// </summary> /// <seealso cref="MongoDB.Driver.Core.Operations.IOperationClock" /> internal class OperationClock : IOperationClock { #region static // public static methods /// <summary> /// Returns the greater of two operation times. /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <returns>The greater operation time.</returns> public static BsonTimestamp GreaterOperationTime(BsonTimestamp x, BsonTimestamp y) { if (x == null) { return y; } else if (y == null) { return x; } else { return x > y ? x : y; } } #endregion // private fields private BsonTimestamp _operationTime; // public properties /// <inheritdoc /> public BsonTimestamp OperationTime => _operationTime; // public methods /// <inheritdoc /> public void AdvanceOperationTime(BsonTimestamp newOperationTime) { Ensure.IsNotNull(newOperationTime, nameof(newOperationTime)); _operationTime = GreaterOperationTime(_operationTime, newOperationTime); } } /// <summary> /// An object that represents no operation clock. /// </summary> /// <seealso cref="MongoDB.Driver.Core.Operations.IOperationClock" /> public sealed class NoOperationClock : IOperationClock { /// <inheritdoc /> public BsonTimestamp OperationTime => null; /// <inheritdoc /> public void AdvanceOperationTime(BsonTimestamp newOperationTime) { } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Operations/ElementNameValidators/UpdateOrReplacementElementNameValidator.cs<|end_filename|> /* Copyright 2013-present MongoDB Inc. * * 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 MongoDB.Bson.IO; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Core.Operations.ElementNameValidators { /// <summary> /// Represents an element name validator that will validate element names for either an update or a replacement based on whether the first element name starts with a "$". /// </summary> public class UpdateOrReplacementElementNameValidator : IElementNameValidator { // private fields private IElementNameValidator _chosenValidator; // constructors /// <summary> /// Initializes a new instance of the <see cref="UpdateOrReplacementElementNameValidator"/> class. /// </summary> public UpdateOrReplacementElementNameValidator() { } // methods /// <inheritdoc/> public IElementNameValidator GetValidatorForChildContent(string elementName) { return _chosenValidator.GetValidatorForChildContent(elementName); } /// <inheritdoc/> public bool IsValidElementName(string elementName) { // the first elementName we see determines whether we are validating an update or a replacement document if (_chosenValidator == null) { if (elementName.Length > 0 && elementName[0] == '$') { _chosenValidator = UpdateElementNameValidator.Instance; ; } else { _chosenValidator = CollectionElementNameValidator.Instance; } } return _chosenValidator.IsValidElementName(elementName); } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/AssemblyInfo.cs<|end_filename|> using System.Runtime.CompilerServices; using UnityEditor.Experimental.UIElements; [assembly: InternalsVisibleTo("Unity.PackageManagerCaptain.Editor")] [assembly: InternalsVisibleTo("Unity.PackageManagerUI.EditorTests")] #if UNITY_2018_3_OR_NEWER [assembly: UxmlNamespacePrefix("UnityEditor.PackageManager.UI", "upm")] #endif <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouchControls/Component/ETCSetDirectActionTransform.cs<|end_filename|> using UnityEngine; using System.Collections; [AddComponentMenu("EasyTouch Controls/Set Direct Action Transform ")] public class ETCSetDirectActionTransform : MonoBehaviour { public string axisName1; public string axisName2; void Start(){ if (!string.IsNullOrEmpty(axisName1)){ ETCInput.SetAxisDirecTransform(axisName1, transform); } if (!string.IsNullOrEmpty(axisName2)){ ETCInput.SetAxisDirecTransform(axisName2, transform); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Operations/ElementNameValidators/UpdateElementNameValidator.cs<|end_filename|> /* Copyright 2013-present MongoDB Inc. * * 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 MongoDB.Bson.IO; namespace MongoDB.Driver.Core.Operations.ElementNameValidators { /// <summary> /// Represents an element name validator for update operations. /// </summary> public class UpdateElementNameValidator : IElementNameValidator { // private static fields private static readonly UpdateElementNameValidator __instance = new UpdateElementNameValidator(); // public static fields /// <summary> /// Gets a pre-created instance of an UpdateElementNameValidator. /// </summary> /// <value> /// The pre-created instance. /// </value> public static UpdateElementNameValidator Instance { get { return __instance; } } // methods /// <inheritdoc/> public IElementNameValidator GetValidatorForChildContent(string elementName) { return NoOpElementNameValidator.Instance; } /// <inheritdoc/> public bool IsValidElementName(string elementName) { return elementName.Length > 0 && elementName[0] == '$'; } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Async/AsyncQueue.cs<|end_filename|> /* Copyright 2013-present MongoDB Inc. * * 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.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MongoDB.Driver.Core.Async { internal class AsyncQueue<T> { // fields private readonly object _lock = new object(); private readonly Queue<T> _queue = new Queue<T>(); private readonly Queue<TaskCompletionSource<T>> _awaiters = new Queue<TaskCompletionSource<T>>(); // properties public int Count { get { lock (_lock) { return _queue.Count; } } } // methods public IEnumerable<T> DequeueAll() { lock (_lock) { while (_queue.Count > 0) { yield return _queue.Dequeue(); } } } public async Task<T> DequeueAsync(CancellationToken cancellationToken) { TaskCompletionSource<T> awaiter; lock (_lock) { if (_queue.Count > 0) { return _queue.Dequeue(); } else { awaiter = new TaskCompletionSource<T>(); _awaiters.Enqueue(awaiter); } } using (cancellationToken.Register(() => awaiter.TrySetCanceled(), useSynchronizationContext: false)) { return await awaiter.Task.ConfigureAwait(false); } } public void Enqueue(T item) { TaskCompletionSource<T> awaiter = null; lock (_lock) { if (_awaiters.Count > 0) { awaiter = _awaiters.Dequeue(); } else { _queue.Enqueue(item); } } if (awaiter != null) { awaiter.TrySetResult(item); } } } } <|start_filename|>Unity/Assets/ThirdParty/ILRuntime/Mono.Cecil/Mono.Cecil/PropertyDefinition.cs<|end_filename|> // // Author: // <NAME> (<EMAIL>) // // Copyright (c) 2008 - 2015 <NAME> // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System.Text; using Mono.Collections.Generic; namespace Mono.Cecil { public sealed class PropertyDefinition : PropertyReference, IMemberDefinition, IConstantProvider { bool? has_this; ushort attributes; Collection<CustomAttribute> custom_attributes; internal MethodDefinition get_method; internal MethodDefinition set_method; internal Collection<MethodDefinition> other_methods; object constant = Mixin.NotResolved; public PropertyAttributes Attributes { get { return (PropertyAttributes) attributes; } set { attributes = (ushort) value; } } public bool HasThis { get { if (has_this.HasValue) return has_this.Value; if (GetMethod != null) return get_method.HasThis; if (SetMethod != null) return set_method.HasThis; return false; } set { has_this = value; } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (Module); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); } } public MethodDefinition GetMethod { get { if (get_method != null) return get_method; InitializeMethods (); return get_method; } set { get_method = value; } } public MethodDefinition SetMethod { get { if (set_method != null) return set_method; InitializeMethods (); return set_method; } set { set_method = value; } } public bool HasOtherMethods { get { if (other_methods != null) return other_methods.Count > 0; InitializeMethods (); return !other_methods.IsNullOrEmpty (); } } public Collection<MethodDefinition> OtherMethods { get { if (other_methods != null) return other_methods; InitializeMethods (); if (other_methods != null) return other_methods; return other_methods = new Collection<MethodDefinition> (); } } public bool HasParameters { get { InitializeMethods (); if (get_method != null) return get_method.HasParameters; if (set_method != null) return set_method.HasParameters && set_method.Parameters.Count > 1; return false; } } public override Collection<ParameterDefinition> Parameters { get { InitializeMethods (); if (get_method != null) return MirrorParameters (get_method, 0); if (set_method != null) return MirrorParameters (set_method, 1); return new Collection<ParameterDefinition> (); } } static Collection<ParameterDefinition> MirrorParameters (MethodDefinition method, int bound) { var parameters = new Collection<ParameterDefinition> (); if (!method.HasParameters) return parameters; var original_parameters = method.Parameters; var end = original_parameters.Count - bound; for (int i = 0; i < end; i++) parameters.Add (original_parameters [i]); return parameters; } public bool HasConstant { get { this.ResolveConstant (ref constant, Module); return constant != Mixin.NoValue; } set { if (!value) constant = Mixin.NoValue; } } public object Constant { get { return HasConstant ? constant : null; } set { constant = value; } } #region PropertyAttributes public bool IsSpecialName { get { return attributes.GetAttributes ((ushort) PropertyAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.SpecialName, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((ushort) PropertyAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.RTSpecialName, value); } } public bool HasDefault { get { return attributes.GetAttributes ((ushort) PropertyAttributes.HasDefault); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.HasDefault, value); } } #endregion public new TypeDefinition DeclaringType { get { return (TypeDefinition) base.DeclaringType; } set { base.DeclaringType = value; } } public override bool IsDefinition { get { return true; } } public override string FullName { get { var builder = new StringBuilder (); builder.Append (PropertyType.ToString ()); builder.Append (' '); builder.Append (MemberFullName ()); builder.Append ('('); if (HasParameters) { var parameters = Parameters; for (int i = 0; i < parameters.Count; i++) { if (i > 0) builder.Append (','); builder.Append (parameters [i].ParameterType.FullName); } } builder.Append (')'); return builder.ToString (); } } public PropertyDefinition (string name, PropertyAttributes attributes, TypeReference propertyType) : base (name, propertyType) { this.attributes = (ushort) attributes; this.token = new MetadataToken (TokenType.Property); } void InitializeMethods () { var module = this.Module; if (module == null) return; lock (module.SyncRoot) { if (get_method != null || set_method != null) return; if (!module.HasImage ()) return; module.Read (this, (property, reader) => reader.ReadMethods (property)); } } public override PropertyDefinition Resolve () { return this; } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Connections/CommandEventHelper.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.WireProtocol.Messages; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders.BinaryEncoders; namespace MongoDB.Driver.Core.Connections { internal class CommandEventHelper { private static readonly string[] __writeConcernIndicators = new[] { "wtimeout", "jnote", "wnote" }; private static readonly HashSet<string> __securitySensitiveCommands = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "authenticate", "saslStart", "saslContinue", "getnonce", "createUser", "updateUser", "copydbgetnonce", "copydbsaslstart", "copydb" }; private readonly ConcurrentDictionary<int, CommandState> _state; private readonly Action<CommandStartedEvent> _startedEvent; private readonly Action<CommandSucceededEvent> _succeededEvent; private readonly Action<CommandFailedEvent> _failedEvent; private readonly bool _shouldProcessRequestMessages; private readonly bool _shouldTrackState; public CommandEventHelper(IEventSubscriber eventSubscriber) { eventSubscriber.TryGetEventHandler(out _startedEvent); eventSubscriber.TryGetEventHandler(out _succeededEvent); eventSubscriber.TryGetEventHandler(out _failedEvent); _shouldTrackState = _succeededEvent != null || _failedEvent != null; _shouldProcessRequestMessages = _startedEvent != null || _shouldTrackState; if (_shouldTrackState) { // we only need to track state if we have to raise // a succeeded or failed event _state = new ConcurrentDictionary<int, CommandState>(); } } public bool ShouldCallBeforeSending { get { return _shouldProcessRequestMessages; } } public bool ShouldCallAfterSending { get { return _shouldTrackState; } } public bool ShouldCallErrorSending { get { return _shouldTrackState; } } public bool ShouldCallAfterReceiving { get { return _shouldTrackState; } } public bool ShouldCallErrorReceiving { get { return _shouldTrackState; } } public void BeforeSending(IEnumerable<RequestMessage> messages, ConnectionId connectionId, IByteBuffer buffer, MessageEncoderSettings encoderSettings, Stopwatch stopwatch) { using (var stream = new ByteBufferStream(buffer, ownsBuffer: false)) { var messageQueue = new Queue<RequestMessage>(messages); while (messageQueue.Count > 0) { ProcessRequestMessages(messageQueue, connectionId, stream, encoderSettings, stopwatch); } } } public void AfterSending(IEnumerable<RequestMessage> messages, ConnectionId connectionId) { foreach (var message in messages) { CommandState state; if (_state.TryGetValue(message.RequestId, out state) && state.ExpectedResponseType == ExpectedResponseType.None) { state.Stopwatch.Stop(); if (_succeededEvent != null) { var @event = new CommandSucceededEvent( state.CommandName, state.NoResponseResponse ?? new BsonDocument("ok", 1), state.OperationId, message.RequestId, connectionId, state.Stopwatch.Elapsed); _succeededEvent(@event); } _state.TryRemove(message.RequestId, out state); } } } public void ErrorSending(IEnumerable<RequestMessage> messages, ConnectionId connectionId, Exception exception) { foreach (var message in messages) { CommandState state; if (_state.TryRemove(message.RequestId, out state)) { state.Stopwatch.Stop(); if (_failedEvent != null) { var @event = new CommandFailedEvent( state.CommandName, exception, state.OperationId, message.RequestId, connectionId, state.Stopwatch.Elapsed); _failedEvent(@event); } } } } public void AfterReceiving(ResponseMessage message, IByteBuffer buffer, ConnectionId connectionId, MessageEncoderSettings encoderSettings) { CommandState state; if (!_state.TryRemove(message.ResponseTo, out state)) { // this indicates a bug in the sending portion... return; } if (message is CommandResponseMessage) { ProcessCommandResponseMessage(state, (CommandResponseMessage)message, buffer, connectionId, encoderSettings); } else { ProcessReplyMessage(state, message, buffer, connectionId, encoderSettings); } } public void ErrorReceiving(int responseTo, ConnectionId connectionId, Exception exception) { CommandState state; if (!_state.TryRemove(responseTo, out state)) { // this indicates a bug in the sending portion... return; } state.Stopwatch.Stop(); if (_failedEvent != null) { _failedEvent(new CommandFailedEvent( state.CommandName, exception, state.OperationId, responseTo, connectionId, state.Stopwatch.Elapsed)); } } public void ConnectionFailed(ConnectionId connectionId, Exception exception) { if (_failedEvent == null) { return; } var requestIds = _state.Keys; foreach (var requestId in requestIds) { CommandState state; if (_state.TryRemove(requestId, out state)) { state.Stopwatch.Stop(); var @event = new CommandFailedEvent( state.CommandName, exception, state.OperationId, requestId, connectionId, state.Stopwatch.Elapsed); _failedEvent(@event); } } } private void ProcessRequestMessages(Queue<RequestMessage> messageQueue, ConnectionId connectionId, Stream stream, MessageEncoderSettings encoderSettings, Stopwatch stopwatch) { var message = messageQueue.Dequeue(); switch (message.MessageType) { case MongoDBMessageType.Command: ProcessCommandRequestMessage((CommandRequestMessage)message, messageQueue, connectionId, new CommandMessageBinaryEncoder(stream, encoderSettings), stopwatch); break; case MongoDBMessageType.Delete: ProcessDeleteMessage((DeleteMessage)message, messageQueue, connectionId, new DeleteMessageBinaryEncoder(stream, encoderSettings), stopwatch); break; case MongoDBMessageType.GetMore: ProcessGetMoreMessage((GetMoreMessage)message, connectionId, stopwatch); break; case MongoDBMessageType.Insert: ProcessInsertMessage(message, messageQueue, connectionId, new InsertMessageBinaryEncoder<RawBsonDocument>(stream, encoderSettings, RawBsonDocumentSerializer.Instance), stopwatch); break; case MongoDBMessageType.KillCursors: ProcessKillCursorsMessages((KillCursorsMessage)message, connectionId, stopwatch); break; case MongoDBMessageType.Query: ProcessQueryMessage((QueryMessage)message, connectionId, new QueryMessageBinaryEncoder(stream, encoderSettings), stopwatch); break; case MongoDBMessageType.Update: ProcessUpdateMessage((UpdateMessage)message, messageQueue, connectionId, new UpdateMessageBinaryEncoder(stream, encoderSettings), stopwatch); break; default: throw new MongoInternalException("Invalid message type."); } } private void ProcessCommandRequestMessage(CommandRequestMessage originalMessage, Queue<RequestMessage> messageQueue, ConnectionId connectionId, CommandMessageBinaryEncoder encoder, Stopwatch stopwatch) { var requestId = originalMessage.RequestId; var operationId = EventContext.OperationId; var decodedMessage = encoder.ReadMessage(); using (new CommandMessageDisposer(decodedMessage)) { var type0Section = decodedMessage.Sections.OfType<Type0CommandMessageSection>().Single(); var command = (BsonDocument)type0Section.Document; var type1Sections = decodedMessage.Sections.OfType<Type1CommandMessageSection>().ToList(); if (type1Sections.Count > 0) { command = new BsonDocument(command); // materialize the top level of the command RawBsonDocument foreach (var type1Section in type1Sections) { var name = type1Section.Identifier; var items = new BsonArray(type1Section.Documents.GetBatchItems().Cast<RawBsonDocument>()); command[name] = items; } } var commandName = command.GetElement(0).Name; var databaseName = command["$db"].AsString; var databaseNamespace = new DatabaseNamespace(databaseName); if (__securitySensitiveCommands.Contains(commandName)) { command = new BsonDocument(); } if (_startedEvent != null) { var @event = new CommandStartedEvent( commandName, command, databaseNamespace, operationId, requestId, connectionId); _startedEvent(@event); } if (_shouldTrackState) { _state.TryAdd(requestId, new CommandState { CommandName = commandName, OperationId = operationId, Stopwatch = stopwatch, QueryNamespace = new CollectionNamespace(databaseNamespace, "$cmd"), ExpectedResponseType = decodedMessage.MoreToCome ? ExpectedResponseType.None : ExpectedResponseType.Command }); } } } private void ProcessCommandResponseMessage(CommandState state, CommandResponseMessage message, IByteBuffer buffer, ConnectionId connectionId, MessageEncoderSettings encoderSettings) { var wrappedMessage = message.WrappedMessage; var type0Section = wrappedMessage.Sections.OfType<Type0CommandMessageSection<RawBsonDocument>>().Single(); var reply = (BsonDocument)type0Section.Document; BsonValue ok; if (!reply.TryGetValue("ok", out ok)) { // this is a degenerate case with the server and // we don't really know what to do here... return; } if (__securitySensitiveCommands.Contains(state.CommandName)) { reply = new BsonDocument(); } if (ok.ToBoolean()) { if (_succeededEvent != null) { _succeededEvent(new CommandSucceededEvent( state.CommandName, reply, state.OperationId, message.ResponseTo, connectionId, state.Stopwatch.Elapsed)); } } else { if (_failedEvent != null) { _failedEvent(new CommandFailedEvent( state.CommandName, new MongoCommandException( connectionId, string.Format("{0} command failed", state.CommandName), null, reply), state.OperationId, message.ResponseTo, connectionId, state.Stopwatch.Elapsed)); } } } private void ProcessDeleteMessage(DeleteMessage originalMessage, Queue<RequestMessage> messageQueue, ConnectionId connectionId, DeleteMessageBinaryEncoder encoder, Stopwatch stopwatch) { var commandName = "delete"; var operationId = EventContext.OperationId; int requestId = originalMessage.RequestId; var expectedResponseType = ExpectedResponseType.None; int gleRequestId; WriteConcern writeConcern; if (TryGetWriteConcernFromGLE(messageQueue, out gleRequestId, out writeConcern)) { requestId = gleRequestId; expectedResponseType = ExpectedResponseType.GLE; } if (_startedEvent != null) { var decodedMessage = encoder.ReadMessage(RawBsonDocumentSerializer.Instance); try { var entry = new BsonDocument { { "q", decodedMessage.Query }, { "limit", decodedMessage.IsMulti ? 0 : 1 } }; var command = new BsonDocument { { commandName, decodedMessage.CollectionNamespace.CollectionName }, { "deletes", new BsonArray(new [] { entry }) } }; if (writeConcern == null) { command["writeConcern"] = WriteConcern.Unacknowledged.ToBsonDocument(); } else if (!writeConcern.IsServerDefault) { command["writeConcern"] = writeConcern.ToBsonDocument(); } var @event = new CommandStartedEvent( commandName, command, decodedMessage.CollectionNamespace.DatabaseNamespace, operationId, requestId, connectionId); _startedEvent(@event); } finally { var disposable = decodedMessage.Query as IDisposable; if (disposable != null) { disposable.Dispose(); } } } if (_shouldTrackState) { _state.TryAdd(requestId, new CommandState { CommandName = commandName, OperationId = operationId, Stopwatch = stopwatch, ExpectedResponseType = expectedResponseType }); } } private void ProcessGetMoreMessage(GetMoreMessage originalMessage, ConnectionId connectionId, Stopwatch stopwatch) { var commandName = "getMore"; var operationId = EventContext.OperationId; if (_startedEvent != null) { var command = new BsonDocument { { commandName, originalMessage.CursorId }, { "collection", originalMessage.CollectionNamespace.CollectionName }, { "batchSize", originalMessage.BatchSize, originalMessage.BatchSize > 0 } }; var @event = new CommandStartedEvent( "getMore", command, originalMessage.CollectionNamespace.DatabaseNamespace, operationId, originalMessage.RequestId, connectionId); _startedEvent(@event); } if (_shouldTrackState) { _state.TryAdd(originalMessage.RequestId, new CommandState { CommandName = commandName, OperationId = operationId, Stopwatch = stopwatch, QueryNamespace = originalMessage.CollectionNamespace, ExpectedResponseType = ExpectedResponseType.Query }); } } private void ProcessInsertMessage(RequestMessage message, Queue<RequestMessage> messageQueue, ConnectionId connectionId, InsertMessageBinaryEncoder<RawBsonDocument> encoder, Stopwatch stopwatch) { var commandName = "insert"; var operationId = EventContext.OperationId; var requestId = message.RequestId; var expectedResponseType = ExpectedResponseType.None; int numberOfDocuments = 0; int gleRequestId; WriteConcern writeConcern; if (TryGetWriteConcernFromGLE(messageQueue, out gleRequestId, out writeConcern)) { requestId = gleRequestId; expectedResponseType = ExpectedResponseType.GLE; } if (_startedEvent != null) { // InsertMessage is generic, and we don't know the generic type... // Plus, for this we really want BsonDocuments, not whatever the generic type is. var decodedMessage = encoder.ReadMessage(); var documents = decodedMessage.DocumentSource.GetBatchItems(); numberOfDocuments = documents.Count; try { var command = new BsonDocument { { commandName, decodedMessage.CollectionNamespace.CollectionName }, { "documents", new BsonArray(documents) }, { "ordered", !decodedMessage.ContinueOnError } }; if (writeConcern == null) { command["writeConcern"] = WriteConcern.Unacknowledged.ToBsonDocument(); } else if (!writeConcern.IsServerDefault) { command["writeConcern"] = writeConcern.ToBsonDocument(); } var @event = new CommandStartedEvent( commandName, command, decodedMessage.CollectionNamespace.DatabaseNamespace, operationId, requestId, connectionId); _startedEvent(@event); } finally { foreach (var document in documents) { document.Dispose(); } } } if (_shouldTrackState) { _state.TryAdd(requestId, new CommandState { CommandName = commandName, OperationId = operationId, Stopwatch = stopwatch, ExpectedResponseType = expectedResponseType, NumberOfInsertedDocuments = numberOfDocuments }); } } private void ProcessKillCursorsMessages(KillCursorsMessage originalMessage, ConnectionId connectionId, Stopwatch stopwatch) { const string commandName = "killCursors"; var operationId = EventContext.OperationId; if (_startedEvent != null) { var collectionNamespace = EventContext.KillCursorsCollectionNamespace ?? DatabaseNamespace.Admin.CommandCollection; var command = new BsonDocument { { commandName, collectionNamespace.CollectionName }, { "cursors", new BsonArray(originalMessage.CursorIds) } }; var @event = new CommandStartedEvent( commandName, command, collectionNamespace.DatabaseNamespace, operationId, originalMessage.RequestId, connectionId); _startedEvent(@event); } if (_shouldTrackState) { _state.TryAdd(originalMessage.RequestId, new CommandState { CommandName = commandName, OperationId = operationId, Stopwatch = stopwatch, ExpectedResponseType = ExpectedResponseType.None, NoResponseResponse = new BsonDocument { { "ok", 1 }, { "cursorsUnknown", new BsonArray(originalMessage.CursorIds) } } }); } } private void ProcessQueryMessage(QueryMessage originalMessage, ConnectionId connectionId, QueryMessageBinaryEncoder encoder, Stopwatch stopwatch) { var requestId = originalMessage.RequestId; var operationId = EventContext.OperationId; var decodedMessage = encoder.ReadMessage(RawBsonDocumentSerializer.Instance); try { var isCommand = IsCommand(decodedMessage.CollectionNamespace); string commandName; BsonDocument command; if (isCommand) { command = decodedMessage.Query; var firstElement = command.GetElement(0); commandName = firstElement.Name; if (__securitySensitiveCommands.Contains(commandName)) { command = new BsonDocument(); } } else { commandName = "find"; command = BuildFindCommandFromQuery(decodedMessage); if (decodedMessage.Query.GetValue("$explain", false).ToBoolean()) { commandName = "explain"; command = new BsonDocument("explain", command); } } if (_startedEvent != null) { var @event = new CommandStartedEvent( commandName, command, decodedMessage.CollectionNamespace.DatabaseNamespace, operationId, requestId, connectionId); _startedEvent(@event); } if (_shouldTrackState) { _state.TryAdd(requestId, new CommandState { CommandName = commandName, OperationId = operationId, Stopwatch = stopwatch, QueryNamespace = decodedMessage.CollectionNamespace, ExpectedResponseType = isCommand ? ExpectedResponseType.Command : ExpectedResponseType.Query }); } } finally { var disposable = decodedMessage.Query as IDisposable; if (disposable != null) { disposable.Dispose(); } disposable = decodedMessage.Fields as IDisposable; if (disposable != null) { disposable.Dispose(); } } } private void ProcessReplyMessage(CommandState state, ResponseMessage message, IByteBuffer buffer, ConnectionId connectionId, MessageEncoderSettings encoderSettings) { state.Stopwatch.Stop(); bool disposeOfDocuments = false; var replyMessage = message as ReplyMessage<RawBsonDocument>; if (replyMessage == null) { // ReplyMessage is generic, which means that we can't use it here, so, we need to use a different one... using (var stream = new ByteBufferStream(buffer, ownsBuffer: false)) { var encoderFactory = new BinaryMessageEncoderFactory(stream, encoderSettings); replyMessage = (ReplyMessage<RawBsonDocument>)encoderFactory .GetReplyMessageEncoder(RawBsonDocumentSerializer.Instance) .ReadMessage(); disposeOfDocuments = true; } } try { if (replyMessage.CursorNotFound || replyMessage.QueryFailure || (state.ExpectedResponseType != ExpectedResponseType.Query && replyMessage.Documents.Count == 0)) { var queryFailureDocument = replyMessage.QueryFailureDocument; if (__securitySensitiveCommands.Contains(state.CommandName)) { queryFailureDocument = new BsonDocument(); } if (_failedEvent != null) { _failedEvent(new CommandFailedEvent( state.CommandName, new MongoCommandException( connectionId, string.Format("{0} command failed", state.CommandName), null, queryFailureDocument), state.OperationId, replyMessage.ResponseTo, connectionId, state.Stopwatch.Elapsed)); } } else { switch (state.ExpectedResponseType) { case ExpectedResponseType.Command: ProcessCommandReplyMessage(state, replyMessage, connectionId); break; case ExpectedResponseType.GLE: ProcessGLEReplyMessage(state, replyMessage, connectionId); break; case ExpectedResponseType.Query: ProcessQueryReplyMessage(state, replyMessage, connectionId); break; } } } finally { if (disposeOfDocuments && replyMessage.Documents != null) { replyMessage.Documents.ForEach(d => d.Dispose()); } } } private void ProcessCommandReplyMessage(CommandState state, ReplyMessage<RawBsonDocument> replyMessage, ConnectionId connectionId) { BsonDocument reply = replyMessage.Documents[0]; BsonValue ok; if (!reply.TryGetValue("ok", out ok)) { // this is a degenerate case with the server and // we don't really know what to do here... return; } if (__securitySensitiveCommands.Contains(state.CommandName)) { reply = new BsonDocument(); } if (!ok.ToBoolean()) { if (_failedEvent != null) { _failedEvent(new CommandFailedEvent( state.CommandName, new MongoCommandException( connectionId, string.Format("{0} command failed", state.CommandName), null, reply), state.OperationId, replyMessage.ResponseTo, connectionId, state.Stopwatch.Elapsed)); } } else if (_succeededEvent != null) { _succeededEvent(new CommandSucceededEvent( state.CommandName, reply, state.OperationId, replyMessage.ResponseTo, connectionId, state.Stopwatch.Elapsed)); } } private void ProcessGLEReplyMessage(CommandState state, ReplyMessage<RawBsonDocument> replyMessage, ConnectionId connectionId) { var reply = replyMessage.Documents[0]; BsonValue ok; if (!reply.TryGetValue("ok", out ok)) { // this is a degenerate case with the server and // we don't really know what to do here... } else if (!ok.ToBoolean()) { if (_failedEvent != null) { _failedEvent(new CommandFailedEvent( state.CommandName, new MongoCommandException( connectionId, string.Format("{0} command failed", state.CommandName), null, reply), state.OperationId, replyMessage.ResponseTo, connectionId, state.Stopwatch.Elapsed)); } } else if (_succeededEvent != null) { var fakeReply = new BsonDocument("ok", 1); BsonValue n; if (reply.TryGetValue("n", out n)) { fakeReply["n"] = n; } BsonValue err; if (reply.TryGetValue("err", out err) && err != BsonNull.Value) { var code = reply.GetValue("code", -1); var errmsg = err.ToString(); var isWriteConcernError = __writeConcernIndicators.Any(x => errmsg.Contains(x)); if (isWriteConcernError) { fakeReply["writeConcernError"] = new BsonDocument { { "code", code }, { "errmsg", err } }; } else { fakeReply["writeErrors"] = new BsonArray(new[] { new BsonDocument { { "index", 0 }, { "code", code }, { "errmsg", err } }}); } } else if (state.CommandName == "insert") { fakeReply["n"] = state.NumberOfInsertedDocuments; } else if (state.CommandName == "update") { // Unfortunately v2.4 GLE does not include the upserted field when // the upserted _id is non-OID type. We can detect this by the // updatedExisting field + an n of 1 BsonValue upsertedValue; var upserted = reply.TryGetValue("upserted", out upsertedValue) || (n == 1 && !reply.GetValue("updatedExisting", false).ToBoolean()); if (upserted) { fakeReply["upserted"] = new BsonArray(new[] { new BsonDocument { { "index", 0 }, { "_id", upsertedValue ?? state.UpsertedId ?? BsonUndefined.Value } }}); } } _succeededEvent(new CommandSucceededEvent( state.CommandName, fakeReply, state.OperationId, replyMessage.ResponseTo, connectionId, state.Stopwatch.Elapsed)); } } private void ProcessQueryReplyMessage(CommandState state, ReplyMessage<RawBsonDocument> replyMessage, ConnectionId connectionId) { if (_succeededEvent != null) { BsonDocument reply; if (state.CommandName == "explain") { reply = new BsonDocument("ok", 1); reply.Merge(replyMessage.Documents[0]); } else { var batchName = state.CommandName == "find" ? "firstBatch" : "nextBatch"; reply = new BsonDocument { { "cursor", new BsonDocument { { "id", replyMessage.CursorId }, { "ns", state.QueryNamespace.FullName }, { batchName, new BsonArray(replyMessage.Documents) } }}, { "ok", 1 } }; } _succeededEvent(new CommandSucceededEvent( state.CommandName, reply, state.OperationId, replyMessage.ResponseTo, connectionId, state.Stopwatch.Elapsed)); } } private void ProcessUpdateMessage(UpdateMessage originalMessage, Queue<RequestMessage> messageQueue, ConnectionId connectionId, UpdateMessageBinaryEncoder encoder, Stopwatch stopwatch) { var commandName = "update"; int requestId = originalMessage.RequestId; var operationId = EventContext.OperationId; var expectedResponseType = ExpectedResponseType.None; BsonValue upsertedId = null; int gleRequestId; WriteConcern writeConcern; if (TryGetWriteConcernFromGLE(messageQueue, out gleRequestId, out writeConcern)) { requestId = gleRequestId; expectedResponseType = ExpectedResponseType.GLE; } if (_startedEvent != null) { var decodedMessage = encoder.ReadMessage(RawBsonDocumentSerializer.Instance); try { if (_shouldTrackState) { // GLE result on older versions of the server didn't return // the upserted id when it wasn't an object id, so we'll // attempt to get it from the messages. if (!decodedMessage.Update.TryGetValue("_id", out upsertedId)) { decodedMessage.Query.TryGetValue("_id", out upsertedId); } } var entry = new BsonDocument { { "q", decodedMessage.Query }, { "u", decodedMessage.Update }, { "upsert", decodedMessage.IsUpsert }, { "multi", decodedMessage.IsMulti } }; var command = new BsonDocument { { commandName, decodedMessage.CollectionNamespace.CollectionName }, { "updates", new BsonArray(new [] { entry }) } }; if (writeConcern == null) { command["writeConcern"] = WriteConcern.Unacknowledged.ToBsonDocument(); } else if (!writeConcern.IsServerDefault) { command["writeConcern"] = writeConcern.ToBsonDocument(); } var @event = new CommandStartedEvent( commandName, command, decodedMessage.CollectionNamespace.DatabaseNamespace, operationId, requestId, connectionId); _startedEvent(@event); } finally { var disposable = decodedMessage.Query as IDisposable; if (disposable != null) { disposable.Dispose(); } disposable = decodedMessage.Update as IDisposable; if (disposable != null) { disposable.Dispose(); } } } if (_shouldTrackState) { _state.TryAdd(requestId, new CommandState { CommandName = commandName, OperationId = operationId, Stopwatch = Stopwatch.StartNew(), ExpectedResponseType = expectedResponseType, UpsertedId = upsertedId }); } } private BsonDocument BuildFindCommandFromQuery(QueryMessage message) { var batchSize = EventContext.FindOperationBatchSize ?? 0; var limit = EventContext.FindOperationLimit ?? 0; var command = new BsonDocument { { "find", message.CollectionNamespace.CollectionName }, { "projection", message.Fields, message.Fields != null }, { "skip", message.Skip, message.Skip > 0 }, { "batchSize", batchSize, batchSize > 0 }, { "limit", limit, limit != 0 }, { "awaitData", message.AwaitData, message.AwaitData }, { "noCursorTimeout", message.NoCursorTimeout, message.NoCursorTimeout }, { "allowPartialResults", message.PartialOk, message.PartialOk }, { "tailable", message.TailableCursor, message.TailableCursor }, { "oplogReplay", message.OplogReplay, message.OplogReplay } }; var query = message.Query; if (query.ElementCount == 1 && !query.Contains("$query")) { command["filter"] = query; } else { foreach (var element in query) { switch (element.Name) { case "$query": command["filter"] = element.Value; break; case "$orderby": command["sort"] = element.Value; break; case "$showDiskLoc": command["showRecordId"] = element.Value; break; case "$explain": // explain is special and gets handled elsewhere break; default: if (element.Name.StartsWith("$")) { command[element.Name.Substring(1)] = element.Value; } else { // theoretically, this should never happen and is illegal. // however, we'll push this up anyways and a command-failure // event will likely get thrown. command[element.Name] = element.Value; } break; } } } return command; } private bool TryGetWriteConcernFromGLE(Queue<RequestMessage> messageQueue, out int requestId, out WriteConcern writeConcern) { requestId = -1; writeConcern = null; if (messageQueue.Count == 0) { return false; } var message = messageQueue.Peek(); if (message.MessageType != MongoDBMessageType.Query) { return false; } var queryMessage = (QueryMessage)message; if (!IsCommand(queryMessage.CollectionNamespace)) { return false; } var query = queryMessage.Query; var firstElement = query.GetElement(0); if (firstElement.Name != "getLastError") { return false; } messageQueue.Dequeue(); // consume it so that we don't process it later... requestId = queryMessage.RequestId; writeConcern = WriteConcern.FromBsonDocument(query); return true; } private static bool IsCommand(CollectionNamespace collectionNamespace) { return collectionNamespace.Equals(collectionNamespace.DatabaseNamespace.CommandCollection); } private enum ExpectedResponseType { None, GLE, Query, Command } private class CommandState { public string CommandName; public long? OperationId; public Stopwatch Stopwatch; public CollectionNamespace QueryNamespace; public int NumberOfInsertedDocuments; public ExpectedResponseType ExpectedResponseType; public BsonDocument NoResponseResponse; public BsonValue UpsertedId; } } } <|start_filename|>Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/PackageTools/VersionedMonoBehaviour.cs<|end_filename|> using UnityEngine; namespace Pathfinding { /** Exposes internal methods from #Pathfinding.VersionedMonoBehaviour */ public interface IVersionedMonoBehaviourInternal { int OnUpgradeSerializedData (int version, bool unityThread); } /** Base class for all components in the package */ public abstract class VersionedMonoBehaviour : MonoBehaviour, ISerializationCallbackReceiver, IVersionedMonoBehaviourInternal { /** Version of the serialized data. Used for script upgrades. */ [SerializeField] [HideInInspector] int version = 0; protected virtual void Awake () { // Make sure the version field is up to date for components created during runtime. // Reset is not called when in play mode. // If the data had to be upgraded then OnAfterDeserialize would have been called earlier. if (Application.isPlaying) version = OnUpgradeSerializedData(int.MaxValue, true); } /** Handle serialization backwards compatibility */ void Reset () { // Set initial version when adding the component for the first time version = OnUpgradeSerializedData(int.MaxValue, true); } /** Handle serialization backwards compatibility */ void ISerializationCallbackReceiver.OnBeforeSerialize () { } /** Handle serialization backwards compatibility */ void ISerializationCallbackReceiver.OnAfterDeserialize () { version = OnUpgradeSerializedData(version, false); } /** Handle serialization backwards compatibility */ protected virtual int OnUpgradeSerializedData (int version, bool unityThread) { return 1; } int IVersionedMonoBehaviourInternal.OnUpgradeSerializedData (int version, bool unityThread) { return OnUpgradeSerializedData(version, unityThread); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Operations/AsyncCursorEnumerableOneTimeAdapter.cs<|end_filename|> /* Copyright 2015-present MongoDB Inc. * * 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; using System.Collections.Generic; using System.Threading; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Core.Operations { internal class AsyncCursorEnumerableOneTimeAdapter<TDocument> : IEnumerable<TDocument> { // private fields private readonly CancellationToken _cancellationToken; private readonly IAsyncCursor<TDocument> _cursor; private bool _hasBeenEnumerated; // constructors public AsyncCursorEnumerableOneTimeAdapter(IAsyncCursor<TDocument> cursor, CancellationToken cancellationToken) { _cursor = Ensure.IsNotNull(cursor, nameof(cursor)); _cancellationToken = cancellationToken; } // public methods public IEnumerator<TDocument> GetEnumerator() { if (_hasBeenEnumerated) { throw new InvalidOperationException("An IAsyncCursor can only be enumerated once."); } _hasBeenEnumerated = true; return new AsyncCursorEnumerator<TDocument>(_cursor, _cancellationToken); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <|start_filename|>Tools/FileServer/Appsettings.cs<|end_filename|> namespace ETFileServer { public class Appsettings { public string DirectoryPath; public int Port; } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Examples/4.X/UnityUI/UITwistPinch/UIPinch.cs<|end_filename|> using UnityEngine; using System.Collections; using HedgehogTeam.EasyTouch; public class UIPinch : MonoBehaviour { public void OnEnable(){ EasyTouch.On_Pinch += On_Pinch; } public void OnDestroy(){ EasyTouch.On_Pinch -= On_Pinch; } void On_Pinch (Gesture gesture){ if (gesture.isOverGui){ if (gesture.pickedUIElement == gameObject || gesture.pickedUIElement.transform.IsChildOf( transform)){ transform.localScale = new Vector3(transform.localScale.x + gesture.deltaPinch * Time.deltaTime, transform.localScale.y+gesture.deltaPinch * Time.deltaTime, transform.localScale.z ); } } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/Linq/Expressions/InjectedFilterExpression.cs<|end_filename|> /* Copyright 2016-present MongoDB Inc. * * 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.Linq.Expressions; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Linq.Expressions { internal sealed class InjectedFilterExpression : ExtensionExpression { private readonly BsonDocument _filter; public InjectedFilterExpression(BsonDocument filter) { _filter = Ensure.IsNotNull(filter, nameof(filter)); } public override ExtensionExpressionType ExtensionType => ExtensionExpressionType.InjectedFilter; public BsonDocument Filter => _filter; public override Type Type => typeof(bool); public override string ToString() => _filter.ToString(); protected internal override Expression Accept(ExtensionExpressionVisitor visitor) { return visitor.VisitInjectedFilter(this); } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/Linq/Processors/EmbeddedPipeline/MethodCallBinders/AggregateBinder.cs<|end_filename|> /* Copyright 2016-present MongoDB Inc. * * 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.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using MongoDB.Driver.Linq.Expressions; using MongoDB.Driver.Linq.Expressions.ResultOperators; using MongoDB.Driver.Support; namespace MongoDB.Driver.Linq.Processors.EmbeddedPipeline.MethodCallBinders { internal sealed class AggregateBinder : IMethodCallBinder<EmbeddedPipelineBindingContext> { public static IEnumerable<MethodInfo> GetSupportedMethods() { yield return MethodHelper.GetMethodDefinition(() => Enumerable.Aggregate<object>(null, null)); yield return MethodHelper.GetMethodDefinition(() => Enumerable.Aggregate<object, object>(null, null, null)); yield return MethodHelper.GetMethodDefinition(() => Enumerable.Aggregate<object, object, object>(null, null, null, null)); yield return MethodHelper.GetMethodDefinition(() => Queryable.Aggregate<object>(null, null)); yield return MethodHelper.GetMethodDefinition(() => Queryable.Aggregate<object, object>(null, null, null)); yield return MethodHelper.GetMethodDefinition(() => Queryable.Aggregate<object, object, object>(null, null, null, null)); } public Expression Bind(PipelineExpression pipeline, EmbeddedPipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable<Expression> arguments) { var sourceSerializer = pipeline.Projector.Serializer; var accumulatorSerializer = sourceSerializer; Expression seed; LambdaExpression lambda; var argumentCount = arguments.Count(); if (argumentCount == 1) { lambda = ExpressionHelper.GetLambda(arguments.Single()); seed = Expression.Constant(accumulatorSerializer.ValueType.GetDefaultValue()); } else { seed = arguments.First(); accumulatorSerializer = bindingContext.GetSerializer(seed.Type, seed); lambda = ExpressionHelper.GetLambda(arguments.ElementAt(1)); } if (seed.NodeType == ExpressionType.Constant) { seed = new SerializedConstantExpression(((ConstantExpression)seed).Value, accumulatorSerializer); } var valueField = new FieldExpression("$value", accumulatorSerializer); var thisField = new FieldExpression("$this", sourceSerializer); bindingContext.AddExpressionMapping(lambda.Parameters[0], valueField); bindingContext.AddExpressionMapping(lambda.Parameters[1], thisField); var reducer = bindingContext.Bind(lambda.Body); var serializer = bindingContext.GetSerializer(reducer.Type, reducer); Expression finalizer = null; string itemName = null; if (argumentCount == 3) { lambda = ExpressionHelper.GetLambda(arguments.Last()); itemName = lambda.Parameters[0].Name; var variable = new FieldExpression("$" + itemName, serializer); bindingContext.AddExpressionMapping(lambda.Parameters[0], variable); finalizer = bindingContext.Bind(lambda.Body); serializer = bindingContext.GetSerializer(finalizer.Type, finalizer); } return new PipelineExpression( pipeline.Source, new DocumentExpression(serializer), new AggregateResultOperator(seed, reducer, finalizer, itemName, serializer)); } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Packages/PackageJsonHelper.cs<|end_filename|> using System.IO; using UnityEngine; namespace UnityEditor.PackageManager.UI { internal class PackageJsonHelper { [SerializeField] private string name = string.Empty; private string path = string.Empty; public static string GetPackagePath(string jsonPath) { return Path.GetDirectoryName(jsonPath).Replace("\\", "/"); } public static PackageJsonHelper Load(string path) { // If the path is a directory, find the `package.json` file path var jsonPath = Directory.Exists(path) ? Path.Combine(path, "package.json") : path; if (!File.Exists(jsonPath)) return null; var packageJson = JsonUtility.FromJson<PackageJsonHelper>(File.ReadAllText(jsonPath)); packageJson.path = GetPackagePath(jsonPath); return string.IsNullOrEmpty(packageJson.name) ? null : packageJson; } public PackageInfo PackageInfo { get { return new PackageInfo {PackageId = string.Format("{0}@file:{1}", name, path)}; } } } } <|start_filename|>Server/ThirdParty/MongoDBDriver/MongoDB.Driver/GeoJsonObjectModel/Serializers/GeoJsonMultiLineStringCoordinatesSerializer.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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.Collections.Generic; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; namespace MongoDB.Driver.GeoJsonObjectModel.Serializers { /// <summary> /// Represents a serializer for a GeoJsonMultiLineStringCoordinates value. /// </summary> /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam> public class GeoJsonMultiLineStringCoordinatesSerializer<TCoordinates> : ClassSerializerBase<GeoJsonMultiLineStringCoordinates<TCoordinates>> where TCoordinates : GeoJsonCoordinates { // private fields private readonly IBsonSerializer<GeoJsonLineStringCoordinates<TCoordinates>> _lineStringCoordinatesSerializer = BsonSerializer.LookupSerializer<GeoJsonLineStringCoordinates<TCoordinates>>(); // protected methods /// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <param name="args">The deserialization args.</param> /// <returns>The value.</returns> protected override GeoJsonMultiLineStringCoordinates<TCoordinates> DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args) { var bsonReader = context.Reader; var lineStrings = new List<GeoJsonLineStringCoordinates<TCoordinates>>(); bsonReader.ReadStartArray(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var lineString = _lineStringCoordinatesSerializer.Deserialize(context); lineStrings.Add(lineString); } bsonReader.ReadEndArray(); return new GeoJsonMultiLineStringCoordinates<TCoordinates>(lineStrings); } /// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The value.</param> protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, GeoJsonMultiLineStringCoordinates<TCoordinates> value) { var bsonWriter = context.Writer; bsonWriter.WriteStartArray(); foreach (var lineString in value.LineStrings) { _lineStringCoordinatesSerializer.Serialize(context, lineString); } bsonWriter.WriteEndArray(); } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Examples/4.X/UnityUI/UICompatibility/UICompatibility.cs<|end_filename|> using UnityEngine; using System.Collections; using HedgehogTeam.EasyTouch; public class UICompatibility : MonoBehaviour { public void SetCompatibility(bool value){ EasyTouch.SetUICompatibily( value); } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Examples/4.X/SimpleExamples/TwoFingers/TwistMe.cs<|end_filename|> using UnityEngine; using System.Collections; using HedgehogTeam.EasyTouch; public class TwistMe : MonoBehaviour { private TextMesh textMesh; // Subscribe to events void OnEnable(){ EasyTouch.On_TouchStart2Fingers += On_TouchStart2Fingers; EasyTouch.On_Twist += On_Twist; EasyTouch.On_TwistEnd += On_TwistEnd; EasyTouch.On_Cancel2Fingers += On_Cancel2Fingers; } void OnDisable(){ UnsubscribeEvent(); } void OnDestroy(){ UnsubscribeEvent(); } void UnsubscribeEvent(){ EasyTouch.On_TouchStart2Fingers -= On_TouchStart2Fingers; EasyTouch.On_Twist -= On_Twist; EasyTouch.On_TwistEnd -= On_TwistEnd; EasyTouch.On_Cancel2Fingers -= On_Cancel2Fingers; } void Start(){ textMesh =(TextMesh) GetComponentInChildren<TextMesh>(); } void On_TouchStart2Fingers(Gesture gesture){ // Verification that the action on the object if (gesture.pickedObject == gameObject ){ // disable twist gesture recognize for a real pinch end EasyTouch.SetEnableTwist( true); EasyTouch.SetEnablePinch( false); } } // during the txist void On_Twist( Gesture gesture){ // Verification that the action on the object if (gesture.pickedObject == gameObject){ transform.Rotate( new Vector3(0,0,gesture.twistAngle)); textMesh.text = "Delta angle : " + gesture.twistAngle.ToString(); } } // at the twist end void On_TwistEnd( Gesture gesture){ // Verification that the action on the object if (gesture.pickedObject == gameObject){ EasyTouch.SetEnablePinch( true); transform.rotation = Quaternion.identity; textMesh.text ="Twist me"; } } // If the two finger gesture is finished void On_Cancel2Fingers(Gesture gesture){ EasyTouch.SetEnablePinch( true); transform.rotation = Quaternion.identity; textMesh.text ="Twist me"; } } <|start_filename|>Server/Model/Module/DB/DBTask.cs<|end_filename|> namespace ETModel { public abstract class DBTask : ComponentWithId { public abstract ETTask Run(); } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Tests/Editor/Common/UITests.cs<|end_filename|> using System.Collections.Generic; using NUnit.Framework; using UnityEditor.Experimental.UIElements; using UnityEngine; using UnityEngine.Experimental.UIElements; namespace UnityEditor.PackageManager.UI.Tests { internal abstract class UITests<TWindow> where TWindow : EditorWindow { private TWindow Window { get; set; } protected VisualElement Container { get { return Window.GetRootVisualContainer(); } } protected MockOperationFactory Factory { get; private set; } [OneTimeSetUp] protected void OneTimeSetUp() { Factory = new MockOperationFactory(); OperationFactory.Instance = Factory; Window = EditorWindow.GetWindow<TWindow>(); Window.Show(); } [OneTimeTearDown] protected void OneTimeTearDown() { OperationFactory.Reset(); Window = null; if (TestContext.CurrentContext.Result.FailCount <= 0) { PackageCollection.Instance.UpdatePackageCollection(true); } } protected void SetSearchPackages(IEnumerable<PackageInfo> packages) { Factory.SearchOperation = new MockSearchOperation(Factory, packages); PackageCollection.Instance.FetchSearchCache(true); } protected void SetListPackages(IEnumerable<PackageInfo> packages) { Factory.Packages = packages; PackageCollection.Instance.FetchListCache(true); } protected static Error MakeError(ErrorCode code, string message) { var error = "{\"errorCode\" : " + (uint)code + ", \"message\" : \"" + message + "\"}"; return JsonUtility.FromJson<Error>(error); } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouch/Examples/5.X new features/Script/SimpleActionExample.cs<|end_filename|> using UnityEngine; using System.Collections; using HedgehogTeam.EasyTouch; public class SimpleActionExample : MonoBehaviour { private TextMesh textMesh; private Vector3 startScale; void Start () { textMesh =(TextMesh) GetComponentInChildren<TextMesh>(); startScale = transform.localScale; } // Change the color public void ChangeColor(Gesture gesture){ RandomColor(); } // display action action public void TimePressed(Gesture gesture){ textMesh.text = "Down since :" + gesture.actionTime.ToString("f2"); } // Display swipe angle public void DisplaySwipeAngle(Gesture gesture){ float angle = gesture.GetSwipeOrDragAngle(); textMesh.text = angle.ToString("f2") + " / " + gesture.swipe.ToString(); } // Change text public void ChangeText(string text){ textMesh.text = text; } public void ResetScale(){ transform.localScale = startScale; } private void RandomColor(){ gameObject.GetComponent<Renderer>().material.color = new Color( Random.Range(0.0f,1.0f), Random.Range(0.0f,1.0f), Random.Range(0.0f,1.0f)); } } <|start_filename|>Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/Serialization/Serializers/NullableGenericSerializer.cs<|end_filename|> /* Copyright 2010-present MongoDB Inc. * * 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 MongoDB.Bson.IO; using MongoDB.Bson.Serialization.Attributes; namespace MongoDB.Bson.Serialization.Serializers { /// <summary> /// Represents a serializer for nullable values. /// </summary> /// <typeparam name="T">The underlying type.</typeparam> public class NullableSerializer<T> : SerializerBase<Nullable<T>>, IChildSerializerConfigurable where T : struct { // private fields private Lazy<IBsonSerializer<T>> _lazySerializer; // constructors /// <summary> /// Initializes a new instance of the <see cref="NullableSerializer{T}"/> class. /// </summary> public NullableSerializer() : this(BsonSerializer.SerializerRegistry) { } /// <summary> /// Initializes a new instance of the <see cref="NullableSerializer{T}"/> class. /// </summary> /// <param name="serializer">The serializer.</param> public NullableSerializer(IBsonSerializer<T> serializer) { if (serializer == null) { throw new ArgumentNullException("serializer"); } _lazySerializer = new Lazy<IBsonSerializer<T>>(() => serializer); } /// <summary> /// Initializes a new instance of the <see cref="NullableSerializer{T}" /> class. /// </summary> /// <param name="serializerRegistry">The serializer registry.</param> public NullableSerializer(IBsonSerializerRegistry serializerRegistry) { if (serializerRegistry == null) { throw new ArgumentNullException("serializerRegistry"); } _lazySerializer = new Lazy<IBsonSerializer<T>>(() => serializerRegistry.GetSerializer<T>()); } // public methods /// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <param name="args">The deserialization args.</param> /// <returns>A deserialized value.</returns> public override T? Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { var bsonReader = context.Reader; var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return null; } else { return _lazySerializer.Value.Deserialize(context); } } /// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The object.</param> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, T? value) { var bsonWriter = context.Writer; if (value == null) { bsonWriter.WriteNull(); } else { _lazySerializer.Value.Serialize(context, value.Value); } } /// <summary> /// Returns a serializer that has been reconfigured with the specified serializer. /// </summary> /// <param name="serializer">The serializer.</param> /// <returns> /// The reconfigured serializer. /// </returns> public NullableSerializer<T> WithSerializer(IBsonSerializer<T> serializer) { if (serializer == _lazySerializer.Value) { return this; } else { return new NullableSerializer<T>(serializer); } } // explicit interface implementations IBsonSerializer IChildSerializerConfigurable.ChildSerializer { get { return _lazySerializer.Value; } } IBsonSerializer IChildSerializerConfigurable.WithChildSerializer(IBsonSerializer childSerializer) { return WithSerializer((IBsonSerializer<T>)childSerializer); } } } <|start_filename|>Unity/Assets/EasyTouchBundle/EasyTouchControls/Examples/_Medias/SliderText.cs<|end_filename|> using UnityEngine; using UnityEngine.UI; using System.Collections; public class SliderText : MonoBehaviour { public void SetText( float value){ GetComponent<Text>().text = value.ToString("f2"); } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/UI/PackageManagerPrefs.cs<|end_filename|> using System.Linq; namespace UnityEditor.PackageManager.UI { internal static class PackageManagerPrefs { private const string kShowPreviewPackagesPrefKeyPrefix = "PackageManager.ShowPreviewPackages_"; private const string kShowPreviewPackagesWarningPrefKey = "PackageManager.ShowPreviewPackagesWarning"; private static string GetProjectIdentifier() { // PlayerSettings.productGUID is already used as LocalProjectID by Analytics, so we use it too return PlayerSettings.productGUID.ToString(); } public static bool ShowPreviewPackages { get { var key = kShowPreviewPackagesPrefKeyPrefix + GetProjectIdentifier(); // If user manually choose to show or not preview packages, use this value if (EditorPrefs.HasKey(key)) return EditorPrefs.GetBool(key); // Returns true if at least one preview package is installed, false otherwise return PackageCollection.Instance.LatestListPackages.Any(p => p.IsPreview && p.IsCurrent); } set { EditorPrefs.SetBool(kShowPreviewPackagesPrefKeyPrefix + GetProjectIdentifier(), value); } } public static bool ShowPreviewPackagesWarning { get { return EditorPrefs.GetBool(kShowPreviewPackagesWarningPrefKey, true); } set { EditorPrefs.SetBool(kShowPreviewPackagesWarningPrefKey, value); } } } } <|start_filename|>Unity/Assets/Model/Base/Object/Component.cs<|end_filename|> using System; using ETModel; using MongoDB.Bson.Serialization.Attributes; #if !SERVER using UnityEngine; #endif namespace ETModel { [BsonIgnoreExtraElements] public abstract class Component : Object, IDisposable { [BsonIgnore] public long InstanceId { get; private set; } #if !SERVER public static GameObject Global { get; } = GameObject.Find("/Global"); [BsonIgnore] public GameObject GameObject { get; protected set; } #endif [BsonIgnore] private bool isFromPool; [BsonIgnore] public bool IsFromPool { get { return this.isFromPool; } set { this.isFromPool = value; if (!this.isFromPool) { return; } if (this.InstanceId == 0) { this.InstanceId = IdGenerater.GenerateInstanceId(); } } } [BsonIgnore] public bool IsDisposed { get { return this.InstanceId == 0; } } private Component parent; [BsonIgnore] public Component Parent { get { return this.parent; } set { this.parent = value; #if !SERVER if (this.parent == null) { this.GameObject.transform.SetParent(Global.transform, false); return; } if (this.GameObject != null && this.parent.GameObject != null) { this.GameObject.transform.SetParent(this.parent.GameObject.transform, false); } #endif } } public T GetParent<T>() where T : Component { return this.Parent as T; } [BsonIgnore] public Entity Entity { get { return this.Parent as Entity; } } protected Component() { this.InstanceId = IdGenerater.GenerateInstanceId(); #if !SERVER if (!this.GetType().IsDefined(typeof(HideInHierarchy), true)) { this.GameObject = new GameObject(); this.GameObject.name = this.GetType().Name; this.GameObject.layer = LayerNames.GetLayerInt(LayerNames.HIDDEN); this.GameObject.transform.SetParent(Global.transform, false); this.GameObject.AddComponent<ComponentView>().Component = this; } #endif } public virtual void Dispose() { if (this.IsDisposed) { return; } // 触发Destroy事件 Game.EventSystem.Destroy(this); Game.EventSystem.Remove(this.InstanceId); this.InstanceId = 0; if (this.IsFromPool) { Game.ObjectPool.Recycle(this); } else { #if !SERVER if (this.GameObject != null) { UnityEngine.Object.Destroy(this.GameObject); } #endif } } public override void EndInit() { Game.EventSystem.Deserialize(this); } public override string ToString() { return MongoHelper.ToJson(this); } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/UI/Common/Alert.cs<|end_filename|> using System; using UnityEngine.Experimental.UIElements; namespace UnityEditor.PackageManager.UI { #if !UNITY_2018_3_OR_NEWER internal class AlertFactory : UxmlFactory<Alert> { protected override Alert DoCreate(IUxmlAttributes bag, CreationContext cc) { return new Alert(); } } #endif internal class Alert : VisualElement { #if UNITY_2018_3_OR_NEWER internal new class UxmlFactory : UxmlFactory<Alert> { } #endif private const string TemplatePath = PackageManagerWindow.ResourcesPath + "Templates/Alert.uxml"; private readonly VisualElement root; private const float originalPositionRight = 5.0f; private const float positionRightWithScroll = 12.0f; public Action OnCloseError; public Alert() { UIUtils.SetElementDisplay(this, false); root = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(TemplatePath).CloneTree(null); Add(root); root.StretchToParentSize(); CloseButton.clickable.clicked += () => { if (null != OnCloseError) OnCloseError(); ClearError(); }; } public void SetError(Error error) { var message = "An error occured."; if (error != null) message = error.message ?? string.Format("An error occurred ({0})", error.errorCode.ToString()); AlertMessage.text = message; UIUtils.SetElementDisplay(this, true); } public void ClearError() { UIUtils.SetElementDisplay(this, false); AdjustSize(false); AlertMessage.text = ""; OnCloseError = null; } public void AdjustSize(bool verticalScrollerVisible) { if (verticalScrollerVisible) style.positionRight = originalPositionRight + positionRightWithScroll; else style.positionRight = originalPositionRight; } private Label AlertMessage { get { return root.Q<Label>("alertMessage"); } } private Button CloseButton { get { return root.Q<Button>("close"); } } } } <|start_filename|>Unity/Library/PackageCache/[email protected]/Editor/Sources/Services/Upm/UpmAddOperation.cs<|end_filename|> using System; using UnityEditor.PackageManager.Requests; using System.Linq; namespace UnityEditor.PackageManager.UI { internal class UpmAddOperation : UpmBaseOperation, IAddOperation { public PackageInfo PackageInfo { get; protected set; } public event Action<PackageInfo> OnOperationSuccess = delegate { }; public void AddPackageAsync(PackageInfo packageInfo, Action<PackageInfo> doneCallbackAction = null, Action<Error> errorCallbackAction = null) { PackageInfo = packageInfo; OnOperationError += errorCallbackAction; OnOperationSuccess += doneCallbackAction; Start(); } protected override Request CreateRequest() { return Client.Add(PackageInfo.PackageId); } protected override void ProcessData() { var request = CurrentRequest as AddRequest; var package = FromUpmPackageInfo(request.Result).First(); OnOperationSuccess(package); } } }
ckyQwQ/CkySpaceGame
<|start_filename|>rvtUnit/Models/Test.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Windows.Media; namespace rvtUnit.Models { public class Test : INotifyPropertyChanged { private bool _IsChecked; public bool IsChecked { get { return _IsChecked; } set { _IsChecked = value; NotifyPropertyChanged("IsChecked"); } } private string _TestName; public string TestName { get { return _TestName; } set { _TestName = value; NotifyPropertyChanged("TestName"); } } private Brush _brush; public Brush Brush { get { return _brush; } set { _brush = value; NotifyPropertyChanged("Brush"); } } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } #endregion } } <|start_filename|>rvtUnit/Models/TestableDll.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.ComponentModel; namespace rvtUnit.Models { public class TestableDll : INotifyPropertyChanged { public TestableDll(string fullFileName) { Name = Path.GetFileName(fullFileName); Folder = Path.GetDirectoryName(fullFileName); IsAllChecked = true; } public IEnumerable<Test> Tests { get; set; } public string Name { get; private set; } public string Folder { get; private set; } public string FullPath { get { return (!String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Folder)) ? Path.Combine(Folder, Name) : null; } } private bool _IsAllChecked; public bool IsAllChecked { get { return _IsAllChecked; } set { _IsAllChecked = value; NotifyPropertyChanged("IsAllChecked"); if (Tests != null) { foreach (Test test in Tests) { test.IsChecked = value; } } } } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } #endregion } }
bimone/RvtUn
<|start_filename|>src/test/java/com/spotify/google/cloud/pubsub/client/PullerTest.java<|end_filename|> /*- * -\-\- * async-google-pubsub-client * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * 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. * -/-/- */ /* * Copyright (c) 2011-2016 Spotify AB * * 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.spotify.google.cloud.pubsub.client; import static java.util.Arrays.asList; import static java.util.concurrent.TimeUnit.SECONDS; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Collections; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; import java.util.function.Supplier; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class PullerTest { private static final String BASE_URI = "https://mock-pubsub/v1/"; private static final String SUBSCRIPTION = "test-subscription"; private static final String PROJECT = "test-project"; @Mock Pubsub pubsub; @Mock Puller.MessageHandler handler; final BlockingQueue<Request> requestQueue = new LinkedBlockingQueue<>(); private Puller puller; @Before public void setUp() { setUpPubsubClient(); } @After public void tearDown() throws Exception { puller.close(); } @Test public void testConfigurationGetters() throws Exception { puller = Puller.builder() .project(PROJECT) .subscription(SUBSCRIPTION) .pubsub(pubsub) .messageHandler(handler) .concurrency(3) .maxOutstandingMessages(4) .batchSize(5) .maxAckQueueSize(10) .pullIntervalMillis(1000) .build(); assertThat(puller.maxAckQueueSize(), is(10)); assertThat(puller.concurrency(), is(3)); assertThat(puller.maxOutstandingMessages(), is(4)); assertThat(puller.batchSize(), is(5)); assertThat(puller.subscription(), is(SUBSCRIPTION)); assertThat(puller.project(), is(PROJECT)); assertThat(puller.pullIntervalMillis(), is(1000L)); } @Test public void testPulling() throws Exception { puller = Puller.builder() .project(PROJECT) .subscription(SUBSCRIPTION) .pubsub(pubsub) .messageHandler(handler) .concurrency(2) .build(); // Immediately handle all messages when(handler.handleMessage(any(Puller.class), any(String.class), any(Message.class), anyString())) .thenAnswer(invocation -> { String ackId = invocation.getArgumentAt(3, String.class); return CompletableFuture.completedFuture(ackId); }); final Request r1 = requestQueue.take(); final Request r2 = requestQueue.take(); assertThat(puller.outstandingRequests(), is(2)); // Verify that concurrency limit is not exceeded final Request unexpected = requestQueue.poll(1, SECONDS); assertThat(unexpected, is(nullValue())); // Complete first request final List<ReceivedMessage> b1 = asList(ReceivedMessage.of("i1", "m1"), ReceivedMessage.of("i2", "m2")); r1.future.succeed(b1); verify(handler, timeout(1000)).handleMessage(puller, SUBSCRIPTION, b1.get(0).message(), b1.get(0).ackId()); verify(handler, timeout(1000)).handleMessage(puller, SUBSCRIPTION, b1.get(1).message(), b1.get(1).ackId()); // Verify that another request is made final Request r3 = requestQueue.take(); assertThat(puller.outstandingRequests(), is(2)); // Complete second request final List<ReceivedMessage> b2 = asList(ReceivedMessage.of("i3", "m3"), ReceivedMessage.of("i4", "m4")); r2.future.succeed(b2); verify(handler, timeout(1000)).handleMessage(puller, SUBSCRIPTION, b2.get(0).message(), b2.get(0).ackId()); verify(handler, timeout(1000)).handleMessage(puller, SUBSCRIPTION, b2.get(1).message(), b2.get(1).ackId()); } @Test public void shouldDecrementOutstandingMessagesOnHandlerError() throws Exception { assertDecrementsOutstandingMessagesOnHandlerError(StackOverflowError::new); } @Test public void shouldDecrementOutstandingMessagesOnHandlerRuntimeException() throws Exception { assertDecrementsOutstandingMessagesOnHandlerError(RuntimeException::new); } private void assertDecrementsOutstandingMessagesOnHandlerError(Supplier<Throwable> t) throws InterruptedException { puller = Puller.builder() .project(PROJECT) .subscription(SUBSCRIPTION) .pubsub(pubsub) .messageHandler(handler) .concurrency(1) .build(); // Set up a handler that throws an Error final Semaphore semaphore = new Semaphore(0); when(handler.handleMessage(any(Puller.class), any(String.class), any(Message.class), anyString())) .thenAnswer(invocation -> { semaphore.acquire(); throw t.get(); }); // Return a single message final Request r = requestQueue.take(); final ReceivedMessage m = ReceivedMessage.of("i1", "m1"); CompletableFuture.supplyAsync(() -> r.future.succeed(Collections.singletonList(m))); // Wait for the handler to get called verify(handler, timeout(1000)).handleMessage(puller, SUBSCRIPTION, m.message(), m.ackId()); // Verify that the outstanding message count was incremented assertThat(puller.outstandingMessages(), is(1)); // Make handler throw semaphore.release(); // Verify that the outstanding messsage count was decremented await().atMost(30, SECONDS).until(() -> puller.outstandingMessages() == 0); } @Test public void testMaxOutstandingMessagesLimit() throws Exception { puller = Puller.builder() .project(PROJECT) .subscription(SUBSCRIPTION) .pubsub(pubsub) .messageHandler(handler) .maxOutstandingMessages(3) .concurrency(2) .build(); final BlockingQueue<CompletableFuture<Void>> futures = new LinkedBlockingQueue<>(); when(handler.handleMessage(any(Puller.class), any(String.class), any(Message.class), anyString())) .thenAnswer(invocation -> { final CompletableFuture<Void> f = new CompletableFuture<>(); futures.add(f); final String ackId = invocation.getArgumentAt(3, String.class); return f.thenApply(ignore -> ackId); }); final Request r1 = requestQueue.take(); final Request r2 = requestQueue.take(); assertThat(puller.outstandingRequests(), is(2)); // Complete requests without immediately handling messages final List<ReceivedMessage> b1 = asList(ReceivedMessage.of("i1", "m1"), ReceivedMessage.of("i2", "m2"), ReceivedMessage.of("i3", "m3"), ReceivedMessage.of("i4", "m4")); r1.future.succeed(b1); // Verify that no new request are made until messages are handled assertThat(requestQueue.poll(1, SECONDS), is(nullValue())); assertThat(puller.outstandingRequests(), is(1)); assertThat(puller.outstandingMessages(), is(4)); // Complete handling of a single message and verify no pull is made futures.take().complete(null); assertThat(requestQueue.poll(1, SECONDS), is(nullValue())); assertThat(puller.outstandingRequests(), is(1)); assertThat(puller.outstandingMessages(), is(3)); // Complete handling of another message and verify that a pull request is made futures.take().complete(null); final Request r3 = requestQueue.take(); assertThat(puller.outstandingRequests(), is(2)); assertThat(puller.outstandingMessages(), is(2)); } @Test public void verifyCloseWillClosePubsubClient() throws Exception { puller = Puller.builder() .project(PROJECT) .subscription(SUBSCRIPTION) .pubsub(pubsub) .messageHandler(handler) .build(); puller.close(); verify(pubsub).close(); } private void setUpPubsubClient() { reset(pubsub); when(pubsub.pull(anyString(), anyString(), anyBoolean(), anyInt())) .thenAnswer(invocation -> { final String project = invocation.getArgumentAt(0, String.class); final String subscription = invocation.getArgumentAt(1, String.class); final boolean returnImmediately = invocation.getArgumentAt(2, Boolean.class); final int maxMessages = invocation.getArgumentAt(3, Integer.class); final String canonicalSubscription = Subscription.canonicalSubscription(project, subscription); final String uri = BASE_URI + canonicalSubscription + ":pull"; final RequestInfo requestInfo = RequestInfo.builder() .operation("pull") .method("POST") .uri(uri) .payloadSize(4711) .build(); final PubsubFuture<List<ReceivedMessage>> future = new PubsubFuture<>(requestInfo); requestQueue.add(new Request(future)); return future; }); } private static class Request { final PubsubFuture<List<ReceivedMessage>> future; Request(final PubsubFuture<List<ReceivedMessage>> future) { this.future = future; } } } <|start_filename|>src/test/java/com/spotify/google/cloud/pubsub/client/integration/PubsubIT.java<|end_filename|> /*- * -\-\- * async-google-pubsub-client * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * 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. * -/-/- */ /* * Copyright (c) 2011-2015 Spotify AB * * 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.spotify.google.cloud.pubsub.client.integration; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.util.Utils; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.io.BaseEncoding; import com.google.common.util.concurrent.Futures; import com.spotify.google.cloud.pubsub.client.Message; import com.spotify.google.cloud.pubsub.client.MessageBuilder; import com.spotify.google.cloud.pubsub.client.Pubsub; import com.spotify.google.cloud.pubsub.client.PubsubFuture; import com.spotify.google.cloud.pubsub.client.ReceivedMessage; import com.spotify.google.cloud.pubsub.client.Subscription; import com.spotify.google.cloud.pubsub.client.SubscriptionList; import com.spotify.google.cloud.pubsub.client.Topic; import com.spotify.google.cloud.pubsub.client.TopicList; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.net.ssl.SSLContext; import static com.spotify.google.cloud.pubsub.client.integration.Util.TEST_NAME_PREFIX; import static java.lang.Long.toHexString; import static java.lang.System.out; import static java.util.stream.Collectors.toList; import static java.util.zip.Deflater.BEST_SPEED; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * Tests talking to the real Google Cloud Pub/Sub service. */ public class PubsubIT { private static final int CONCURRENCY = 128; private static final String PROJECT = Util.defaultProject(); private static final String TOPIC = TEST_NAME_PREFIX + toHexString(ThreadLocalRandom.current().nextLong()); private static final String SUBSCRIPTION = TEST_NAME_PREFIX + toHexString(ThreadLocalRandom.current().nextLong()); private static GoogleCredential CREDENTIAL; private Pubsub pubsub; @BeforeClass public static void setUpCredentials() throws IOException { CREDENTIAL = GoogleCredential.getApplicationDefault( Utils.getDefaultTransport(), Utils.getDefaultJsonFactory()); } @Before public void setUp() { pubsub = Pubsub.builder() .maxConnections(CONCURRENCY) .credential(CREDENTIAL) .build(); } @After public void tearDown() throws ExecutionException, InterruptedException { if (pubsub != null) { pubsub.deleteSubscription(PROJECT, SUBSCRIPTION).exceptionally(t -> null).get(); pubsub.deleteTopic(PROJECT, TOPIC).exceptionally(t -> null).get(); pubsub.close(); } } @Test public void testCreateGetListDeleteTopics() throws Exception { testCreateGetListDeleteTopics(pubsub); } private static void testCreateGetListDeleteTopics(final Pubsub pubsub) throws Exception { // Create topic final Topic expected = Topic.of(PROJECT, TOPIC); { final Topic topic = pubsub.createTopic(PROJECT, TOPIC).get(); assertThat(topic, is(expected)); } // Get topic { final Topic topic = pubsub.getTopic(PROJECT, TOPIC).get(); assertThat(topic, is(expected)); } // Verify that the topic is listed { final List<Topic> topics = topics(pubsub); assertThat(topics, hasItem(expected)); } // Delete topic { pubsub.deleteTopic(PROJECT, TOPIC).get(); } // Verify that topic is gone { final Topic topic = pubsub.getTopic(PROJECT, TOPIC).get(); assertThat(topic, is(nullValue())); } { final List<Topic> topics = topics(pubsub); assertThat(topics, not(contains(expected))); } } private static List<Topic> topics(final Pubsub pubsub) throws ExecutionException, InterruptedException { final List<Topic> topics = new ArrayList<>(); Optional<String> pageToken = Optional.empty(); while (true) { final TopicList response = pubsub.listTopics(PROJECT, pageToken.orElse(null)).get(); topics.addAll(response.topics()); pageToken = response.nextPageToken(); if (!pageToken.isPresent()) { break; } } return topics; } @Test public void testCreateGetListDeleteSubscriptions() throws Exception { // Create topic to subscribe to final Topic topic = pubsub.createTopic(PROJECT, TOPIC).get(); // Create subscription final Subscription expected = Subscription.of(PROJECT, SUBSCRIPTION, TOPIC); { final Subscription subscription = pubsub.createSubscription(PROJECT, SUBSCRIPTION, TOPIC).get(); assertThat(subscription.name(), is(expected.name())); assertThat(subscription.topic(), is(expected.topic())); } // Get subscription { final Subscription subscription = pubsub.getSubscription(PROJECT, SUBSCRIPTION).get(); assertThat(subscription.name(), is(expected.name())); assertThat(subscription.topic(), is(expected.topic())); } // Verify that the subscription is listed { final List<Subscription> subscriptions = subscriptions(pubsub); assertThat(subscriptions.stream() .anyMatch(s -> s.name().equals(expected.name()) && s.topic().equals(expected.topic())), is(true)); } // Delete subscription { pubsub.deleteSubscription(PROJECT, SUBSCRIPTION).get(); } // Verify that subscription is gone { final Subscription subscription = pubsub.getSubscription(PROJECT, SUBSCRIPTION).get(); assertThat(subscription, is(nullValue())); } { final List<Subscription> subscriptions = subscriptions(pubsub); assertThat(subscriptions.stream() .noneMatch(s -> s.name().equals(expected.name())), is(true)); } } private static List<Subscription> subscriptions(final Pubsub pubsub) throws ExecutionException, InterruptedException { final List<Subscription> subscriptions = new ArrayList<>(); Optional<String> pageToken = Optional.empty(); while (true) { final SubscriptionList response = pubsub.listSubscriptions(PROJECT, pageToken.orElse(null)).get(); subscriptions.addAll(response.subscriptions()); pageToken = response.nextPageToken(); if (!pageToken.isPresent()) { break; } } return subscriptions; } @Test public void testPublish() throws IOException, ExecutionException, InterruptedException { pubsub.createTopic(PROJECT, TOPIC).get(); final String data = BaseEncoding.base64().encode("hello world".getBytes("UTF-8")); final Message message = new MessageBuilder().data(data).build(); final List<String> response = pubsub.publish(PROJECT, TOPIC, message).get(); out.println(response); } @Test public void testPullSingle() throws IOException, ExecutionException, InterruptedException { // Create topic and subscription pubsub.createTopic(PROJECT, TOPIC).get(); pubsub.createSubscription(PROJECT, SUBSCRIPTION, TOPIC).get(); // Publish a message final String data = BaseEncoding.base64().encode("hello world".getBytes("UTF-8")); final Message message = Message.of(data); final List<String> ids = pubsub.publish(PROJECT, TOPIC, message).get(); final String id = ids.get(0); final List<ReceivedMessage> response = pubsub.pull(PROJECT, SUBSCRIPTION, false).get(); // Verify received message assertThat(response.size(), is(1)); assertThat(response.get(0).message().data(), is(data)); assertThat(response.get(0).message().messageId().get(), is(id)); assertThat(response.get(0).message().publishTime().get(), is(notNullValue())); assertThat(response.get(0).ackId(), not(isEmptyOrNullString())); // Modify ack deadline pubsub.modifyAckDeadline(PROJECT, SUBSCRIPTION, 30, response.get(0).ackId()).get(); // Ack message pubsub.acknowledge(PROJECT, SUBSCRIPTION, response.get(0).ackId()).get(); } @Test public void testPullBatch() throws IOException, ExecutionException, InterruptedException { pubsub.createTopic(PROJECT, TOPIC).get(); pubsub.createSubscription(PROJECT, SUBSCRIPTION, TOPIC).get(); final List<Message> messages = ImmutableList.of(Message.ofEncoded("m0"), Message.ofEncoded("m1"), Message.ofEncoded("m2")); final List<String> ids = pubsub.publish(PROJECT, TOPIC, messages).get(); final Map<String, ReceivedMessage> received = new HashMap<>(); // Pull until we've received 3 messages or time out. Store received messages in a map as they might be out of order. final long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); while (true) { final List<ReceivedMessage> response = pubsub.pull(PROJECT, SUBSCRIPTION).get(); for (final ReceivedMessage message : response) { received.put(message.message().messageId().get(), message); } if (received.size() >= 3) { break; } if (System.nanoTime() > deadlineNanos) { fail("timeout"); } } // Verify received messages assertThat(received.size(), is(3)); for (int i = 0; i < 3; i++) { final String id = ids.get(i); final ReceivedMessage receivedMessage = received.get(id); assertThat(receivedMessage.message().data(), is(messages.get(i).data())); assertThat(receivedMessage.message().messageId().get(), is(id)); assertThat(receivedMessage.ackId(), not(isEmptyOrNullString())); } final List<String> ackIds = received.values().stream() .map(ReceivedMessage::ackId) .collect(Collectors.toList()); // Batch modify ack deadline pubsub.modifyAckDeadline(PROJECT, SUBSCRIPTION, 30, ackIds).get(); // Batch ack the messages pubsub.acknowledge(PROJECT, SUBSCRIPTION, ackIds).get(); } @Test public void testBestSpeedCompressionPublish() throws IOException, ExecutionException, InterruptedException { pubsub = Pubsub.builder() .maxConnections(CONCURRENCY) .credential(CREDENTIAL) .compressionLevel(BEST_SPEED) .build(); pubsub.createTopic(PROJECT, TOPIC).get(); final String data = BaseEncoding.base64().encode(Strings.repeat("hello world", 100).getBytes("UTF-8")); final Message message = new MessageBuilder().data(data).build(); final PubsubFuture<List<String>> future = pubsub.publish(PROJECT, TOPIC, message); out.println("raw size: " + data.length()); out.println("payload size: " + future.payloadSize()); } @Test public void testEnabledCipherSuites() throws Exception { pubsub.close(); final String[] defaultCiphers = SSLContext.getDefault().getDefaultSSLParameters().getCipherSuites(); final List<String> nonGcmCiphers = Stream.of(defaultCiphers) .filter(cipher -> !cipher.contains("GCM")) .collect(Collectors.toList()); pubsub = Pubsub.builder() .maxConnections(CONCURRENCY) .credential(CREDENTIAL) .enabledCipherSuites(nonGcmCiphers) .build(); testCreateGetListDeleteTopics(pubsub); } @Test @Ignore public void listAllTopics() throws ExecutionException, InterruptedException { topics(pubsub).stream().map(Topic::name).forEach(System.out::println); } @Test @Ignore public void listAllSubscriptions() throws ExecutionException, InterruptedException { subscriptions(pubsub).stream().map(s -> s.name() + ", topic=" + s.topic()).forEach(System.out::println); } @Test @Ignore public void cleanUpTestTopics() throws ExecutionException, InterruptedException { final ExecutorService executor = Executors.newFixedThreadPool(CONCURRENCY / 2); Optional<String> pageToken = Optional.empty(); while (true) { final TopicList response = pubsub.listTopics(PROJECT, pageToken.orElse(null)).get(); response.topics().stream() .map(Topic::name) .filter(t -> t.contains(TEST_NAME_PREFIX)) .map(t -> executor.submit(() -> { System.out.println("Removing topic: " + t); return pubsub.deleteTopic(t).get(); })) .collect(toList()) .forEach(Futures::getUnchecked); pageToken = response.nextPageToken(); if (!pageToken.isPresent()) { break; } } } @Test @Ignore public void cleanUpTestSubscriptions() throws ExecutionException, InterruptedException { final ExecutorService executor = Executors.newFixedThreadPool(CONCURRENCY / 2); Optional<String> pageToken = Optional.empty(); while (true) { final SubscriptionList response = pubsub.listSubscriptions(PROJECT, pageToken.orElse(null)).get(); response.subscriptions().stream() .map(Subscription::name) .filter(s -> s.contains(TEST_NAME_PREFIX)) .map(s -> executor.submit(() -> { System.out.println("Removing subscription: " + s); return pubsub.deleteSubscription(s).get(); })) .collect(toList()) .forEach(Futures::getUnchecked); pageToken = response.nextPageToken(); if (!pageToken.isPresent()) { break; } } } } <|start_filename|>src/main/java/com/spotify/google/cloud/pubsub/client/Json.java<|end_filename|> /*- * -\-\- * async-google-pubsub-client * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * 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. * -/-/- */ /* * Copyright (c) 2011-2015 Spotify AB * * 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.spotify.google.cloud.pubsub.client; import com.google.common.base.Throwables; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import io.norberg.automatter.jackson.AutoMatterModule; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; class Json { private static final ObjectMapper MAPPER = new ObjectMapper() .setSerializationInclusion(NON_EMPTY) .configure(FAIL_ON_UNKNOWN_PROPERTIES, false) .registerModule(new AutoMatterModule()) .registerModule(new Jdk8Module()) .registerModule(new JavaTimeModule()) .registerModule(new GuavaModule()); static <T> T read(final byte[] src, final Class<T> cls) throws IOException { return MAPPER.readValue(src, cls); } static <T> T read(final InputStream src, final Class<T> cls) throws IOException { return MAPPER.readValue(src, cls); } static byte[] write(final Object value) { try { return MAPPER.writeValueAsBytes(value); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } } static void write(final OutputStream stream, final Object value) throws IOException { try { MAPPER.writeValue(stream, value); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } } } <|start_filename|>src/main/java/com/spotify/google/cloud/pubsub/client/Pubsub.java<|end_filename|> /*- * -\-\- * async-google-pubsub-client * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * 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. * -/-/- */ /* * Copyright (c) 2011-2015 Spotify AB * * 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.spotify.google.cloud.pubsub.client; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.util.concurrent.MoreExecutors.getExitingExecutorService; import static com.google.common.util.concurrent.MoreExecutors.getExitingScheduledExecutorService; import static com.spotify.google.cloud.pubsub.client.Message.isEncoded; import static com.spotify.google.cloud.pubsub.client.Pubsub.ResponseReader.VOID; import static com.spotify.google.cloud.pubsub.client.Subscription.canonicalSubscription; import static com.spotify.google.cloud.pubsub.client.Subscription.validateCanonicalSubscription; import static com.spotify.google.cloud.pubsub.client.Topic.canonicalTopic; import static com.spotify.google.cloud.pubsub.client.Topic.validateCanonicalTopic; import static java.util.Arrays.asList; import static java.util.concurrent.TimeUnit.SECONDS; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_ENCODING; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import static org.jboss.netty.handler.codec.http.HttpHeaders.Values.GZIP; import static org.jboss.netty.handler.codec.http.HttpMethod.POST; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.util.Utils; import com.google.api.client.http.ByteArrayContent; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.io.ByteStreams; import com.ning.http.client.AsyncHandler; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.HttpResponseBodyPart; import com.ning.http.client.HttpResponseHeaders; import com.ning.http.client.HttpResponseStatus; import com.ning.http.client.Request; import com.ning.http.client.RequestBuilder; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import java.util.function.Function; import java.util.zip.Deflater; import java.util.zip.GZIPOutputStream; import javax.net.ssl.SSLSocketFactory; import org.jboss.netty.handler.codec.http.HttpMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An async low-level Google Cloud Pub/Sub client. */ public class Pubsub implements Closeable { private static final Logger log = LoggerFactory.getLogger(Pubsub.class); private static final String VERSION = "1.0.0"; private static final String USER_AGENT = "Spotify-Google-Pubsub-Java-Client/" + VERSION + " (gzip)"; private static final Object NO_PAYLOAD = new Object(); private static final String CLOUD_PLATFORM = "https://www.googleapis.com/auth/cloud-platform"; private static final String PUBSUB = "https://www.googleapis.com/auth/pubsub"; private static final List<String> SCOPES = ImmutableList.of(CLOUD_PLATFORM, PUBSUB); private static final String APPLICATION_JSON_UTF8 = "application/json; charset=UTF-8"; private static final int DEFAULT_PULL_MAX_MESSAGES = 1000; private static final boolean DEFAULT_PULL_RETURN_IMMEDIATELY = true; private final AsyncHttpClient client; private final String baseUri; private final Credential credential; private final CompletableFuture<Void> closeFuture = new CompletableFuture<>(); private final ScheduledExecutorService scheduler = getExitingScheduledExecutorService( new ScheduledThreadPoolExecutor(1)); private final ExecutorService executor = getExitingExecutorService( (ThreadPoolExecutor) Executors.newCachedThreadPool()); private volatile String accessToken; private final int compressionLevel; private NetHttpTransport transport; private Pubsub(final Builder builder) { final AsyncHttpClientConfig config = builder.clientConfig.build(); log.debug("creating new pubsub client with config:"); log.debug("uri: {}", builder.uri); log.debug("connect timeout: {}", config.getConnectTimeout()); log.debug("read timeout: {}", config.getReadTimeout()); log.debug("request timeout: {}", config.getRequestTimeout()); log.debug("max connections: {}", config.getMaxConnections()); log.debug("max connections per host: {}", config.getMaxConnectionsPerHost()); log.debug("enabled cipher suites: {}", Arrays.toString(config.getEnabledCipherSuites())); log.debug("response compression enforced: {}", config.isCompressionEnforced()); log.debug("request compression level: {}", builder.compressionLevel); log.debug("accept any certificate: {}", config.isAcceptAnyCertificate()); log.debug("follows redirect: {}", config.isFollowRedirect()); log.debug("pooled connection TTL: {}", config.getConnectionTTL()); log.debug("pooled connection idle timeout: {}", config.getPooledConnectionIdleTimeout()); log.debug("pooling connections: {}", config.isAllowPoolingConnections()); log.debug("pooling SSL connections: {}", config.isAllowPoolingSslConnections()); log.debug("user agent: {}", config.getUserAgent()); log.debug("max request retry: {}", config.getMaxRequestRetry()); final SSLSocketFactory sslSocketFactory = new ConfigurableSSLSocketFactory(config.getEnabledCipherSuites(), (SSLSocketFactory) SSLSocketFactory.getDefault()); this.transport = new NetHttpTransport.Builder() .setSslSocketFactory(sslSocketFactory) .build(); this.client = new AsyncHttpClient(config); this.compressionLevel = builder.compressionLevel; if (builder.credential == null) { this.credential = scoped(defaultCredential()); } else { this.credential = scoped(builder.credential); } this.baseUri = builder.uri.toString(); // Get initial access token refreshAccessToken(); if (accessToken == null) { throw new RuntimeException("Failed to get access token"); } // Wake up every 10 seconds to check if access token has expired scheduler.scheduleAtFixedRate(this::refreshAccessToken, 10, 10, SECONDS); } private Credential scoped(final Credential credential) { if (credential instanceof GoogleCredential) { return scoped((GoogleCredential) credential); } return credential; } private Credential scoped(final GoogleCredential credential) { if (credential.createScopedRequired()) { return credential.createScoped(SCOPES); } return credential; } private static Credential defaultCredential() { try { return GoogleCredential.getApplicationDefault( Utils.getDefaultTransport(), Utils.getDefaultJsonFactory()); } catch (IOException e) { throw Throwables.propagate(e); } } /** * Close this {@link Pubsub} client. */ @Override public void close() { executor.shutdown(); scheduler.shutdown(); client.close(); closeFuture.complete(null); } /** * Get a future that is completed when this {@link Pubsub} client is closed. */ public CompletableFuture<Void> closeFuture() { return closeFuture; } /** * Refresh the Google Cloud API access token, if necessary. */ private void refreshAccessToken() { final Long expiresIn = credential.getExpiresInSeconds(); // trigger refresh if token is about to expire String accessToken = credential.getAccessToken(); if (accessToken == null || expiresIn != null && expiresIn <= 60) { try { credential.refreshToken(); accessToken = credential.getAccessToken(); } catch (final IOException e) { log.error("Failed to fetch access token", e); } } if (accessToken != null) { this.accessToken = accessToken; } } /** * List the Pub/Sub topics in a project. This will get the first page of topics. To enumerate all topics you might * have to make further calls to {@link #listTopics(String, String)} with the page token in order to get further * pages. * * @param project The Google Cloud project. * @return A future that is completed when this request is completed. */ public PubsubFuture<TopicList> listTopics(final String project) { final String path = "projects/" + project + "/topics"; return get("list topics", path, readJson(TopicList.class)); } /** * Get a page of Pub/Sub topics in a project using a specified page token. * * @param project The Google Cloud project. * @param pageToken A token for the page of topics to get. * @return A future that is completed when this request is completed. */ public PubsubFuture<TopicList> listTopics(final String project, final String pageToken) { final String query = (pageToken == null) ? "" : "?pageToken=" + pageToken; final String path = "projects/" + project + "/topics" + query; return get("list topics", path, readJson(TopicList.class)); } /** * Create a Pub/Sub topic. * * @param project The Google Cloud project. * @param topic The name of the topic to create. * @return A future that is completed when this request is completed. */ public PubsubFuture<Topic> createTopic(final String project, final String topic) { return createTopic(canonicalTopic(project, topic)); } /** * Create a Pub/Sub topic. * * @param canonicalTopic The canonical (including project) name of the topic to create. * @return A future that is completed when this request is completed. */ private PubsubFuture<Topic> createTopic(final String canonicalTopic) { validateCanonicalTopic(canonicalTopic); return put("create topic", canonicalTopic, NO_PAYLOAD, readJson(Topic.class)); } /** * Get a Pub/Sub topic. * * @param project The Google Cloud project. * @param topic The name of the topic to get. * @return A future that is completed when this request is completed. The future will be completed with {@code null} * if the response is 404. */ public PubsubFuture<Topic> getTopic(final String project, final String topic) { return getTopic(canonicalTopic(project, topic)); } /** * Get a Pub/Sub topic. * * @param canonicalTopic The canonical (including project) name of the topic to get. * @return A future that is completed when this request is completed. The future will be completed with {@code null} * if the response is 404. */ public PubsubFuture<Topic> getTopic(final String canonicalTopic) { validateCanonicalTopic(canonicalTopic); return get("get topic", canonicalTopic, readJson(Topic.class)); } /** * Delete a Pub/Sub topic. * * @param project The Google Cloud project. * @param topic The name of the topic to delete. * @return A future that is completed when this request is completed. The future will be completed with {@code null} * if the response is 404. */ public PubsubFuture<Void> deleteTopic(final String project, final String topic) { return deleteTopic(canonicalTopic(project, topic)); } /** * Delete a Pub/Sub topic. * * @param canonicalTopic The canonical (including project) name of the topic to delete. * @return A future that is completed when this request is completed. The future will be completed with {@code null} * if the response is 404. */ public PubsubFuture<Void> deleteTopic(final String canonicalTopic) { validateCanonicalTopic(canonicalTopic); return delete("delete topic", canonicalTopic, VOID); } /** * Create a Pub/Sub subscription. * * @param project The Google Cloud project. * @param subscriptionName The name of the subscription to create. * @param topic The name of the topic to subscribe to. * @return A future that is completed when this request is completed. */ public PubsubFuture<Subscription> createSubscription(final String project, final String subscriptionName, final String topic) { return createSubscription(canonicalSubscription(project, subscriptionName), canonicalTopic(project, topic)); } /** * List the Pub/Sub subscriptions in a project. This will get the first page of subscriptions. To enumerate all * subscriptions you might have to make further calls to {@link #listTopics(String, String)} with the page token in * order to get further pages. * * @param project The Google Cloud project. * @return A future that is completed when this request is completed. */ public PubsubFuture<SubscriptionList> listSubscriptions(final String project) { final String path = "projects/" + project + "/subscriptions"; return get("list subscriptions", path, readJson(SubscriptionList.class)); } /** * Get a page of Pub/Sub subscriptions in a project using a specified page token. * * @param project The Google Cloud project. * @param pageToken A token for the page of subscriptions to get. * @return A future that is completed when this request is completed. */ public PubsubFuture<SubscriptionList> listSubscriptions(final String project, final String pageToken) { final String query = (pageToken == null) ? "" : "?pageToken=" + pageToken; final String path = "projects/" + project + "/subscriptions" + query; return get("list subscriptions", path, readJson(SubscriptionList.class)); } /** * Create a Pub/Sub subscription. * * @param canonicalSubscriptionName The canonical (including project) name of the scubscription to create. * @param canonicalTopic The canonical (including project) name of the topic to subscribe to. * @return A future that is completed when this request is completed. */ public PubsubFuture<Subscription> createSubscription(final String canonicalSubscriptionName, final String canonicalTopic) { return createSubscription(Subscription.of(canonicalSubscriptionName, canonicalTopic)); } /** * Create a Pub/Sub subscription. * * @param subscription The subscription to create. * @return A future that is completed when this request is completed. */ private PubsubFuture<Subscription> createSubscription(final Subscription subscription) { return createSubscription(subscription.name(), subscription); } /** * Create a Pub/Sub subscription. * * @param canonicalSubscriptionName The canonical (including project) name of the subscription to create. * @param subscription The subscription to create. * @return A future that is completed when this request is completed. */ private PubsubFuture<Subscription> createSubscription(final String canonicalSubscriptionName, final Subscription subscription) { validateCanonicalSubscription(canonicalSubscriptionName); return put("create subscription", canonicalSubscriptionName, SubscriptionCreateRequest.of(subscription), readJson(Subscription.class)); } /** * Get a Pub/Sub subscription. * * @param project The Google Cloud project. * @param subscription The name of the subscription to get. * @return A future that is completed when this request is completed. The future will be completed with {@code null} * if the response is 404. */ public PubsubFuture<Subscription> getSubscription(final String project, final String subscription) { return getSubscription(canonicalSubscription(project, subscription)); } /** * Get a Pub/Sub subscription. * * @param canonicalSubscriptionName The canonical (including project) name of the subscription to get. * @return A future that is completed when this request is completed. The future will be completed with {@code null} * if the response is 404. */ public PubsubFuture<Subscription> getSubscription(final String canonicalSubscriptionName) { validateCanonicalSubscription(canonicalSubscriptionName); return get("get subscription", canonicalSubscriptionName, readJson(Subscription.class)); } /** * Delete a Pub/Sub subscription. * * @param project The Google Cloud project. * @param subscription The name of the subscription to delete. * @return A future that is completed when this request is completed. The future will be completed with {@code null} * if the response is 404. */ public PubsubFuture<Void> deleteSubscription(final String project, final String subscription) { return deleteSubscription(canonicalSubscription(project, subscription)); } /** * Delete a Pub/Sub subscription. * * @param canonicalSubscriptionName The canonical (including project) name of the subscription to delete. * @return A future that is completed when this request is completed. The future will be completed with {@code null} * if the response is 404. */ public PubsubFuture<Void> deleteSubscription(final String canonicalSubscriptionName) { validateCanonicalSubscription(canonicalSubscriptionName); return delete("delete subscription", canonicalSubscriptionName, VOID); } /** * Publish a batch of messages. * * @param project The Google Cloud project. * @param topic The topic to publish on. * @param messages The batch of messages. * @return a future that is completed with a list of message ID's for the published messages. */ public PubsubFuture<List<String>> publish(final String project, final String topic, final Message... messages) { return publish(project, topic, asList(messages)); } /** * Publish a batch of messages. * * @param project The Google Cloud project. * @param topic The topic to publish on. * @param messages The batch of messages. * @return a future that is completed with a list of message ID's for the published messages. */ public PubsubFuture<List<String>> publish(final String project, final String topic, final List<Message> messages) { return publish0(messages, Topic.canonicalTopic(project, topic)); } /** * Publish a batch of messages. * * @param messages The batch of messages. * @param canonicalTopic The canonical topic to publish on. * @return a future that is completed with a list of message ID's for the published messages. */ public PubsubFuture<List<String>> publish(final List<Message> messages, final String canonicalTopic) { Topic.validateCanonicalTopic(canonicalTopic); return publish0(messages, canonicalTopic); } /** * Publish a batch of messages. * * @param messages The batch of messages. * @param canonicalTopic The canonical topic to publish on. * @return a future that is completed with a list of message ID's for the published messages. */ private PubsubFuture<List<String>> publish0(final List<Message> messages, final String canonicalTopic) { final String path = canonicalTopic + ":publish"; for (final Message message : messages) { if (!isEncoded(message)) { throw new IllegalArgumentException("Message data must be Base64 encoded: " + message); } } return post("publish", path, PublishRequest.of(messages), readJson(PublishResponse.class) .andThen(PublishResponse::messageIds)); } /** * Pull a batch of messages. * * @param project The Google Cloud project. * @param subscription The subscription to pull from. * @return a future that is completed with a list of received messages. */ public PubsubFuture<List<ReceivedMessage>> pull(final String project, final String subscription) { return pull(project, subscription, DEFAULT_PULL_RETURN_IMMEDIATELY, DEFAULT_PULL_MAX_MESSAGES); } /** * Pull a batch of messages. * * @param project The Google Cloud project. * @param subscription The subscription to pull from. * @param returnImmediately {@code true} to return immediately if the queue is empty. {@code false} to wait for at * least one message before returning. * @return a future that is completed with a list of received messages. */ public PubsubFuture<List<ReceivedMessage>> pull(final String project, final String subscription, final boolean returnImmediately) { return pull(project, subscription, returnImmediately, DEFAULT_PULL_MAX_MESSAGES); } /** * Pull a batch of messages. * * @param project The Google Cloud project. * @param subscription The subscription to pull from. * @param returnImmediately {@code true} to return immediately if the queue is empty. {@code false} to wait for at * least one message before returning. * @param maxMessages Maximum number of messages to return in batch. * @return a future that is completed with a list of received messages. */ public PubsubFuture<List<ReceivedMessage>> pull(final String project, final String subscription, final boolean returnImmediately, final int maxMessages) { return pull(Subscription.canonicalSubscription(project, subscription), returnImmediately, maxMessages); } /** * Pull a batch of messages. * * @param canonicalSubscriptionName The canonical (including project name) subscription to pull from. * @return a future that is completed with a list of received messages. */ public PubsubFuture<List<ReceivedMessage>> pull(final String canonicalSubscriptionName) { return pull(canonicalSubscriptionName, DEFAULT_PULL_RETURN_IMMEDIATELY); } /** * Pull a batch of messages. * * @param canonicalSubscriptionName The canonical (including project name) subscription to pull from. * @param returnImmediately {@code true} to return immediately if the queue is empty. {@code false} to wait * for at least one message before returning. * @return a future that is completed with a list of received messages. */ public PubsubFuture<List<ReceivedMessage>> pull(final String canonicalSubscriptionName, final boolean returnImmediately) { return pull(canonicalSubscriptionName, returnImmediately, DEFAULT_PULL_MAX_MESSAGES); } /** * Pull a batch of messages. * * @param canonicalSubscriptionName The canonical (including project name) subscription to pull from. * @param returnImmediately {@code true} to return immediately if the queue is empty. {@code false} to wait * for at least one message before returning. * @param maxMessages Maximum number of messages to return in batch. * @return a future that is completed with a list of received messages. */ public PubsubFuture<List<ReceivedMessage>> pull(final String canonicalSubscriptionName, final boolean returnImmediately, final int maxMessages) { final String path = canonicalSubscriptionName + ":pull"; final PullRequest req = PullRequest.builder() .returnImmediately(returnImmediately) .maxMessages(maxMessages) .build(); return pull(path, req); } /** * Pull a batch of messages. * * @param pullRequest The pull request. * @return a future that is completed with a list of received messages. */ public PubsubFuture<List<ReceivedMessage>> pull(final String path, final PullRequest pullRequest) { // TODO (dano): use async client when chunked encoding is fixed // return post("pull", path, pullRequest, PullResponse.class) // .thenApply(PullResponse::receivedMessages); return requestJavaNet("pull", POST, path, pullRequest, readJson(PullResponse.class).andThen(PullResponse::receivedMessages)); } /** * Acknowledge a batch of received messages. * * @param project The Google Cloud project. * @param subscription The subscription to acknowledge messages on. * @param ackIds List of message ID's to acknowledge. * @return A future that is completed when this request is completed. */ public PubsubFuture<Void> acknowledge(final String project, final String subscription, final String... ackIds) { return acknowledge(project, subscription, asList(ackIds)); } /** * Acknowledge a batch of received messages. * * @param project The Google Cloud project. * @param subscription The subscription to acknowledge messages on. * @param ackIds List of message ID's to acknowledge. * @return A future that is completed when this request is completed. */ public PubsubFuture<Void> acknowledge(final String project, final String subscription, final List<String> ackIds) { return acknowledge(Subscription.canonicalSubscription(project, subscription), ackIds); } /** * Acknowledge a batch of received messages. * * @param canonicalSubscriptionName The canonical (including project name) subscription to acknowledge messages on. * @param ackIds List of message ID's to acknowledge. * @return A future that is completed when this request is completed. */ public PubsubFuture<Void> acknowledge(final String canonicalSubscriptionName, final List<String> ackIds) { final String path = canonicalSubscriptionName + ":acknowledge"; final AcknowledgeRequest req = AcknowledgeRequest.builder() .ackIds(ackIds) .build(); return post("acknowledge", path, req, VOID); } /** * Modify the ack deadline for a list of received messages. * * @param project The Google Cloud project. * @param subscription The subscription of the received message to modify the ack deadline on. * @param ackDeadlineSeconds The new ack deadline. * @param ackIds List of message ID's to modify the ack deadline on. * @return A future that is completed when this request is completed. */ public PubsubFuture<Void> modifyAckDeadline(final String project, final String subscription, final int ackDeadlineSeconds, final String... ackIds) { return modifyAckDeadline(project, subscription, ackDeadlineSeconds, asList(ackIds)); } /** * Modify the ack deadline for a list of received messages. * * @param project The Google Cloud project. * @param subscription The subscription of the received message to modify the ack deadline on. * @param ackDeadlineSeconds The new ack deadline. * @param ackIds List of message ID's to modify the ack deadline on. * @return A future that is completed when this request is completed. */ public PubsubFuture<Void> modifyAckDeadline(final String project, final String subscription, final int ackDeadlineSeconds, final List<String> ackIds) { return modifyAckDeadline(Subscription.canonicalSubscription(project, subscription), ackDeadlineSeconds, ackIds); } /** * Modify the ack deadline for a list of received messages. * * @param canonicalSubscriptionName The canonical (including project name) subscription of the received message to * modify the ack deadline on. * @param ackDeadlineSeconds The new ack deadline. * @param ackIds List of message ID's to modify the ack deadline on. * @return A future that is completed when this request is completed. */ public PubsubFuture<Void> modifyAckDeadline(final String canonicalSubscriptionName, final int ackDeadlineSeconds, final List<String> ackIds) { final String path = canonicalSubscriptionName + ":modifyAckDeadline"; final ModifyAckDeadlineRequest req = ModifyAckDeadlineRequest.builder() .ackDeadlineSeconds(ackDeadlineSeconds) .ackIds(ackIds) .build(); return post("modify ack deadline", path, req, VOID); } /** * Make a GET request. */ private <T> PubsubFuture<T> get(final String operation, final String path, final ResponseReader<T> responseReader) { return request(operation, HttpMethod.GET, path, responseReader); } /** * Make a POST request. */ private <T> PubsubFuture<T> post(final String operation, final String path, final Object payload, final ResponseReader<T> responseReader) { return request(operation, HttpMethod.POST, path, payload, responseReader); } /** * Make a PUT request. */ private <T> PubsubFuture<T> put(final String operation, final String path, final Object payload, final ResponseReader<T> responseReader) { return request(operation, HttpMethod.PUT, path, payload, responseReader); } /** * Make a DELETE request. */ private <T> PubsubFuture<T> delete(final String operation, final String path, final ResponseReader<T> responseReader) { return request(operation, HttpMethod.DELETE, path, responseReader); } /** * Make an HTTP request. */ private <T> PubsubFuture<T> request(final String operation, final HttpMethod method, final String path, final ResponseReader<T> responseReader) { return request(operation, method, path, NO_PAYLOAD, responseReader); } /** * Make an HTTP request. */ private <T> PubsubFuture<T> request(final String operation, final HttpMethod method, final String path, final Object payload, final ResponseReader<T> responseReader) { final String uri = baseUri + path; final RequestBuilder builder = new RequestBuilder() .setUrl(uri) .setMethod(method.toString()) .setHeader("Authorization", "Bearer " + accessToken) .setHeader("User-Agent", USER_AGENT); final long payloadSize; if (payload != NO_PAYLOAD) { final byte[] json = gzipJson(payload); payloadSize = json.length; builder.setHeader(CONTENT_ENCODING, GZIP); builder.setHeader(CONTENT_LENGTH, String.valueOf(json.length)); builder.setHeader(CONTENT_TYPE, APPLICATION_JSON_UTF8); builder.setBody(json); } else { builder.setHeader(CONTENT_LENGTH, String.valueOf(0)); payloadSize = 0; } final Request request = builder.build(); final RequestInfo requestInfo = RequestInfo.builder() .operation(operation) .method(method.toString()) .uri(uri) .payloadSize(payloadSize) .build(); final PubsubFuture<T> future = new PubsubFuture<>(requestInfo); client.executeRequest(request, new AsyncHandler<Void>() { private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); @Override public void onThrowable(final Throwable t) { future.fail(t); } @Override public STATE onBodyPartReceived(final HttpResponseBodyPart bodyPart) throws Exception { bytes.write(bodyPart.getBodyPartBytes()); return STATE.CONTINUE; } @Override public STATE onStatusReceived(final HttpResponseStatus status) throws Exception { // Return null for 404'd GET & DELETE requests if (status.getStatusCode() == 404 && method == HttpMethod.GET || method == HttpMethod.DELETE) { future.succeed(null); return STATE.ABORT; } // Fail on non-2xx responses final int statusCode = status.getStatusCode(); if (!(statusCode >= 200 && statusCode < 300)) { future.fail(new RequestFailedException(status.getStatusCode(), status.getStatusText())); return STATE.ABORT; } if (responseReader == VOID) { future.succeed(null); return STATE.ABORT; } return STATE.CONTINUE; } @Override public STATE onHeadersReceived(final HttpResponseHeaders headers) throws Exception { return STATE.CONTINUE; } @Override public Void onCompleted() throws Exception { if (future.isDone()) { return null; } try { future.succeed(responseReader.read(bytes.toByteArray())); } catch (Exception e) { future.fail(e); } return null; } }); return future; } /** * Make an HTTP request using {@link java.net.HttpURLConnection}. */ private <T> PubsubFuture<T> requestJavaNet(final String operation, final HttpMethod method, final String path, final Object payload, final ResponseReader<T> responseReader) { final HttpRequestFactory requestFactory = transport.createRequestFactory(); final String uri = baseUri + path; final HttpHeaders headers = new HttpHeaders(); final HttpRequest request; try { request = requestFactory.buildRequest(method.getName(), new GenericUrl(URI.create(uri)), null); } catch (IOException e) { throw Throwables.propagate(e); } headers.setAuthorization("Bearer " + accessToken); headers.setUserAgent("Spotify"); final long payloadSize; if (payload != NO_PAYLOAD) { final byte[] json = gzipJson(payload); payloadSize = json.length; headers.setContentEncoding(GZIP); headers.setContentLength((long) json.length); headers.setContentType(APPLICATION_JSON_UTF8); request.setContent(new ByteArrayContent(APPLICATION_JSON_UTF8, json)); } else { payloadSize = 0; } request.setHeaders(headers); final RequestInfo requestInfo = RequestInfo.builder() .operation(operation) .method(method.toString()) .uri(uri) .payloadSize(payloadSize) .build(); final PubsubFuture<T> future = new PubsubFuture<>(requestInfo); executor.execute(() -> { final HttpResponse response; try { response = request.execute(); } catch (IOException e) { future.fail(e); return; } // Return null for 404'd GET & DELETE requests if (response.getStatusCode() == 404 && method == HttpMethod.GET || method == HttpMethod.DELETE) { future.succeed(null); return; } // Fail on non-2xx responses final int statusCode = response.getStatusCode(); if (!(statusCode >= 200 && statusCode < 300)) { future.fail(new RequestFailedException(response.getStatusCode(), response.getStatusMessage())); return; } if (responseReader == VOID) { future.succeed(null); return; } try { future.succeed(responseReader.read(ByteStreams.toByteArray(response.getContent()))); } catch (Exception e) { future.fail(e); } }); return future; } private byte[] gzipJson(final Object payload) { // TODO (dano): cache and reuse deflater try ( final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final GZIPOutputStream gzip = new GZIPOutputStream(bytes) { { this.def.setLevel(compressionLevel); } } ) { Json.write(gzip, payload); return bytes.toByteArray(); } catch (IOException e) { throw Throwables.propagate(e); } } /** * Create a new {@link Pubsub} client with default configuration. */ public static Pubsub create() { return builder().build(); } /** * Create a new {@link Builder} that can be used to build a new {@link Pubsub} client. */ public static Builder builder() { return new Builder(); } /** * A {@link Builder} that can be used to build a new {@link Pubsub} client. */ public static class Builder { private static final URI DEFAULT_URI = URI.create("https://pubsub.googleapis.com/v1/"); private static final int DEFAULT_REQUEST_TIMEOUT_MS = 30000; private final AsyncHttpClientConfig.Builder clientConfig = new AsyncHttpClientConfig.Builder() .setCompressionEnforced(true) .setUseProxySelector(true) .setRequestTimeout(DEFAULT_REQUEST_TIMEOUT_MS) .setReadTimeout(DEFAULT_REQUEST_TIMEOUT_MS); private Credential credential; private URI uri = DEFAULT_URI; private int compressionLevel = Deflater.DEFAULT_COMPRESSION; private Builder() { } /** * Creates a new {@code Pubsub}. */ public Pubsub build() { return new Pubsub(this); } /** * Set the maximum time in milliseconds the client will can wait when connecting to a remote host. * * @param connectTimeout the connect timeout in milliseconds. * @return this config builder. */ public Builder connectTimeout(final int connectTimeout) { clientConfig.setConnectTimeout(connectTimeout); return this; } /** * Set the Gzip compression level to use, 0-9 or -1 for default. * * @param compressionLevel The compression level to use. * @return this config builder. * @see Deflater#setLevel(int) * @see Deflater#DEFAULT_COMPRESSION * @see Deflater#BEST_COMPRESSION * @see Deflater#BEST_SPEED */ public Builder compressionLevel(final int compressionLevel) { checkArgument(compressionLevel > -1 && compressionLevel <= 9, "compressionLevel must be -1 or 0-9."); this.compressionLevel = compressionLevel; return this; } /** * Set the connection read timeout in milliseconds. * * @param readTimeout the read timeout in milliseconds. * @return this config builder. */ public Builder readTimeout(final int readTimeout) { clientConfig.setReadTimeout(readTimeout); return this; } /** * Set the request timeout in milliseconds. * * @param requestTimeout the maximum time in milliseconds. * @return this config builder. */ public Builder requestTimeout(final int requestTimeout) { clientConfig.setRequestTimeout(requestTimeout); return this; } /** * Set the maximum number of connections client will open. Default is unlimited (-1). * * @param maxConnections the maximum number of connections. * @return this config builder. */ public Builder maxConnections(final int maxConnections) { clientConfig.setMaxConnections(maxConnections); return this; } /** * Set the maximum number of milliseconds a pooled connection will be reused. -1 for no limit. * * @param pooledConnectionTTL the maximum time in milliseconds. * @return this config builder. */ public Builder pooledConnectionTTL(final int pooledConnectionTTL) { clientConfig.setConnectionTTL(pooledConnectionTTL); return this; } /** * Set the maximum number of milliseconds an idle pooled connection will be be kept. * * @param pooledConnectionIdleTimeout the timeout in milliseconds. * @return this config builder. */ public Builder pooledConnectionIdleTimeout(final int pooledConnectionIdleTimeout) { clientConfig.setPooledConnectionIdleTimeout(pooledConnectionIdleTimeout); return this; } /** * Set whether to allow connection pooling or not. Default is true. * * @param allowPoolingConnections the maximum number of connections. * @return this config builder. */ public Builder allowPoolingConnections(final boolean allowPoolingConnections) { clientConfig.setAllowPoolingConnections(allowPoolingConnections); clientConfig.setAllowPoolingSslConnections(allowPoolingConnections); return this; } /** * Set Google Cloud API credentials to use. Set to null to use application default credentials. * * @param credential the credentials used to authenticate. */ public Builder credential(final Credential credential) { this.credential = credential; return this; } /** * Set cipher suites to enable for SSL/TLS. * * @param enabledCipherSuites The cipher suites to enable. */ public Builder enabledCipherSuites(final String... enabledCipherSuites) { clientConfig.setEnabledCipherSuites(enabledCipherSuites); return this; } /** * Set cipher suites to enable for SSL/TLS. * * @param enabledCipherSuites The cipher suites to enable. */ public Builder enabledCipherSuites(final List<String> enabledCipherSuites) { clientConfig.setEnabledCipherSuites(enabledCipherSuites.toArray(new String[enabledCipherSuites.size()])); return this; } /** * The Google Cloud Pub/Sub API URI. By default, this is the Google Cloud Pub/Sub provider, however you may run a * local Developer Server. * * @param uri the service to connect to. */ public Builder uri(final URI uri) { checkNotNull(uri, "uri"); checkArgument(uri.getRawQuery() == null, "illegal service uri: %s", uri); checkArgument(uri.getRawFragment() == null, "illegal service uri: %s", uri); this.uri = uri; return this; } } /** * A {@link ResponseReader} that parses a response payload as Json into a specified {@link Class}. * @param cls The {@link Class} to parse the Json payload as. */ private <T> ResponseReader<T> readJson(Class<T> cls) { return payload -> Json.read(payload, cls); } /** * A function that takes a payload byte array and parses it into some object. */ @FunctionalInterface interface ResponseReader<T> { /** * A marker {@link ResponseReader} that completely disables reading of the response payload. */ ResponseReader<Void> VOID = bytes -> null; /** * Parse a byte array into an object. */ T read(byte[] bytes) throws Exception; /** * Perform additional transformation on the parsed object. */ default <U> ResponseReader<U> andThen(Function<T, U> f) { return bytes -> f.apply(read(bytes)); } } }
pedro-carneiro/async-google-pubsub-client
<|start_filename|>renderer/cpp/src/core/kernels.hpp<|end_filename|> #pragma once #include <cuda.h> #include <curand_kernel.h> #include <glm/glm.hpp> #include "pathstate.hpp" #include "geometry.hpp" #include "camera.hpp" #include "shape.hpp" __global__ void initRand(curandState *randState, int size); __global__ void init(PathstateSoA pathstates, const int lenStates, int *pathRequests, int *raycastRequests, int *shadowRaycastRequests, int *diffuseMaterialRequests, int *specularReflectionRequests, int *specularTransmissionRequests); __global__ void render(Camera camera, PathstateSoA pathstates, const int lenPathStates, int *pathRequests, int *numPathRequests, int *diffuseMaterialRequests, int *numDiffuseMaterialRequests, int *specularReflectionRequests, int *numSpecularReflectionRequests, int *specularTransmissionRequests, int *numSpecularTransmissionRequests, curandState *randState, const bool useLightSampling, const bool renderCaustics, const int maxBounce); __global__ void newPath(int *pathRequests, PathstateSoA states, const int *numPathRequests, int *raycastRequests, Ray *rays, int *numRaycastRequests, Camera camera, curandState *randState); __global__ void raycast(int *raycastRequests, Ray *rays, int *numRaycastRequests, PathstateSoA states, const int lenPathStates, const Shape *shapes, const int numShapes); __global__ void shadowRaycast(int *raycastRequests, Ray *rays, int *numRaycastRequests, PathstateSoA states, const int lenPathStates, const Shape *shapes, const int numShapes); __global__ void filterImage(const glm::vec3 *srcImage, unsigned int *destImage, const int widthFinal, const int heightFinal, const int stratificationLevel, const int numIterations, const float gamma); <|start_filename|>.vscode/settings.json<|end_filename|> { "python.pythonPath": "/home/stephen/anaconda3/envs/pyside/bin/python", "files.associations": { "thread": "cpp" } } <|start_filename|>renderer/cpp/src/core/Renderer.hpp<|end_filename|> #include <cuda.h> #include <curand_kernel.h> #include <thread> #include <mutex> #include <atomic> #include <glm/glm.hpp> #include <vector> #include <unordered_map> #include "shape.hpp" #include "camera.hpp" #include "pathstate.hpp" enum SceneObjectType {sphere = 0, cube, plane, disc, camera}; class Renderer { public: Renderer(int width, int height); ~Renderer(); void setResolution(int width, int height); void updateCamera(float worldPos[3], float target[3], float fov_y, float fStop, float focusDistance, int stratificationLevel); void addObject(int id, int materialId, int sceneObjectType, float arr[16], float lightIntensity, float lightColor[3], float area, bool isVisible); void addDiffuseMaterial(int id, float colorArray[3]); void addSpecularMaterial(int id, float reflectionColorArray[3], float transmissionColorArray[3], float IOR); void setRenderSettings(bool useLightSampling, bool renderCaustics, int numBounces); void clearObjects(); void clearMaterials(); void start(); void stop(); int getData(unsigned int *outImage, int width, int height); int getWidth(); int getHeight(); private: void setup(); void renderLoop(); void clearImage(); void copyShapes(); void copyLights(); void freeArrays(); std::thread *renderThread; int width, height, r_width, r_height, iterationsDone, destIterationsDone, destImageWidth, destImageHeight, numBounces, r_numBounces; glm::vec3 *image; unsigned int *destImage; Camera camera; bool resetImage, useLightSampling, renderCaustics, r_useLightSampling, r_renderCaustics; Shape *shapes; Shape *lights; int shapeLen; int lightLen; Pathstate *pathstates; Ray *rays; Ray *shadowRays; int *pathRequests; int *raycastRequests; int *shadowRaycastRequests; int *diffuseMaterialRequests; int *specularReflectionRequests; int *specularTransmissionRequests; int *filmIndex; int *numPathRequests; int *numRaycastRequests; int *numShadowRaycastRequests; int *numDiffuseMaterialRequests; int *numSpecularReflectionRequests; int *numSpecularTransmissionRequests; std::vector<Shape> shapeVec; std::vector<Shape> lightVec; std::unordered_map<int, Material> materialMap; curandState *randState; PathstateSoA pathstateSoA; // Synchronisation std::atomic_bool stopRendering; std::atomic_bool resolutionChanged; std::atomic_bool sceneChanged; std::atomic_bool imageUpdated; std::atomic_bool cameraChanged; std::mutex destImageMutex; std::mutex cameraMutex; std::mutex sceneMutex; std::mutex resolutionMutex; std::mutex stopMutex; }; <|start_filename|>renderer/cpp/src/util/util.hpp<|end_filename|> /* This source file makes use of modified code from pbrt-v3 pbrt source code is Copyright(c) 1998-2016 <NAME>, <NAME>, and <NAME>. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <glm/glm.hpp> __device__ bool Quadratic(const float a, const float b, const float c, float *t0, float *t1); __host__ __device__ glm::vec3 pow(const glm::vec3 &v, const float exponent); template <typename T> __device__ void swap(T &a, T &b) { T temp = a; a = b; b = temp; } __device__ float clamp(const float &v, const float &min, const float &max); void waitAndCheckError(const char *location); <|start_filename|>renderer/cpp/src/core/kernels.cu<|end_filename|> #include "kernels.hpp" #include "../util/util.hpp" __global__ void initRand(curandState *randState, int size) { int index = blockIdx.x * blockDim.x + threadIdx.x; if(index >= size) return; curand_init((254 << 20) + index, 0, 0, &randState[index]); } __global__ void init(PathstateSoA pathstates, const int lenStates, int *pathRequests, int *raycastRequests, int *shadowRaycastRequests, int *diffuseMaterialRequests, int *specularReflectionRequests, int *specularTransmissionRequests) { const int index = blockIdx.x * blockDim.x + threadIdx.x; if(index < lenStates) { pathstates.isActive[index] = true; pathstates.bounces[index] = -1; pathstates.foundExtensionIsect[index] = false; pathstates.diffuseBounce[index] = false; pathRequests[index] = -1; raycastRequests[index] = -1; shadowRaycastRequests[index] = -1; diffuseMaterialRequests[index] = -1; specularReflectionRequests[index] = -1; specularTransmissionRequests[index] = -1; } } __global__ void render(Camera camera, PathstateSoA pathstates, const int lenPathStates, int *pathRequests, int *numPathRequests, int *diffuseMaterialRequests, int *numDiffuseMaterialRequests, int *specularReflectionRequests, int *numSpecularReflectionRequests, int *specularTransmissionRequests, int *numSpecularTransmissionRequests, curandState *randState, const bool useLightSampling, const bool renderCaustics, const int maxBounce) { const int index = blockIdx.x * blockDim.x + threadIdx.x; if(index >= lenPathStates) return; Pathstate state; state.currentIsect = pathstates.currentIsect[index]; state.extensionIsect = pathstates.extensionIsect[index]; state.foundExtensionIsect = pathstates.foundExtensionIsect[index]; state.material = pathstates.material[index]; state.isActive = pathstates.isActive[index]; state.pdf = pathstates.pdf[index]; state.bounces = pathstates.bounces[index]; state.beta = pathstates.beta[index]; state.L = pathstates.L[index]; state.Lemit = pathstates.Lemit[index]; state.filmIndex = pathstates.filmIndex[index]; state.f = pathstates.f[index]; state.isLightSample = pathstates.isLightSample[index]; state.light_f = pathstates.light_f[index]; state.Lsample = pathstates.Lsample[index]; state.lightPdf = pathstates.lightPdf[index]; state.LsampleOccluded = pathstates.LsampleOccluded[index]; state.wi_L = pathstates.wi_L[index]; state.diffuseBounce = pathstates.diffuseBounce[index]; curandState localRandState = randState[index]; if(!state.isActive) return; bool zeroBeta = glm::dot(state.beta, state.beta) < 0.00001; bool zero_f = isZeroVec(state.f); bool hitLight = !isZeroVec(state.Lemit); bool endPath = false; bool causticStop = !renderCaustics && state.diffuseBounce && state.material.materialType == Materialtype::specular; if(state.bounces == -1 || state.bounces >= maxBounce || zeroBeta || !state.foundExtensionIsect || zero_f || hitLight || causticStop) { endPath = true; int reqIdx = atomicAdd(numPathRequests, 1); pathRequests[reqIdx] = index; } if(useLightSampling && state.isLightSample && !isZeroVec(state.Lsample) && !state.LsampleOccluded) { state.L += state.Lsample * state.beta * state.light_f * abs(glm::dot(state.wi_L, state.currentIsect.n)) / state.lightPdf; } if(state.foundExtensionIsect) { if(state.bounces == 0) { state.L += state.Lemit; } else { state.beta *= state.f * abs(glm::dot(-state.extensionIsect.wo, state.currentIsect.n)) / state.pdf; if(!useLightSampling || !state.isLightSample) state.L += state.Lemit * state.beta; } ++state.bounces; if(!endPath) { int reqIdx; if(state.material.materialType == Materialtype::diffuse) { reqIdx = atomicAdd(numDiffuseMaterialRequests, 1); diffuseMaterialRequests[reqIdx] = index; state.diffuseBounce = true; } else if(state.material.materialType == Materialtype::specular) { if(curand_uniform(&localRandState) > 0.5f) { reqIdx = atomicAdd(numSpecularReflectionRequests, 1); specularReflectionRequests[reqIdx] = index; } else { reqIdx = atomicAdd(numSpecularTransmissionRequests, 1); specularTransmissionRequests[reqIdx] = index; } state.diffuseBounce = false; } } } if(endPath && state.bounces != -1) { if(!state.foundExtensionIsect && state.bounces == 0) { camera.addPixelVal(state.filmIndex, glm::vec3(0.015)); } else { #ifdef CudaDebug bool error = false; if(state.pdf == 0 && state.bounces - 1 > 0) { camera.addPixelVal(state.filmIndex, glm::vec3(0.0, 0.0, 1.0)); error = true; } if(isnan(state.extensionIsect.wo.x) || isnan(state.extensionIsect.wo.y) || isnan(state.extensionIsect.wo.z)) { camera.addPixelVal(state.filmIndex, glm::vec3(1.0, 0.0, 0.0)); error = true; } if(!error) camera.addPixelVal(state.filmIndex, state.L); #else camera.addPixelVal(state.filmIndex, state.L); #endif } state.beta = glm::vec3(0.0); } pathstates.currentIsect[index] = state.extensionIsect; pathstates.foundExtensionIsect[index] = false; pathstates.bounces[index] = state.bounces; pathstates.beta[index] = state.beta; pathstates.L[index] = state.L; pathstates.diffuseBounce[index] = state.diffuseBounce; pathstates.isLightSample[index] = false; randState[index] = localRandState; } __global__ void newPath(int *pathRequests, PathstateSoA states, const int *numPathRequests, int *raycastRequests, Ray *rays, int *numRaycastRequests, Camera camera, curandState *randState) { const int index = blockIdx.x * blockDim.x + threadIdx.x; if(index >= *numPathRequests) return; int pathIdx = pathRequests[index]; if(pathIdx >= 0) { int filmIndex = camera.getFilmIndex(); if(filmIndex < 0) { states.isActive[pathIdx] = false; return; } Pathstate state; state.bounces = 0; state.foundExtensionIsect = false; state.isActive = true; state.beta = glm::vec3(1.0); state.f = glm::vec3(1.0); state.L = glm::vec3(0.0); state.Lemit = glm::vec3(0.0); state.filmIndex = filmIndex; state.isLightSample = false; state.diffuseBounce = false; Ray ray; curandState localRandState = randState[pathIdx]; camera.getRay(filmIndex, &ray, glm::vec2(curand_uniform(&localRandState), curand_uniform(&localRandState)), glm::vec2(curand_uniform(&localRandState), curand_uniform(&localRandState))); randState[pathIdx] = localRandState; int reqIdx = atomicAdd(numRaycastRequests, 1); rays[reqIdx] = ray; raycastRequests[reqIdx] = pathIdx; pathRequests[index] = -1; states.foundExtensionIsect[pathIdx] = state.foundExtensionIsect; states.isActive[pathIdx] = state.isActive; states.bounces[pathIdx] = state.bounces; states.beta[pathIdx] = state.beta; states.L[pathIdx] = state.L; states.Lemit[pathIdx] = state.Lemit; states.filmIndex[pathIdx] = state.filmIndex; states.f[pathIdx] = state.f; states.isLightSample[pathIdx] = state.isLightSample; states.diffuseBounce[pathIdx] = state.diffuseBounce; } } __global__ void raycast(int *raycastRequests, Ray *rays, int *numRaycastRequests, PathstateSoA states, const int lenPathStates, const Shape *shapes, const int numShapes) { const int index = blockIdx.x * blockDim.x + threadIdx.x; if(index >= *numRaycastRequests) return; int pathIdx = raycastRequests[index]; if(pathIdx >= 0) { Ray ray = rays[index]; Pathstate state; state.bounces = states.bounces[pathIdx]; Interaction isect; Material material; glm::vec3 Lemit; bool hit = false; for(int i = 0; i < numShapes; ++i) { if(shapes[i].Intersect(ray, &isect, &material, &Lemit, state.bounces == 0)) { hit = true; } } if(hit) { isect.n = glm::normalize(isect.n); isect.wo = glm::normalize(isect.wo); state.extensionIsect = isect; state.foundExtensionIsect = true; state.material = material; state.Lemit = Lemit; states.extensionIsect[pathIdx] = state.extensionIsect; states.foundExtensionIsect[pathIdx] = state.foundExtensionIsect; states.Lemit[pathIdx] = state.Lemit; states.material[pathIdx] = state.material; } raycastRequests[index] = -1; } } __global__ void shadowRaycast(int *raycastRequests, Ray *rays, int *numRaycastRequests, PathstateSoA states, const int lenPathStates, const Shape *shapes, const int numShapes) { const int index = blockIdx.x * blockDim.x + threadIdx.x; if(index >= *numRaycastRequests) return; int pathIdx = raycastRequests[index]; if(pathIdx >= 0) { Ray ray = rays[index]; bool hit = false; for(int i = 0; i < numShapes; ++i) { if(shapes[i].OccludesRay(ray)) { hit = true; } } if(hit) { states.LsampleOccluded[pathIdx] = true; } else { states.wi_L[pathIdx] = ray.d; } raycastRequests[index] = -1; } } __global__ void filterImage(const glm::vec3 *srcImage, unsigned int *destImage, const int widthFinal, const int heightFinal, const int stratificationLevel, const int numIterations, const float gamma) { int x = blockIdx.x * blockDim.x + threadIdx.x; int y = blockIdx.y * blockDim.y + threadIdx.y; int index = y * widthFinal + x; if(index >= widthFinal * heightFinal) return; glm::vec3 val(0.0); float weight = 1.0 / numIterations; for(int j = 0; j < stratificationLevel; ++j) { for(int i = 0; i < stratificationLevel; ++i) { int srcX = stratificationLevel * x + j; int srcY = stratificationLevel * y + i; int srcIndex = srcY * widthFinal * stratificationLevel + srcX; val += srcImage[srcIndex] * weight; } } val /= stratificationLevel * stratificationLevel; val = pow(val, gamma); val *= 255; unsigned int pixR = lrintf(val.r); unsigned int pixG = lrintf(val.g); unsigned int pixB = lrintf(val.b); pixR = pixR > 255 ? 255 : pixR; pixG = pixG > 255 ? 255 : pixG; pixB = pixB > 255 ? 255 : pixB; destImage[index] = (pixR << 16) + (pixG << 8) + pixB; } <|start_filename|>renderer/cpp/src/core/shape.hpp<|end_filename|> #pragma once #include <glm/glm.hpp> #include <math.h> #include "geometry.hpp" #include "material.hpp" enum class ShapeType {sphere = 0, cube, plane, disc}; class Shape { public: __device__ __host__ Shape(const ShapeType shapeType, Material material, float area, const glm::mat4 &objectToWorld = glm::mat4(1.0), const glm::vec3 &Lemit = glm::vec3(0.0), const bool isVisible = true); __device__ bool Intersect(const Ray &ray, Interaction *isect, Material *mat, glm::vec3 *Lemit, bool firstRay) const; __device__ bool OccludesRay(const Ray &ray) const; __device__ float Sample(Ray &ray, glm::vec3 &Lsample, const glm::vec2 &sample) const; const glm::mat4 objectToWorld, worldToObject; Material material; const ShapeType shapeType; glm::vec3 Lemit; float area; bool isVisible; private: __device__ bool IntersectSphere(const Ray &ray, Interaction *isect, Material *mat, glm::vec3 *Lemit) const; __device__ bool IntersectPlane(const Ray &ray, Interaction *isect, Material *mat, glm::vec3 *Lemit) const; __device__ bool IntersectDisc(const Ray &ray, Interaction *isect, Material *mat, glm::vec3 *Lemit) const; __device__ bool IntersectCube(const Ray &ray, Interaction *isect, Material *mat, glm::vec3 *Lemit) const; __device__ bool SphereOccludesRay(const Ray &ray) const; __device__ bool PlaneOccludesRay(const Ray &ray) const; __device__ bool DiscOccludesRay(const Ray &ray) const; __device__ bool CubeOccludesRay(const Ray &ray) const; __device__ float SampleSphere(Ray &ray, glm::vec3 &Lsample, const glm::vec2 &sample) const; __device__ float SamplePlane(Ray &ray, glm::vec3 &Lsample, const glm::vec2 &sample) const; __device__ float SampleDisc(Ray &ray, glm::vec3 &Lsample, const glm::vec2 &sample) const; __device__ float SampleCube(Ray &ray, glm::vec3 &Lsample, const glm::vec2 &sample) const; }; <|start_filename|>renderer/cpp/src/core/sampling.cu<|end_filename|> /* This source file makes use of modified code from pbrt-v3 pbrt source code is Copyright(c) 1998-2016 <NAME>, <NAME>, and <NAME>. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cmath> #include "sampling.hpp" __device__ glm::vec2 UniformSampleDisk(const glm::vec2 &sample) { float r = sqrt(sample.x); float theta = 2 * M_PI * sample.y; return glm::vec2(r * cos(theta), r * sin(theta)); } __device__ glm::vec3 CosineSampleHemisphere(const glm::vec2 &sample) { glm::vec2 d = UniformSampleDisk(sample); float z = sqrt(fmaxf(0.00001f, 1.0f - d.x * d.x - d.y * d.y)); return glm::vec3(d.x, d.y, z); } __device__ glm::vec3 UniformSampleSphere(const glm::vec2 &sample) { float z = 1 - 2 * sample.x; float r = sqrt(fmaxf(0.0f, 1.0f - z * z)); float phi = 2 * M_PI * sample.y; return glm::vec3(r * cos(phi), r * sin(phi), z); } <|start_filename|>renderer/cpp/src/core/geometry.cu<|end_filename|> /* This source file makes use of modified code from pbrt-v3 pbrt source code is Copyright(c) 1998-2016 <NAME>, <NAME>, and <NAME>. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "geometry.hpp" __device__ __host__ glm::vec3 operator*(const glm::mat4 &m, const glm::vec3 &v) { return glm::vec3(m * glm::vec4(v, 1.0)); } __device__ __host__ bool isZeroVec(const glm::vec3 &v) { return v.x == 0.0 && v.y == 0.0 && v.z == 0.0; } __device__ Ray operator*(const glm::mat4 &m, const Ray &ray) { glm::vec3 o = m * ray.o; glm::vec3 d = m * glm::vec4(ray.d, 0.0); return Ray(o, d, ray.t); } __device__ Interaction operator*(const glm::mat4 &m, const Interaction &i) { glm::mat3 invTrans = glm::transpose(glm::inverse(glm::mat3(m))); return Interaction(m * i.p, invTrans * i.n, m * glm::vec4(i.wo, 0.0)); } __device__ Ray::Ray() : t(INFINITY) {} __device__ Ray::Ray(const glm::vec3 &o, const glm::vec3 &d, float t) :o(o), d(d), t(t) {} __device__ glm::vec3 Ray::operator()(const float t) const { return o + d * t; } __device__ Interaction::Interaction() :p(glm::vec3(0.0)), n(glm::vec3(0.0)), wo(glm::vec3(0.0)) {} __device__ Interaction::Interaction(const glm::vec3 &p, const glm::vec3 &n, const glm::vec3 &wo) :p(p), n(n), wo(wo) {} <|start_filename|>renderer/cpp/src/core/camera.hpp<|end_filename|> #pragma once #include "geometry.hpp" class Camera { public: __host__ Camera(const int resX, const int resY, const glm::vec3 &worldPos = glm::vec3(), const glm::vec3 &target = glm::vec3(0.0, 0.0, 1.0), const float fov_y = 45.0, const float fStop = 5.6, const float focusDistance = 10.0, const int stratificationLevel = 1); __host__ void update(const glm::vec3 &worldPos, const glm::vec3 &target, const float fov_y, const float fStop, const float focusDistance, const int stratificationLevel); __host__ void update(const int resX, const int resY); __device__ void getRay(const int filmIndex, Ray *ray, const glm::vec2 &pixelSample, const glm::vec2 &lensSample) const; __device__ int getFilmIndex(); __host__ bool isDone() const; __host__ void resetFilmIndex(); __host__ void setImage(glm::vec3 *pImage); __host__ void setFilmIndexPointer(int *pFilmIndex); __device__ void addPixelVal(const int filmIndex, const glm::vec3 &val); __host__ int getStratificationLevel() const; private: __device__ void getRay(const int x, const int y, Ray *ray, const glm::vec2 &pixelSample, const glm::vec2 &lensSample) const; __host__ float fStopToApertureSize(const float fStop) const; glm::vec3 worldPos; glm::vec3 target; float fov_y; int resX; int resY; float width; float height; glm::vec3 *pImage; int *pFilmIndex; float focusDistance; float apertureRadius; int stratificationLevel; }; <|start_filename|>editor/ui/shaders/vertex.vert<|end_filename|> #version 450 core layout (location = 0) in vec3 vPos; layout (location = 1) in vec3 vNormal; out vec4 outColor; out vec3 position; out vec3 normal; uniform mat4 model; uniform mat4 view; uniform mat4 projection; uniform vec4 inColor; void main() { gl_Position = projection * view * model * vec4(vPos, 1.0); outColor = inColor; position = vec3(model * vec4(vPos, 1.0)); normal = vec3(transpose(inverse(model)) * vec4(vNormal, 0.0)); } <|start_filename|>editor/ui/shaders/fragment.frag<|end_filename|> #version 450 core in vec4 outColor; in vec3 position; in vec3 normal; out vec4 FragColor; uniform vec3 eyePos; vec3 ambient = vec3(0.2); vec3 lightColor = vec3(1.0, 1.0, 1.0); void main() { vec3 norm = normalize(normal); vec3 lightDir = normalize(eyePos - position); float diff = max(dot(norm, lightDir), 0.0); vec3 diffuse = diff * lightColor; FragColor = vec4((ambient + diffuse) * vec3(outColor), 1.0); } <|start_filename|>renderer/cpp/src/core/pathstate.hpp<|end_filename|> #pragma once #include <glm/glm.hpp> #include "geometry.hpp" #include "material.hpp" struct Pathstate { Interaction currentIsect; Interaction extensionIsect; Material material; glm::vec3 beta; glm::vec3 L; glm::vec3 Lemit; glm::vec3 Lsample; glm::vec3 f; glm::vec3 light_f; glm::vec3 wi_L; bool foundExtensionIsect; bool isActive; bool LsampleOccluded; bool isLightSample; bool diffuseBounce; int bounces; int filmIndex; float pdf; float lightPdf; }; struct PathstateSoA { PathstateSoA(); Interaction *currentIsect; Interaction *extensionIsect; bool *foundExtensionIsect; bool *isActive; float *pdf; float *lightPdf; int *bounces; glm::vec3 *beta; glm::vec3 *L; glm::vec3 *wi_L; glm::vec3 *Lemit; glm::vec3 *Lsample; bool *LsampleOccluded; bool *isLightSample; int *filmIndex; Material *material; glm::vec3 *f; glm::vec3 *light_f; bool *diffuseBounce; void freeArrays(); }; <|start_filename|>renderer/cpp/src/core/Renderer.cu<|end_filename|> #include "Renderer.hpp" #include "kernels.hpp" #include "shading.hpp" #include "../util/util.hpp" #include <iostream> #include "math.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <cstring> const int queueSize = 200000; const int blockDimensionX = 512; const float gamma22 = 2.2; Renderer::Renderer(int width, int height) : width(width), height(height), r_width(width), r_height(height), iterationsDone(0), destIterationsDone(0), numBounces(30), r_numBounces(30), image(nullptr), destImage(nullptr), randState(nullptr), pathstates(nullptr), rays(nullptr), shadowRays(nullptr), pathRequests(nullptr), raycastRequests(nullptr), shadowRaycastRequests(nullptr), diffuseMaterialRequests(nullptr), specularReflectionRequests(nullptr), specularTransmissionRequests(nullptr), filmIndex(nullptr), numPathRequests(nullptr), numRaycastRequests(nullptr), numShadowRaycastRequests(nullptr), numDiffuseMaterialRequests(nullptr), numSpecularReflectionRequests(nullptr), numSpecularTransmissionRequests(nullptr), shapes(nullptr), lights(nullptr), shapeLen(0), lightLen(0), camera(width, height, glm::vec3(0.0, 0.0, 10.0), glm::vec3(0.0)), stopRendering(false), sceneChanged(false), resolutionChanged(false), imageUpdated(false), cameraChanged(false), renderThread(nullptr), useLightSampling(true), renderCaustics(true), r_useLightSampling(true), r_renderCaustics(true) { setup(); } void Renderer::start() { stopRendering = false; renderThread = new std::thread(&Renderer::renderLoop, this); } Renderer::~Renderer() { stop(); freeArrays(); } int Renderer::getWidth() { return width; } int Renderer::getHeight() { return height; } void Renderer::copyShapes() { cudaMallocManaged(&shapes, shapeVec.size() * sizeof(Shape)); waitAndCheckError("setup::cudaMallocManaged(shapes)"); std::memcpy(shapes, shapeVec.data(), shapeVec.size() * sizeof(Shape)); } void Renderer::copyLights() { cudaMallocManaged(&lights, lightVec.size() * sizeof(Shape)); waitAndCheckError("setup::cudaMallocManaged(lights)"); std::memcpy(lights, lightVec.data(), lightVec.size() * sizeof(Shape)); } void Renderer::setup() { freeArrays(); r_width = width; r_height = height; r_useLightSampling = useLightSampling; r_renderCaustics = renderCaustics; r_numBounces = numBounces; camera.update(r_width, r_height); int imgLen = r_width * r_height; int imgLenStratified = imgLen * camera.getStratificationLevel() * camera.getStratificationLevel(); cudaMallocManaged(&destImage, imgLen * sizeof(float)); waitAndCheckError("setup::cudaMallocManaged(destImage)"); cudaMallocManaged(&image, imgLenStratified * sizeof(glm::vec3)); waitAndCheckError("setup::cudaMallocManaged(image)"); cudaMallocManaged(&randState, queueSize * sizeof(curandState)); waitAndCheckError("setup::cudaMallocManaged(randState)"); if(shapeVec.size() > 0) { copyShapes(); } if(lightVec.size() > 0) { copyLights(); } shapeLen = shapeVec.size(); lightLen = lightVec.size(); cudaMallocManaged(&pathstates, queueSize * sizeof(Pathstate)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&rays, queueSize * sizeof(Ray)); waitAndCheckError("setup::cudaMallocManaged(rays)"); cudaMallocManaged(&shadowRays, queueSize * sizeof(Ray)); waitAndCheckError("setup::cudaMallocManaged(shadowRays)"); cudaMallocManaged(&pathRequests, queueSize * sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(pathRequests)"); cudaMallocManaged(&raycastRequests, queueSize * sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(raycastRequests)"); cudaMallocManaged(&shadowRaycastRequests, queueSize * sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(shadowRaycastRequests)"); cudaMallocManaged(&diffuseMaterialRequests, queueSize * sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(diffuseMaterialRequests)"); cudaMallocManaged(&specularReflectionRequests, queueSize * sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(specularReflectionRequests)"); cudaMallocManaged(&specularTransmissionRequests, queueSize * sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(specularTransmissionRequests)"); cudaMallocManaged(&filmIndex, sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(filmIndex)"); cudaMallocManaged(&numRaycastRequests, sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(numRaycastRequests)"); cudaMallocManaged(&numShadowRaycastRequests, sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(numShadowRaycastRequests)"); cudaMallocManaged(&numPathRequests, sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(numPathRequests)"); cudaMallocManaged(&numDiffuseMaterialRequests, sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(numDiffuseMaterialRequests)"); cudaMallocManaged(&numSpecularReflectionRequests, sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(numSpecularReflectionRequests)"); cudaMallocManaged(&numSpecularTransmissionRequests, sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(numSpecularTransmissionRequests)"); cudaMemset(image, 0, imgLenStratified * sizeof(glm::vec3)); waitAndCheckError("setup::cudaMallocManaged(image)"); cudaMemset(destImage, 0, imgLen * sizeof(unsigned int)); waitAndCheckError("setup::cudaMallocManaged(destImage)"); cudaMallocManaged(&pathstateSoA.currentIsect, queueSize * sizeof(Interaction)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.extensionIsect, queueSize * sizeof(Interaction)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.foundExtensionIsect, queueSize * sizeof(bool)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.isActive, queueSize * sizeof(bool)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.pdf, queueSize * sizeof(float)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.lightPdf, queueSize * sizeof(float)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.bounces, queueSize * sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.beta, queueSize * sizeof(glm::vec3)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.L, queueSize * sizeof(glm::vec3)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.wi_L, queueSize * sizeof(glm::vec3)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.Lemit, queueSize * sizeof(glm::vec3)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.filmIndex, queueSize * sizeof(int)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.material, queueSize * sizeof(Material)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.f, queueSize * sizeof(glm::vec3)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.light_f, queueSize * sizeof(glm::vec3)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.Lsample, queueSize * sizeof(glm::vec3)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.LsampleOccluded, queueSize * sizeof(bool)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.isLightSample, queueSize * sizeof(bool)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); cudaMallocManaged(&pathstateSoA.diffuseBounce, queueSize * sizeof(bool)); waitAndCheckError("setup::cudaMallocManaged(pathstates)"); iterationsDone = 0; destIterationsDone = 0; *filmIndex = 0; *numPathRequests = 0; *numRaycastRequests = 0; *numShadowRaycastRequests = 0; *numDiffuseMaterialRequests = 0; *numSpecularReflectionRequests = 0; *numSpecularTransmissionRequests = 0; camera.setImage(image); camera.setFilmIndexPointer(filmIndex); dim3 blockDim(blockDimensionX); dim3 gridDim(queueSize / blockDim.x + (queueSize % blockDim.x ? 1 : 0)); initRand<<<gridDim, blockDim>>>(randState, queueSize); waitAndCheckError("setup::initRand<<<>>>"); resolutionChanged = false; sceneChanged = false; } void Renderer::clearImage() { cudaMemset(image, 0, r_width * r_height * camera.getStratificationLevel() * camera.getStratificationLevel() * sizeof(glm::vec3)); waitAndCheckError("clearImage::cudaMemset"); iterationsDone = 0; destIterationsDone = 0; } void Renderer::renderLoop() { while(!stopRendering) { // if resolutionChanged bool lock mutex and copy resolution -> setup cameraMutex.lock(); resolutionMutex.lock(); if(resolutionChanged) { destImageMutex.lock(); sceneMutex.lock(); setup(); destImageMutex.unlock(); sceneMutex.unlock(); } // if cameraChanged bool lock mutex and copy camera Camera renderCamera = camera; renderCamera.resetFilmIndex(); if(cameraChanged) { clearImage(); cameraChanged = false; } cameraMutex.unlock(); resolutionMutex.unlock(); // if sceneChanged bool lock mutex and copy scene -> setup if(sceneChanged) { std::lock_guard<std::mutex> sceneLock(sceneMutex); if(shapes) { cudaFree(shapes); waitAndCheckError("start::cudaFree(shapes)"); shapes = nullptr; } if(shapeVec.size() > 0) { copyShapes(); } if(lights) { cudaFree(lights); waitAndCheckError("start::cudaFree(lights)"); lights = nullptr; } if(lightVec.size() > 0) { copyLights(); } shapeLen = shapeVec.size(); lightLen = lightVec.size(); clearImage(); r_useLightSampling = useLightSampling; r_renderCaustics = renderCaustics; r_numBounces = numBounces; sceneChanged = false; } dim3 blockDim(blockDimensionX); dim3 gridDim(queueSize / blockDim.x + (queueSize % blockDim.x ? 1 : 0)); init<<<gridDim, blockDim>>>(pathstateSoA, queueSize, pathRequests, raycastRequests, shadowRaycastRequests, diffuseMaterialRequests, specularReflectionRequests, specularTransmissionRequests); waitAndCheckError("renderLoop::init<<<>>>"); do { *numPathRequests = 0; *numRaycastRequests = 0; *numShadowRaycastRequests = 0; *numDiffuseMaterialRequests = 0; *numSpecularReflectionRequests = 0; *numSpecularTransmissionRequests = 0; render<<<gridDim, blockDim>>>(renderCamera, pathstateSoA, queueSize, pathRequests, numPathRequests, diffuseMaterialRequests, numDiffuseMaterialRequests, specularReflectionRequests, numSpecularReflectionRequests, specularTransmissionRequests, numSpecularTransmissionRequests, randState, r_useLightSampling, r_renderCaustics, r_numBounces); waitAndCheckError("renderLoop::render<<<>>>(loop)"); newPath<<<gridDim, blockDim>>>(pathRequests, pathstateSoA, numPathRequests, raycastRequests, rays, numRaycastRequests, renderCamera, randState); waitAndCheckError("renderLoop::newPath<<<>>>"); diffuseKernel<<<gridDim, blockDim>>>(diffuseMaterialRequests, numDiffuseMaterialRequests, pathstateSoA, queueSize, raycastRequests, rays, numRaycastRequests, shadowRaycastRequests, shadowRays, numShadowRaycastRequests, lights, lightLen, randState, r_useLightSampling); waitAndCheckError("renderLoop::diffuseKernel<<<>>>"); specularReflectionKernel<<<gridDim, blockDim>>>(specularReflectionRequests, numSpecularReflectionRequests, pathstateSoA, queueSize, raycastRequests, rays, numRaycastRequests, randState); waitAndCheckError("renderLoop::specularReflectionKernel<<<>>>"); specularTransmissionKernel<<<gridDim, blockDim>>>(specularTransmissionRequests, numSpecularTransmissionRequests, pathstateSoA, queueSize, raycastRequests, rays, numRaycastRequests, randState); waitAndCheckError("renderLoop::specularTransmissionKernel<<<>>>"); raycast<<<gridDim, blockDim>>>(raycastRequests, rays, numRaycastRequests, pathstateSoA, queueSize, shapes, shapeLen); waitAndCheckError("renderLoop::raycast<<<>>>"); shadowRaycast<<<gridDim, blockDim>>>(shadowRaycastRequests, shadowRays, numShadowRaycastRequests, pathstateSoA, queueSize, shapes, shapeLen); waitAndCheckError("renderLoop::shadowRaycast<<<>>>"); cudaDeviceSynchronize(); } while(!(*numRaycastRequests == 0 && *numShadowRaycastRequests == 0 && *numDiffuseMaterialRequests == 0 && *numSpecularReflectionRequests == 0 && *numSpecularTransmissionRequests == 0)); ++iterationsDone; if(destImageMutex.try_lock()) { dim3 filterBlockDim(32, 32, 1); dim3 filterGridDim(r_width / filterBlockDim.x + (r_width % filterBlockDim.x ? 1 : 0), r_height / filterBlockDim.y + (r_height % filterBlockDim.y ? 1 : 0)); filterImage<<<filterGridDim, filterBlockDim>>>(image, destImage, r_width, r_height, renderCamera.getStratificationLevel(), iterationsDone, 1 / gamma22); waitAndCheckError("renderLoop::filterImage<<<>>>"); imageUpdated = true; destImageWidth = r_width; destImageHeight = r_height; destIterationsDone = iterationsDone; cudaDeviceSynchronize(); // need to wait for kernel before unlocking mutex destImageMutex.unlock(); } } } int Renderer::getData(unsigned int *outImage, int width, int height) { if(!imageUpdated) { return -1; } std::lock_guard<std::mutex> destImageLock(destImageMutex); imageUpdated = false; if(width != destImageWidth || height != destImageHeight || destImage == nullptr) { return -1; } std::memcpy(outImage, destImage, width * height * sizeof(unsigned int)); return destIterationsDone; } void Renderer::stop() { if(!stopRendering) { stopRendering = true; renderThread->join(); delete renderThread; renderThread = nullptr; } } void Renderer::addObject(int id, int materialId, int sceneObjectType, float arr[16], float lightIntensity, float lightColor[3], float area, bool isVisible) { std::lock_guard<std::mutex> sceneLock(sceneMutex); glm::mat4 objectToWorld = glm::make_mat4(arr); glm::vec3 color = glm::make_vec3(lightColor); bool isLight = !isZeroVec(color) && lightIntensity != 0; switch(sceneObjectType) { case SceneObjectType::sphere: shapeVec.push_back(Shape(ShapeType::sphere, materialMap[materialId], area, objectToWorld, lightIntensity * pow(color, 1.0 / gamma22), isVisible)); if(isLight) lightVec.push_back(Shape(ShapeType::sphere, materialMap[materialId], area, objectToWorld, lightIntensity * pow(color, 1.0 / gamma22),isVisible)); break; case SceneObjectType::cube: shapeVec.push_back(Shape(ShapeType::cube, materialMap[materialId], area, objectToWorld, lightIntensity * pow(color, 1.0 / gamma22), isVisible)); if(isLight) lightVec.push_back(Shape(ShapeType::cube, materialMap[materialId], area, objectToWorld, lightIntensity * pow(color, 1.0 / gamma22),isVisible)); break; case SceneObjectType::plane: shapeVec.push_back(Shape(ShapeType::plane, materialMap[materialId], area, objectToWorld, lightIntensity * pow(color, 1.0 / gamma22), isVisible)); if(isLight) lightVec.push_back(Shape(ShapeType::plane, materialMap[materialId], area, objectToWorld, lightIntensity * pow(color, 1.0 / gamma22),isVisible)); break; case SceneObjectType::disc: shapeVec.push_back(Shape(ShapeType::disc, materialMap[materialId], area, objectToWorld, lightIntensity * pow(color, 1.0 / gamma22), isVisible)); if(isLight) lightVec.push_back(Shape(ShapeType::disc, materialMap[materialId], area, objectToWorld, lightIntensity * pow(color, 1.0 / gamma22),isVisible)); break; default: return; } sceneChanged = true; } void Renderer::addDiffuseMaterial(int id, float colorArray[3]) { std::lock_guard<std::mutex> sceneLock(sceneMutex); glm::vec3 color = glm::make_vec3(colorArray); color = pow(color, gamma22); Material m; m.materialType = Materialtype::diffuse; m.diffuse = DiffuseMaterial{color}; materialMap.insert(std::pair<int, Material>(id, m)); } void Renderer::addSpecularMaterial(int id, float reflectionColorArray[3], float transmissionColorArray[3], float IOR) { std::lock_guard<std::mutex> sceneLock(sceneMutex); glm::vec3 reflectionColor = glm::make_vec3(reflectionColorArray); glm::vec3 transmissionColor = glm::make_vec3(transmissionColorArray); reflectionColor = pow(reflectionColor, gamma22); transmissionColor = pow(transmissionColor, gamma22); Material m; m.materialType = Materialtype::specular; m.specular = SpecularMaterial{reflectionColor, transmissionColor, 1.0, IOR}; materialMap.insert(std::pair<int, Material>(id, m)); } void Renderer::clearObjects() { std::lock_guard<std::mutex> sceneLock(sceneMutex); shapeVec.clear(); lightVec.clear(); sceneChanged = true; } void Renderer::clearMaterials() { std::lock_guard<std::mutex> sceneLock(sceneMutex); materialMap.clear(); sceneChanged = true; } void Renderer::setResolution(int width, int height) { std::lock_guard<std::mutex> resolutionLock(resolutionMutex); this->width = width; this->height = height; resolutionChanged = true; } void Renderer::updateCamera(float worldPos[3], float target[3], float fov_y, float fStop, float focusDistance, int stratificationLevel) { std::lock_guard<std::mutex> cameraLock(cameraMutex); std::lock_guard<std::mutex> resolutionLock(resolutionMutex); glm::vec3 worldVec = glm::make_vec3(worldPos); glm::vec3 targetVec = glm::make_vec3(target); if(stratificationLevel != camera.getStratificationLevel()) resolutionChanged = true; camera.update(worldVec, targetVec, fov_y, fStop, focusDistance, stratificationLevel); cameraChanged = true; } void Renderer::freeArrays() { if(image) { cudaFree(image); waitAndCheckError("setup::cudaFree(image)"); image = nullptr; } if(destImage) { cudaFree(destImage); waitAndCheckError("setup::cudaFree(destImage)"); destImage = nullptr; } if(randState) { cudaFree(randState); waitAndCheckError("setup::cudaFree(randstate)"); randState = nullptr; } if(shapes) { cudaFree(shapes); waitAndCheckError("setup::cudaFree(shapes)"); shapes = nullptr; } if(pathstates) { cudaFree(pathstates); waitAndCheckError("setup::cudaFree(pathstates)"); pathstates = nullptr; } if(rays) { cudaFree(rays); waitAndCheckError("setup::cudaFree(rays)"); rays = nullptr; } if(shadowRays) { cudaFree(shadowRays); waitAndCheckError("setup::cudaFree(shadowRays)"); shadowRays = nullptr; } if(pathRequests) { cudaFree(pathRequests); waitAndCheckError("setup::cudaFree(pathRequests)"); pathRequests = nullptr; } if(filmIndex) { cudaFree(filmIndex); waitAndCheckError("setup::cudaFree(filmIndex)"); filmIndex = nullptr; } if(raycastRequests) { cudaFree(raycastRequests); waitAndCheckError("setup::cudaFree(raycastRequests)"); raycastRequests = nullptr; } if(numRaycastRequests) { cudaFree(numRaycastRequests); waitAndCheckError("setup::cudaFree(numRaycastRequests)"); numRaycastRequests = nullptr; } if(shadowRaycastRequests) { cudaFree(shadowRaycastRequests); waitAndCheckError("setup::cudaFree(shadowRaycastRequests)"); shadowRaycastRequests = nullptr; } if(numShadowRaycastRequests) { cudaFree(numShadowRaycastRequests); waitAndCheckError("setup::cudaFree(numShadowRaycastRequests)"); numShadowRaycastRequests = nullptr; } if(numPathRequests) { cudaFree(numPathRequests); waitAndCheckError("setup::cudaFree(numPathRequests)"); numPathRequests = nullptr; } if(diffuseMaterialRequests) { cudaFree(diffuseMaterialRequests); waitAndCheckError("setup::cudaFree(diffuseMaterialRequests)"); diffuseMaterialRequests = nullptr; } if(numDiffuseMaterialRequests) { cudaFree(numDiffuseMaterialRequests); waitAndCheckError("setup::cudaFree(numDiffuseMaterialRequests)"); numDiffuseMaterialRequests = nullptr; } if(specularReflectionRequests) { cudaFree(specularReflectionRequests); waitAndCheckError("setup::cudaFree(specularReflectionRequests)"); specularReflectionRequests = nullptr; } if(specularTransmissionRequests) { cudaFree(specularTransmissionRequests); waitAndCheckError("setup::cudaFree(specularTransmissionRequests)"); specularTransmissionRequests = nullptr; } if(numSpecularReflectionRequests) { cudaFree(numSpecularReflectionRequests); waitAndCheckError("setup::cudaFree(numSpecularReflectionRequests)"); numSpecularReflectionRequests = nullptr; } if(numSpecularTransmissionRequests) { cudaFree(numSpecularTransmissionRequests); waitAndCheckError("setup::cudaFree(numSpecularTransmissionRequests)"); numSpecularTransmissionRequests = nullptr; } pathstateSoA.freeArrays(); } void Renderer::setRenderSettings(bool useLightSampling, bool renderCaustics, int numBounces) { std::lock_guard<std::mutex> sceneLock(sceneMutex); this->useLightSampling = useLightSampling; this->renderCaustics = renderCaustics; this->numBounces = numBounces; sceneChanged = true; } <|start_filename|>renderer/cpp/src/util/util.cu<|end_filename|> /* This source file makes use of modified code from pbrt-v3 pbrt source code is Copyright(c) 1998-2016 <NAME>, <NAME>, and <NAME>. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "util.hpp" #include <iostream> __device__ bool Quadratic(const float a, const float b, const float c, float *t0, float *t1) { float dis = b * b - 4.0 * a * c; if(dis < 0.0 || a == 0.0) { return false; } dis = sqrt(dis); float x0 = (-b + dis) / (2 * a); float x1 = (-b - dis) / (2 * a); if(x0 <= x1) { *t0 = x0; *t1 = x1; } else { *t0 = x1; *t1 = x0; } return true; } __host__ __device__ glm::vec3 pow(const glm::vec3 &v, const float exponent) { return glm::vec3(pow(v.r, exponent), pow(v.g, exponent), pow(v.b, exponent)); } __device__ float clamp(const float &v, const float &min, const float &max) { return fmaxf(min, fminf(v, max)); } void waitAndCheckError(const char* location) { #ifdef CudaDebug cudaDeviceSynchronize(); cudaError_t err = cudaGetLastError(); if(err != cudaSuccess) std::cout << location << ": " << cudaGetErrorString(err) << std::endl; #endif } <|start_filename|>renderer/cpp/src/core/geometry.hpp<|end_filename|> /* This source file makes use of modified code from pbrt-v3 pbrt source code is Copyright(c) 1998-2016 <NAME>, <NAME>, and <NAME>. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <glm/glm.hpp> #include <math.h> struct Ray; struct Interaction; __device__ __host__ glm::vec3 operator*(const glm::mat4 &m, const glm::vec3 &v); __device__ __host__ bool isZeroVec(const glm::vec3 &v); __device__ Ray operator*(const glm::mat4 &m, const Ray &ray); __device__ Interaction operator*(const glm::mat4 &m, const Interaction &i); struct Ray { __device__ Ray(); __device__ Ray(const glm::vec3 &o, const glm::vec3 &d, const float t = INFINITY); __device__ glm::vec3 operator()(const float t) const; glm::vec3 o; glm::vec3 d; mutable float t; }; struct Interaction { __device__ Interaction(); __device__ Interaction(const glm::vec3 &p, const glm::vec3 &n, const glm::vec3 &wo); glm::vec3 p; glm::vec3 n; glm::vec3 wo; }; <|start_filename|>renderer/cpp/src/core/shading.hpp<|end_filename|> #pragma once #include <curand_kernel.h> #include "pathstate.hpp" #include "shape.hpp" __global__ void diffuseKernel(int *materialRequests, const int *numMaterialRequests, PathstateSoA states, const int lenPathStates, int *raycastRequests, Ray *rays, int *numRaycastRequests, int *shadowRaycastRequests, Ray *shadowRays, int *numShadowRaycastRequests, const Shape *lights, const int numLights, curandState *randState, bool useLightSampling); __global__ void specularReflectionKernel(int *materialRequests, const int *numMaterialRequests, PathstateSoA states, const int lenPathStates, int *raycastRequests, Ray *rays, int *numRaycastRequests, curandState *randState); __global__ void specularTransmissionKernel(int *materialRequests, const int *numMaterialRequests, PathstateSoA states, const int lenPathStates, int *raycastRequests, Ray *rays, int *numRaycastRequests, curandState *randState); <|start_filename|>renderer/cpp/src/core/material.hpp<|end_filename|> #pragma once #include <glm/glm.hpp> enum class Materialtype { nullMaterial = 0, diffuse = 1, specular = 2 }; struct DiffuseMaterial { glm::vec3 color; }; struct SpecularMaterial { glm::vec3 R, T; float etaA, etaB; }; struct Material { Materialtype materialType; union { DiffuseMaterial diffuse; SpecularMaterial specular; }; }; <|start_filename|>renderer/cpp/src/core/shading.cu<|end_filename|> /* This source file makes use of modified code from pbrt-v3 pbrt source code is Copyright(c) 1998-2016 <NAME>, <NAME>, and <NAME>. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "shading.hpp" #include "sampling.hpp" #include "../util/util.hpp" #include <cmath> #include <algorithm> const float InvPi = 1.0 / M_PI; __device__ float CosTheta(const glm::vec3 &v) { return v.z; } __device__ float AbsCosTheta(const glm::vec3 &v) { return abs(v.z); } __device__ bool SameHemisphere(const glm::vec3 &v1, const glm::vec3 &v2) { return v1.z * v2.z > 0; } __device__ void NormalToCoordinateSystem(const glm::vec3 &n, glm::mat3 *localToWorld, glm::mat3 *worldToLocal) { glm::vec3 s, t; if (abs(n.x) > abs(n.y)) { s = glm::vec3(-n.z, 0, n.x) / sqrt(n.x * n.x + n.z * n.z); } else { s = glm::vec3(0, n.z, -n.y) / sqrt(n.y * n.y + n.z * n.z); } t = glm::cross(n, s); *localToWorld = glm::mat3(s, t, n); *worldToLocal = glm::inverse(*localToWorld); } __device__ float FrDielectric(float cosThetaI, float etaI, float etaT) { cosThetaI = clamp(cosThetaI, -1, 1); // Potentially swap indices of refraction bool entering = cosThetaI > 0.f; if (!entering) { swap(etaI, etaT); cosThetaI = abs(cosThetaI); } // Compute _cosThetaT_ using Snell's law float sinThetaI = sqrt(fmaxf((float)0, 1 - cosThetaI * cosThetaI)); float sinThetaT = etaI / etaT * sinThetaI; // Handle total internal reflection if (sinThetaT >= 1) return 1; float cosThetaT = sqrt(fmaxf((float)0, 1 - sinThetaT * sinThetaT)); float Rparl = ((etaT * cosThetaI) - (etaI * cosThetaT)) / ((etaT * cosThetaI) + (etaI * cosThetaT)); float Rperp = ((etaI * cosThetaI) - (etaT * cosThetaT)) / ((etaI * cosThetaI) + (etaT * cosThetaT)); return (Rparl * Rparl + Rperp * Rperp) / 2; } __device__ bool Refract(const glm::vec3 &wi, const glm::vec3 &n, float eta, glm::vec3 *wt) { // Compute $\cos \theta_\roman{t}$ using Snell's law float cosThetaI = glm::dot(n, wi); float sin2ThetaI = fmaxf(float(0), float(1 - cosThetaI * cosThetaI)); float sin2ThetaT = eta * eta * sin2ThetaI; // Handle total internal reflection for transmission if (sin2ThetaT >= 1) return false; float cosThetaT = sqrt(1 - sin2ThetaT); *wt = eta * -wi + (eta * cosThetaI - cosThetaT) * n; return true; } __device__ glm::vec3 Faceforward(const glm::vec3 &n, const glm::vec3 &v) { return (glm::dot(n, v) < 0.f) ? -n : n; } __device__ glm::vec3 diffuse_f(const Material &material, const glm::vec3 &wo, const glm::vec3 &wi) { return material.diffuse.color * InvPi; } __device__ float diffuse_Pdf(const Material &material, const glm::vec3 &wo, const glm::vec3 &wi) { return SameHemisphere(wo, wi) ? AbsCosTheta(wi) * InvPi : 0.0; } __device__ glm::vec3 diffuse_Sample_f(const Material &material, const glm::vec3 &wo, glm::vec3 *wi, const glm::vec2 &sample, float *pdf) { *wi = CosineSampleHemisphere(sample); if (wo.z < 0) wi->z *= -1; *pdf = diffuse_Pdf(material, wo, *wi); return diffuse_f(material, wo, *wi); } __device__ glm::vec3 specularReflection_Sample_f(const Material &material, const glm::vec3 &wo, glm::vec3 *wi, float *pdf) { float F = FrDielectric(CosTheta(wo), material.specular.etaA, material.specular.etaB); // Compute specular reflection for _FresnelSpecular_ // Compute perfect specular reflection direction *wi = glm::vec3(-wo.x, -wo.y, wo.z); *pdf = 0.5; return F * material.specular.R / AbsCosTheta(*wi); } __device__ glm::vec3 specularTransmission_Sample_f(const Material &material, const glm::vec3 &wo, glm::vec3 *wi, float *pdf) { float F = FrDielectric(CosTheta(wo), material.specular.etaA, material.specular.etaB); // Compute specular transmission for _FresnelSpecular_ // Figure out which $\eta$ is incident and which is transmitted bool entering = CosTheta(wo) > 0; float etaI = entering ? material.specular.etaA : material.specular.etaB; float etaT = entering ? material.specular.etaB : material.specular.etaA; // Compute ray direction for specular transmission if (!Refract(wo, Faceforward(glm::vec3(0.0, 0.0, 1.0), wo), etaI / etaT, wi)) return glm::vec3(0.0); glm::vec3 ft = material.specular.T * (1 - F); *pdf = 0.5; return ft / AbsCosTheta(*wi); } __global__ void diffuseKernel(int *materialRequests, const int *numMaterialRequests, PathstateSoA states, const int lenPathStates, int *raycastRequests, Ray *rays, int *numRaycastRequests, int *shadowRaycastRequests, Ray *shadowRays, int *numShadowRaycastRequests, const Shape *lights, const int numLights, curandState *randState, bool useLightSampling) { const int index = blockIdx.x * blockDim.x + threadIdx.x; if(index >= *numMaterialRequests) return; int pathIdx = materialRequests[index]; if(pathIdx >= 0) { Pathstate state; state.currentIsect = states.currentIsect[pathIdx]; state.material = states.material[pathIdx]; bool inside = glm::dot(state.currentIsect.n, state.currentIsect.wo) < 0.0f; glm::mat3 localToWorld, worldToLocal; Ray ray(state.currentIsect.p, glm::vec3(0.0)); curandState localRandState = randState[pathIdx]; glm::vec2 sample(curand_uniform(&localRandState), curand_uniform(&localRandState)); NormalToCoordinateSystem(state.currentIsect.n, &localToWorld, &worldToLocal); state.f = diffuse_Sample_f(state.material, worldToLocal * state.currentIsect.wo, &ray.d, sample, &state.pdf); ray.d = glm::normalize(localToWorld * ray.d); ray.o = ray.o + 0.00005f * (inside ? -state.currentIsect.n : state.currentIsect.n); int reqIdx = atomicAdd(numRaycastRequests, 1); rays[reqIdx] = ray; raycastRequests[reqIdx] = pathIdx; // Light Sampling if(useLightSampling) { state.Lsample = glm::vec3(0.0); if (numLights > 0) { int lightIndex = min(int(numLights * curand_uniform(&localRandState)), numLights - 1); sample = glm::vec2(curand_uniform(&localRandState), curand_uniform(&localRandState)); Ray shadowRay(ray.o, glm::vec3(0.0)); state.lightPdf = lights[lightIndex].Sample(shadowRay, state.Lsample, sample); if(glm::dot(shadowRay.d, (inside ? -state.currentIsect.n : state.currentIsect.n)) > 0.0001) { reqIdx = atomicAdd(numShadowRaycastRequests, 1); shadowRays[reqIdx] = shadowRay; shadowRaycastRequests[reqIdx] = pathIdx; states.lightPdf[pathIdx] = float(1.0 / numLights) * state.lightPdf; states.LsampleOccluded[pathIdx] = false; states.light_f[pathIdx] = diffuse_f(state.material, worldToLocal * state.currentIsect.wo, worldToLocal * shadowRay.d); } else { state.Lsample = glm::vec3(0.0); } } states.Lsample[pathIdx] = state.Lsample; states.isLightSample[pathIdx] = true; } states.pdf[pathIdx] = state.pdf; states.f[pathIdx] = state.f; materialRequests[index] = -1; randState[pathIdx] = localRandState; } } __global__ void specularReflectionKernel(int *materialRequests, const int *numMaterialRequests, PathstateSoA states, const int lenPathStates, int *raycastRequests, Ray *rays, int *numRaycastRequests, curandState *randState) { const int index = blockIdx.x * blockDim.x + threadIdx.x; if(index >= *numMaterialRequests) return; int pathIdx = materialRequests[index]; if(pathIdx >= 0) { Pathstate state; state.currentIsect = states.currentIsect[pathIdx]; state.material = states.material[pathIdx]; glm::mat3 localToWorld, worldToLocal; Ray ray(state.currentIsect.p, glm::vec3(0.0)); NormalToCoordinateSystem(state.currentIsect.n, &localToWorld, &worldToLocal); state.f = specularReflection_Sample_f(state.material, worldToLocal * state.currentIsect.wo, &ray.d, &state.pdf); ray.d = glm::normalize(localToWorld * ray.d); ray.o = ray.o + 0.0001f * ray.d; int reqIdx = atomicAdd(numRaycastRequests, 1); rays[reqIdx] = ray; raycastRequests[reqIdx] = pathIdx; states.pdf[pathIdx] = state.pdf; states.f[pathIdx] = state.f; materialRequests[index] = -1; } } __global__ void specularTransmissionKernel(int *materialRequests, const int *numMaterialRequests, PathstateSoA states, const int lenPathStates, int *raycastRequests, Ray *rays, int *numRaycastRequests, curandState *randState) { const int index = blockIdx.x * blockDim.x + threadIdx.x; if(index >= *numMaterialRequests) return; int pathIdx = materialRequests[index]; if(pathIdx >= 0) { Pathstate state; state.currentIsect = states.currentIsect[pathIdx]; state.material = states.material[pathIdx]; glm::mat3 localToWorld, worldToLocal; Ray ray(state.currentIsect.p, glm::vec3(0.0)); NormalToCoordinateSystem(state.currentIsect.n, &localToWorld, &worldToLocal); state.f = specularTransmission_Sample_f(state.material, worldToLocal * state.currentIsect.wo, &ray.d, &state.pdf); if(!isZeroVec(state.f)) { ray.d = glm::normalize(localToWorld * ray.d); ray.o = ray.o + 0.0001f * ray.d; int reqIdx = atomicAdd(numRaycastRequests, 1); rays[reqIdx] = ray; raycastRequests[reqIdx] = pathIdx; } states.pdf[pathIdx] = state.pdf; states.f[pathIdx] = state.f; materialRequests[index] = -1; } } <|start_filename|>editor/ui/shaders/lightfragment.frag<|end_filename|> #version 450 core in vec4 outColor; in vec3 position; in vec3 normal; out vec4 FragColor; uniform vec3 eyePos; vec3 ambient = vec3(0.2); vec3 lightColor = vec3(1.0, 1.0, 1.0); void main() { FragColor = outColor; } <|start_filename|>renderer/cpp/src/core/camera.cu<|end_filename|> #include "camera.hpp" #include "sampling.hpp" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <iostream> __host__ Camera::Camera(const int resX, const int resY, const glm::vec3 &worldPos, const glm::vec3 &target, const float fov_y, const float fStop, const float focusDistance, const int stratificationLevel) : resX(resX), resY(resY), worldPos(worldPos), target(target), fov_y(fov_y), pFilmIndex(nullptr), pImage(nullptr), focusDistance(focusDistance), stratificationLevel(stratificationLevel) { height = 2 * tan(glm::radians(fov_y * 0.5)); width = height * ((float)resX) / resY; this->apertureRadius = fStopToApertureSize(fStop); } __host__ void Camera::update(const glm::vec3 &worldPos, const glm::vec3 &target, const float fov_y, const float fStop, const float focusDistance, const int stratificationLevel) { this->worldPos = worldPos; this->target = target; this->fov_y = fov_y; this->apertureRadius = fStopToApertureSize(fStop); this->focusDistance = focusDistance; this->stratificationLevel = stratificationLevel; height = 2 * tan(glm::radians(fov_y * 0.5)); width = height * ((float)resX) / resY; } __host__ int Camera::getStratificationLevel() const { return stratificationLevel; } __host__ void Camera::update(const int resX, const int resY) { this->resX = resX * stratificationLevel; this->resY = resY * stratificationLevel; height = 2 * tan(glm::radians(fov_y * 0.5)); width = height * ((float)this->resX) / this->resY; } __device__ void Camera::getRay(const int filmIndex, Ray *ray, const glm::vec2 &pixelSample, const glm::vec2 &lensSample) const { if(filmIndex < resX * resY) { long y = filmIndex / resX; long x = filmIndex % resX; getRay(x, y, ray, pixelSample, lensSample); } } __device__ void Camera::getRay(const int x, const int y, Ray *ray, const glm::vec2 &pixelSample, const glm::vec2 &lensSample) const { float scaleX = (x + pixelSample.x) / resX; float scaleY = (y + pixelSample.y) / resY; glm::vec3 imgPoint(-width * 0.5 + scaleX * width, -height * 0.5 + scaleY * height, -1.0); glm::vec3 focusPoint(imgPoint.x * focusDistance, imgPoint.y * focusDistance, -focusDistance); glm::vec3 lensPoint = apertureRadius * glm::vec3(UniformSampleDisk(lensSample), 0.0); Ray r(lensPoint, focusPoint - lensPoint); glm::mat4 lookAt = glm::inverse(glm::lookAt(worldPos, target, glm::vec3(0.0, 1.0, 0.0))); *ray = lookAt * r; ray->d = glm::normalize(ray->d); } __device__ int Camera::getFilmIndex() { int idx = atomicAdd(pFilmIndex, 1); return idx < resX * resY ? idx : -1; } __host__ bool Camera::isDone() const { return *pFilmIndex >= resX * resY; } __host__ void Camera::resetFilmIndex() { *pFilmIndex = 0; } __host__ void Camera::setImage(glm::vec3 *pImage) { this->pImage = pImage; } __host__ void Camera::setFilmIndexPointer(int *pFilmIndex) { this->pFilmIndex = pFilmIndex; } __device__ void Camera::addPixelVal(const int filmindex, const glm::vec3 &val) { if(filmindex < resX * resY) { pImage[filmindex] += val; } } __host__ float Camera::fStopToApertureSize(const float fStop) const { float f = 1 / tan(glm::radians(fov_y * 0.5)) / 2; return f * 0.5 / fStop; } <|start_filename|>editor/ui/shaders/viewportfragment.frag<|end_filename|> #version 450 core in vec2 outUv; out vec4 FragColor; uniform sampler2D viewportTexture; void main() { FragColor = texture(viewportTexture, outUv); } <|start_filename|>renderer/cpp/src/core/shape.cu<|end_filename|> /* This source file makes use of modified code from pbrt-v3 pbrt source code is Copyright(c) 1998-2016 <NAME>, <NAME>, and <NAME>. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "shape.hpp" #include "sampling.hpp" #include <cmath> #include "../util/util.hpp" __device__ __host__ Shape::Shape(const ShapeType shapeType, Material material, float area, const glm::mat4 &objectToWorld, const glm::vec3 &Lemit, const bool isVisible) :shapeType(shapeType), material(material), area(area), objectToWorld(objectToWorld), worldToObject(glm::inverse(objectToWorld)), Lemit(Lemit), isVisible(isVisible) {} __device__ bool Shape::Intersect(const Ray &ray, Interaction *isect, Material *mat, glm::vec3 *Lemit, bool firstRay) const { if(!isVisible && firstRay) return false; switch(shapeType) { case ShapeType::sphere: return IntersectSphere(ray, isect, mat, Lemit); case ShapeType::plane: return IntersectPlane(ray, isect, mat, Lemit); case ShapeType::disc: return IntersectDisc(ray, isect, mat, Lemit); case ShapeType::cube: return IntersectCube(ray, isect, mat, Lemit); default: return false; } } __device__ bool Shape::OccludesRay(const Ray &ray) const { switch(shapeType) { case ShapeType::sphere: return SphereOccludesRay(ray); case ShapeType::plane: return PlaneOccludesRay(ray); case ShapeType::disc: return DiscOccludesRay(ray); case ShapeType::cube: return CubeOccludesRay(ray); default: return false; } } __device__ float Shape::Sample(Ray &ray, glm::vec3 &Lsample, const glm::vec2 &sample) const { switch(shapeType) { case ShapeType::sphere: return SampleSphere(ray, Lsample, sample); case ShapeType::plane: return SamplePlane(ray, Lsample, sample); case ShapeType::disc: return SampleDisc(ray, Lsample, sample); case ShapeType::cube: return SampleCube(ray, Lsample, sample); default: return 0.0; } } __device__ bool Shape::IntersectSphere(const Ray &ray, Interaction *isect, Material *mat, glm::vec3 *Lemit) const { glm::vec3 pHit; Ray objRay = worldToObject * ray; float a = objRay.d.x * objRay.d.x + objRay.d.y * objRay.d.y + objRay.d.z * objRay.d.z; float b = 2 * (objRay.d.x * objRay.o.x + objRay.d.y * objRay.o.y + objRay.d.z * objRay.o.z); float c = objRay.o.x * objRay.o.x + objRay.o.y * objRay.o.y + objRay.o.z * objRay.o.z - 1.0; float t0, t1; if(!Quadratic(a, b, c, &t0, &t1)) { return false; } if(t0 > objRay.t || t1 <= 0.0) { return false; } float tShapeHit = t0; if(tShapeHit <= 0) { tShapeHit = t1; if(tShapeHit > objRay.t) { return false; } } pHit = objRay(tShapeHit); *isect = objectToWorld * Interaction(pHit, pHit, -objRay.d); *mat = material; *Lemit = this->Lemit; ray.t = tShapeHit; return true; } __device__ bool Shape::IntersectPlane(const Ray &ray, Interaction *isect, Material *mat, glm::vec3 *Lemit) const { glm::vec3 pHit; glm::vec3 pMin(-1.0, 0.0, -1.0); glm::vec3 pMax(1.0, 1.0, 1.0); glm::vec3 n; Ray objRay = worldToObject * ray; float t0 = 0.0, t1 = objRay.t; int indexNear = -1; int indexFar = -1; for(int i = 0; i < 3; ++i) { float invRayDir = 1.0 / objRay.d[i]; float tNear = (pMin[i] - objRay.o[i]) * invRayDir; float tFar = (pMax[i] - objRay.o[i]) * invRayDir; if(tNear > tFar) { float temp = tNear; tNear = tFar; tFar = temp; } if(tNear > t0) { t0 = tNear; indexNear = i; } if(tFar < t1) { t1 = tFar; indexFar = i; } if(t0 > t1) return false; } n = glm::vec3(0.0, 1.0, 0.0); if(indexNear == 1 && indexFar == 1) { if(objRay(t0).y <= objRay(t1).y) { pHit = objRay(t0); ray.t = t0; } else { pHit = objRay(t1); ray.t = t1; } } else if(indexNear == 1 && glm::dot(n, objRay.d) >= 0.0) { pHit = objRay(t0); ray.t = t0; } else if(indexFar == 1 && glm::dot(n, objRay.d) < 0.0) { pHit = objRay(t1); ray.t = t1; } else { return false; } if(glm::dot(objRay.d, n) > 0.0) n *= -1.0; *isect = objectToWorld * Interaction(pHit, n, -objRay.d); *mat = material; *Lemit = this->Lemit; return true; } __device__ bool Shape::IntersectCube(const Ray &ray, Interaction *isect, Material *mat, glm::vec3 *Lemit) const { glm::vec3 pHit; glm::vec3 pMin(-1.0, -1.0, -1.0); glm::vec3 pMax(1.0, 1.0, 1.0); glm::vec3 n(0.0); Ray objRay = worldToObject * ray; float t0 = 0.0, t1 = objRay.t; int it0 = -1, it1 = -1; for(int i = 0; i < 3; ++i) { float invRayDir = 1.0 / objRay.d[i]; float tNear = (pMin[i] - objRay.o[i]) * invRayDir; float tFar = (pMax[i] - objRay.o[i]) * invRayDir; if(tNear > tFar) { float temp = tNear; tNear = tFar; tFar = temp; } if(tNear > t0) { t0 = tNear; it0 = i; } if(tFar < t1) { t1 = tFar; it1 = i; } if(t0 > t1) return false; } if (it0 >= 0){ pHit = objRay(t0); ray.t = t0; n[it0] = objRay.d[it0] < 0.0 ? -1.0 : 1.0; } else if (t1 < objRay.t && t1 > 0.0) { pHit = objRay(t1); ray.t = t1; n[it1] = objRay.d[it1] > 0.0 ? -1.0 : 1.0; } else { return false; } *isect = objectToWorld * Interaction(pHit, n, -objRay.d); *mat = material; *Lemit = this->Lemit; return true; } __device__ bool Shape::IntersectDisc(const Ray &ray, Interaction *isect, Material *mat, glm::vec3 *Lemit) const { glm::vec3 pHit; glm::vec3 n = glm::vec3(glm::transpose(glm::inverse(objectToWorld)) * glm::vec4(0.0, 1.0, 0.0, 0.0)); glm::vec3 worldPos = objectToWorld * glm::vec4(0.0, 0.0, 0.0, 1.0); n = glm::normalize(n); float denom = glm::dot(n, ray.d); float t; if(abs(denom) > 1e-6) { glm::vec3 pOriginTorOrigin = worldPos - ray.o; t = glm::dot(pOriginTorOrigin, n) / denom; } else { return false; } if(t < 0.0 || t >= ray.t) { return false; } pHit = ray(t); glm::vec3 pHitObj = worldToObject * pHit; if(glm::dot(pHitObj, pHitObj) > 1.0) { return false; } *isect = Interaction(pHit, glm::dot(ray.d, n) >= 0.0 ? -n : n, -ray.d); *mat = material; *Lemit = this->Lemit; ray.t = t; return true; } __device__ bool Shape::SphereOccludesRay(const Ray &ray) const { Ray objRay = worldToObject * ray; float a = objRay.d.x * objRay.d.x + objRay.d.y * objRay.d.y + objRay.d.z * objRay.d.z; float b = 2 * (objRay.d.x * objRay.o.x + objRay.d.y * objRay.o.y + objRay.d.z * objRay.o.z); float c = objRay.o.x * objRay.o.x + objRay.o.y * objRay.o.y + objRay.o.z * objRay.o.z - 1.0; float t0, t1; if(!Quadratic(a, b, c, &t0, &t1)) { return false; } if(t0 > objRay.t || t1 <= 0.0) { return false; } float tShapeHit = t0; if(tShapeHit <= 0) { tShapeHit = t1; if(tShapeHit > objRay.t) { return false; } } return true; } __device__ bool Shape::PlaneOccludesRay(const Ray &ray) const { glm::vec3 n; glm::vec3 pMin(-1.0, 0.0, -1.0); glm::vec3 pMax(1.0, 1.0, 1.0); Ray objRay = worldToObject * ray; float t0 = 0.0, t1 = objRay.t; int indexNear = -1; int indexFar = -1; for(int i = 0; i < 3; ++i) { float invRayDir = 1.0 / objRay.d[i]; float tNear = (pMin[i] - objRay.o[i]) * invRayDir; float tFar = (pMax[i] - objRay.o[i]) * invRayDir; if(tNear > tFar) { float temp = tNear; tNear = tFar; tFar = temp; } if(tNear > t0) { t0 = tNear; indexNear = i; } if(tFar < t1) { t1 = tFar; indexFar = i; } if(t0 > t1) return false; } n = glm::vec3(0.0, 1.0, 0.0); if(indexNear == 1 && (indexFar == 1 || glm::dot(n, objRay.d) >= 0.0) || indexFar == 1 && glm::dot(n, objRay.d) < 0.0) { return true; } return false; } __device__ bool Shape::CubeOccludesRay(const Ray &ray) const { glm::vec3 pMin(-1.0, -1.0, -1.0); glm::vec3 pMax(1.0, 1.0, 1.0); Ray objRay = worldToObject * ray; float t0 = 0.0, t1 = objRay.t; int it0 = -1; for(int i = 0; i < 3; ++i) { float invRayDir = 1.0 / objRay.d[i]; float tNear = (pMin[i] - objRay.o[i]) * invRayDir; float tFar = (pMax[i] - objRay.o[i]) * invRayDir; if(tNear > tFar) { float temp = tNear; tNear = tFar; tFar = temp; } if(tNear > t0) { t0 = tNear; it0 = i; } if(tFar < t1) { t1 = tFar; } if(t0 > t1) return false; } if (!(it0 >= 0 || t1 < objRay.t && t1 > 0.0)) return false; return true; } __device__ bool Shape::DiscOccludesRay(const Ray &ray) const { glm::vec3 pHit; glm::vec3 n = glm::vec3(glm::transpose(glm::inverse(objectToWorld)) * glm::vec4(0.0, 1.0, 0.0, 0.0)); glm::vec3 worldPos = objectToWorld * glm::vec4(0.0, 0.0, 0.0, 1.0); n = glm::normalize(n); float denom = glm::dot(n, ray.d); float t; if(abs(denom) > 1e-6) { glm::vec3 pOriginTorOrigin = worldPos - ray.o; t = glm::dot(pOriginTorOrigin, n) / denom; } else { return false; } if(t < 0.0 || t >= ray.t) { return false; } pHit = ray(t); glm::vec3 pHitObj = worldToObject * pHit; if(glm::dot(pHitObj, pHitObj) > 1.0) { return false; } return true; } __device__ float Shape::SampleSphere(Ray &ray, glm::vec3 &Lsample, const glm::vec2 &sample) const { glm::vec3 p = UniformSampleSphere(sample); glm::vec3 p_world = objectToWorld * p; glm::mat3 invTransp = glm::transpose(glm::inverse(glm::mat3(objectToWorld))); glm::vec3 n_world = glm::normalize(invTransp * p); ray.d = p_world - ray.o; ray.t = 0.9999f * glm::length(ray.d); ray.d = glm::normalize(ray.d); Lsample = Lemit; return ray.t * ray.t / (abs(glm::dot(-ray.d, n_world)) * area); } __device__ float Shape::SamplePlane(Ray &ray, glm::vec3 &Lsample, const glm::vec2 &sample) const { glm:: vec3 n(0.0, 1.0, 0.0); glm::vec3 p = glm::vec3(-1.0, 0.0, -1.0) + 2.0f * glm::vec3(sample.x, 0.0, sample.y); glm::vec3 p_world = objectToWorld * p; glm::mat3 invTransp = glm::transpose(glm::inverse(glm::mat3(objectToWorld))); glm::vec3 n_world = glm::normalize(invTransp * n); ray.d = p_world - ray.o; ray.t = 0.9999f * glm::length(ray.d); ray.d = glm::normalize(ray.d); Lsample = Lemit; return ray.t * ray.t / (abs(glm::dot(-ray.d, n_world)) * area); } __device__ float Shape::SampleDisc(Ray &ray, glm::vec3 &Lsample, const glm::vec2 &sample) const { glm:: vec3 n(0.0, 1.0, 0.0); glm::vec2 s = UniformSampleDisk(sample); glm::vec3 p = glm::vec3(s.x, 0.0, s.y); glm::vec3 p_world = objectToWorld * p; glm::mat3 invTransp = glm::transpose(glm::inverse(glm::mat3(objectToWorld))); glm::vec3 n_world = glm::normalize(invTransp * n); ray.d = p_world - ray.o; ray.t = 0.9999f * glm::length(ray.d); ray.d = glm::normalize(ray.d); Lsample = Lemit; return ray.t * ray.t / (abs(glm::dot(-ray.d, n_world)) * area); } __device__ float Shape::SampleCube(Ray &ray, glm::vec3 &Lsample, const glm::vec2 &sample) const { glm::vec2 s = sample; int i = min(int(3 * s.x), 2); glm::vec3 o(1.0, 1.0, 1.0); glm::vec3 axis1; glm::vec3 axis2; glm::vec3 n; if(i == 0) { axis1 = glm::vec3(-1.0, 0.0, 0.0); axis2 = glm::vec3(0.0, -1.0, 0.0); n = glm::vec3(0.0, 0.0, 1.0); s.x *= 3.0; } else if(i == 1) { axis1 = glm::vec3(0.0, 0.0, -1.0); axis2 = glm::vec3(0.0, -1.0, 0.0); n = glm::vec3(1.0, 0.0, 0.0); s.x = s.x * 3.0 - 1.0; } else if(i == 2) { axis1 = glm::vec3(-1.0, 0.0, 0.0); axis2 = glm::vec3(0.0, 0.0, -1.0); n = glm::vec3(0.0, 1.0, 0.0); s.x = s.x * 3.0 - 2.0; } if(s.y > 0.5) { o *= -1.0f; axis1 *= -1.0f; axis2 *= -1.0f; n *= -1.0f; s.y = s.y * 2.0 - 1.0; } else { s.y *= 2.0; } glm::vec3 p = o + 2.0f * s.x * axis1 + 2.0f * s.y * axis2; glm::vec3 p_world = objectToWorld * p; glm::mat3 invTransp = glm::transpose(glm::inverse(glm::mat3(objectToWorld))); glm::vec3 n_world = glm::normalize(invTransp * n); ray.d = p_world - ray.o; ray.t = 0.9999f * glm::length(ray.d); ray.d = glm::normalize(ray.d); Lsample = Lemit; return ray.t * ray.t / (abs(glm::dot(-ray.d, n_world)) * area); } <|start_filename|>editor/ui/shaders/viewportvertex.vert<|end_filename|> #version 450 core layout (location = 0) in vec3 vPos; layout (location = 1) in vec2 uv; out vec2 outUv; void main() { gl_Position = vec4(vPos, 1.0); outUv = uv; } <|start_filename|>renderer/cpp/src/core/pathstate.cu<|end_filename|> #include "pathstate.hpp" #include "../util/util.hpp" PathstateSoA::PathstateSoA() : currentIsect(nullptr), extensionIsect(nullptr), foundExtensionIsect(nullptr), isActive(nullptr), pdf(nullptr), lightPdf(nullptr), bounces(nullptr), beta(nullptr), L(nullptr), wi_L(nullptr), Lemit(nullptr), Lsample(nullptr), LsampleOccluded(nullptr), isLightSample(nullptr), filmIndex(nullptr), material(nullptr), f(nullptr), light_f(nullptr), diffuseBounce(nullptr) {} void PathstateSoA::freeArrays() { if(currentIsect) { cudaFree(currentIsect); waitAndCheckError("PathstateSoA::freeArrays(currentIsect)"); currentIsect = nullptr; } if(extensionIsect) { cudaFree(extensionIsect); waitAndCheckError("PathstateSoA::freeArrays(extensionIsect)"); extensionIsect = nullptr; } if(foundExtensionIsect) { cudaFree(foundExtensionIsect); waitAndCheckError("PathstateSoA::freeArrays(foundExtensionIsect)"); foundExtensionIsect = nullptr; } if(isActive) { cudaFree(isActive); waitAndCheckError("PathstateSoA::freeArrays(isActive)"); isActive = nullptr; } if(pdf) { cudaFree(pdf); waitAndCheckError("PathstateSoA::freeArrays(pdf)"); pdf = nullptr; } if(lightPdf) { cudaFree(lightPdf); waitAndCheckError("PathstateSoA::freeArrays(lightPdf)"); lightPdf = nullptr; } if(bounces) { cudaFree(bounces); waitAndCheckError("PathstateSoA::freeArrays(bounces)"); bounces = nullptr; } if(beta) { cudaFree(beta); waitAndCheckError("PathstateSoA::freeArrays(beta)"); beta = nullptr; } if(L) { cudaFree(L); waitAndCheckError("PathstateSoA::freeArrays(L)"); L = nullptr; } if(wi_L) { cudaFree(wi_L); waitAndCheckError("PathstateSoA::freeArrays(wi_L)"); wi_L = nullptr; } if(Lemit) { cudaFree(Lemit); waitAndCheckError("PathstateSoA::freeArrays(Lemit)"); Lemit = nullptr; } if(filmIndex) { cudaFree(filmIndex); waitAndCheckError("PathstateSoA::freeArrays(filmIndex)"); filmIndex = nullptr; } if(material) { cudaFree(material); waitAndCheckError("PathstateSoA::freeArrays(material)"); material = nullptr; } if(f) { cudaFree(f); waitAndCheckError("PathstateSoA::freeArrays(f)"); f = nullptr; } if(light_f) { cudaFree(light_f); waitAndCheckError("PathstateSoA::freeArrays(light_f)"); light_f = nullptr; } if(Lsample) { cudaFree(Lsample); waitAndCheckError("PathstateSoA::freeArrays(Lsample)"); Lsample = nullptr; } if(LsampleOccluded) { cudaFree(LsampleOccluded); waitAndCheckError("PathstateSoA::freeArrays(LsampleOccluded)"); LsampleOccluded = nullptr; } if(isLightSample) { cudaFree(isLightSample); waitAndCheckError("PathstateSoA::freeArrays(isLightSample)"); isLightSample = nullptr; } if(diffuseBounce) { cudaFree(diffuseBounce); waitAndCheckError("PathstateSoA::freeArrays(diffuseBounce)"); diffuseBounce = nullptr; } }
BashPrince/pathtracer
<|start_filename|>src/mrb_hiredis.h<|end_filename|> #ifndef MRB_HIREDIS_H #define MRB_HIREDIS_H #include <hiredis/hiredis.h> #include <hiredis/async.h> #include <mruby/data.h> #include <errno.h> #include <mruby/error.h> #include <mruby/numeric.h> #include <mruby/array.h> #include <mruby/hash.h> #include <mruby/string.h> #include <mruby/throw.h> #include <string.h> #include <mruby/class.h> #include <mruby/variable.h> #include <mruby/hash.h> #include <strings.h> #include <stdio.h> #include <stdlib.h> #if (MRB_INT_BIT < 64) #error "mruby-hiredis: MRB_INT64 must be defined in mrbconf.h" #endif #if (__GNUC__ >= 3) || (__INTEL_COMPILER >= 800) || defined(__clang__) # define likely(x) __builtin_expect(!!(x), 1) # define unlikely(x) __builtin_expect(!!(x), 0) #else # define likely(x) (x) # define unlikely(x) (x) #endif static void mrb_redisFree_gc(mrb_state *mrb, void *p) { redisFree((redisContext *) p); } static const struct mrb_data_type mrb_redisContext_type = { "$i_mrb_redisContext_type", mrb_redisFree_gc }; typedef struct { mrb_value self; redisReply *reply; } mrb_redisGetReply_cb_data; static const struct mrb_data_type mrb_redisCallbackFn_cb_data_type = { "$i_mrb_redisCallbackFn_cb_data_type", mrb_free }; typedef struct { const mrb_sym command; const mrb_value *mrb_argv; mrb_int *argc_p; const char ***argv_p; size_t **argvlen_p; } mrb_hiredis_generate_argv_argc_array_cb_data; MRB_INLINE mrb_value mrb_hiredis_generate_argv_argc_array_cb(mrb_state *mrb, const mrb_value command_argv_argc) { mrb_hiredis_generate_argv_argc_array_cb_data *cb_data = (mrb_hiredis_generate_argv_argc_array_cb_data *) mrb_cptr(command_argv_argc); *cb_data->argv_p = NULL; *cb_data->argvlen_p = NULL; *cb_data->argc_p += 1; if (likely((*cb_data->argc_p <= SIZE_MAX / sizeof(const char *)) && (*cb_data->argc_p <= SIZE_MAX / sizeof(size_t)))) { const char **argv = *cb_data->argv_p = mrb_malloc(mrb, *cb_data->argc_p * sizeof(*argv)); size_t *argvlen = *cb_data->argvlen_p = mrb_malloc(mrb, *cb_data->argc_p * sizeof(*argvlen)); mrb_int command_len; argv[0] = mrb_sym2name_len(mrb, cb_data->command, &command_len); argvlen[0] = command_len; mrb_int argc_current; for (argc_current = 1; argc_current < *cb_data->argc_p; argc_current++) { mrb_value curr = mrb_str_to_str(mrb, cb_data->mrb_argv[argc_current - 1]); argv[argc_current] = RSTRING_PTR(curr); argvlen[argc_current] = RSTRING_LEN(curr); } } else { mrb_raise(mrb, E_RUNTIME_ERROR, "Cannot allocate argv array"); } return mrb_nil_value(); } static void mrb_hiredis_generate_argv_argc_array(mrb_state *mrb, const mrb_sym command, const mrb_value *mrb_argv, mrb_int *argc_p, const char ***argv_p, size_t **argvlen_p) { mrb_hiredis_generate_argv_argc_array_cb_data cb_data = {command, mrb_argv, argc_p, argv_p, argvlen_p}; mrb_bool error; mrb_value result = mrb_protect(mrb, mrb_hiredis_generate_argv_argc_array_cb, mrb_cptr_value(mrb, &cb_data), &error); if (unlikely(error)) { mrb_free(mrb, *argv_p); mrb_free(mrb, *argvlen_p); mrb_exc_raise(mrb, result); } } typedef struct { mrb_state *mrb; mrb_value self; mrb_value callbacks; mrb_value evloop; redisAsyncContext *async_context; mrb_value replies; mrb_value subscriptions; } mrb_hiredis_async_context; static void mrb_redisAsyncFree_gc(mrb_state *mrb, void *p) { redisAsyncContext *async_context = (redisAsyncContext *) p; mrb_free(mrb, async_context->ev.data); async_context->ev.data = NULL; redisAsyncFree(async_context); } static const struct mrb_data_type mrb_redisAsyncContext_type = { "$i_mrb_redisAsyncContext_type", mrb_redisAsyncFree_gc }; #endif <|start_filename|>include/mruby/hiredis.h<|end_filename|> #ifndef MRUBY_HIREDIS_H #define MRUBY_HIREDIS_H #include <mruby.h> MRB_BEGIN_DECL #define E_HIREDIS_ERROR (mrb_class_get_under(mrb, mrb_class_get(mrb, "Hiredis"), "Error")) #define E_HIREDIS_REPLY_ERROR (mrb_class_get_under(mrb, mrb_class_get(mrb, "Hiredis"), "ReplyError")) #ifndef E_EOF_ERROR #define E_EOF_ERROR (mrb_class_get(mrb, "EOFError")) #endif #ifndef E_IO_ERROR #define E_IO_ERROR (mrb_class_get(mrb, "IOError")) #endif #define E_HIREDIS_ERR_PROTOCOL (mrb_class_get_under(mrb, mrb_class_get(mrb, "Hiredis"), "ProtocolError")) #define E_HIREDIS_ERR_OOM (mrb_class_get_under(mrb, mrb_class_get(mrb, "Hiredis"), "OOMError")) MRB_END_DECL #endif <|start_filename|>src/mrb_hiredis.c<|end_filename|> #include "mruby/hiredis.h" #include "mrb_hiredis.h" static void mrb_hiredis_check_error(mrb_state *mrb, const redisContext *context) { switch (context->err) { case REDIS_ERR_IO: mrb_sys_fail(mrb, context->errstr); break; case REDIS_ERR_EOF: mrb_raise(mrb, E_EOF_ERROR, context->errstr); break; case REDIS_ERR_PROTOCOL: mrb_raise(mrb, E_HIREDIS_ERR_PROTOCOL, context->errstr); break; case REDIS_ERR_OOM: mrb_raise(mrb, E_HIREDIS_ERR_OOM, context->errstr); break; default: mrb_raise(mrb, E_HIREDIS_ERROR, context->errstr); } } static mrb_value mrb_redisConnect(mrb_state *mrb, mrb_value self) { char *host_or_path = (char *) "localhost"; mrb_int port = 6379; mrb_get_args(mrb, "|zi", &host_or_path, &port); mrb_assert(port >= INT_MIN && port <= INT_MAX); redisContext *context = NULL; errno = 0; if (port == -1) { context = redisConnectUnix(host_or_path); } else { context = redisConnect(host_or_path, port); } if (likely(context != NULL)) { mrb_data_init(self, context, &mrb_redisContext_type); if (likely(context->err == 0)) { return self; } else { mrb_hiredis_check_error(mrb, context); return mrb_false_value(); } } else { mrb_sys_fail(mrb, "redisConnect"); return mrb_false_value(); } } static mrb_value mrb_redisFree(mrb_state *mrb, mrb_value self) { redisContext *context = (redisContext *) DATA_PTR(self); if (likely(context)) { redisFree(context); mrb_data_init(self, NULL, NULL); return mrb_nil_value(); } else { mrb_raise(mrb, E_IO_ERROR, "closed stream"); return mrb_false_value(); } } MRB_INLINE mrb_value mrb_hiredis_get_ary_reply(redisReply *reply, mrb_state *mrb); MRB_INLINE mrb_value mrb_hiredis_get_map_reply(redisReply *reply, mrb_state *mrb); static mrb_value mrb_hiredis_get_reply(redisReply *reply, mrb_state *mrb) { if (likely(reply)) { switch (reply->type) { case REDIS_REPLY_STRING: case REDIS_REPLY_STATUS: case REDIS_REPLY_BIGNUM: return mrb_str_new(mrb, reply->str, reply->len); break; case REDIS_REPLY_ARRAY: case REDIS_REPLY_SET: case REDIS_REPLY_PUSH: return mrb_hiredis_get_ary_reply(reply, mrb); break; case REDIS_REPLY_MAP: case REDIS_REPLY_ATTR: return mrb_hiredis_get_map_reply(reply, mrb); break; case REDIS_REPLY_INTEGER: return mrb_int_value(mrb, reply->integer); break; case REDIS_REPLY_NIL: return mrb_nil_value(); break; case REDIS_REPLY_ERROR: return mrb_exc_new_str(mrb, E_HIREDIS_REPLY_ERROR, mrb_str_new(mrb, reply->str, reply->len)); break; case REDIS_REPLY_DOUBLE: return mrb_float_value(mrb, reply->dval); break; case REDIS_REPLY_BOOL: return mrb_bool_value(reply->integer); break; case REDIS_REPLY_VERB: { mrb_value argv[] = { mrb_str_new(mrb, reply->str, reply->len), mrb_str_new_cstr(mrb, reply->vtype) }; return mrb_obj_new(mrb, mrb_class_get_under(mrb, mrb_class_get(mrb, "Hiredis"), "Verb"), 2, argv); } break; default: mrb_raisef(mrb, E_HIREDIS_ERROR, "unknown reply type %S", mrb_int_value(mrb, reply->type)); } } else { return mrb_nil_value(); } } MRB_INLINE mrb_value mrb_hiredis_get_ary_reply(redisReply *reply, mrb_state *mrb) { mrb_value ary = mrb_ary_new_capa(mrb, reply->elements); int ai = mrb_gc_arena_save(mrb); size_t element_couter; for (element_couter = 0; element_couter < reply->elements; element_couter++) { mrb_ary_push(mrb, ary, mrb_hiredis_get_reply(reply->element[element_couter], mrb)); mrb_gc_arena_restore(mrb, ai); } return ary; } MRB_INLINE mrb_value mrb_hiredis_get_map_reply(redisReply *reply, mrb_state *mrb) { mrb_value map = mrb_hash_new_capa(mrb, reply->elements / 2); int ai = mrb_gc_arena_save(mrb); size_t element_couter; for (element_couter = 0; element_couter < reply->elements; element_couter++) { mrb_value key = mrb_hiredis_get_reply(reply->element[element_couter], mrb); element_couter++; mrb_value value = mrb_hiredis_get_reply(reply->element[element_couter], mrb); mrb_hash_set(mrb, map, key, value); mrb_gc_arena_restore(mrb, ai); } return map; } MRB_INLINE mrb_value mrb_redisCommandArgv_cb(mrb_state *mrb, mrb_value reply) { return mrb_hiredis_get_reply(mrb_cptr(reply), mrb); } MRB_INLINE mrb_value mrb_redisCommandArgv_ensure(mrb_state *mrb, mrb_value reply) { freeReplyObject(mrb_cptr(reply)); return mrb_nil_value(); } static mrb_value mrb_redisCommandArgv(mrb_state *mrb, mrb_value self) { redisContext *context = (redisContext *) DATA_PTR(self); if (likely(context)) { if (likely(context->err == 0)) { mrb_sym command; mrb_value *mrb_argv = NULL; mrb_int argc = 0; mrb_get_args(mrb, "n*", &command, &mrb_argv, &argc); const char **argv = NULL; size_t *argvlen = NULL; mrb_hiredis_generate_argv_argc_array(mrb, command, mrb_argv, &argc, &argv, &argvlen); errno = 0; redisReply *reply = redisCommandArgv(context, argc, argv, argvlen); mrb_free(mrb, argv); mrb_free(mrb, argvlen); if (likely(reply != NULL)) { mrb_value reply_cptr_value = mrb_cptr_value(mrb, reply); return mrb_ensure(mrb, mrb_redisCommandArgv_cb, reply_cptr_value, mrb_redisCommandArgv_ensure, reply_cptr_value); } else { mrb_hiredis_check_error(mrb, context); return mrb_false_value(); } } else { mrb_hiredis_check_error(mrb, context); return mrb_false_value(); } } else { mrb_raise(mrb, E_IO_ERROR, "closed stream"); return mrb_false_value(); } } static mrb_value mrb_redisAppendCommandArgv(mrb_state *mrb, mrb_value self) { redisContext *context = (redisContext *) DATA_PTR(self); if (likely(context)) { if (likely(context->err == 0)) { mrb_sym command; mrb_value *mrb_argv = NULL; mrb_int argc = 0; mrb_get_args(mrb, "n*", &command, &mrb_argv, &argc); mrb_sym queue_counter_sym = mrb_intern_lit(mrb, "queue_counter"); mrb_value queue_counter_val = mrb_iv_get(mrb, self, queue_counter_sym); mrb_int queue_counter = 1; if (mrb_integer_p(queue_counter_val)) { queue_counter = mrb_integer(queue_counter_val); if (unlikely(mrb_int_add_overflow(queue_counter, 1, &queue_counter))) { mrb_raise(mrb, E_RUNTIME_ERROR, "integer addition would overflow"); } } const char **argv = NULL; size_t *argvlen = NULL; mrb_hiredis_generate_argv_argc_array(mrb, command, mrb_argv, &argc, &argv, &argvlen); errno = 0; int rc = redisAppendCommandArgv(context, argc, argv, argvlen); mrb_free(mrb, argv); mrb_free(mrb, argvlen); if (likely(rc == REDIS_OK)) { mrb_iv_set(mrb, self, queue_counter_sym, mrb_int_value(mrb, queue_counter)); return self; } else { mrb_hiredis_check_error(mrb, context); return mrb_false_value(); } } else { mrb_hiredis_check_error(mrb, context); return mrb_false_value(); } } else { mrb_raise(mrb, E_IO_ERROR, "closed stream"); return mrb_false_value(); } } MRB_INLINE mrb_value mrb_redisGetReply_cb(mrb_state *mrb, mrb_value self_reply) { mrb_redisGetReply_cb_data *cb_data = (mrb_redisGetReply_cb_data *)mrb_cptr(self_reply); mrb_value self = cb_data->self; mrb_sym queue_counter_sym = mrb_intern_lit(mrb, "queue_counter"); mrb_value queue_counter_val = mrb_iv_get(mrb, self, queue_counter_sym); mrb_int queue_counter = -1; if (mrb_integer_p(queue_counter_val)) { queue_counter = mrb_integer(queue_counter_val); } mrb_value reply_val = mrb_hiredis_get_reply(cb_data->reply, mrb); if (queue_counter > 1) { mrb_iv_set(mrb, self, queue_counter_sym, mrb_int_value(mrb, --queue_counter)); } else { mrb_iv_remove(mrb, self, queue_counter_sym); } return reply_val; } MRB_INLINE mrb_value mrb_redisGetReply_ensure(mrb_state *mrb, mrb_value self_reply) { mrb_redisGetReply_cb_data *cb_data = (mrb_redisGetReply_cb_data *)mrb_cptr(self_reply); freeReplyObject(cb_data->reply); return mrb_nil_value(); } static mrb_value mrb_redisGetReply(mrb_state *mrb, mrb_value self) { redisContext *context = (redisContext *) DATA_PTR(self); if (likely(context)) { if (likely(context->err == 0)) { redisReply *reply = NULL; errno = 0; int rc = redisGetReply(context, (void **) &reply); if (likely(rc == REDIS_OK)) { if (likely(reply != NULL)) { mrb_redisGetReply_cb_data cb_data = { self, reply }; mrb_value cb_data_val = mrb_cptr_value(mrb, &cb_data); return mrb_ensure(mrb, mrb_redisGetReply_cb, cb_data_val, mrb_redisGetReply_ensure, cb_data_val); } else { return mrb_nil_value(); } } else { mrb_hiredis_check_error(mrb, context); return mrb_false_value(); } } else { mrb_hiredis_check_error(mrb, context); return mrb_false_value(); } } else { mrb_raise(mrb, E_IO_ERROR, "closed stream"); return mrb_false_value(); } } static mrb_value mrb_redisGetBulkReply(mrb_state *mrb, mrb_value self) { mrb_value queue_counter_val = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "queue_counter")); if (likely(mrb_integer_p(queue_counter_val))) { mrb_int queue_counter = mrb_integer(queue_counter_val); mrb_value bulk_reply = mrb_ary_new_capa(mrb, queue_counter); int ai = mrb_gc_arena_save(mrb); do { mrb_ary_push(mrb, bulk_reply, mrb_redisGetReply(mrb, self)); mrb_gc_arena_restore(mrb, ai); } while (--queue_counter > 0); return bulk_reply; } else { mrb_raise(mrb, E_RUNTIME_ERROR, "nothing queued yet"); return mrb_false_value(); } } #if ((HIREDIS_MAJOR == 0) && (HIREDIS_MINOR >= 13) || (HIREDIS_MAJOR > 0)) static mrb_value mrb_redisReconnect(mrb_state *mrb, mrb_value self) { redisContext *context = (redisContext *) DATA_PTR(self); if (likely(context)) { int rc = redisReconnect(context); if (likely(rc == REDIS_OK)) { return self; } else { mrb_hiredis_check_error(mrb, context); return mrb_false_value(); } } else { mrb_raise(mrb, E_IO_ERROR, "closed stream"); return mrb_false_value(); } } #endif MRB_INLINE void mrb_hiredis_dataCleanup(void *privdata) { mrb_hiredis_async_context *mrb_async_context = (mrb_hiredis_async_context *) privdata; mrb_data_init(mrb_async_context->self, NULL, NULL); mrb_free(mrb_async_context->mrb, privdata); } MRB_INLINE void mrb_hiredis_addRead(void *privdata) { mrb_assert(privdata); mrb_hiredis_async_context *mrb_async_context = (mrb_hiredis_async_context *) privdata; mrb_state *mrb = mrb_async_context->mrb; mrb_assert(mrb); int ai = mrb_gc_arena_save(mrb); mrb_value block = mrb_iv_get(mrb, mrb_async_context->callbacks, mrb_intern_lit(mrb, "@addRead")); if (likely(mrb_type(block) == MRB_TT_PROC)) { mrb_value argv[] = { mrb_async_context->self, mrb_async_context->evloop, mrb_int_value(mrb, mrb_async_context->async_context->c.fd) }; mrb_yield_argv(mrb, block, 3, argv); mrb_gc_arena_restore(mrb, ai); } } MRB_INLINE void mrb_hiredis_delRead(void *privdata) { mrb_assert(privdata); mrb_hiredis_async_context *mrb_async_context = (mrb_hiredis_async_context *) privdata; mrb_state *mrb = mrb_async_context->mrb; mrb_assert(mrb); int ai = mrb_gc_arena_save(mrb); mrb_value block = mrb_iv_get(mrb, mrb_async_context->callbacks, mrb_intern_lit(mrb, "@delRead")); if (likely(mrb_type(block) == MRB_TT_PROC)) { mrb_value argv[] = { mrb_async_context->self, mrb_async_context->evloop, mrb_int_value(mrb, mrb_async_context->async_context->c.fd) }; mrb_yield_argv(mrb, block, 3, argv); mrb_gc_arena_restore(mrb, ai); } } MRB_INLINE void mrb_hiredis_addWrite(void *privdata) { mrb_assert(privdata); mrb_hiredis_async_context *mrb_async_context = (mrb_hiredis_async_context *) privdata; mrb_state *mrb = mrb_async_context->mrb; mrb_assert(mrb); int ai = mrb_gc_arena_save(mrb); mrb_value block = mrb_iv_get(mrb, mrb_async_context->callbacks, mrb_intern_lit(mrb, "@addWrite")); if (likely(mrb_type(block) == MRB_TT_PROC)) { mrb_value argv[] = { mrb_async_context->self, mrb_async_context->evloop, mrb_int_value(mrb, mrb_async_context->async_context->c.fd) }; mrb_yield_argv(mrb, block, 3, argv); mrb_gc_arena_restore(mrb, ai); } } MRB_INLINE void mrb_hiredis_delWrite(void *privdata) { mrb_assert(privdata); mrb_hiredis_async_context *mrb_async_context = (mrb_hiredis_async_context *) privdata; mrb_state *mrb = mrb_async_context->mrb; mrb_assert(mrb); int ai = mrb_gc_arena_save(mrb); mrb_value block = mrb_iv_get(mrb, mrb_async_context->callbacks, mrb_intern_lit(mrb, "@delWrite")); if (likely(mrb_type(block) == MRB_TT_PROC)) { mrb_value argv[] = { mrb_async_context->self, mrb_async_context->evloop, mrb_int_value(mrb, mrb_async_context->async_context->c.fd) }; mrb_yield_argv(mrb, block, 3, argv); mrb_gc_arena_restore(mrb, ai); } } MRB_INLINE void mrb_hiredis_cleanup(void *privdata) { mrb_assert(privdata); mrb_hiredis_async_context *mrb_async_context = (mrb_hiredis_async_context *) privdata; mrb_state *mrb = mrb_async_context->mrb; mrb_assert(mrb); int ai = mrb_gc_arena_save(mrb); mrb_value block = mrb_iv_get(mrb, mrb_async_context->callbacks, mrb_intern_lit(mrb, "@cleanup")); if (likely(mrb_type(block) == MRB_TT_PROC)) { mrb_value argv[] = { mrb_async_context->self, mrb_async_context->evloop }; mrb_yield_argv(mrb, block, 2, argv); mrb_gc_arena_restore(mrb, ai); } } MRB_INLINE void mrb_redisDisconnectCallback(const struct redisAsyncContext *async_context, int status) { mrb_hiredis_async_context *mrb_async_context = (mrb_hiredis_async_context *) async_context->data; mrb_state *mrb = mrb_async_context->mrb; mrb_assert(mrb); int ai = mrb_gc_arena_save(mrb); mrb_value block = mrb_iv_get(mrb, mrb_async_context->callbacks, mrb_intern_lit(mrb, "@disconnect")); if (likely(mrb_type(block) == MRB_TT_PROC)) { mrb_value argv[] = { mrb_async_context->self, mrb_async_context->evloop, mrb_int_value(mrb, status) }; mrb_yield_argv(mrb, block, 3, argv); mrb_gc_arena_restore(mrb, ai); } } MRB_INLINE void mrb_redisConnectCallback(const struct redisAsyncContext *async_context, int status) { mrb_hiredis_async_context *mrb_async_context = (mrb_hiredis_async_context *) async_context->data; mrb_state *mrb = mrb_async_context->mrb; mrb_assert(mrb); int ai = mrb_gc_arena_save(mrb); mrb_value block = mrb_iv_get(mrb, mrb_async_context->callbacks, mrb_intern_lit(mrb, "@connect")); if (likely(mrb_type(block) == MRB_TT_PROC)) { mrb_value argv[] = { mrb_async_context->self, mrb_async_context->evloop, mrb_int_value(mrb, status) }; mrb_yield_argv(mrb, block, 3, argv); mrb_gc_arena_restore(mrb, ai); } } MRB_INLINE mrb_value mrb_hiredis_setup_async_context(mrb_state *mrb, mrb_value self, mrb_value callbacks, mrb_value evloop, redisAsyncContext *async_context) { mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@callbacks"), callbacks); mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@evloop"), evloop); mrb_value replies = mrb_ary_new(mrb); mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "replies"), replies); mrb_value subscriptions = mrb_hash_new(mrb); mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "subscriptions"), subscriptions); mrb_hiredis_async_context *mrb_async_context = (mrb_hiredis_async_context *) mrb_malloc(mrb, sizeof(mrb_hiredis_async_context)); mrb_async_context->mrb = mrb; mrb_async_context->self = self; mrb_async_context->callbacks = callbacks; mrb_async_context->evloop = evloop; mrb_async_context->async_context = async_context; mrb_async_context->replies = replies; mrb_async_context->subscriptions = subscriptions; async_context->data = async_context->ev.data = mrb_async_context; async_context->dataCleanup = mrb_hiredis_dataCleanup; async_context->ev.addRead = mrb_hiredis_addRead; async_context->ev.delRead = mrb_hiredis_delRead; async_context->ev.addWrite = mrb_hiredis_addWrite; async_context->ev.delWrite = mrb_hiredis_delWrite; async_context->ev.cleanup = mrb_hiredis_cleanup; redisAsyncSetDisconnectCallback(async_context, mrb_redisDisconnectCallback); redisAsyncSetConnectCallback(async_context, mrb_redisConnectCallback); return self; } static mrb_value mrb_redisAsyncConnect(mrb_state *mrb, mrb_value self) { mrb_value callbacks = mrb_nil_value(), evloop = mrb_nil_value(); char *host_or_path = (char *) "localhost"; mrb_int port = 6379; mrb_get_args(mrb, "|oozi", &callbacks, &evloop, &host_or_path, &port); mrb_assert(port >= INT_MIN && port <= INT_MAX); if (mrb_nil_p(callbacks)) { callbacks = mrb_obj_new(mrb, mrb_class_get_under(mrb, mrb_class(mrb, self), "Callbacks"), 0, NULL); } if (mrb_nil_p(evloop)) { evloop = mrb_obj_new(mrb, mrb_class_get(mrb, "RedisAe"), 0, NULL); } redisAsyncContext *async_context = NULL; errno = 0; if (port == -1) { async_context = redisAsyncConnectUnix(host_or_path); } else { async_context = redisAsyncConnect(host_or_path, port); } if (likely(async_context != NULL)) { mrb_data_init(self, async_context, &mrb_redisAsyncContext_type); if (likely(async_context->c.err == 0)) { return mrb_hiredis_setup_async_context(mrb, self, callbacks, evloop, async_context); } else { mrb_hiredis_check_error(mrb, &async_context->c); return mrb_false_value(); } } else { mrb_sys_fail(mrb, "redisAsyncConnect"); return mrb_false_value(); } } static mrb_value mrb_redisAsyncHandleRead(mrb_state *mrb, mrb_value self) { redisAsyncContext *async_context = (redisAsyncContext *) DATA_PTR(self); if (likely(async_context)) { redisAsyncHandleRead(async_context); return self; } else { mrb_raise(mrb, E_IO_ERROR, "closed stream"); return mrb_false_value(); } } static mrb_value mrb_redisAsyncHandleWrite(mrb_state *mrb, mrb_value self) { redisAsyncContext *async_context = (redisAsyncContext *) DATA_PTR(self); if (likely(async_context)) { redisAsyncHandleWrite(async_context); return self; } else { mrb_raise(mrb, E_IO_ERROR, "closed stream"); return mrb_false_value(); } } MRB_INLINE void mrb_redisCallbackFn(struct redisAsyncContext *async_context, void *r, void *privdata) { mrb_hiredis_async_context *mrb_async_context = (mrb_hiredis_async_context *) async_context->data; mrb_assert(mrb_async_context); mrb_state *mrb = mrb_async_context->mrb; mrb_assert(mrb); int ai = mrb_gc_arena_save(mrb); mrb_value block = mrb_obj_value(privdata); mrb_funcall(mrb, mrb_async_context->replies, "delete", 1, block); if (likely(mrb_type(block) == MRB_TT_PROC)) { mrb_value reply = mrb_nil_value(); if (likely(r)) { reply = mrb_hiredis_get_reply((redisReply *)r, mrb); } mrb_yield(mrb, block, reply); } mrb_gc_arena_restore(mrb, ai); } static mrb_value mrb_redisAsyncCommandArgv(mrb_state *mrb, mrb_value self) { redisAsyncContext *async_context = (redisAsyncContext *) DATA_PTR(self); if (likely(async_context)) { mrb_sym command; mrb_value *mrb_argv = NULL; mrb_int argc = 0; mrb_value block = mrb_nil_value(); mrb_get_args(mrb, "n*&", &command, &mrb_argv, &argc, &block); const char **argv; size_t *argvlen; mrb_hiredis_generate_argv_argc_array(mrb, command, mrb_argv, &argc, &argv, &argvlen); int rc; errno = 0; if (mrb_type(block) == MRB_TT_PROC) { rc = redisAsyncCommandArgv(async_context, mrb_redisCallbackFn, mrb_ptr(block), argc, argv, argvlen); mrb_free(mrb, argv); mrb_int command_len = argvlen[0]; mrb_free(mrb, argvlen); if (likely(rc == REDIS_OK)) { if ((command_len == 9 && strncasecmp(argv[0], "subscribe", command_len) == 0)|| (command_len == 10 && strncasecmp(argv[0], "psubscribe", command_len) == 0)) { if (likely(argc == 2)) { mrb_hash_set(mrb, ((mrb_hiredis_async_context *) async_context->ev.data)->subscriptions, mrb_argv[0], block); } else { mrb_raise(mrb, E_ARGUMENT_ERROR, "hiredis only supports one topic Subscribtions"); } } else if ((command_len == 11 && strncasecmp(argv[0], "unsubscribe", command_len) == 0)|| (command_len == 12 && strncasecmp(argv[0], "punsubscribe", command_len) == 0)) { if (likely(argc == 2)) { mrb_hash_delete_key(mrb, ((mrb_hiredis_async_context *) async_context->ev.data)->subscriptions, mrb_argv[0]); } else { mrb_raise(mrb, E_ARGUMENT_ERROR, "hiredis only supports one topic Subscribtions"); } } else if (command_len == 7 && strncasecmp(argv[0], "monitor", command_len) == 0) { mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "monitor"), block); } else { mrb_ary_push(mrb, ((mrb_hiredis_async_context *) async_context->ev.data)->replies, block); } } } else { rc = redisAsyncCommandArgv(async_context, NULL, NULL, argc, argv, argvlen); mrb_free(mrb, argv); mrb_free(mrb, argvlen); } if (likely(rc == REDIS_OK)) { return self; } else { mrb_hiredis_check_error(mrb, &async_context->c); return mrb_false_value(); } } else { mrb_raise(mrb, E_IO_ERROR, "closed stream"); return mrb_false_value(); } } static mrb_value mrb_redisAsyncDisconnect(mrb_state *mrb, mrb_value self) { redisAsyncContext *async_context = (redisAsyncContext *) DATA_PTR(self); if (likely(async_context)) { redisAsyncDisconnect(async_context); return mrb_nil_value(); } else { mrb_raise(mrb, E_IO_ERROR, "closed stream"); return mrb_false_value(); } } void mrb_mruby_hiredis_gem_init(mrb_state* mrb) { struct RClass *hiredis_class, *hiredis_error_class, *hiredis_async_class; hiredis_class = mrb_define_class(mrb, "Hiredis", mrb->object_class); MRB_SET_INSTANCE_TT(hiredis_class, MRB_TT_DATA); hiredis_error_class = mrb_define_class_under(mrb, hiredis_class, "Error", E_RUNTIME_ERROR); mrb_define_class_under(mrb, hiredis_class, "ReplyError", hiredis_error_class); mrb_define_class_under(mrb, hiredis_class, "ProtocolError", hiredis_error_class); mrb_define_class_under(mrb, hiredis_class, "OOMError", hiredis_error_class); mrb_define_method(mrb, hiredis_class, "initialize", mrb_redisConnect, MRB_ARGS_OPT(2)); mrb_define_method(mrb, hiredis_class, "free", mrb_redisFree, MRB_ARGS_NONE()); mrb_define_alias (mrb, hiredis_class, "close", "free"); mrb_define_method(mrb, hiredis_class, "call", mrb_redisCommandArgv, (MRB_ARGS_REQ(1)|MRB_ARGS_REST())); mrb_define_method(mrb, hiredis_class, "queue", mrb_redisAppendCommandArgv, (MRB_ARGS_REQ(1)|MRB_ARGS_REST())); mrb_define_method(mrb, hiredis_class, "reply", mrb_redisGetReply, MRB_ARGS_NONE()); mrb_define_method(mrb, hiredis_class, "bulk_reply", mrb_redisGetBulkReply, MRB_ARGS_NONE()); #if ((HIREDIS_MAJOR == 0) && (HIREDIS_MINOR >= 13) || (HIREDIS_MAJOR > 0)) mrb_define_method(mrb, hiredis_class, "reconnect", mrb_redisReconnect, MRB_ARGS_NONE()); #endif hiredis_async_class = mrb_define_class_under(mrb, hiredis_class, "Async", mrb->object_class); MRB_SET_INSTANCE_TT(hiredis_async_class, MRB_TT_DATA); mrb_define_method(mrb, hiredis_async_class, "initialize", mrb_redisAsyncConnect, MRB_ARGS_ARG(2, 2)); mrb_define_method(mrb, hiredis_async_class, "read", mrb_redisAsyncHandleRead, MRB_ARGS_NONE()); mrb_define_method(mrb, hiredis_async_class, "write", mrb_redisAsyncHandleWrite, MRB_ARGS_NONE()); mrb_define_method(mrb, hiredis_async_class, "queue", mrb_redisAsyncCommandArgv, (MRB_ARGS_REQ(1)|MRB_ARGS_REST()|MRB_ARGS_BLOCK())); mrb_define_method(mrb, hiredis_async_class, "disconnect", mrb_redisAsyncDisconnect, MRB_ARGS_NONE()); mrb_define_alias (mrb, hiredis_async_class, "close", "disconnect"); } void mrb_mruby_hiredis_gem_final(mrb_state* mrb) {}
Asmod4n/mruby-hiredis
<|start_filename|>index.js<|end_filename|> import fs from "fs/promises"; import marked from "marked"; import mustache from "mustache"; const readJSONFile = async (file) => { const content = await fs.readFile(file, "utf8"); return JSON.parse(content); }; const extendPractice = async (language, id) => { const content = await fs.readFile(`./src/${id}/${language}.md`, "utf8"); const [title, ...body] = content.split("\n"); const practice = { body: body.join("\n").trim(), id, title: title.trim().replace(/^# /u, ""), }; return { ...practice, bodyHTML: marked(practice.body), titleHTML: marked(practice.title) .trim() .replace(/^<p>(.*?)<\/p>$/u, "$1"), }; }; const extendSection = async (language, extradata, section, index) => { const practices = await Promise.all( section.practices.map(extendPractice.bind(null, language)) ); return { ...section, ...extradata.sections[index], practices, }; }; const build = async (src, data, dest) => { const template = await fs.readFile(src, "utf8"); const rendered = mustache.render(template, data); await fs.writeFile(dest, rendered); }; const generate = async (data, language) => { const extradata = await readJSONFile(`./src/${language.code}.json`); const sections = await Promise.all( data.sections.map(extendSection.bind(null, language.code, extradata)) ); const extended = { ...data, ...extradata, language, sections, }; await Promise.all([ build("./src/md.mustache", extended, `./README${language.ext}.md`), build("./src/html.mustache", extended, `./docs/index${language.ext}.html`), ]); }; const main = async () => { const data = await readJSONFile("./src/data.json"); await Promise.all(data.languages.map(generate.bind(null, data))); }; main().catch((e) => { console.trace(e); process.exitCode = 1; }); <|start_filename|>src/tr.json<|end_filename|> { "title": "HTML'de Örnek Yöntemler", "description": "Bakım yapılabilir ve ölçeklenebilir HTML belgeleri yazmak için", "sections": [ { "title": "Genel" }, { "title": "Kök elemanı" }, { "title": "Metadata'yı belgeleyin" }, { "title": "Bölümler" }, { "title": "İçeriği gruplama" }, { "title": "Metin düzeyinde anlambilim" }, { "title": "Düzenlemeler" }, { "title": "Gömülü içerik" }, { "title": "Tablo verileri" }, { "title": "Formlar" }, { "title": "Script ekleme" }, { "title": "Diğer" } ] } <|start_filename|>docs/index.tr.html<|end_filename|> <html lang="tr"> <head> <meta charset="UTF-8"> <title>HTML&#39;de Örnek Yöntemler—Bakım yapılabilir ve ölçeklenebilir HTML belgeleri yazmak için</title> <meta content="Bakım yapılabilir ve ölçeklenebilir HTML belgeleri yazmak için" name="description"> <meta content="width=device-width" name=viewport> <link href="./index.tr.html" rel="canonical"> <style> body { font-family: sans-serif; line-height: 1.5; margin-left: auto; margin-right: auto; max-width: 42em; padding-left: 1em; padding-right: 1em; } h2 { margin-top: 4em; } h3 { margin-top: 3em; } p { overflow-wrap: break-word; } pre, code { font-family: monospace, monospace; font-size: 1em; } pre { background-color: whitesmoke; overflow-wrap: break-word; padding: 0.5em; white-space: pre-wrap; } </style> </head> <body> <nav> <h4>Translations</h4> <ul> <li><a href="./index.html">English (en)</a></li> <li><a href="./index.ja.html">日本語 (ja)</a></li> <li><a href="./index.ko.html">한국어 (ko)</a></li> <li><a href="./index.tr.html">Türkçe (tr)</a></li> </ul> </nav> <header> <h1>HTML&#39;de Örnek Yöntemler</h1> <p>Bakım yapılabilir ve ölçeklenebilir HTML belgeleri yazmak için</p> </header> <nav> <h4><abbr title="Table of Contents">ToC</abbr></h4> <ol> <li><a href="#general">Genel</a> <ol> <li><a href="#start-with-doctype">DOCTYPE ile başla</a> <li><a href="#dont-use-legacy-or-obsolete-doctype">Eskimiş yada geçersiz DOCTYPE kullanmayın</a> <li><a href="#dont-use-xml-declaration">XML etiketi kullanmayın</a> <li><a href="#dont-use-character-references-as-much-as-possible">Karakter referanslarını mümkün olduğunca kullanmayın</a> <li><a href="#escape-amp-lt-gt-quot-and-apos-with-named-character-references"><code>&amp;</code>, <code>&lt;</code>, <code>&gt;</code> , <code>&quot;</code>, ve <code>&#39;</code> karakter referanslarını olduğu gibi kullanmaktan kaçının</a> <li><a href="#use-numeric-character-references-for-control-or-invisible-characters">Kontrol veya görünmeyen karakterler için sayısal karakter referanslarını kullanın.</a> <li><a href="#put-white-spaces-around-comment-contents">Yorum içeriğinin etrafına boşluk karakteri yerleştirin</a> <li><a href="#dont-omit-closing-tag">Kapanış etiketini unutmayın</a> <li><a href="#dont-mix-empty-element-format">Boş eleman formatını karıştırmayın</a> <li><a href="#dont-put-white-spaces-around-tags-and-attribute-values">Etiketlerin ve özelliklerin değerlerinin etrafına boşluk karakteri koymayın</a> <li><a href="#dont-mix-character-cases">Büyük küçük karakterleri aynı anda kullanmayın</a> <li><a href="#dont-mix-quotation-marks">Tırnak işaretlerini karıştırmayın</a> <li><a href="#dont-separate-attributes-with-two-or-more-white-spaces">Özellikleri iki veya daha fazla boşluk ile ayırmayın</a> <li><a href="#omit-boolean-attribute-value">Boolean özellik değerini yazmayın</a> <li><a href="#omit-namespaces">Ad alanlarını kullanmayın</a> <li><a href="#dont-use-xml-attributes">XML özelliklerini kullanmayın</a> <li><a href="#dont-mix-data-microdata-and-rdfa-lite-attributes-with-common-attributes"><code>data-*</code>, Microdata ve RDFa Lite özelliklerini ile ortak özellikleri karıştırmayın</a> <li><a href="#prefer-default-implicit-aria-semantics">Varsayılan örtülü ARIA gramerini tercih edin</a> </ol> </li> <li><a href="#the-root-element">Kök elemanı</a> <ol> <li><a href="#add-lang-attribute"><code>lang</code> özelliği ekleyin</a> <li><a href="#keep-lang-attribute-value-as-short-as-possible"><code>lang</code> değerini mümkün olduğunca kısa tutun</a> <li><a href="#avoid-data-as-much-as-possible">Mümkün olduğunca <code>data-*</code> kullanmayın</a> </ol> </li> <li><a href="#document-metadata">Metadata&#39;yı belgeleyin</a> <ol> <li><a href="#add-title-element"><code>title</code> elemanı ekleyin</a> <li><a href="#dont-use-base-element"><code>base</code> elemanı kullanmayın</a> <li><a href="#specify-mime-type-of-minor-linked-resources">Bağlantılı kaynakların MIME türünü belirtin</a> <li><a href="#dont-link-to-faviconico"><code>favicon.ico</code>&#39;ya link vermeyin</a> <li><a href="#add-apple-touch-icon-link"><code>apple-touch-icon</code> ekleyin</a> <li><a href="#add-title-attribute-to-alternate-stylesheets">Alternatif stil sayfalarına <code>title</code> ekleyin</a> <li><a href="#for-url-use-link-element">URL için <code>link</code> kullanın</a> <li><a href="#specify-document-character-encoding">Belge karakter kodunu belirtin</a> <li><a href="#dont-use-legacy-character-encoding-format">Eski karakter kodlama formatını kullanmayın</a> <li><a href="#specify-character-encoding-at-first">İlk önce karakter kodlamasını belirtin</a> <li><a href="#use-utf-8">UTF-8&#39;i kullanın</a> <li><a href="#omit-type-attribute-for-css">CSS için <code>type</code> kullanmayın</a> <li><a href="#dont-comment-out-contents-of-style-element"><code>style</code> etiketinin içeriğini yorum içine almayın</a> <li><a href="#dont-mix-tag-for-css-and-javascript">CSS ve JavaScript etiketlerini karıştırmayın</a> </ol> </li> <li><a href="#sections">Bölümler</a> <ol> <li><a href="#add-body-element"><code>body</code> etiketi ekleyin</a> <li><a href="#forget-about-hgroup-element"><code>hgroup</code> etiketini unutun</a> <li><a href="#use-address-element-only-for-contact-information"><code>address</code> etiketini yalnızca iletişim bilgileri için kullanın</a> </ol> </li> <li><a href="#grouping-content">İçeriği gruplama</a> <ol> <li><a href="#dont-start-with-newline-in-pre-element"><code>pre</code> elemandaki satır başı ile başlamayın</a> <li><a href="#use-appropriate-element-in-blockquote-element"><code>blockquote</code> içinde uygun etiket kullanın</a> <li><a href="#dont-include-attribution-directly-in-blockquote-element">Özniteliği doğrudan <code>blockquote</code> öğesinin içine dahil etme</a> <li><a href="#write-one-list-item-per-line">Satır başına bir liste öğesi yaz</a> <li><a href="#use-type-attribute-for-ol-element"><code>ol</code> etiketi için <code>type</code> özelliğini kullanın</a> <li><a href="#dont-use-dl-for-dialogue">Diyalog için <code>dl</code> kullanmayın</a> <li><a href="#place-figcaption-element-as-first-or-last-child-of-figure-element"><code>figcaption</code> etiketini, <code>figure</code> etiketinin ilk veya son çocuğu olarak yerleştirin</a> <li><a href="#use-main-element"><code>main</code> etiketini kullanın</a> <li><a href="#avoid-div-element-as-much-as-possible"><code>div</code> etiketini mümkün olduğu kadar kullanmayın</a> </ol> </li> <li><a href="#text-level-semantics">Metin düzeyinde anlambilim</a> <ol> <li><a href="#dont-split-same-link-that-can-be-grouped">Gruplandırılabilen aynı bağlantıyı bölmeyin</a> <li><a href="#use-download-attribute-for-downloading-a-resource">İndirilebilir kaynağı belirtmek için <code>download</code> özelliğini kullanın</a> <li><a href="#use-rel-hreflang-and-type-attribute-if-needed">Gerekirse <code>rel</code> , <code>hreflang</code> ve <code>type</code> özelliklerini kullanın</a> <li><a href="#clear-link-text">Bağlantı metinlerini amacına uygun yapın</a> <li><a href="#dont-use-em-element-for-warning-or-caution">Uyarı vermek için <code>em</code> etiketi kullanmayın</a> <li><a href="#avoid-s-i-b-and-u-element-as-much-as-possible"><code>s</code> , <code>i</code> , <code>b</code> ve <code>u</code> etiketlerinden mümkün olduğunca kaçının</a> <li><a href="#dont-put-quotes-to-q-element"><code>q</code> öğesine tırnak koymayın</a> <li><a href="#add-title-attribute-to-abbr-element"><code>abbr</code> etiketine <code>title</code> özelliğini ekleyin</a> <li><a href="#markup-ruby-element-verbosely"><code>ruby</code> etiketini detaylandırın</a> <li><a href="#add-datetime-attribute-to-non-machine-readable-time-element">Makine tarafından okunamayacak <code>time</code> etiketine <code>datetime</code> özelliği ekleyin</a> <li><a href="#specify-code-language-with-class-attribute-prefixed-with-language"><code>language-</code> öneki ile kod dilini <code>class</code> etiketi le belirtin</a> <li><a href="#keep-kbd-element-as-simple-as-possible"><code>kbd</code> etiketini mümkün olduğu kadar basit tutun</a> <li><a href="#avoid-span-element-as-much-as-possible"><code>span</code> etiketinden mümkün olduğunca kaçının</a> <li><a href="#break-after-br-element"><code>br</code> etiketinden sonra satır sonu yapın</a> <li><a href="#dont-use-br-element-only-for-presentational-purpose"><code>br</code> öğesini yalnızca sunum amacıyla kullanmayın</a> </ol> </li> <li><a href="#edits">Düzenlemeler</a> <ol> <li><a href="#dont-stride-ins-and-del-element-over-other-elements"><code>ins</code> ve <code>del</code> etiketlerini diğer öğelerin arasında kullanmayın</a> </ol> </li> <li><a href="#embedded-content">Gömülü içerik</a> <ol> <li><a href="#provide-fallback-img-element-for-picture-element"><code>picture</code> elemanı için yedek <code>img</code> elemanı kullanın</a> <li><a href="#add-alt-attrbute-to-img-element-if-needed">Gerekirse <code>img</code> öğesine <code>alt</code> özelliği ekleyin</a> <li><a href="#empty-alt-attribute-if-possible">Mümkünse <code>alt</code> özelliğini boş olarak kullanın</a> <li><a href="#omit-alt-attribute-if-possible">Mümkünse <code>alt</code> özelliğini atlayın</a> <li><a href="#empty-iframe-element">Boş <code>iframe</code> öğesi kullanın</a> <li><a href="#markup-map-element-content"><code>map</code> etiketinin içeriğini işaretleyin</a> <li><a href="#provide-fallback-content-for-audio-or-video-element"><code>audio</code> veya <code>video</code> öğesi için yedek içerik sağlayın</a> </ol> </li> <li><a href="#tabular-data">Tablo verileri</a> <ol> <li><a href="#write-one-cell-per-line">Her satıra bir hücre yazın</a> <li><a href="#use-th-element-for-header-cell">Başlık hücresi için <code>th</code> etiketini kullanın</a> </ol> </li> <li><a href="#forms">Formlar</a> <ol> <li><a href="#wrap-form-control-with-label-element"><code>label</code> etiketini ile form kontrolünü sağlayın</a> <li><a href="#omit-for-attribute-if-possible">Mümkünse <code>for</code> özelliğini kullanmayın</a> <li><a href="#use-appropriate-type-attribute-for-input-element"><code>input</code> etiketi için uygun <code>type</code> özelliğini kullanın</a> <li><a href="#add-value-attribute-to-input-typesubmit"><code>input type=&quot;submit&quot;</code> elemanına <code>value</code> özelliği ekleyin</a> <li><a href="#add-title-attribute-to-input-element-when-there-is-pattern-attribute"><code>pattern</code> özelliği olduğunda <code>input</code> etiketine <code>title</code> özelliği ekleyin</a> <li><a href="#dont-use-placeholder-attribute-for-labeling">Etiketleme için <code>placeholder</code> özelliğini kullanmayın</a> <li><a href="#write-one-option-element-per-line">Her satıra bir <code>option</code> etiketi yazın</a> <li><a href="#add-max-attribute-to-progress-element"><code>progress</code> etiketine <code>max</code> özelliği ekleyin</a> <li><a href="#add-min-and-max-attribute-to-meter-element"><code>meter</code> etiketine <code>min</code> ve <code>max</code> özelliği ekleyin</a> <li><a href="#place-legend-element-as-the-first-child-of-fieldset-element"><code>legend</code> etiketini <code>fieldset</code> etiketinin ilk çocuğu olarak elemanı olarak oluşturun</a> </ol> </li> <li><a href="#scripting">Script ekleme</a> <ol> <li><a href="#omit-type-attribute-for-javascript">JavaScript için <code>type</code> özelliğini kullanmayın</a> <li><a href="#dont-comment-out-contents-of-script-element"><code>script</code> etiketinin içeriğini yorumla kapatmayın</a> <li><a href="#dont-use-script-injected-script-element">Komut dosyası eklenmiş <code>script</code> öğesini kullanmayın</a> </ol> </li> <li><a href="#other">Diğer</a> <ol> <li><a href="#indent-consistently">Tutarlı girintiler kullanın</a> <li><a href="#use-absolute-path-for-internal-links">Dahili bağlantılar için mutlak yol kullanın</a> <li><a href="#dont-use-protocol-relative-url-for-external-resources">Harici kaynaklar için protokole bağlı URL kullanmayın</a> </ol> </li> <li><a href="#contributors">Contributors</a></li> <li><a href="#translators">Translators</a></li> <li><a href="#license">License</a></li> </ol> </nav> <main> <section id="general"> <h2>Genel</h2> <section id="start-with-doctype"> <h3>DOCTYPE ile başla</h3> <p>DOCTYPE standart modu etkinleştirmek için gereklidir.</p> <p>Yanlış:</p> <pre><code>&lt;html&gt; ... &lt;/html&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; ... &lt;/html&gt;</code></pre> </section> <section id="dont-use-legacy-or-obsolete-doctype"> <h3>Eskimiş yada geçersiz DOCTYPE kullanmayın</h3> <p>DOCTYPE artık DTD için değil, basit olsun.</p> <p>Yanlış:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;!DOCTYPE html&gt;</code></pre> </section> <section id="dont-use-xml-declaration"> <h3>XML etiketi kullanmayın</h3> <p>XHTML yazmak istediğinize emin misiniz?</p> <p>Yanlış:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt; &lt;!DOCTYPE html&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;!DOCTYPE html&gt;</code></pre> </section> <section id="dont-use-character-references-as-much-as-possible"> <h3>Karakter referanslarını mümkün olduğunca kullanmayın</h3> <p>UTF-8 ile bir HTML belgesi yazarsanız, hemen hemen tüm karakterler (Emoji dahil) doğrudan yazılabilir.</p> <p>Yanlış:</p> <pre><code>&lt;p&gt;&lt;small&gt;Copyright &amp;copy; 2014 W3C&lt;sup&gt;&amp;reg;&lt;/sup&gt;&lt;/small&gt;&lt;/p&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;p&gt;&lt;small&gt;Copyright © 2014 W3C&lt;sup&gt;®&lt;/sup&gt;&lt;/small&gt;&lt;/p&gt;</code></pre> </section> <section id="escape-amp-lt-gt-quot-and-apos-with-named-character-references"> <h3><code>&amp;</code>, <code>&lt;</code>, <code>&gt;</code> , <code>&quot;</code>, ve <code>&#39;</code> karakter referanslarını olduğu gibi kullanmaktan kaçının</h3> <p>Bu karakterlerden hatasız bir HTML belgesi için her zaman kaçınılmalıdır.</p> <p>Yanlış:</p> <pre><code>&lt;h1&gt;The &quot;&amp;&quot; character&lt;/h1&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;h1&gt;The &amp;quot;&amp;amp;&amp;quot; character&lt;/h1&gt;</code></pre> </section> <section id="use-numeric-character-references-for-control-or-invisible-characters"> <h3>Kontrol veya görünmeyen karakterler için sayısal karakter referanslarını kullanın.</h3> <p>Bu karakterler başka bir karakter için kolayca karıştırılabilir. Ayrıca spec bu karakterler için okunabilir bir isim tanımlamayı da garanti etmez.</p> <p>Yanlış:</p> <pre><code>&lt;p&gt;This book can read in 1 hour.&lt;/p&gt;</code></pre><p>This book can read in 1 hour.</p> <pre><code>&lt;p&gt;This book can read in 1&amp;#xA0;hour.&lt;/p&gt;</code></pre> </section> <section id="put-white-spaces-around-comment-contents"> <h3>Yorum içeriğinin etrafına boşluk karakteri yerleştirin</h3> <p>Bazı karakterler yorum açıldıktan hemen sonra veya yorum kapatmadan önce kullanılamaz.</p> <p>Yanlış:</p> <pre><code>&lt;!--This section is non-normative--&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;!-- This section is non-normative --&gt;</code></pre> </section> <section id="dont-omit-closing-tag"> <h3>Kapanış etiketini unutmayın</h3> <p>Kapanış etiketini atlamak için bir kural yok.</p> <p>Yanlış:</p> <pre><code>&lt;html&gt; &lt;body&gt; ...</code></pre><p>Doğru:</p> <pre><code>&lt;html&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre> </section> <section id="dont-mix-empty-element-format"> <h3>Boş eleman formatını karıştırmayın</h3> <p>Tutarlılık, okunabilirliğin anahtarıdır.</p> <p>Yanlış:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot;&gt; &lt;hr /&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot;&gt; &lt;hr&gt;</code></pre> </section> <section id="dont-put-white-spaces-around-tags-and-attribute-values"> <h3>Etiketlerin ve özelliklerin değerlerinin etrafına boşluk karakteri koymayın</h3> <p>Bunu yapmak için hiçbir sebep yoktur.</p> <p>Yanlış:</p> <pre><code>&lt;h1 class=&quot; title &quot; &gt;HTML Best Practices&lt;/h1&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;h1 class=&quot;title&quot;&gt;HTML Best Practices&lt;/h1&gt;</code></pre> </section> <section id="dont-mix-character-cases"> <h3>Büyük küçük karakterleri aynı anda kullanmayın</h3> <p>Aynı zamanda bir tutarlılık da oluşturur.</p> <p>Yanlış:</p> <pre><code>&lt;a HREF=&quot;#general&quot;&gt;General&lt;/A&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;a href=&quot;#general&quot;&gt;General&lt;/a&gt;</code></pre><p>Bu da doğru:</p> <pre><code>&lt;A HREF=&quot;#general&quot;&gt;General&lt;/A&gt;</code></pre> </section> <section id="dont-mix-quotation-marks"> <h3>Tırnak işaretlerini karıştırmayın</h3> <p>Yukarıdaki ile aynı sebepten ötürü.</p> <p>Yanlış:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&#39;/img/logo.jpg&#39;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.jpg&quot;&gt;</code></pre> </section> <section id="dont-separate-attributes-with-two-or-more-white-spaces"> <h3>Özellikleri iki veya daha fazla boşluk ile ayırmayın</h3> <p>Garip biçimlendirme kuralınız insanları şaşırtır.</p> <p>Yanlış:</p> <pre><code>&lt;input name=&quot;q&quot; type=&quot;search&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;input name=&quot;q&quot; type=&quot;search&quot;&gt;</code></pre> </section> <section id="omit-boolean-attribute-value"> <h3>Boolean özellik değerini yazmayın</h3> <p>Yazması kolay, değil mi?</p> <p>Yanlış:</p> <pre><code>&lt;audio autoplay=&quot;autoplay&quot; src=&quot;/audio/theme.mp3&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;audio autoplay src=&quot;/audio/theme.mp3&quot;&gt;</code></pre> </section> <section id="omit-namespaces"> <h3>Ad alanlarını kullanmayın</h3> <p>SVG ve MathML bir HTML belgesinde doğrudan kullanılabilir.</p> <p>Yanlış:</p> <pre><code>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt; ... &lt;/svg&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;svg&gt; ... &lt;/svg&gt;</code></pre> </section> <section id="dont-use-xml-attributes"> <h3>XML özelliklerini kullanmayın</h3> <p>Sadece HTML belgesi yazıyoruz.</p> <p>Yanlış:</p> <pre><code>&lt;span lang=&quot;ja&quot; xml:lang=&quot;ja&quot;&gt;...&lt;/span&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;span lang=&quot;ja&quot;&gt;...&lt;/span&gt;</code></pre> </section> <section id="dont-mix-data-microdata-and-rdfa-lite-attributes-with-common-attributes"> <h3><code>data-*</code>, Microdata ve RDFa Lite özelliklerini ile ortak özellikleri karıştırmayın</h3> <p>Bir etiket dizesi çok karmaşık olabilir. Bu basit kural, böyle bir etiket dizesini okumak için yardımcı olur.</p> <p>Yanlış:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; data-height=&quot;31&quot; data-width=&quot;88&quot; itemprop=&quot;image&quot; src=&quot;/img/logo.png&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot; data-width=&quot;88&quot; data-height=&quot;31&quot; itemprop=&quot;image&quot;&gt;</code></pre> </section> <section id="prefer-default-implicit-aria-semantics"> <h3>Varsayılan örtülü ARIA gramerini tercih edin</h3> <p>Bazı öğelerin bir HTML belgesinde örtük olarak bir ARIA <code>role</code> değeri vardır, belirtmenize gerek yoktur.</p> <p>Yanlış:</p> <pre><code>&lt;nav role=&quot;navigation&quot;&gt; ... &lt;/nav&gt; &lt;hr role=&quot;separator&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;nav&gt; ... &lt;/nav&gt; &lt;hr&gt;</code></pre> </section> </section> <section id="the-root-element"> <h2>Kök elemanı</h2> <section id="add-lang-attribute"> <h3><code>lang</code> özelliği ekleyin</h3> <p><code>lang</code> özelliği HTML belgesinin çeviriminin yapılmasına yardımcı olacaktır.</p> <p>Yanlış:</p> <pre><code>&lt;html&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;html lang=&quot;en-US&quot;&gt;</code></pre> </section> <section id="keep-lang-attribute-value-as-short-as-possible"> <h3><code>lang</code> değerini mümkün olduğunca kısa tutun</h3> <p>Japonca yalnızca Japonya&#39;da kullanılır. Yani ülke kodu gerekli değildir.</p> <p>Yanlış:</p> <pre><code>&lt;html lang=&quot;ja-JP&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;html lang=&quot;ja&quot;&gt;</code></pre> </section> <section id="avoid-data-as-much-as-possible"> <h3>Mümkün olduğunca <code>data-*</code> kullanmayın</h3> <p>Uygun bir özellik de tarayıcılar tarafından doğru bir şekilde ele alınabilir.</p> <p>Yanlış:</p> <pre><code>&lt;span data-language=&quot;french&quot;&gt;chemises&lt;/span&gt; ... &lt;strong data-type=&quot;warning&quot;&gt;Do not wash!&lt;/strong&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;span title=&quot;French&quot;&gt;&lt;span lang=&quot;fr-FR&quot;&gt;chemises&lt;/span&gt;&lt;/span&gt; ... &lt;strong class=&quot;warning&quot;&gt;Do not wash!&lt;/strong&gt;</code></pre> </section> </section> <section id="document-metadata"> <h2>Metadata&#39;yı belgeleyin</h2> <section id="add-title-element"> <h3><code>title</code> elemanı ekleyin</h3> <p><code>title</code> değeri, yalnızca tarayıcı tarafından değil, çeşitli uygulamalar tarafından da kullanılır.</p> <p>Yanlış:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;/head&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;HTML Best Practices&lt;/title&gt; &lt;/head&gt;</code></pre> </section> <section id="dont-use-base-element"> <h3><code>base</code> elemanı kullanmayın</h3> <p>Mutlak bir yol veya URL, hem geliştiriciler hem de kullanıcılar için daha güvenlidir.</p> <p>Yanlış:</p> <pre><code>&lt;head&gt; ... &lt;base href=&quot;/blog/&quot;&gt; &lt;link href=&quot;hello-world&quot; rel=&quot;canonical&quot;&gt; ... &lt;/head&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;head&gt; ... &lt;link href=&quot;/blog/hello-world&quot; rel=&quot;canonical&quot;&gt; ... &lt;/head&gt;</code></pre> </section> <section id="specify-mime-type-of-minor-linked-resources"> <h3>Bağlantılı kaynakların MIME türünü belirtin</h3> <p>Bu, uygulamanın bu kaynağı nasıl kullandığı hakkında bir ipucudur.</p> <p>Yanlış:</p> <pre><code>&lt;link href=&quot;/pdf&quot; rel=&quot;alternate&quot;&gt; &lt;link href=&quot;/feed&quot; rel=&quot;alternate&quot;&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;link href=&quot;/pdf&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt; &lt;link href=&quot;/feed&quot; rel=&quot;alternate&quot; type=&quot;application/rss+xml&quot;&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt;</code></pre> </section> <section id="dont-link-to-faviconico"> <h3><code>favicon.ico</code>&#39;ya link vermeyin</h3> <p>Hemen hemen tüm tarayıcılar <code>/favicon.ico</code>&#39;yu otomatik ve asenkron olarak alır.</p> <p>Yanlış:</p> <pre><code>&lt;link href=&quot;/favicon.ico&quot; rel=&quot;icon&quot; type=&quot;image/vnd.microsoft.icon&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;!-- Place `favicon.ico` in the root directory. --&gt;</code></pre> </section> <section id="add-apple-touch-icon-link"> <h3><code>apple-touch-icon</code> ekleyin</h3> <p>Dokunma simgesi için varsayılan istek yolu değiştirildi.</p> <p>Yanlış:</p> <pre><code>&lt;!-- Hey Apple! Please download `/apple-touch-icon.png`! --&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;link href=&quot;/apple-touch-icon.png&quot; rel=&quot;apple-touch-icon&quot;&gt;</code></pre> </section> <section id="add-title-attribute-to-alternate-stylesheets"> <h3>Alternatif stil sayfalarına <code>title</code> ekleyin</h3> <p>İnsan tarafından okunabilen bir değer, insanların uygun stil sayfasını seçmelerine yardımcı olur.</p> <p>Yanlış:</p> <pre><code>&lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;link href=&quot;/css/high-contrast.css&quot; rel=&quot;alternate stylesheet&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;link href=&quot;/css/high-contrast.css&quot; rel=&quot;alternate stylesheet&quot; title=&quot;High contrast&quot;&gt;</code></pre> </section> <section id="for-url-use-link-element"> <h3>URL için <code>link</code> kullanın</h3> <p>Bir <code>href</code> değeri URL olarak çözülebilir.</p> <p>Yanlış:</p> <pre><code>&lt;section itemscope itemtype=&quot;http://schema.org/BlogPosting&quot;&gt; &lt;meta content=&quot;https://example.com/blog/hello&quot; itemprop=&quot;url&quot;&gt; ... &lt;/section&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;section itemscope itemtype=&quot;http://schema.org/BlogPosting&quot;&gt; &lt;link href=&quot;/blog/hello&quot; itemprop=&quot;url&quot;&gt; ... &lt;/section&gt;</code></pre> </section> <section id="specify-document-character-encoding"> <h3>Belge karakter kodunu belirtin</h3> <p>UTF-8 henüz tüm tarayıcılarda varsayılan değil.</p> <p>Yanlış:</p> <pre><code>&lt;head&gt; &lt;title&gt;HTML Best Practices&lt;/title&gt; &lt;/head&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;HTML Best Practices&lt;/title&gt; &lt;/head&gt;</code></pre> </section> <section id="dont-use-legacy-character-encoding-format"> <h3>Eski karakter kodlama formatını kullanmayın</h3> <p>HTTP başlıkları bir sunucu tarafından belirtilmelidir, basit olmalıdır.</p> <p>Yanlış:</p> <pre><code>&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;meta charset=&quot;UTF-8&quot;&gt;</code></pre> </section> <section id="specify-character-encoding-at-first"> <h3>İlk önce karakter kodlamasını belirtin</h3> <p>Spec, karakter kodlamasının dökümanın ilk 1024 bayt içinde belirtilmesini gerektirir.</p> <p>Yanlış:</p> <pre><code>&lt;head&gt; &lt;meta content=&quot;width=device-width&quot; name=&quot;viewport&quot;&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; ... &lt;/head&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta content=&quot;width=device-width&quot; name=&quot;viewport&quot;&gt; ... &lt;/head&gt;</code></pre> </section> <section id="use-utf-8"> <h3>UTF-8&#39;i kullanın</h3> <p>UTF-8 ile Emoji&#39;yi kullanmakta özgürsünüz.</p> <p>Yanlış:</p> <pre><code>&lt;meta charset=&quot;Shift_JIS&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;meta charset=&quot;UTF-8&quot;&gt;</code></pre> </section> <section id="omit-type-attribute-for-css"> <h3>CSS için <code>type</code> kullanmayın</h3> <p>HTML&#39;de, <code>style</code> etiketinin <code>type</code> özelliğinin ön tanımlı değeri <code>text/css</code>&#39;tir.</p> <p>Yanlış:</p> <pre><code>&lt;style type=&quot;text/css&quot;&gt; ... &lt;/style&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;style&gt; ... &lt;/style&gt;</code></pre> </section> <section id="dont-comment-out-contents-of-style-element"> <h3><code>style</code> etiketinin içeriğini yorum içine almayın</h3> <p>Bu ritüel eski tarayıcı içindir.</p> <p>Yanlış:</p> <pre><code>&lt;style&gt; &lt;!-- ... --&gt; &lt;/style&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;style&gt; ... &lt;/style&gt;</code></pre> </section> <section id="dont-mix-tag-for-css-and-javascript"> <h3>CSS ve JavaScript etiketlerini karıştırmayın</h3> <p>Bazen <code>script</code> elemanı DOM inşasını engeller.</p> <p>Yanlış:</p> <pre><code>&lt;script src=&quot;/js/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;script src=&quot;/js/main.js&quot;&gt;&lt;/script&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;script src=&quot;/js/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;/js/main.js&quot;&gt;&lt;/script&gt;</code></pre><p>Bu da doğru:</p> <pre><code>&lt;script src=&quot;/js/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;/js/main.js&quot;&gt;&lt;/script&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt;</code></pre> </section> </section> <section id="sections"> <h2>Bölümler</h2> <section id="add-body-element"> <h3><code>body</code> etiketi ekleyin</h3> <p>Bazen <code>body</code> etiketi beklenmedik bir pozisyonda bir tarayıcı tarafından tamamlanmaktadır.</p> <p>Yanlış:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; ... &lt;/html&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre> </section> <section id="forget-about-hgroup-element"> <h3><code>hgroup</code> etiketini unutun</h3> <p>Bu etiket çok fazla kullanılmıyor.</p> <p>Yanlış:</p> <pre><code>&lt;hgroup&gt; &lt;h1&gt;HTML Best Practices&lt;/h1&gt; &lt;h2&gt;For writing maintainable and scalable HTML documents.&lt;/h2&gt; &lt;/hgroup&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;h1&gt;HTML Best Practices&lt;/h1&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt;</code></pre> </section> <section id="use-address-element-only-for-contact-information"> <h3><code>address</code> etiketini yalnızca iletişim bilgileri için kullanın</h3> <p><code>address</code> sadece e-posta adresi, sosyal ağ hesabı, sokak adresi, telefon numarası veya iletişim kurabileceğiniz bir şey içindir.</p> <p>Yanlış:</p> <pre><code>&lt;address&gt;No rights reserved.&lt;/address&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;address&gt;Contact: &lt;a href=&quot;https://twitter.com/hail2u_&quot;&gt;<NAME>&lt;/a&gt;&lt;/address&gt;</code></pre> </section> </section> <section id="grouping-content"> <h2>İçeriği gruplama</h2> <section id="dont-start-with-newline-in-pre-element"> <h3><code>pre</code> elemandaki satır başı ile başlamayın</h3> <p>Tarayıcılarda ilk yeni satır yok sayılır, ancak ikinci ve sonraki satırlar oluşturulur.</p> <p>Yanlış:</p> <pre><code>&lt;pre&gt; &amp;lt;!DOCTYPE html&amp;gt; &lt;/pre&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;pre&gt;&amp;lt;!DOCTYPE html&amp;gt; &lt;/pre&gt;</code></pre> </section> <section id="use-appropriate-element-in-blockquote-element"> <h3><code>blockquote</code> içinde uygun etiket kullanın</h3> <p><code>blockquote</code> bir alıntıdır, yani içeriği bir karakter kümesi değildir.</p> <p>Yanlış:</p> <pre><code>&lt;blockquote&gt;For writing maintainable and scalable HTML documents.&lt;/blockquote&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;/blockquote&gt;</code></pre> </section> <section id="dont-include-attribution-directly-in-blockquote-element"> <h3>Özniteliği doğrudan <code>blockquote</code> öğesinin içine dahil etme</h3> <p><code>blockquote</code> içeriği bir alıntıdır.</p> <p>Yanlış:</p> <pre><code>&lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;p&gt;— HTML Best Practices&lt;/p&gt; &lt;/blockquote&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;/blockquote&gt; &lt;p&gt;— HTML Best Practices&lt;/p&gt;</code></pre><p>Bu da doğru:</p> <pre><code>&lt;figure&gt; &lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;/blockquote&gt; &lt;figcaption&gt;— HTML Best Practices&lt;/figcaption&gt; &lt;/figure&gt;</code></pre> </section> <section id="write-one-list-item-per-line"> <h3>Satır başına bir liste öğesi yaz</h3> <p>Uzuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuun bir satırı okuması çooooooooooooooooooooooooooooooooooooooooooooooooook zordur</p> <p>Yanlış:</p> <pre><code>&lt;ul&gt; &lt;li&gt;General&lt;/li&gt;&lt;li&gt;The root Element&lt;/li&gt;&lt;li&gt;Sections&lt;/li&gt;... &lt;/ul&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;ul&gt; &lt;li&gt;General&lt;/li&gt; &lt;li&gt;The root Element&lt;/li&gt; &lt;li&gt;Sections&lt;/li&gt; ... &lt;/ul&gt;</code></pre> </section> <section id="use-type-attribute-for-ol-element"> <h3><code>ol</code> etiketi için <code>type</code> özelliğini kullanın</h3> <p>Bazen yakınlardaki içerikler referans verilir. İşaretçiyi değiştirirseniz <code>type</code> özelliği ile kullanırsanız güvende olacaksınız.</p> <p>Yanlış:</p> <pre><code>&lt;head&gt; &lt;style&gt; .toc { list-style-type: upper-roman; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;ol class=&quot;toc&quot;&gt; &lt;li&gt;General&lt;/li&gt; &lt;li&gt;The root Element&lt;/li&gt; &lt;li&gt;Sections&lt;/li&gt; ... &lt;/ol&gt; &lt;/body&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;body&gt; &lt;ol type=&quot;I&quot;&gt; &lt;li&gt;General&lt;/li&gt; &lt;li&gt;The root Element&lt;/li&gt; &lt;li&gt;Sections&lt;/li&gt; ... &lt;/ol&gt; &lt;/body&gt;</code></pre> </section> <section id="dont-use-dl-for-dialogue"> <h3>Diyalog için <code>dl</code> kullanmayın</h3> <p><code>dl</code> etiketi, HTML&#39;deki bir ilişkilendirme listesi ile sınırlandırılmıştır.</p> <p>Yanlış:</p> <pre><code>&lt;dl&gt; &lt;dt&gt;Costello&lt;/dt&gt; &lt;dd&gt;Look, you gotta first baseman?&lt;/dd&gt; &lt;dt&gt;Abbott&lt;/dt&gt; &lt;dd&gt;Certainly.&lt;/dd&gt; &lt;dt&gt;Costello&lt;/dt&gt; &lt;dd&gt;Who’s playing first?&lt;/dd&gt; &lt;dt&gt;Abbott&lt;/dt&gt; &lt;dd&gt;That’s right.&lt;/dd&gt; &lt;dt&gt;Costello becomes exasperated.&lt;/dd&gt; &lt;dt&gt;Costello&lt;/dt&gt; &lt;dd&gt;When you pay off the first baseman every month, who gets the money?&lt;/dd&gt; &lt;dt&gt;Abbott&lt;/dt&gt; &lt;dd&gt;Every dollar of it.&lt;/dd&gt; &lt;/dl&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;p&gt;Costello: Look, you gotta first baseman?&lt;/p&gt; &lt;p&gt;Abbott: Certainly.&lt;/p&gt; &lt;p&gt;Costello: Who’s playing first?&lt;/p&gt; &lt;p&gt;Abbott: That’s right.&lt;/p&gt; &lt;p&gt;Costello becomes exasperated.&lt;/p&gt; &lt;p&gt;Costello: When you pay off the first baseman every month, who gets the money?&lt;/p&gt; &lt;p&gt;Abbott: Every dollar of it.&lt;/p&gt;</code></pre> </section> <section id="place-figcaption-element-as-first-or-last-child-of-figure-element"> <h3><code>figcaption</code> etiketini, <code>figure</code> etiketinin ilk veya son çocuğu olarak yerleştirin</h3> <p>Spec, <code>figure</code> etiketinin ortasındaki <code>figcaption</code> etiketine izin vermez.</p> <p>Yanlış:</p> <pre><code>&lt;figure&gt; &lt;img alt=&quot;Front cover of the “HTML Best Practices” book&quot; src=&quot;/img/front-cover.png&quot;&gt; &lt;figcaption&gt;“HTML Best Practices” Cover Art&lt;/figcaption&gt; &lt;img alt=&quot;Back cover of the “HTML Best Practices” book&quot; src=&quot;/img/back-cover.png&quot;&gt; &lt;/figure&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;figure&gt; &lt;img alt=&quot;Front cover of the “HTML Best Practices” book&quot; src=&quot;/img/front-cover.png&quot;&gt; &lt;img alt=&quot;Back cover of the “HTML Best Practices” book&quot; src=&quot;/img/back-cover.png&quot;&gt; &lt;figcaption&gt;“HTML Best Practices” Cover Art&lt;/figcaption&gt; &lt;/figure&gt;</code></pre> </section> <section id="use-main-element"> <h3><code>main</code> etiketini kullanın</h3> <p><code>main</code> içerikleri kapsamak için kullanılabilir.</p> <p>Yanlış:</p> <pre><code>&lt;div id=&quot;content&quot;&gt; ... &lt;/div&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;main&gt; ... &lt;/main&gt;</code></pre> </section> <section id="avoid-div-element-as-much-as-possible"> <h3><code>div</code> etiketini mümkün olduğu kadar kullanmayın</h3> <p><code>div</code> son çaredir</p> <p>Yanlış:</p> <pre><code>&lt;div class=&quot;chapter&quot;&gt; ... &lt;/div&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;section&gt; ... &lt;/section&gt;</code></pre> </section> </section> <section id="text-level-semantics"> <h2>Metin düzeyinde anlambilim</h2> <section id="dont-split-same-link-that-can-be-grouped"> <h3>Gruplandırılabilen aynı bağlantıyı bölmeyin</h3> <p><code>a</code> etiketi hemen hemen tüm etiketleri sarabilir (form gibi etkileşimli elemanlar hariç) kontroller ve <code>a</code> elemanın kendisi).</p> <p>Yanlış:</p> <pre><code>&lt;h1&gt;&lt;a href=&quot;https://whatwg.org/&quot;&gt;WHATWG&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;&lt;a href=&quot;https://whatwg.org/&quot;&gt;A community maintaining and evolving HTML since 2004.&lt;/a&gt;&lt;/p&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;a href=&quot;https://whatwg.org/&quot;&gt; &lt;h1&gt;WHATWG&lt;/h1&gt; &lt;p&gt;A community maintaining and evolving HTML since 2004.&lt;/p&gt; &lt;/a&gt;</code></pre> </section> <section id="use-download-attribute-for-downloading-a-resource"> <h3>İndirilebilir kaynağı belirtmek için <code>download</code> özelliğini kullanın</h3> <p>Tarayıcıları bağlı kaynakları depoya indirmeye zorlar.</p> <p>Yanlış:</p> <pre><code>&lt;a href=&quot;/downloads/offline.zip&quot;&gt;offline version&lt;/a&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;a download href=&quot;/downloads/offline.zip&quot;&gt;offline version&lt;/a&gt;</code></pre> </section> <section id="use-rel-hreflang-and-type-attribute-if-needed"> <h3>Gerekirse <code>rel</code> , <code>hreflang</code> ve <code>type</code> özelliklerini kullanın</h3> <p>Bu ipuçları bağlantılı kaynakların nasıl işleneceğini belirterek uygulamalara yardımcı olur.</p> <p>Yanlış:</p> <pre><code>&lt;a href=&quot;/ja/pdf&quot;&gt;Japanese PDF version&lt;/a&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;a href=&quot;/ja/pdf&quot; hreflang=&quot;ja&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt;Japanese PDF version&lt;/a&gt;</code></pre> </section> <section id="clear-link-text"> <h3>Bağlantı metinlerini amacına uygun yapın</h3> <p>Link metni, linklenen kaynağın etiketi olmalıdır.</p> <p>Yanlış:</p> <pre><code>&lt;p&gt;&lt;a href=&quot;/pdf&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt;Click here&lt;/a&gt; to view PDF version.&lt;/p&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;p&gt;&lt;a href=&quot;/pdf&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt;PDF version&lt;/a&gt; is also available.&lt;/p&gt;</code></pre> </section> <section id="dont-use-em-element-for-warning-or-caution"> <h3>Uyarı vermek için <code>em</code> etiketi kullanmayın</h3> <p>Bu ciddiyettir. Yani, <code>strong</code> eleman daha uygundur.</p> <p>Yanlış:</p> <pre><code>&lt;em&gt;Caution!&lt;/em&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;strong&gt;Caution!&lt;/strong&gt;</code></pre> </section> <section id="avoid-s-i-b-and-u-element-as-much-as-possible"> <h3><code>s</code> , <code>i</code> , <code>b</code> ve <code>u</code> etiketlerinden mümkün olduğunca kaçının</h3> <p>Bu etiketlerin anlambilimi insanlar için çok zordur.</p> <p>Yanlış:</p> <pre><code>&lt;i class=&quot;icon-search&quot;&gt;&lt;/i&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;span class=&quot;icon-search&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt;</code></pre> </section> <section id="dont-put-quotes-to-q-element"> <h3><code>q</code> öğesine tırnak koymayın</h3> <p>Tırnaklar tarayıcı tarafından sağlanır.</p> <p>Yanlış:</p> <pre><code>&lt;q&gt;“For writing maintainable and scalable HTML documents”&lt;/q&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;q&gt;For writing maintainable and scalable HTML documents&lt;/q&gt;</code></pre><p>Bu da doğru:</p> <pre><code>“For writing maintainable and scalable HTML documents”</code></pre> </section> <section id="add-title-attribute-to-abbr-element"> <h3><code>abbr</code> etiketine <code>title</code> özelliğini ekleyin</h3> <p>Açıklamasını temsil etmenin başka bir yolu yoktur.</p> <p>Yanlış:</p> <pre><code>&lt;abbr&gt;HBP&lt;/abbr&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;abbr title=&quot;HTML Best Practices&quot;&gt;HBP&lt;/abbr&gt;</code></pre> </section> <section id="markup-ruby-element-verbosely"> <h3><code>ruby</code> etiketini detaylandırın</h3> <p>Modern tarayıcılarda <code>ruby</code> etiketi desteği henğz tamamlanmadı.</p> <p>Yanlış:</p> <pre><code>&lt;ruby&gt;HTML&lt;rt&gt;えいちてぃーえむえる&lt;/ruby&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;ruby&gt;HTML&lt;rp&gt; (&lt;/rp&gt;&lt;rt&gt;えいちてぃーえむえる&lt;/rt&gt;&lt;rp&gt;) &lt;/rp&gt;&lt;/ruby&gt;</code></pre> </section> <section id="add-datetime-attribute-to-non-machine-readable-time-element"> <h3>Makine tarafından okunamayacak <code>time</code> etiketine <code>datetime</code> özelliği ekleyin</h3> <p><code>datetime</code> özelliği bulunmadığında, <code>time</code> öğesinin içeriğinin biçimi kısıtlıdır.</p> <p>Yanlış:</p> <pre><code>&lt;time&gt;Dec 19, 2014&lt;/time&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;time datetime=&quot;2014-12-19&quot;&gt;Dec 19, 2014&lt;/time&gt;</code></pre> </section> <section id="specify-code-language-with-class-attribute-prefixed-with-language"> <h3><code>language-</code> öneki ile kod dilini <code>class</code> etiketi le belirtin</h3> <p>Bu kesin bir yol değil, ancak spec bundan bahseder.</p> <p>Yanlış:</p> <pre><code>&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;/code&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;code class=&quot;language-html&quot;&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;/code&gt;</code></pre> </section> <section id="keep-kbd-element-as-simple-as-possible"> <h3><code>kbd</code> etiketini mümkün olduğu kadar basit tutun</h3> <p><code>kbd</code> etiketini iç içe kullanmak insanlar için çok zor.</p> <p>Yanlış:</p> <pre><code>&lt;kbd&gt;&lt;kbd&gt;Ctrl&lt;/kbd&gt;+&lt;kbd&gt;F5&lt;/kbd&gt;&lt;/kbd&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;kbd&gt;Ctrl+F5&lt;/kbd&gt;</code></pre> </section> <section id="avoid-span-element-as-much-as-possible"> <h3><code>span</code> etiketinden mümkün olduğunca kaçının</h3> <p><code>span</code> element son çaredir.</p> <p>Yanlış:</p> <pre><code>HTML &lt;span class=&quot;best&quot;&gt;Best&lt;/span&gt; Practices</code></pre><p>Doğru:</p> <pre><code>HTML &lt;em&gt;Best&lt;/em&gt; Practices</code></pre> </section> <section id="break-after-br-element"> <h3><code>br</code> etiketinden sonra satır sonu yapın</h3> <p><code>br</code> etiketi kullanıldığında satır sonu gereklidir.</p> <p>Yanlış:</p> <pre><code>&lt;p&gt;HTML&lt;br&gt;Best&lt;br&gt;Practices&lt;/p&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;p&gt;HTML&lt;br&gt; Best&lt;br&gt; Practices&lt;/p&gt;</code></pre> </section> <section id="dont-use-br-element-only-for-presentational-purpose"> <h3><code>br</code> öğesini yalnızca sunum amacıyla kullanmayın</h3> <p><code>br</code> elemanı satır kesmek için değil, içerikteki satır kesmeler içindir.</p> <p>Yanlış:</p> <pre><code>&lt;p&gt;&lt;label&gt;Rule name: &lt;input name=&quot;rule-name&quot; type=&quot;text&quot;&gt;&lt;/label&gt;&lt;br&gt; &lt;label&gt;Rule description:&lt;br&gt; &lt;textarea name=&quot;rule-description&quot;&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;/p&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;p&gt;&lt;label&gt;Rule name: &lt;input name=&quot;rule-name&quot; type=&quot;text&quot;&gt;&lt;/label&gt;&lt;/p&gt; &lt;p&gt;&lt;label&gt;Rule description:&lt;br&gt; &lt;textarea name=&quot;rule-description&quot;&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;/p&gt;</code></pre> </section> </section> <section id="edits"> <h2>Düzenlemeler</h2> <section id="dont-stride-ins-and-del-element-over-other-elements"> <h3><code>ins</code> ve <code>del</code> etiketlerini diğer öğelerin arasında kullanmayın</h3> <p>Etiketler diğer etidektlere taşamaz.</p> <p>Yanlış:</p> <pre><code>&lt;p&gt;For writing maintainable and scalable HTML documents.&lt;del&gt; And for mental stability.&lt;/p&gt; &lt;p&gt;Don’t trust!&lt;/p&gt;&lt;/del&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;p&gt;For writing maintainable and scalable HTML documents.&lt;del&gt; And for mental stability.&lt;/del&gt;&lt;/p&gt; &lt;del&gt;&lt;p&gt;Don’t trust!&lt;/p&gt;&lt;/del&gt;</code></pre> </section> </section> <section id="embedded-content"> <h2>Gömülü içerik</h2> <section id="provide-fallback-img-element-for-picture-element"> <h3><code>picture</code> elemanı için yedek <code>img</code> elemanı kullanın</h3> <p><code>picture</code> etiketinin desteği henüz iyi değil.</p> <p>Yanlış:</p> <pre><code>&lt;picture&gt; &lt;source srcset=&quot;/img/logo.webp&quot; type=&quot;image/webp&quot;&gt; &lt;source srcset=&quot;/img/logo.hdp&quot; type=&quot;image/vnd.ms-photo&quot;&gt; &lt;source srcset=&quot;/img/logo.jp2&quot; type=&quot;image/jp2&quot;&gt; &lt;source srcset=&quot;/img/logo.jpg&quot; type=&quot;image/jpg&quot;&gt; &lt;/picture&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;picture&gt; &lt;source srcset=&quot;/img/logo.webp&quot; type=&quot;image/webp&quot;&gt; &lt;source srcset=&quot;/img/logo.hdp&quot; type=&quot;image/vnd.ms-photo&quot;&gt; &lt;source srcset=&quot;/img/logo.jp2&quot; type=&quot;image/jp2&quot;&gt; &lt;img src=&quot;/img/logo.jpg&quot;&gt; &lt;/picture&gt;</code></pre> </section> <section id="add-alt-attrbute-to-img-element-if-needed"> <h3>Gerekirse <code>img</code> öğesine <code>alt</code> özelliği ekleyin</h3> <p><code>alt</code> niteliği, görüntüleri işleyemeyen veya görüntü yüklemesi engelli olanlara yardımcı olur.</p> <p>Yanlış:</p> <pre><code>&lt;img src=&quot;/img/logo.png&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot;&gt;</code></pre> </section> <section id="empty-alt-attribute-if-possible"> <h3>Mümkünse <code>alt</code> özelliğini boş olarak kullanın</h3> <p>Resim tamamlayıcı ise, yakınlarda bir yerde eşdeğer içerik vardır.</p> <p>Yanlış:</p> <pre><code>&lt;img alt=&quot;Question mark icon&quot; src=&quot;/img/icon/help.png&quot;&gt; Help</code></pre><p>Doğru:</p> <pre><code>&lt;img alt=&quot;&quot; src=&quot;/img/icon/help.png&quot;&gt; Help</code></pre> </section> <section id="omit-alt-attribute-if-possible"> <h3>Mümkünse <code>alt</code> özelliğini atlayın</h3> <p>Bazen hangi metnin <code>alt</code> özellik için uygun olduğunu bilemezsiniz.</p> <p>Yanlış:</p> <pre><code>&lt;img alt=&quot;CAPTCHA&quot; src=&quot;captcha.cgi?id=82174&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;img src=&quot;captcha.cgi?id=82174&quot; title=&quot;CAPTCHA&quot;&gt; (If you cannot see the image, you can use an &lt;a href=&quot;?audio&quot;&gt;audio&lt;/a&gt; test instead.)</code></pre> </section> <section id="empty-iframe-element"> <h3>Boş <code>iframe</code> öğesi kullanın</h3> <p>İçeriği için bazı kısıtlamalar vardır. Boş olması her zaman güvenlidir.</p> <p>Yanlış:</p> <pre><code>&lt;iframe src=&quot;/ads/default.html&quot;&gt; &lt;p&gt;If your browser support inline frame, ads are displayed here.&lt;/p&gt; &lt;/iframe&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;iframe src=&quot;/ads/default.html&quot;&gt;&lt;/iframe&gt;</code></pre> </section> <section id="markup-map-element-content"> <h3><code>map</code> etiketinin içeriğini işaretleyin</h3> <p>Bu içerik bir ekran okuyucu sunar.</p> <p>Yanlış:</p> <pre><code>&lt;map name=&quot;toc&quot;&gt; &lt;a href=&quot;#general&quot;&gt;General&lt;/a&gt; &lt;area alt=&quot;General&quot; coords=&quot;0, 0, 40, 40&quot; href=&quot;#General&quot;&gt; | &lt;a href=&quot;#the_root_element&quot;&gt;The root element&lt;/a&gt; &lt;area alt=&quot;The root element&quot; coords=&quot;50, 0, 90, 40&quot; href=&quot;#the_root_element&quot;&gt; | &lt;a href=&quot;#sections&quot;&gt;Sections&lt;/a&gt; &lt;area alt=&quot;Sections&quot; coords=&quot;100, 0, 140, 40&quot; href=&quot;#sections&quot;&gt; &lt;/map&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;map name=&quot;toc&quot;&gt; &lt;p&gt; &lt;a href=&quot;#general&quot;&gt;General&lt;/a&gt; &lt;area alt=&quot;General&quot; coords=&quot;0, 0, 40, 40&quot; href=&quot;#General&quot;&gt; | &lt;a href=&quot;#the_root_element&quot;&gt;The root element&lt;/a&gt; &lt;area alt=&quot;The root element&quot; coords=&quot;50, 0, 90, 40&quot; href=&quot;#the_root_element&quot;&gt; | &lt;a href=&quot;#sections&quot;&gt;Sections&lt;/a&gt; &lt;area alt=&quot;Sections&quot; coords=&quot;100, 0, 140, 40&quot; href=&quot;#sections&quot;&gt; &lt;/p&gt; &lt;/map&gt;</code></pre> </section> <section id="provide-fallback-content-for-audio-or-video-element"> <h3><code>audio</code> veya <code>video</code> öğesi için yedek içerik sağlayın</h3> <p>HTML’de yeni tanıtılan öğeler için yedek içerik gereklidir.</p> <p>Yanlış:</p> <pre><code>&lt;video&gt; &lt;source src=&quot;/mov/theme.mp4&quot; type=&quot;video/mp4&quot;&gt; &lt;source src=&quot;/mov/theme.ogv&quot; type=&quot;video/ogg&quot;&gt; ... &lt;/video&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;video&gt; &lt;source src=&quot;/mov/theme.mp4&quot; type=&quot;video/mp4&quot;&gt; &lt;source src=&quot;/mov/theme.ogv&quot; type=&quot;video/ogg&quot;&gt; ... &lt;iframe src=&quot;//www.youtube.com/embed/...&quot; allowfullscreen&gt;&lt;/iframe&gt; &lt;/video&gt;</code></pre> </section> </section> <section id="tabular-data"> <h2>Tablo verileri</h2> <section id="write-one-cell-per-line"> <h3>Her satıra bir hücre yazın</h3> <p>Uzun satırların taranması zordur.</p> <p>Yanlış:</p> <pre><code>&lt;tr&gt; &lt;td&gt;General&lt;/td&gt;&lt;td&gt;The root Element&lt;/td&gt;&lt;td&gt;Sections&lt;/td&gt; &lt;/tr&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;tr&gt; &lt;td&gt;General&lt;/td&gt; &lt;td&gt;The root Element&lt;/td&gt; &lt;td&gt;Sections&lt;/td&gt; &lt;/tr&gt;</code></pre> </section> <section id="use-th-element-for-header-cell"> <h3>Başlık hücresi için <code>th</code> etiketini kullanın</h3> <p>Bundan kaçınmak için hiçbir sebep yoktur.</p> <p>Yanlış:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;Element&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;Empty&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;Tag omission&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;&lt;code&gt;pre&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;No&lt;/td&gt; &lt;td&gt;Neither tag is omissible&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;&lt;code&gt;img&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;Yes&lt;/td&gt; &lt;td&gt;No end tag&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Element&lt;/th&gt; &lt;th&gt;Empty&lt;/th&gt; &lt;th&gt;Tag omission&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;&lt;code&gt;pre&lt;/code&gt;&lt;/th&gt; &lt;td&gt;No&lt;/td&gt; &lt;td&gt;Neither tag is omissible&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&lt;code&gt;img&lt;/code&gt;&lt;/th&gt; &lt;td&gt;Yes&lt;/td&gt; &lt;td&gt;No end tag&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </section> </section> <section id="forms"> <h2>Formlar</h2> <section id="wrap-form-control-with-label-element"> <h3><code>label</code> etiketini ile form kontrolünü sağlayın</h3> <p><code>label</code> etiketi form öğesinin odaklanmasına yardımcı olur.</p> <p>Yanlış:</p> <pre><code>&lt;p&gt;Query: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/p&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;p&gt;&lt;label&gt;Query: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/label&gt;&lt;/p&gt;</code></pre> </section> <section id="omit-for-attribute-if-possible"> <h3>Mümkünse <code>for</code> özelliğini kullanmayın</h3> <p><code>label</code> etiketi bazı form etiketlerini içerebilir.</p> <p>Yanlış:</p> <pre><code>&lt;label for=&quot;q&quot;&gt;Query: &lt;/label&gt;&lt;input id=&quot;q&quot; name=&quot;q&quot; type=&quot;text&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;label&gt;Query: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/label&gt;</code></pre> </section> <section id="use-appropriate-type-attribute-for-input-element"> <h3><code>input</code> etiketi için uygun <code>type</code> özelliğini kullanın</h3> <p>Uygun <code>type</code> özelliği ile, tarayıcılar <code>input</code> elemanına küçük özellikler kazandırır.</p> <p>Yanlış:</p> <pre><code>&lt;label&gt;Search keyword: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/label&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;label&gt;Search keyword: &lt;input name=&quot;q&quot; type=&quot;search&quot;&gt;&lt;/label&gt;</code></pre> </section> <section id="add-value-attribute-to-input-typesubmit"> <h3><code>input type=&quot;submit&quot;</code> elemanına <code>value</code> özelliği ekleyin</h3> <p>Gönderme düğmesi için varsayılan etiket tarayıcılarda ve dillerde standardize edilmemiştir.</p> <p>Yanlış:</p> <pre><code>&lt;input type=&quot;submit&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;input type=&quot;submit&quot; value=&quot;Search&quot;&gt;</code></pre> </section> <section id="add-title-attribute-to-input-element-when-there-is-pattern-attribute"> <h3><code>pattern</code> özelliği olduğunda <code>input</code> etiketine <code>title</code> özelliği ekleyin</h3> <p>Girilen metni <code>pattern</code> niteliğiyle eşleşmiyorsa, <code>title</code> özelliğinin değeri ipucu olarak görüntülenecektir.</p> <p>Yanlış:</p> <pre><code>&lt;input name=&quot;security-code&quot; pattern=&quot;[0-9] type=&quot;text&quot;&gt;</code></pre><p>Doğru: <input name="security-code" pattern="[0-9]{3}" title="A security code is a number in three figures." type="text"></p> </section> <section id="dont-use-placeholder-attribute-for-labeling"> <h3>Etiketleme için <code>placeholder</code> özelliğini kullanmayın</h3> <p><code>label</code> öğesi bir etiket içindir, <code>placeholder</code> özelliği kısa bir ipucu içindir.</p> <p>Yanlış:</p> <pre><code>&lt;input name=&quot;email&quot; placeholder=&quot;Email&quot; type=&quot;text&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;label&gt;Email: &lt;input name=&quot;email&quot; placeholder=&quot;<EMAIL>&quot; type=&quot;text&quot;&gt;&lt;/label&gt;</code></pre> </section> <section id="write-one-option-element-per-line"> <h3>Her satıra bir <code>option</code> etiketi yazın</h3> <p>Uzun satırların taranması zordur.</p> <p>Yanlış:</p> <pre><code>&lt;datalist id=&quot;toc&quot;&gt; &lt;option label=&quot;General&quot;&gt;&lt;option label=&quot;The root element&quot;&gt;&lt;option label=&quot;Sections&quot;&gt;&lt;/datalist&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;datalist id=&quot;toc&quot;&gt; &lt;option label=&quot;General&quot;&gt; &lt;option label=&quot;The root element&quot;&gt; &lt;option label=&quot;Sections&quot;&gt; &lt;/datalist&gt;</code></pre> </section> <section id="add-max-attribute-to-progress-element"> <h3><code>progress</code> etiketine <code>max</code> özelliği ekleyin</h3> <p><code>max</code> özelliği ile, <code>value</code> özelliği kolay bir biçimde yazılabilir.</p> <p>Yanlış:</p> <pre><code>&lt;progress value=&quot;0.5&quot;&gt; 50%&lt;/progress&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;progress max=&quot;100&quot; value=&quot;50&quot;&gt; 50%&lt;/progress&gt;</code></pre> </section> <section id="add-min-and-max-attribute-to-meter-element"> <h3><code>meter</code> etiketine <code>min</code> ve <code>max</code> özelliği ekleyin</h3> <p><code>min</code> ve <code>max</code> özelliği ile <code>value</code> özelliği kolay bir şekilde yazılabilir.</p> <p>Yanlış:</p> <pre><code>&lt;meter value=&quot;0.5&quot;&gt; 512GB used (1024GB total&lt;/meter&gt;</code></pre><p>Doğru: <meter min="0" max="1024" value="512"> 512GB used (1024GB total</meter></p> </section> <section id="place-legend-element-as-the-first-child-of-fieldset-element"> <h3><code>legend</code> etiketini <code>fieldset</code> etiketinin ilk çocuğu olarak elemanı olarak oluşturun</h3> <p>Spec bunu gerektirir.</p> <p>Yanlış:</p> <pre><code>&lt;fieldset&gt; &lt;p&gt;&lt;label&gt;Is this section is useful?: &lt;input name=&quot;usefulness-general&quot; type=&quot;checkbox&quot;&gt;&lt;/label&gt;&lt;/p&gt; ... &lt;legend&gt;About &quot;General&quot;&lt;/legend&gt; &lt;/fieldset&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;fieldset&gt; &lt;legend&gt;About &quot;General&quot;&lt;/legend&gt; &lt;p&gt;&lt;label&gt;Is this section is useful?: &lt;input name=&quot;usefulness-general&quot; type=&quot;checkbox&quot;&gt;&lt;/label&gt;&lt;/p&gt; ... &lt;/fieldset&gt;</code></pre> </section> </section> <section id="scripting"> <h2>Script ekleme</h2> <section id="omit-type-attribute-for-javascript"> <h3>JavaScript için <code>type</code> özelliğini kullanmayın</h3> <p>HTML’de,<code>type</code> özelliğinin <code>script</code> etiketi için varsayılan değeri <code>text/javascript</code>tir.</p> <p>Yanlış:</p> <pre><code>&lt;script type=&quot;text/javascript&quot;&gt; ...&lt;/script&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;script&gt; ...&lt;/script&gt;</code></pre> </section> <section id="dont-comment-out-contents-of-script-element"> <h3><code>script</code> etiketinin içeriğini yorumla kapatmayın</h3> <p>Bu ritüel eski tarayıcılar içindir.</p> <p>Yanlış:</p> <pre><code>&lt;script&gt;/*&lt;![CDATA[*/ .../*]]&gt;*/&lt;/script&gt;</code></pre><p>Bu da kötü:</p> <pre><code>&lt;script&gt;&lt;!-- ...// --&gt;&lt;/script&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;script&gt; ...&lt;/script&gt;</code></pre> </section> <section id="dont-use-script-injected-script-element"> <h3>Komut dosyası eklenmiş <code>script</code> öğesini kullanmayın</h3> <p><code>async</code> özelliği hem sadelik hem de performans için en iyisidir.</p> <p>Yanlış:</p> <pre><code>&lt;script&gt; var script = document.createElement(&quot;script&quot;; script.async = true; script.src = &quot;//example.com/widget.js&quot;; document.getElementsByTagName(&quot;head&quot;[0].appendChild(script); &lt;/script&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;script async defer src=&quot;https://example.com/widget.js&quot;&gt;&lt;/script&gt;</code></pre> </section> </section> <section id="other"> <h2>Diğer</h2> <section id="indent-consistently"> <h3>Tutarlı girintiler kullanın</h3> <p>Girinti okunabilirlik için önemlidir.</p> <p>Yanlış:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre> </section> <section id="use-absolute-path-for-internal-links"> <h3>Dahili bağlantılar için mutlak yol kullanın</h3> <p>Mutlak bir yol, internet bağlantınız olmadan localhost&#39;ta daha iyi çalışır.</p> <p>Yanlış:</p> <pre><code>&lt;link rel=&quot;apple-touch-icon&quot; href=&quot;http://you.example.com/apple-touch-icon-precomposed.png&quot;&gt;...&lt;p&gt;You can find more at &lt;a href=&quot;//you.example.com/contact.html&quot;&gt;contact page&lt;/a&gt;.&lt;/p&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;link rel=&quot;apple-touch-icon&quot; href=&quot;/apple-touch-icon-precomposed.png&quot;&gt;...&lt;p&gt;You can find more at &lt;a href=&quot;/contact.html&quot;&gt;contact page&lt;/a&gt;.&lt;/p&gt;</code></pre> </section> <section id="dont-use-protocol-relative-url-for-external-resources"> <h3>Harici kaynaklar için protokole bağlı URL kullanmayın</h3> <p>Protokol ile dış kaynakları güvenilir ve güvenli bir şekilde yükleyebilirsiniz.</p> <p>Yanlış:</p> <pre><code>&lt;script src=&quot;//example.com/js/library.js&quot;&gt;</code></pre><p>Doğru:</p> <pre><code>&lt;script src=&quot;https://example.com/js/library.js&quot;&gt;</code></pre> </section> </section> <section id="contributors"> <h2>Contributors</h2> <ul> <li><a href="https://github.com/@hail2u_">hail2u_</a></li> <li><a href="https://github.com/@momdo">momdo</a></li> </ul> </section> <section id="translators"> <h2>Translators</h2> <ul> <li><a href="https://github.com/@techhtml">techhtml</a></li> <li><a href="https://github.com/@umutphp">umutphp</a></li> </ul> </section> <sections id="license"> <h2>License</h2> <p><a href="http:&#x2F;&#x2F;creativecommons.org&#x2F;publicdomain&#x2F;zero&#x2F;1.0&#x2F;">CC0</a></p> </section> </main> </body> </html> <|start_filename|>docs/index.html<|end_filename|> <html lang="en"> <head> <meta charset="UTF-8"> <title>HTML Best Practices—For writing maintainable and scalable HTML documents</title> <meta content="For writing maintainable and scalable HTML documents" name="description"> <meta content="width=device-width" name=viewport> <link href="./index.html" rel="canonical"> <style> body { font-family: sans-serif; line-height: 1.5; margin-left: auto; margin-right: auto; max-width: 42em; padding-left: 1em; padding-right: 1em; } h2 { margin-top: 4em; } h3 { margin-top: 3em; } p { overflow-wrap: break-word; } pre, code { font-family: monospace, monospace; font-size: 1em; } pre { background-color: whitesmoke; overflow-wrap: break-word; padding: 0.5em; white-space: pre-wrap; } </style> </head> <body> <nav> <h4>Translations</h4> <ul> <li><a href="./index.html">English (en)</a></li> <li><a href="./index.ja.html">日本語 (ja)</a></li> <li><a href="./index.ko.html">한국어 (ko)</a></li> <li><a href="./index.tr.html">Türkçe (tr)</a></li> </ul> </nav> <header> <h1>HTML Best Practices</h1> <p>For writing maintainable and scalable HTML documents</p> </header> <nav> <h4><abbr title="Table of Contents">ToC</abbr></h4> <ol> <li><a href="#general">General</a> <ol> <li><a href="#start-with-doctype">Start with DOCTYPE</a> <li><a href="#dont-use-legacy-or-obsolete-doctype">Don’t use legacy or obsolete DOCTYPE</a> <li><a href="#dont-use-xml-declaration">Don’t use XML Declaration</a> <li><a href="#dont-use-character-references-as-much-as-possible">Don’t use character references as much as possible</a> <li><a href="#escape-amp-lt-gt-quot-and-apos-with-named-character-references">Escape <code>&amp;</code>, <code>&lt;</code>, <code>&gt;</code>, <code>&quot;</code>, and <code>&#39;</code> with named character references</a> <li><a href="#use-numeric-character-references-for-control-or-invisible-characters">Use numeric character references for control or invisible characters</a> <li><a href="#put-white-spaces-around-comment-contents">Put white spaces around comment contents</a> <li><a href="#dont-omit-closing-tag">Don’t omit closing tag</a> <li><a href="#dont-mix-empty-element-format">Don’t mix empty element format</a> <li><a href="#dont-put-white-spaces-around-tags-and-attribute-values">Don’t put white spaces around tags and attribute values</a> <li><a href="#dont-mix-character-cases">Don’t mix character cases</a> <li><a href="#dont-mix-quotation-marks">Don’t mix quotation marks</a> <li><a href="#dont-separate-attributes-with-two-or-more-white-spaces">Don’t separate attributes with two or more white spaces</a> <li><a href="#omit-boolean-attribute-value">Omit boolean attribute value</a> <li><a href="#omit-namespaces">Omit namespaces</a> <li><a href="#dont-use-xml-attributes">Don’t use XML attributes</a> <li><a href="#dont-mix-data-microdata-and-rdfa-lite-attributes-with-common-attributes">Don’t mix <code>data-*</code>, Microdata, and RDFa Lite attributes with common attributes</a> <li><a href="#prefer-default-implicit-aria-semantics">Prefer default implicit ARIA semantics</a> </ol> </li> <li><a href="#the-root-element">The root element</a> <ol> <li><a href="#add-lang-attribute">Add <code>lang</code> attribute</a> <li><a href="#keep-lang-attribute-value-as-short-as-possible">Keep <code>lang</code> attribute value as short as possible</a> <li><a href="#avoid-data-as-much-as-possible">Avoid <code>data-*</code> as much as possible</a> </ol> </li> <li><a href="#document-metadata">Document metadata</a> <ol> <li><a href="#add-title-element">Add <code>title</code> element</a> <li><a href="#dont-use-base-element">Don’t use <code>base</code> element</a> <li><a href="#specify-mime-type-of-minor-linked-resources">Specify MIME type of minor linked resources</a> <li><a href="#dont-link-to-faviconico">Don’t link to <code>favicon.ico</code></a> <li><a href="#add-apple-touch-icon-link">Add <code>apple-touch-icon</code> link</a> <li><a href="#add-title-attribute-to-alternate-stylesheets">Add <code>title</code> attribute to alternate stylesheets</a> <li><a href="#for-url-use-link-element">For URL, use <code>link</code> element</a> <li><a href="#specify-document-character-encoding">Specify document character encoding</a> <li><a href="#dont-use-legacy-character-encoding-format">Don’t use legacy character encoding format</a> <li><a href="#specify-character-encoding-at-first">Specify character encoding at first</a> <li><a href="#use-utf-8">Use UTF-8</a> <li><a href="#omit-type-attribute-for-css">Omit <code>type</code> attribute for CSS</a> <li><a href="#dont-comment-out-contents-of-style-element">Don’t comment out contents of <code>style</code> element</a> <li><a href="#dont-mix-tag-for-css-and-javascript">Don’t mix tag for CSS and JavaScript</a> </ol> </li> <li><a href="#sections">Sections</a> <ol> <li><a href="#add-body-element">Add <code>body</code> element</a> <li><a href="#forget-about-hgroup-element">Forget about <code>hgroup</code> element</a> <li><a href="#use-address-element-only-for-contact-information">Use <code>address</code> element only for contact information</a> </ol> </li> <li><a href="#grouping-content">Grouping content</a> <ol> <li><a href="#dont-start-with-newline-in-pre-element">Don’t start with newline in <code>pre</code> element</a> <li><a href="#use-appropriate-element-in-blockquote-element">Use appropriate element in <code>blockquote</code> element</a> <li><a href="#dont-include-attribution-directly-in-blockquote-element">Don’t include attribution directly in <code>blockquote</code> element</a> <li><a href="#write-one-list-item-per-line">Write one list item per line</a> <li><a href="#use-type-attribute-for-ol-element">Use <code>type</code> attribute for <code>ol</code> element</a> <li><a href="#dont-use-dl-for-dialogue">Don’t use <code>dl</code> for dialogue</a> <li><a href="#place-figcaption-element-as-first-or-last-child-of-figure-element">Place <code>figcaption</code> element as first or last child of <code>figure</code> element</a> <li><a href="#use-main-element">Use <code>main</code> element</a> <li><a href="#avoid-div-element-as-much-as-possible">Avoid <code>div</code> element as much as possible</a> </ol> </li> <li><a href="#text-level-semantics">Text-level semantics</a> <ol> <li><a href="#dont-split-same-link-that-can-be-grouped">Don’t split same link that can be grouped</a> <li><a href="#use-download-attribute-for-downloading-a-resource">Use <code>download</code> attribute for downloading a resource</a> <li><a href="#use-rel-hreflang-and-type-attribute-if-needed">Use <code>rel</code>, <code>hreflang</code>, and <code>type</code> attribute if needed</a> <li><a href="#clear-link-text">Clear link text</a> <li><a href="#dont-use-em-element-for-warning-or-caution">Don’t use <code>em</code> element for warning or caution</a> <li><a href="#avoid-s-i-b-and-u-element-as-much-as-possible">Avoid <code>s</code>, <code>i</code>, <code>b</code>, and <code>u</code> element as much as possible</a> <li><a href="#dont-put-quotes-to-q-element">Don’t put quotes to <code>q</code> element</a> <li><a href="#add-title-attribute-to-abbr-element">Add <code>title</code> attribute to <code>abbr</code> element</a> <li><a href="#markup-ruby-element-verbosely">Markup <code>ruby</code> element verbosely</a> <li><a href="#add-datetime-attribute-to-non-machine-readable-time-element">Add <code>datetime</code> attribute to non-machine-readable <code>time</code> element</a> <li><a href="#specify-code-language-with-class-attribute-prefixed-with-language">Specify code language with <code>class</code> attribute prefixed with <code>language-</code></a> <li><a href="#keep-kbd-element-as-simple-as-possible">Keep <code>kbd</code> element as simple as possible</a> <li><a href="#avoid-span-element-as-much-as-possible">Avoid <code>span</code> element as much as possible</a> <li><a href="#break-after-br-element">Break after <code>br</code> element</a> <li><a href="#dont-use-br-element-only-for-presentational-purpose">Don’t use <code>br</code> element only for presentational purpose</a> </ol> </li> <li><a href="#edits">Edits</a> <ol> <li><a href="#dont-stride-ins-and-del-element-over-other-elements">Don’t stride <code>ins</code> and <code>del</code> element over other elements</a> </ol> </li> <li><a href="#embedded-content">Embedded content</a> <ol> <li><a href="#provide-fallback-img-element-for-picture-element">Provide fallback <code>img</code> element for <code>picture</code> element</a> <li><a href="#add-alt-attrbute-to-img-element-if-needed">Add <code>alt</code> attrbute to <code>img</code> element if needed</a> <li><a href="#empty-alt-attribute-if-possible">Empty <code>alt</code> attribute if possible</a> <li><a href="#omit-alt-attribute-if-possible">Omit <code>alt</code> attribute if possible</a> <li><a href="#empty-iframe-element">Empty <code>iframe</code> element</a> <li><a href="#markup-map-element-content">Markup <code>map</code> element content</a> <li><a href="#provide-fallback-content-for-audio-or-video-element">Provide fallback content for <code>audio</code> or <code>video</code> element</a> </ol> </li> <li><a href="#tabular-data">Tabular data</a> <ol> <li><a href="#write-one-cell-per-line">Write one cell per line</a> <li><a href="#use-th-element-for-header-cell">Use <code>th</code> element for header cell</a> </ol> </li> <li><a href="#forms">Forms</a> <ol> <li><a href="#wrap-form-control-with-label-element">Wrap form control with <code>label</code> element</a> <li><a href="#omit-for-attribute-if-possible">Omit <code>for</code> attribute if possible</a> <li><a href="#use-appropriate-type-attribute-for-input-element">Use appropriate <code>type</code> attribute for <code>input</code> element</a> <li><a href="#add-value-attribute-to-input-typesubmit">Add <code>value</code> attribute to <code>input type=&quot;submit&quot;</code></a> <li><a href="#add-title-attribute-to-input-element-when-there-is-pattern-attribute">Add <code>title</code> attribute to <code>input</code> element when there is <code>pattern</code> attribute</a> <li><a href="#dont-use-placeholder-attribute-for-labeling">Don’t use <code>placeholder</code> attribute for labeling</a> <li><a href="#write-one-option-element-per-line">Write one <code>option</code> element per line</a> <li><a href="#add-max-attribute-to-progress-element">Add <code>max</code> attribute to <code>progress</code> element</a> <li><a href="#add-min-and-max-attribute-to-meter-element">Add <code>min</code> and <code>max</code> attribute to <code>meter</code> element</a> <li><a href="#place-legend-element-as-the-first-child-of-fieldset-element">Place <code>legend</code> element as the first child of <code>fieldset</code> element</a> </ol> </li> <li><a href="#scripting">Scripting</a> <ol> <li><a href="#omit-type-attribute-for-javascript">Omit <code>type</code> attribute for JavaScript</a> <li><a href="#dont-comment-out-contents-of-script-element">Don’t comment out contents of <code>script</code> element</a> <li><a href="#dont-use-script-injected-script-element">Don’t use script-injected <code>script</code> element</a> </ol> </li> <li><a href="#other">Other</a> <ol> <li><a href="#indent-consistently">Indent consistently</a> <li><a href="#use-absolute-path-for-internal-links">Use absolute path for internal links</a> <li><a href="#dont-use-protocol-relative-url-for-external-resources">Don’t use protocol-relative URL for external resources</a> </ol> </li> <li><a href="#contributors">Contributors</a></li> <li><a href="#translators">Translators</a></li> <li><a href="#license">License</a></li> </ol> </nav> <main> <section id="general"> <h2>General</h2> <section id="start-with-doctype"> <h3>Start with DOCTYPE</h3> <p>DOCTYPE is required for activating standard mode.</p> <p>Bad:</p> <pre><code>&lt;html&gt; ... &lt;/html&gt;</code></pre><p>Good:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; ... &lt;/html&gt;</code></pre> </section> <section id="dont-use-legacy-or-obsolete-doctype"> <h3>Don’t use legacy or obsolete DOCTYPE</h3> <p>DOCTYPE is not for DTD anymore, be simple.</p> <p>Bad:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;!DOCTYPE html&gt;</code></pre> </section> <section id="dont-use-xml-declaration"> <h3>Don’t use XML Declaration</h3> <p>Are you sure you want to write XHTML?</p> <p>Bad:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt; &lt;!DOCTYPE html&gt;</code></pre><p>Good:</p> <pre><code>&lt;!DOCTYPE html&gt;</code></pre> </section> <section id="dont-use-character-references-as-much-as-possible"> <h3>Don’t use character references as much as possible</h3> <p>If you write an HTML document with UTF-8, almost all characters (including Emoji) can be write directly.</p> <p>Bad:</p> <pre><code>&lt;p&gt;&lt;small&gt;Copyright &amp;copy; 2014 W3C&lt;sup&gt;&amp;reg;&lt;/sup&gt;&lt;/small&gt;&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;&lt;small&gt;Copyright © 2014 W3C&lt;sup&gt;®&lt;/sup&gt;&lt;/small&gt;&lt;/p&gt;</code></pre> </section> <section id="escape-amp-lt-gt-quot-and-apos-with-named-character-references"> <h3>Escape <code>&amp;</code>, <code>&lt;</code>, <code>&gt;</code>, <code>&quot;</code>, and <code>&#39;</code> with named character references</h3> <p>These characters should escape always for a bug-free HTML document.</p> <p>Bad:</p> <pre><code>&lt;h1&gt;The &quot;&amp;&quot; character&lt;/h1&gt;</code></pre><p>Good:</p> <pre><code>&lt;h1&gt;The &amp;quot;&amp;amp;&amp;quot; character&lt;/h1&gt;</code></pre> </section> <section id="use-numeric-character-references-for-control-or-invisible-characters"> <h3>Use numeric character references for control or invisible characters</h3> <p>These characters are easily mistaken for another character. And also spec does not guarantee to define a human readable name for these characters.</p> <p>Bad:</p> <pre><code>&lt;p&gt;This book can read in 1 hour.&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;This book can read in 1&amp;#xA0;hour.&lt;/p&gt;</code></pre> </section> <section id="put-white-spaces-around-comment-contents"> <h3>Put white spaces around comment contents</h3> <p>Some character cannot be used immediately after comment open or before comment close.</p> <p>Bad:</p> <pre><code>&lt;!--This section is non-normative--&gt;</code></pre><p>Good:</p> <pre><code>&lt;!-- This section is non-normative --&gt;</code></pre> </section> <section id="dont-omit-closing-tag"> <h3>Don’t omit closing tag</h3> <p>I think you don’t understand a rule for omitting closing tag.</p> <p>Bad:</p> <pre><code>&lt;html&gt; &lt;body&gt; ...</code></pre><p>Good:</p> <pre><code>&lt;html&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre> </section> <section id="dont-mix-empty-element-format"> <h3>Don’t mix empty element format</h3> <p>Consistency is a key for readability.</p> <p>Bad:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot;&gt; &lt;hr /&gt;</code></pre><p>Good:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot;&gt; &lt;hr&gt;</code></pre> </section> <section id="dont-put-white-spaces-around-tags-and-attribute-values"> <h3>Don’t put white spaces around tags and attribute values</h3> <p>There is no reason for doing this.</p> <p>Bad:</p> <pre><code>&lt;h1 class=&quot; title &quot; &gt;HTML Best Practices&lt;/h1&gt;</code></pre><p>Good:</p> <pre><code>&lt;h1 class=&quot;title&quot;&gt;HTML Best Practices&lt;/h1&gt;</code></pre> </section> <section id="dont-mix-character-cases"> <h3>Don’t mix character cases</h3> <p>It gives a consistency also.</p> <p>Bad:</p> <pre><code>&lt;a HREF=&quot;#general&quot;&gt;General&lt;/A&gt;</code></pre><p>Good:</p> <pre><code>&lt;a href=&quot;#general&quot;&gt;General&lt;/a&gt;</code></pre><p>Also Good:</p> <pre><code>&lt;A HREF=&quot;#general&quot;&gt;General&lt;/A&gt;</code></pre> </section> <section id="dont-mix-quotation-marks"> <h3>Don’t mix quotation marks</h3> <p>Same as above.</p> <p>Bad:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&#39;/img/logo.jpg&#39;&gt;</code></pre><p>Good:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.jpg&quot;&gt;</code></pre> </section> <section id="dont-separate-attributes-with-two-or-more-white-spaces"> <h3>Don’t separate attributes with two or more white spaces</h3> <p>Your weird formatting rule confuses someone.</p> <p>Bad:</p> <pre><code>&lt;input name=&quot;q&quot; type=&quot;search&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;input name=&quot;q&quot; type=&quot;search&quot;&gt;</code></pre> </section> <section id="omit-boolean-attribute-value"> <h3>Omit boolean attribute value</h3> <p>It’s easy to write, isn’t it?</p> <p>Bad:</p> <pre><code>&lt;audio autoplay=&quot;autoplay&quot; src=&quot;/audio/theme.mp3&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;audio autoplay src=&quot;/audio/theme.mp3&quot;&gt;</code></pre> </section> <section id="omit-namespaces"> <h3>Omit namespaces</h3> <p>SVG and MathML can be used directly in an HTML document.</p> <p>Bad:</p> <pre><code>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt; ... &lt;/svg&gt;</code></pre><p>Good:</p> <pre><code>&lt;svg&gt; ... &lt;/svg&gt;</code></pre> </section> <section id="dont-use-xml-attributes"> <h3>Don’t use XML attributes</h3> <p>We write an HTML document.</p> <p>Bad:</p> <pre><code>&lt;span lang=&quot;ja&quot; xml:lang=&quot;ja&quot;&gt;...&lt;/span&gt;</code></pre><p>Good:</p> <pre><code>&lt;span lang=&quot;ja&quot;&gt;...&lt;/span&gt;</code></pre> </section> <section id="dont-mix-data-microdata-and-rdfa-lite-attributes-with-common-attributes"> <h3>Don’t mix <code>data-*</code>, Microdata, and RDFa Lite attributes with common attributes</h3> <p>A tag string can be very complicated. This simple rule helps reading such tag string.</p> <p>Bad:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; data-height=&quot;31&quot; data-width=&quot;88&quot; itemprop=&quot;image&quot; src=&quot;/img/logo.png&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot; data-width=&quot;88&quot; data-height=&quot;31&quot; itemprop=&quot;image&quot;&gt;</code></pre> </section> <section id="prefer-default-implicit-aria-semantics"> <h3>Prefer default implicit ARIA semantics</h3> <p>Some element has an ARIA <code>role</code> implicitly in an HTML document, don’t specify it.</p> <p>Bad:</p> <pre><code>&lt;nav role=&quot;navigation&quot;&gt; ... &lt;/nav&gt; &lt;hr role=&quot;separator&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;nav&gt; ... &lt;/nav&gt; &lt;hr&gt;</code></pre> </section> </section> <section id="the-root-element"> <h2>The root element</h2> <section id="add-lang-attribute"> <h3>Add <code>lang</code> attribute</h3> <p><code>lang</code> attribute will help translating an HTML document.</p> <p>Bad:</p> <pre><code>&lt;html&gt;</code></pre><p>Good:</p> <pre><code>&lt;html lang=&quot;en-US&quot;&gt;</code></pre> </section> <section id="keep-lang-attribute-value-as-short-as-possible"> <h3>Keep <code>lang</code> attribute value as short as possible</h3> <p>Japanese is only used in Japan. So country code is not necessary.</p> <p>Bad:</p> <pre><code>&lt;html lang=&quot;ja-JP&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;html lang=&quot;ja&quot;&gt;</code></pre> </section> <section id="avoid-data-as-much-as-possible"> <h3>Avoid <code>data-*</code> as much as possible</h3> <p>An appropriate attribute can be handled properly by browsers.</p> <p>Bad:</p> <pre><code>&lt;span data-language=&quot;french&quot;&gt;chemises&lt;/span&gt; ... &lt;strong data-type=&quot;warning&quot;&gt;Do not wash!&lt;/strong&gt;</code></pre><p>Good:</p> <pre><code>&lt;span title=&quot;French&quot;&gt;&lt;span lang=&quot;fr-FR&quot;&gt;chemises&lt;/span&gt;&lt;/span&gt; ... &lt;strong class=&quot;warning&quot;&gt;Do not wash!&lt;/strong&gt;</code></pre> </section> </section> <section id="document-metadata"> <h2>Document metadata</h2> <section id="add-title-element"> <h3>Add <code>title</code> element</h3> <p>A value for <code>title</code> element is used by various application not only a browser.</p> <p>Bad:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;/head&gt;</code></pre><p>Good:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;HTML Best Practices&lt;/title&gt; &lt;/head&gt;</code></pre> </section> <section id="dont-use-base-element"> <h3>Don’t use <code>base</code> element</h3> <p>An absolute path or URL is safer for both developers and users.</p> <p>Bad:</p> <pre><code>&lt;head&gt; ... &lt;base href=&quot;/blog/&quot;&gt; &lt;link href=&quot;hello-world&quot; rel=&quot;canonical&quot;&gt; ... &lt;/head&gt;</code></pre><p>Good:</p> <pre><code>&lt;head&gt; ... &lt;link href=&quot;/blog/hello-world&quot; rel=&quot;canonical&quot;&gt; ... &lt;/head&gt;</code></pre> </section> <section id="specify-mime-type-of-minor-linked-resources"> <h3>Specify MIME type of minor linked resources</h3> <p>This is a hint how application handles this resource.</p> <p>Bad:</p> <pre><code>&lt;link href=&quot;/pdf&quot; rel=&quot;alternate&quot;&gt; &lt;link href=&quot;/feed&quot; rel=&quot;alternate&quot;&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;link href=&quot;/pdf&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt; &lt;link href=&quot;/feed&quot; rel=&quot;alternate&quot; type=&quot;application/rss+xml&quot;&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt;</code></pre> </section> <section id="dont-link-to-faviconico"> <h3>Don’t link to <code>favicon.ico</code></h3> <p>Almost all browsers fetch <code>/favicon.ico</code> automatically and asynchronously.</p> <p>Bad:</p> <pre><code>&lt;link href=&quot;/favicon.ico&quot; rel=&quot;icon&quot; type=&quot;image/vnd.microsoft.icon&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;!-- Place `favicon.ico` in the root directory. --&gt;</code></pre> </section> <section id="add-apple-touch-icon-link"> <h3>Add <code>apple-touch-icon</code> link</h3> <p>A default request path for touch icon was changed suddenly.</p> <p>Bad:</p> <pre><code>&lt;!-- Hey Apple! Please download `/apple-touch-icon.png`! --&gt;</code></pre><p>Good:</p> <pre><code>&lt;link href=&quot;/apple-touch-icon.png&quot; rel=&quot;apple-touch-icon&quot;&gt;</code></pre> </section> <section id="add-title-attribute-to-alternate-stylesheets"> <h3>Add <code>title</code> attribute to alternate stylesheets</h3> <p>A human readable label helps people selecting proper stylesheet.</p> <p>Bad:</p> <pre><code>&lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;link href=&quot;/css/high-contrast.css&quot; rel=&quot;alternate stylesheet&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;link href=&quot;/css/high-contrast.css&quot; rel=&quot;alternate stylesheet&quot; title=&quot;High contrast&quot;&gt;</code></pre> </section> <section id="for-url-use-link-element"> <h3>For URL, use <code>link</code> element</h3> <p>A value of <code>href</code> attribute can be resolved as URL.</p> <p>Bad:</p> <pre><code>&lt;section itemscope itemtype=&quot;http://schema.org/BlogPosting&quot;&gt; &lt;meta content=&quot;https://example.com/blog/hello&quot; itemprop=&quot;url&quot;&gt; ... &lt;/section&gt;</code></pre><p>Good:</p> <pre><code>&lt;section itemscope itemtype=&quot;http://schema.org/BlogPosting&quot;&gt; &lt;link href=&quot;/blog/hello&quot; itemprop=&quot;url&quot;&gt; ... &lt;/section&gt;</code></pre> </section> <section id="specify-document-character-encoding"> <h3>Specify document character encoding</h3> <p>UTF-8 is not default in all browsers yet.</p> <p>Bad:</p> <pre><code>&lt;head&gt; &lt;title&gt;HTML Best Practices&lt;/title&gt; &lt;/head&gt;</code></pre><p>Good:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;HTML Best Practices&lt;/title&gt; &lt;/head&gt;</code></pre> </section> <section id="dont-use-legacy-character-encoding-format"> <h3>Don’t use legacy character encoding format</h3> <p>HTTP headers should be specified by a server, be simple.</p> <p>Bad:</p> <pre><code>&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;meta charset=&quot;UTF-8&quot;&gt;</code></pre> </section> <section id="specify-character-encoding-at-first"> <h3>Specify character encoding at first</h3> <p>Spec requires the character encoding is specified within the first 1024 bytes of the document.</p> <p>Bad:</p> <pre><code>&lt;head&gt; &lt;meta content=&quot;width=device-width&quot; name=&quot;viewport&quot;&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; ... &lt;/head&gt;</code></pre><p>Good:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta content=&quot;width=device-width&quot; name=&quot;viewport&quot;&gt; ... &lt;/head&gt;</code></pre> </section> <section id="use-utf-8"> <h3>Use UTF-8</h3> <p>With UTF-8, you are free to use Emoji.</p> <p>Bad:</p> <pre><code>&lt;meta charset=&quot;Shift_JIS&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;meta charset=&quot;UTF-8&quot;&gt;</code></pre> </section> <section id="omit-type-attribute-for-css"> <h3>Omit <code>type</code> attribute for CSS</h3> <p>In HTML, default <code>type</code> attribute’s value of <code>style</code> element is <code>text/css</code>.</p> <p>Bad:</p> <pre><code>&lt;style type=&quot;text/css&quot;&gt; ... &lt;/style&gt;</code></pre><p>Good:</p> <pre><code>&lt;style&gt; ... &lt;/style&gt;</code></pre> </section> <section id="dont-comment-out-contents-of-style-element"> <h3>Don’t comment out contents of <code>style</code> element</h3> <p>This ritual is for the old browser.</p> <p>Bad:</p> <pre><code>&lt;style&gt; &lt;!-- ... --&gt; &lt;/style&gt;</code></pre><p>Good:</p> <pre><code>&lt;style&gt; ... &lt;/style&gt;</code></pre> </section> <section id="dont-mix-tag-for-css-and-javascript"> <h3>Don’t mix tag for CSS and JavaScript</h3> <p>Sometimes <code>script</code> element blocks DOM construction.</p> <p>Bad:</p> <pre><code>&lt;script src=&quot;/js/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;script src=&quot;/js/main.js&quot;&gt;&lt;/script&gt;</code></pre><p>Good:</p> <pre><code>&lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;script src=&quot;/js/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;/js/main.js&quot;&gt;&lt;/script&gt;</code></pre><p>Also good:</p> <pre><code>&lt;script src=&quot;/js/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;/js/main.js&quot;&gt;&lt;/script&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt;</code></pre> </section> </section> <section id="sections"> <h2>Sections</h2> <section id="add-body-element"> <h3>Add <code>body</code> element</h3> <p>Sometimes <code>body</code> element is complemented in unexpected position by a browser.</p> <p>Bad:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; ... &lt;/html&gt;</code></pre><p>Good:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre> </section> <section id="forget-about-hgroup-element"> <h3>Forget about <code>hgroup</code> element</h3> <p>This element is not used very much.</p> <p>Bad:</p> <pre><code>&lt;hgroup&gt; &lt;h1&gt;HTML Best Practices&lt;/h1&gt; &lt;h2&gt;For writing maintainable and scalable HTML documents.&lt;/h2&gt; &lt;/hgroup&gt;</code></pre><p>Good:</p> <pre><code>&lt;h1&gt;HTML Best Practices&lt;/h1&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt;</code></pre> </section> <section id="use-address-element-only-for-contact-information"> <h3>Use <code>address</code> element only for contact information</h3> <p><code>address</code> element is for email address, social network account, street address, telephone number, or something you can get in touch with.</p> <p>Bad:</p> <pre><code>&lt;address&gt;No rights reserved.&lt;/address&gt;</code></pre><p>Good:</p> <pre><code>&lt;address&gt;Contact: &lt;a href=&quot;https://twitter.com/hail2u_&quot;&gt;<NAME>&lt;/a&gt;&lt;/address&gt;</code></pre> </section> </section> <section id="grouping-content"> <h2>Grouping content</h2> <section id="dont-start-with-newline-in-pre-element"> <h3>Don’t start with newline in <code>pre</code> element</h3> <p>A first newline will ignored in the browsers, but second and later are rendered.</p> <p>Bad:</p> <pre><code>&lt;pre&gt; &amp;lt;!DOCTYPE html&amp;gt; &lt;/pre&gt;</code></pre><p>Good:</p> <pre><code>&lt;pre&gt;&amp;lt;!DOCTYPE html&amp;gt; &lt;/pre&gt;</code></pre> </section> <section id="use-appropriate-element-in-blockquote-element"> <h3>Use appropriate element in <code>blockquote</code> element</h3> <p><code>blockquote</code> element’s content is a quote, not a chunks of characters.</p> <p>Bad:</p> <pre><code>&lt;blockquote&gt;For writing maintainable and scalable HTML documents.&lt;/blockquote&gt;</code></pre><p>Good:</p> <pre><code>&lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;/blockquote&gt;</code></pre> </section> <section id="dont-include-attribution-directly-in-blockquote-element"> <h3>Don’t include attribution directly in <code>blockquote</code> element</h3> <p><code>blockquote</code> element’s content is a quote.</p> <p>Bad:</p> <pre><code>&lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;p&gt;— HTML Best Practices&lt;/p&gt; &lt;/blockquote&gt;</code></pre><p>Good:</p> <pre><code>&lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;/blockquote&gt; &lt;p&gt;— HTML Best Practices&lt;/p&gt;</code></pre><p>Also good:</p> <pre><code>&lt;figure&gt; &lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;/blockquote&gt; &lt;figcaption&gt;— HTML Best Practices&lt;/figcaption&gt; &lt;/figure&gt;</code></pre> </section> <section id="write-one-list-item-per-line"> <h3>Write one list item per line</h3> <p>Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line is hard toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo read.</p> <p>Bad:</p> <pre><code>&lt;ul&gt; &lt;li&gt;General&lt;/li&gt;&lt;li&gt;The root Element&lt;/li&gt;&lt;li&gt;Sections&lt;/li&gt;... &lt;/ul&gt;</code></pre><p>Good:</p> <pre><code>&lt;ul&gt; &lt;li&gt;General&lt;/li&gt; &lt;li&gt;The root Element&lt;/li&gt; &lt;li&gt;Sections&lt;/li&gt; ... &lt;/ul&gt;</code></pre> </section> <section id="use-type-attribute-for-ol-element"> <h3>Use <code>type</code> attribute for <code>ol</code> element</h3> <p>Sometimes marker referenced by the contents in the near. If you change marker with <code>type</code> attribute, you will be safe to reference.</p> <p>Bad:</p> <pre><code>&lt;head&gt; &lt;style&gt; .toc { list-style-type: upper-roman; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;ol class=&quot;toc&quot;&gt; &lt;li&gt;General&lt;/li&gt; &lt;li&gt;The root Element&lt;/li&gt; &lt;li&gt;Sections&lt;/li&gt; ... &lt;/ol&gt; &lt;/body&gt;</code></pre><p>Good:</p> <pre><code>&lt;body&gt; &lt;ol type=&quot;I&quot;&gt; &lt;li&gt;General&lt;/li&gt; &lt;li&gt;The root Element&lt;/li&gt; &lt;li&gt;Sections&lt;/li&gt; ... &lt;/ol&gt; &lt;/body&gt;</code></pre> </section> <section id="dont-use-dl-for-dialogue"> <h3>Don’t use <code>dl</code> for dialogue</h3> <p><code>dl</code> element is restricted to an association list in HTML.</p> <p>Bad:</p> <pre><code>&lt;dl&gt; &lt;dt&gt;Costello&lt;/dt&gt; &lt;dd&gt;Look, you gotta first baseman?&lt;/dd&gt; &lt;dt&gt;Abbott&lt;/dt&gt; &lt;dd&gt;Certainly.&lt;/dd&gt; &lt;dt&gt;Costello&lt;/dt&gt; &lt;dd&gt;Who’s playing first?&lt;/dd&gt; &lt;dt&gt;Abbott&lt;/dt&gt; &lt;dd&gt;That’s right.&lt;/dd&gt; &lt;dt&gt;Costello becomes exasperated.&lt;/dd&gt; &lt;dt&gt;Costello&lt;/dt&gt; &lt;dd&gt;When you pay off the first baseman every month, who gets the money?&lt;/dd&gt; &lt;dt&gt;Abbott&lt;/dt&gt; &lt;dd&gt;Every dollar of it.&lt;/dd&gt; &lt;/dl&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;Costello: Look, you gotta first baseman?&lt;/p&gt; &lt;p&gt;Abbott: Certainly.&lt;/p&gt; &lt;p&gt;Costello: Who’s playing first?&lt;/p&gt; &lt;p&gt;Abbott: That’s right.&lt;/p&gt; &lt;p&gt;Costello becomes exasperated.&lt;/p&gt; &lt;p&gt;Costello: When you pay off the first baseman every month, who gets the money?&lt;/p&gt; &lt;p&gt;Abbott: Every dollar of it.&lt;/p&gt;</code></pre> </section> <section id="place-figcaption-element-as-first-or-last-child-of-figure-element"> <h3>Place <code>figcaption</code> element as first or last child of <code>figure</code> element</h3> <p>Spec disallows <code>figcaption</code> element in the middle of <code>figure</code> element.</p> <p>Bad:</p> <pre><code>&lt;figure&gt; &lt;img alt=&quot;Front cover of the “HTML Best Practices” book&quot; src=&quot;/img/front-cover.png&quot;&gt; &lt;figcaption&gt;“HTML Best Practices” Cover Art&lt;/figcaption&gt; &lt;img alt=&quot;Back cover of the “HTML Best Practices” book&quot; src=&quot;/img/back-cover.png&quot;&gt; &lt;/figure&gt;</code></pre><p>Good:</p> <pre><code>&lt;figure&gt; &lt;img alt=&quot;Front cover of the “HTML Best Practices” book&quot; src=&quot;/img/front-cover.png&quot;&gt; &lt;img alt=&quot;Back cover of the “HTML Best Practices” book&quot; src=&quot;/img/back-cover.png&quot;&gt; &lt;figcaption&gt;“HTML Best Practices” Cover Art&lt;/figcaption&gt; &lt;/figure&gt;</code></pre> </section> <section id="use-main-element"> <h3>Use <code>main</code> element</h3> <p><code>main</code> element can be used wrapping contents.</p> <p>Bad:</p> <pre><code>&lt;div id=&quot;content&quot;&gt; ... &lt;/div&gt;</code></pre><p>Good:</p> <pre><code>&lt;main&gt; ... &lt;/main&gt;</code></pre> </section> <section id="avoid-div-element-as-much-as-possible"> <h3>Avoid <code>div</code> element as much as possible</h3> <p><code>div</code> element is an element of last resort.</p> <p>Bad:</p> <pre><code>&lt;div class=&quot;chapter&quot;&gt; ... &lt;/div&gt;</code></pre><p>Good:</p> <pre><code>&lt;section&gt; ... &lt;/section&gt;</code></pre> </section> </section> <section id="text-level-semantics"> <h2>Text-level semantics</h2> <section id="dont-split-same-link-that-can-be-grouped"> <h3>Don’t split same link that can be grouped</h3> <p><code>a</code> element can wrap almost all elements (except interactive elements like form controls and <code>a</code> element itself).</p> <p>Bad:</p> <pre><code>&lt;h1&gt;&lt;a href=&quot;https://whatwg.org/&quot;&gt;WHATWG&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;&lt;a href=&quot;https://whatwg.org/&quot;&gt;A community maintaining and evolving HTML since 2004.&lt;/a&gt;&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;a href=&quot;https://whatwg.org/&quot;&gt; &lt;h1&gt;WHATWG&lt;/h1&gt; &lt;p&gt;A community maintaining and evolving HTML since 2004.&lt;/p&gt; &lt;/a&gt;</code></pre> </section> <section id="use-download-attribute-for-downloading-a-resource"> <h3>Use <code>download</code> attribute for downloading a resource</h3> <p>It will force browsers to download linked resource to the storage.</p> <p>Bad:</p> <pre><code>&lt;a href=&quot;/downloads/offline.zip&quot;&gt;offline version&lt;/a&gt;</code></pre><p>Good:</p> <pre><code>&lt;a download href=&quot;/downloads/offline.zip&quot;&gt;offline version&lt;/a&gt;</code></pre> </section> <section id="use-rel-hreflang-and-type-attribute-if-needed"> <h3>Use <code>rel</code>, <code>hreflang</code>, and <code>type</code> attribute if needed</h3> <p>These hints helps applications how handle linked resource.</p> <p>Bad:</p> <pre><code>&lt;a href=&quot;/ja/pdf&quot;&gt;Japanese PDF version&lt;/a&gt;</code></pre><p>Good:</p> <pre><code>&lt;a href=&quot;/ja/pdf&quot; hreflang=&quot;ja&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt;Japanese PDF version&lt;/a&gt;</code></pre> </section> <section id="clear-link-text"> <h3>Clear link text</h3> <p>Link text should be the label of its linked resource.</p> <p>Bad:</p> <pre><code>&lt;p&gt;&lt;a href=&quot;/pdf&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt;Click here&lt;/a&gt; to view PDF version.&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;&lt;a href=&quot;/pdf&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt;PDF version&lt;/a&gt; is also available.&lt;/p&gt;</code></pre> </section> <section id="dont-use-em-element-for-warning-or-caution"> <h3>Don’t use <code>em</code> element for warning or caution</h3> <p>These are seriousness. So, <code>strong</code> element is more appropriate.</p> <p>Bad:</p> <pre><code>&lt;em&gt;Caution!&lt;/em&gt;</code></pre><p>Good:</p> <pre><code>&lt;strong&gt;Caution!&lt;/strong&gt;</code></pre> </section> <section id="avoid-s-i-b-and-u-element-as-much-as-possible"> <h3>Avoid <code>s</code>, <code>i</code>, <code>b</code>, and <code>u</code> element as much as possible</h3> <p>These elements’ semantics is too difficult to humans.</p> <p>Bad:</p> <pre><code>&lt;i class=&quot;icon-search&quot;&gt;&lt;/i&gt;</code></pre><p>Good:</p> <pre><code>&lt;span class=&quot;icon-search&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt;</code></pre> </section> <section id="dont-put-quotes-to-q-element"> <h3>Don’t put quotes to <code>q</code> element</h3> <p>Quotes are provided by the browser.</p> <p>Bad:</p> <pre><code>&lt;q&gt;“For writing maintainable and scalable HTML documents”&lt;/q&gt;</code></pre><p>Good:</p> <pre><code>&lt;q&gt;For writing maintainable and scalable HTML documents&lt;/q&gt;</code></pre><p>Also good:</p> <pre><code>“For writing maintainable and scalable HTML documents”</code></pre> </section> <section id="add-title-attribute-to-abbr-element"> <h3>Add <code>title</code> attribute to <code>abbr</code> element</h3> <p>There is no other way to represent its expansion.</p> <p>Bad:</p> <pre><code>&lt;abbr&gt;HBP&lt;/abbr&gt;</code></pre><p>Good:</p> <pre><code>&lt;abbr title=&quot;HTML Best Practices&quot;&gt;HBP&lt;/abbr&gt;</code></pre> </section> <section id="markup-ruby-element-verbosely"> <h3>Markup <code>ruby</code> element verbosely</h3> <p><code>ruby</code> element support is not completed across the modern browsers.</p> <p>Bad:</p> <pre><code>&lt;ruby&gt;HTML&lt;rt&gt;えいちてぃーえむえる&lt;/ruby&gt;</code></pre><p>Good:</p> <pre><code>&lt;ruby&gt;HTML&lt;rp&gt; (&lt;/rp&gt;&lt;rt&gt;えいちてぃーえむえる&lt;/rt&gt;&lt;rp&gt;) &lt;/rp&gt;&lt;/ruby&gt;</code></pre> </section> <section id="add-datetime-attribute-to-non-machine-readable-time-element"> <h3>Add <code>datetime</code> attribute to non-machine-readable <code>time</code> element</h3> <p>When <code>datetime</code> attribute does not present, the format of <code>time</code> element’s content is restricted.</p> <p>Bad:</p> <pre><code>&lt;time&gt;Dec 19, 2014&lt;/time&gt;</code></pre><p>Good:</p> <pre><code>&lt;time datetime=&quot;2014-12-19&quot;&gt;Dec 19, 2014&lt;/time&gt;</code></pre> </section> <section id="specify-code-language-with-class-attribute-prefixed-with-language"> <h3>Specify code language with <code>class</code> attribute prefixed with <code>language-</code></h3> <p>This is not a formal way, but spec mentions this.</p> <p>Bad:</p> <pre><code>&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;/code&gt;</code></pre><p>Good:</p> <pre><code>&lt;code class=&quot;language-html&quot;&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;/code&gt;</code></pre> </section> <section id="keep-kbd-element-as-simple-as-possible"> <h3>Keep <code>kbd</code> element as simple as possible</h3> <p>Nesting <code>kbd</code> element is too difficult to humans.</p> <p>Bad:</p> <pre><code>&lt;kbd&gt;&lt;kbd&gt;Ctrl&lt;/kbd&gt;+&lt;kbd&gt;F5&lt;/kbd&gt;&lt;/kbd&gt;</code></pre><p>Good:</p> <pre><code>&lt;kbd&gt;Ctrl+F5&lt;/kbd&gt;</code></pre> </section> <section id="avoid-span-element-as-much-as-possible"> <h3>Avoid <code>span</code> element as much as possible</h3> <p><code>span</code> element is an element of last resort.</p> <p>Bad:</p> <pre><code>HTML &lt;span class=&quot;best&quot;&gt;Best&lt;/span&gt; Practices</code></pre><p>Good:</p> <pre><code>HTML &lt;em&gt;Best&lt;/em&gt; Practices</code></pre> </section> <section id="break-after-br-element"> <h3>Break after <code>br</code> element</h3> <p>Line break should be needed where <code>br</code> element is used.</p> <p>Bad:</p> <pre><code>&lt;p&gt;HTML&lt;br&gt;Best&lt;br&gt;Practices&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;HTML&lt;br&gt; Best&lt;br&gt; Practices&lt;/p&gt;</code></pre> </section> <section id="dont-use-br-element-only-for-presentational-purpose"> <h3>Don’t use <code>br</code> element only for presentational purpose</h3> <p><code>br</code> element is not for line breaking, it is for line breaks in the contents.</p> <p>Bad:</p> <pre><code>&lt;p&gt;&lt;label&gt;Rule name: &lt;input name=&quot;rule-name&quot; type=&quot;text&quot;&gt;&lt;/label&gt;&lt;br&gt; &lt;label&gt;Rule description:&lt;br&gt; &lt;textarea name=&quot;rule-description&quot;&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;&lt;label&gt;Rule name: &lt;input name=&quot;rule-name&quot; type=&quot;text&quot;&gt;&lt;/label&gt;&lt;/p&gt; &lt;p&gt;&lt;label&gt;Rule description:&lt;br&gt; &lt;textarea name=&quot;rule-description&quot;&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;/p&gt;</code></pre> </section> </section> <section id="edits"> <h2>Edits</h2> <section id="dont-stride-ins-and-del-element-over-other-elements"> <h3>Don’t stride <code>ins</code> and <code>del</code> element over other elements</h3> <p>Elements cannot be overflow other elements.</p> <p>Bad:</p> <pre><code>&lt;p&gt;For writing maintainable and scalable HTML documents.&lt;del&gt; And for mental stability.&lt;/p&gt; &lt;p&gt;Don’t trust!&lt;/p&gt;&lt;/del&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;For writing maintainable and scalable HTML documents.&lt;del&gt; And for mental stability.&lt;/del&gt;&lt;/p&gt; &lt;del&gt;&lt;p&gt;Don’t trust!&lt;/p&gt;&lt;/del&gt;</code></pre> </section> </section> <section id="embedded-content"> <h2>Embedded content</h2> <section id="provide-fallback-img-element-for-picture-element"> <h3>Provide fallback <code>img</code> element for <code>picture</code> element</h3> <p>The support of <code>picture</code> element is not good yet.</p> <p>Bad:</p> <pre><code>&lt;picture&gt; &lt;source srcset=&quot;/img/logo.webp&quot; type=&quot;image/webp&quot;&gt; &lt;source srcset=&quot;/img/logo.hdp&quot; type=&quot;image/vnd.ms-photo&quot;&gt; &lt;source srcset=&quot;/img/logo.jp2&quot; type=&quot;image/jp2&quot;&gt; &lt;source srcset=&quot;/img/logo.jpg&quot; type=&quot;image/jpg&quot;&gt; &lt;/picture&gt;</code></pre><p>Good:</p> <pre><code>&lt;picture&gt; &lt;source srcset=&quot;/img/logo.webp&quot; type=&quot;image/webp&quot;&gt; &lt;source srcset=&quot;/img/logo.hdp&quot; type=&quot;image/vnd.ms-photo&quot;&gt; &lt;source srcset=&quot;/img/logo.jp2&quot; type=&quot;image/jp2&quot;&gt; &lt;img src=&quot;/img/logo.jpg&quot;&gt; &lt;/picture&gt;</code></pre> </section> <section id="add-alt-attrbute-to-img-element-if-needed"> <h3>Add <code>alt</code> attrbute to <code>img</code> element if needed</h3> <p><code>alt</code> attribute helps those who cannot process images or have image loading disabled.</p> <p>Bad:</p> <pre><code>&lt;img src=&quot;/img/logo.png&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot;&gt;</code></pre> </section> <section id="empty-alt-attribute-if-possible"> <h3>Empty <code>alt</code> attribute if possible</h3> <p>If the image is supplemental, there is equivalent content somewhere in the near.</p> <p>Bad:</p> <pre><code>&lt;img alt=&quot;Question mark icon&quot; src=&quot;/img/icon/help.png&quot;&gt; Help</code></pre><p>Good:</p> <pre><code>&lt;img alt=&quot;&quot; src=&quot;/img/icon/help.png&quot;&gt; Help</code></pre> </section> <section id="omit-alt-attribute-if-possible"> <h3>Omit <code>alt</code> attribute if possible</h3> <p>Sometimes you don’t know what text is suitable for <code>alt</code> attribute.</p> <p>Bad:</p> <pre><code>&lt;img alt=&quot;CAPTCHA&quot; src=&quot;captcha.cgi?id=82174&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;img src=&quot;captcha.cgi?id=82174&quot; title=&quot;CAPTCHA&quot;&gt; (If you cannot see the image, you can use an &lt;a href=&quot;?audio&quot;&gt;audio&lt;/a&gt; test instead.)</code></pre> </section> <section id="empty-iframe-element"> <h3>Empty <code>iframe</code> element</h3> <p>There is some restriction in its content. Being empty is always safe.</p> <p>Bad:</p> <pre><code>&lt;iframe src=&quot;/ads/default.html&quot;&gt; &lt;p&gt;If your browser support inline frame, ads are displayed here.&lt;/p&gt; &lt;/iframe&gt;</code></pre><p>Good:</p> <pre><code>&lt;iframe src=&quot;/ads/default.html&quot;&gt;&lt;/iframe&gt;</code></pre> </section> <section id="markup-map-element-content"> <h3>Markup <code>map</code> element content</h3> <p>This content presents to a screen reader.</p> <p>Bad:</p> <pre><code>&lt;map name=&quot;toc&quot;&gt; &lt;a href=&quot;#general&quot;&gt;General&lt;/a&gt; &lt;area alt=&quot;General&quot; coords=&quot;0, 0, 40, 40&quot; href=&quot;#General&quot;&gt; | &lt;a href=&quot;#the_root_element&quot;&gt;The root element&lt;/a&gt; &lt;area alt=&quot;The root element&quot; coords=&quot;50, 0, 90, 40&quot; href=&quot;#the_root_element&quot;&gt; | &lt;a href=&quot;#sections&quot;&gt;Sections&lt;/a&gt; &lt;area alt=&quot;Sections&quot; coords=&quot;100, 0, 140, 40&quot; href=&quot;#sections&quot;&gt; &lt;/map&gt;</code></pre><p>Good:</p> <pre><code>&lt;map name=&quot;toc&quot;&gt; &lt;p&gt; &lt;a href=&quot;#general&quot;&gt;General&lt;/a&gt; &lt;area alt=&quot;General&quot; coords=&quot;0, 0, 40, 40&quot; href=&quot;#General&quot;&gt; | &lt;a href=&quot;#the_root_element&quot;&gt;The root element&lt;/a&gt; &lt;area alt=&quot;The root element&quot; coords=&quot;50, 0, 90, 40&quot; href=&quot;#the_root_element&quot;&gt; | &lt;a href=&quot;#sections&quot;&gt;Sections&lt;/a&gt; &lt;area alt=&quot;Sections&quot; coords=&quot;100, 0, 140, 40&quot; href=&quot;#sections&quot;&gt; &lt;/p&gt; &lt;/map&gt;</code></pre> </section> <section id="provide-fallback-content-for-audio-or-video-element"> <h3>Provide fallback content for <code>audio</code> or <code>video</code> element</h3> <p>Fallback content is needed for newly introduced elements in HTML.</p> <p>Bad:</p> <pre><code>&lt;video&gt; &lt;source src=&quot;/mov/theme.mp4&quot; type=&quot;video/mp4&quot;&gt; &lt;source src=&quot;/mov/theme.ogv&quot; type=&quot;video/ogg&quot;&gt; ... &lt;/video&gt;</code></pre><p>Good:</p> <pre><code>&lt;video&gt; &lt;source src=&quot;/mov/theme.mp4&quot; type=&quot;video/mp4&quot;&gt; &lt;source src=&quot;/mov/theme.ogv&quot; type=&quot;video/ogg&quot;&gt; ... &lt;iframe src=&quot;//www.youtube.com/embed/...&quot; allowfullscreen&gt;&lt;/iframe&gt; &lt;/video&gt;</code></pre> </section> </section> <section id="tabular-data"> <h2>Tabular data</h2> <section id="write-one-cell-per-line"> <h3>Write one cell per line</h3> <p>Long lines are hard to scan.</p> <p>Bad:</p> <pre><code>&lt;tr&gt; &lt;td&gt;General&lt;/td&gt;&lt;td&gt;The root Element&lt;/td&gt;&lt;td&gt;Sections&lt;/td&gt; &lt;/tr&gt;</code></pre><p>Good:</p> <pre><code>&lt;tr&gt; &lt;td&gt;General&lt;/td&gt; &lt;td&gt;The root Element&lt;/td&gt; &lt;td&gt;Sections&lt;/td&gt; &lt;/tr&gt;</code></pre> </section> <section id="use-th-element-for-header-cell"> <h3>Use <code>th</code> element for header cell</h3> <p>There is no reason to avoid this.</p> <p>Bad:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;Element&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;Empty&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;Tag omission&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;&lt;code&gt;pre&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;No&lt;/td&gt; &lt;td&gt;Neither tag is omissible&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;&lt;code&gt;img&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;Yes&lt;/td&gt; &lt;td&gt;No end tag&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre><p>Good:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Element&lt;/th&gt; &lt;th&gt;Empty&lt;/th&gt; &lt;th&gt;Tag omission&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;&lt;code&gt;pre&lt;/code&gt;&lt;/th&gt; &lt;td&gt;No&lt;/td&gt; &lt;td&gt;Neither tag is omissible&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&lt;code&gt;img&lt;/code&gt;&lt;/th&gt; &lt;td&gt;Yes&lt;/td&gt; &lt;td&gt;No end tag&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </section> </section> <section id="forms"> <h2>Forms</h2> <section id="wrap-form-control-with-label-element"> <h3>Wrap form control with <code>label</code> element</h3> <p><code>label</code> element helps focusing form element.</p> <p>Bad:</p> <pre><code>&lt;p&gt;Query: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;&lt;label&gt;Query: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/label&gt;&lt;/p&gt;</code></pre> </section> <section id="omit-for-attribute-if-possible"> <h3>Omit <code>for</code> attribute if possible</h3> <p><code>label</code> element can contain some form elements.</p> <p>Bad:</p> <pre><code>&lt;label for=&quot;q&quot;&gt;Query: &lt;/label&gt;&lt;input id=&quot;q&quot; name=&quot;q&quot; type=&quot;text&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;label&gt;Query: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/label&gt;</code></pre> </section> <section id="use-appropriate-type-attribute-for-input-element"> <h3>Use appropriate <code>type</code> attribute for <code>input</code> element</h3> <p>With appropriate <code>type</code>, a browser gives tiny features to the <code>input</code> element.</p> <p>Bad:</p> <pre><code>&lt;label&gt;Search keyword: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/label&gt;</code></pre><p>Good:</p> <pre><code>&lt;label&gt;Search keyword: &lt;input name=&quot;q&quot; type=&quot;search&quot;&gt;&lt;/label&gt;</code></pre> </section> <section id="add-value-attribute-to-input-typesubmit"> <h3>Add <code>value</code> attribute to <code>input type=&quot;submit&quot;</code></h3> <p>The default label for submit button is not standarized across the browser and languages.</p> <p>Bad:</p> <pre><code>&lt;input type=&quot;submit&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;input type=&quot;submit&quot; value=&quot;Search&quot;&gt;</code></pre> </section> <section id="add-title-attribute-to-input-element-when-there-is-pattern-attribute"> <h3>Add <code>title</code> attribute to <code>input</code> element when there is <code>pattern</code> attribute</h3> <p>If input text does not match to <code>pattern</code> attribute, the value of <code>title</code> attribute will be display as a hint.</p> <p>Bad:</p> <pre><code>&lt;input name=&quot;security-code&quot; pattern=&quot;[0-9]{3}&quot; type=&quot;text&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;input name=&quot;security-code&quot; pattern=&quot;[0-9]{3}&quot; title=&quot;A security code is a number in three figures.&quot; type=&quot;text&quot;&gt;</code></pre> </section> <section id="dont-use-placeholder-attribute-for-labeling"> <h3>Don’t use <code>placeholder</code> attribute for labeling</h3> <p><code>label</code> element is for a label, <code>placeholder</code> attribute is for a short hint.</p> <p>Bad:</p> <pre><code>&lt;input name=&quot;email&quot; placeholder=&quot;Email&quot; type=&quot;text&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;label&gt;Email: &lt;input name=&quot;email&quot; placeholder=&quot;<EMAIL>&quot; type=&quot;text&quot;&gt;&lt;/label&gt;</code></pre> </section> <section id="write-one-option-element-per-line"> <h3>Write one <code>option</code> element per line</h3> <p>Long lines are hard to scan.</p> <p>Bad:</p> <pre><code>&lt;datalist id=&quot;toc&quot;&gt; &lt;option label=&quot;General&quot;&gt;&lt;option label=&quot;The root element&quot;&gt;&lt;option label=&quot;Sections&quot;&gt; &lt;/datalist&gt;</code></pre><p>Good:</p> <pre><code>&lt;datalist id=&quot;toc&quot;&gt; &lt;option label=&quot;General&quot;&gt; &lt;option label=&quot;The root element&quot;&gt; &lt;option label=&quot;Sections&quot;&gt; &lt;/datalist&gt;</code></pre> </section> <section id="add-max-attribute-to-progress-element"> <h3>Add <code>max</code> attribute to <code>progress</code> element</h3> <p>With <code>max</code> attribute, the <code>value</code> attribute can be write in an easy format.</p> <p>Bad:</p> <pre><code>&lt;progress value=&quot;0.5&quot;&gt; 50%&lt;/progress&gt;</code></pre><p>Good:</p> <pre><code>&lt;progress max=&quot;100&quot; value=&quot;50&quot;&gt; 50%&lt;/progress&gt;</code></pre> </section> <section id="add-min-and-max-attribute-to-meter-element"> <h3>Add <code>min</code> and <code>max</code> attribute to <code>meter</code> element</h3> <p>With <code>min</code> and <code>max</code> attribute, the <code>value</code> attribute can be write in an easy format.</p> <p>Bad:</p> <pre><code>&lt;meter value=&quot;0.5&quot;&gt; 512GB used (1024GB total)&lt;/meter&gt;</code></pre><p>Good:</p> <pre><code>&lt;meter min=&quot;0&quot; max=&quot;1024&quot; value=&quot;512&quot;&gt; 512GB used (1024GB total)&lt;/meter&gt;</code></pre> </section> <section id="place-legend-element-as-the-first-child-of-fieldset-element"> <h3>Place <code>legend</code> element as the first child of <code>fieldset</code> element</h3> <p>Spec requires this.</p> <p>Bad:</p> <pre><code>&lt;fieldset&gt; &lt;p&gt;&lt;label&gt;Is this section is useful?: &lt;input name=&quot;usefulness-general&quot; type=&quot;checkbox&quot;&gt;&lt;/label&gt;&lt;/p&gt; ... &lt;legend&gt;About &quot;General&quot;&lt;/legend&gt; &lt;/fieldset&gt;</code></pre><p>Good:</p> <pre><code>&lt;fieldset&gt; &lt;legend&gt;About &quot;General&quot;&lt;/legend&gt; &lt;p&gt;&lt;label&gt;Is this section is useful?: &lt;input name=&quot;usefulness-general&quot; type=&quot;checkbox&quot;&gt;&lt;/label&gt;&lt;/p&gt; ... &lt;/fieldset&gt;</code></pre> </section> </section> <section id="scripting"> <h2>Scripting</h2> <section id="omit-type-attribute-for-javascript"> <h3>Omit <code>type</code> attribute for JavaScript</h3> <p>In HTML, the default <code>type</code> attribute’s value of <code>script</code> element is <code>text/javascript</code>.</p> <p>Bad:</p> <pre><code>&lt;script type=&quot;text/javascript&quot;&gt; ... &lt;/script&gt;</code></pre><p>Good:</p> <pre><code>&lt;script&gt; ... &lt;/script&gt;</code></pre> </section> <section id="dont-comment-out-contents-of-script-element"> <h3>Don’t comment out contents of <code>script</code> element</h3> <p>This ritual is for the old browser.</p> <p>Bad:</p> <pre><code>&lt;script&gt; /*&lt;![CDATA[*/ ... /*]]&gt;*/ &lt;/script&gt;</code></pre><p>Also bad:</p> <pre><code>&lt;script&gt; &lt;!-- ... // --&gt; &lt;/script&gt;</code></pre><p>Good:</p> <pre><code>&lt;script&gt; ... &lt;/script&gt;</code></pre> </section> <section id="dont-use-script-injected-script-element"> <h3>Don’t use script-injected <code>script</code> element</h3> <p><code>async</code> attribute is the best for both simplicity and performance.</p> <p>Bad:</p> <pre><code>&lt;script&gt; var script = document.createElement(&quot;script&quot;); script.async = true; script.src = &quot;//example.com/widget.js&quot;; document.getElementsByTagName(&quot;head&quot;)[0].appendChild(script); &lt;/script&gt;</code></pre><p>Good:</p> <pre><code>&lt;script async defer src=&quot;https://example.com/widget.js&quot;&gt;&lt;/script&gt;</code></pre> </section> </section> <section id="other"> <h2>Other</h2> <section id="indent-consistently"> <h3>Indent consistently</h3> <p>Indentation is important for readability.</p> <p>Bad:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre><p>Good:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre> </section> <section id="use-absolute-path-for-internal-links"> <h3>Use absolute path for internal links</h3> <p>An absolute path works better on your localhost without internet connection.</p> <p>Bad:</p> <pre><code>&lt;link rel=&quot;apple-touch-icon&quot; href=&quot;http://you.example.com/apple-touch-icon-precomposed.png&quot;&gt; ... &lt;p&gt;You can find more at &lt;a href=&quot;//you.example.com/contact.html&quot;&gt;contact page&lt;/a&gt;.&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;link rel=&quot;apple-touch-icon&quot; href=&quot;/apple-touch-icon-precomposed.png&quot;&gt; ... &lt;p&gt;You can find more at &lt;a href=&quot;/contact.html&quot;&gt;contact page&lt;/a&gt;.&lt;/p&gt;</code></pre> </section> <section id="dont-use-protocol-relative-url-for-external-resources"> <h3>Don’t use protocol-relative URL for external resources</h3> <p>With protocol, you can load external resources reliably and safely.</p> <p>Bad:</p> <pre><code>&lt;script src=&quot;//example.com/js/library.js&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;script src=&quot;https://example.com/js/library.js&quot;&gt;</code></pre> </section> </section> <section id="contributors"> <h2>Contributors</h2> <ul> <li><a href="https://github.com/@hail2u_">hail2u_</a></li> <li><a href="https://github.com/@momdo">momdo</a></li> </ul> </section> <section id="translators"> <h2>Translators</h2> <ul> <li><a href="https://github.com/@techhtml">techhtml</a></li> <li><a href="https://github.com/@umutphp">umutphp</a></li> </ul> </section> <sections id="license"> <h2>License</h2> <p><a href="http:&#x2F;&#x2F;creativecommons.org&#x2F;publicdomain&#x2F;zero&#x2F;1.0&#x2F;">CC0</a></p> </section> </main> </body> </html> <|start_filename|>package-lock.json<|end_filename|> { "name": "html-best-practices", "version": "2.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "version": "2.0.0", "license": "CC0-1.0", "devDependencies": { "marked": "^2.0.0", "mustache": "4.1.0" } }, "node_modules/marked": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/marked/-/marked-2.0.0.tgz", "integrity": "<KEY> "dev": true, "bin": { "marked": "bin/marked" }, "engines": { "node": ">= 8.16.2" } }, "node_modules/mustache": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.1.0.tgz", "integrity": "<KEY> "dev": true, "bin": { "mustache": "bin/mustache" } } }, "dependencies": { "marked": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/marked/-/marked-2.0.0.tgz", "integrity": "<KEY> "dev": true }, "mustache": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.1.0.tgz", "integrity": "<KEY> "dev": true } } } <|start_filename|>src/en.json<|end_filename|> { "title": "HTML Best Practices", "description": "For writing maintainable and scalable HTML documents", "sections": [ { "title": "General" }, { "title": "The root element" }, { "title": "Document metadata" }, { "title": "Sections" }, { "title": "Grouping content" }, { "title": "Text-level semantics" }, { "title": "Edits" }, { "title": "Embedded content" }, { "title": "Tabular data" }, { "title": "Forms" }, { "title": "Scripting" }, { "title": "Other" } ] } <|start_filename|>docs/index.ko.html<|end_filename|> <html lang="ko"> <head> <meta charset="UTF-8"> <title>HTML Best Practices—유지보수 및 확장할 수 있는 HTML 문서를 만들기 위해</title> <meta content="유지보수 및 확장할 수 있는 HTML 문서를 만들기 위해" name="description"> <meta content="width=device-width" name=viewport> <link href="./index.ko.html" rel="canonical"> <style> body { font-family: sans-serif; line-height: 1.5; margin-left: auto; margin-right: auto; max-width: 42em; padding-left: 1em; padding-right: 1em; } h2 { margin-top: 4em; } h3 { margin-top: 3em; } p { overflow-wrap: break-word; } pre, code { font-family: monospace, monospace; font-size: 1em; } pre { background-color: whitesmoke; overflow-wrap: break-word; padding: 0.5em; white-space: pre-wrap; } </style> </head> <body> <nav> <h4>Translations</h4> <ul> <li><a href="./index.html">English (en)</a></li> <li><a href="./index.ja.html">日本語 (ja)</a></li> <li><a href="./index.ko.html">한국어 (ko)</a></li> <li><a href="./index.tr.html">Türkçe (tr)</a></li> </ul> </nav> <header> <h1>HTML Best Practices</h1> <p>유지보수 및 확장할 수 있는 HTML 문서를 만들기 위해</p> </header> <nav> <h4><abbr title="Table of Contents">ToC</abbr></h4> <ol> <li><a href="#general">공통</a> <ol> <li><a href="#start-with-doctype">DOCTYPE으로 시작해라</a> <li><a href="#dont-use-legacy-or-obsolete-doctype">레거시 혹은 폐기된 DOCTYPE을 쓰지 마라</a> <li><a href="#dont-use-xml-declaration">XML 선언을 쓰지 말아라</a> <li><a href="#dont-use-character-references-as-much-as-possible">문자 레퍼런스를 가능한 한 사용하지 말아라</a> <li><a href="#escape-amp-lt-gt-quot-and-apos-with-named-character-references"><code>&amp;</code>, <code>&lt;</code>, <code>&gt;</code>, <code>&quot;</code>, <code>&#39;</code>를 문자 레퍼런스로 변환해라</a> <li><a href="#use-numeric-character-references-for-control-or-invisible-characters">제어 문자나 보이지 않는 문자를 제어하기 위해 숫자 문자 레퍼런스를 사용하라</a> <li><a href="#put-white-spaces-around-comment-contents">주석 내용 주위에 공백을 넣어라</a> <li><a href="#dont-omit-closing-tag">닫는 태그를 생략하지 말아라</a> <li><a href="#dont-mix-empty-element-format">빈 요소 포맷을 섞지 마라</a> <li><a href="#dont-put-white-spaces-around-tags-and-attribute-values">태그 및 속성 값 사이에 공백문자를 넣지 말아라</a> <li><a href="#dont-mix-character-cases">대소문자를 섞지 말아라</a> <li><a href="#dont-mix-quotation-marks">인용 부호를 섞지 말아라</a> <li><a href="#dont-separate-attributes-with-two-or-more-white-spaces">속성을 두개 이상의 공백 문자로 나누지 마라</a> <li><a href="#omit-boolean-attribute-value">불리언 속성값을 생략해라</a> <li><a href="#omit-namespaces">네임스페이스를 생략해라</a> <li><a href="#dont-use-xml-attributes">XML 속성을 쓰지 마라</a> <li><a href="#dont-mix-data-microdata-and-rdfa-lite-attributes-with-common-attributes"><code>data-*</code>, 마이크로데이터, RDFa Lite 속성을 일반 속성과 섞어쓰지 마라</a> <li><a href="#prefer-default-implicit-aria-semantics">기본 암시적 ARIA 시맨틱을 선호하라</a> </ol> </li> <li><a href="#the-root-element">루트 요소</a> <ol> <li><a href="#add-lang-attribute"><code>lang</code> 속성을 추가해라</a> <li><a href="#keep-lang-attribute-value-as-short-as-possible"><code>lang</code> 속성을 가능하면 짧게 유지해라</a> <li><a href="#avoid-data-as-much-as-possible"><code>data-*</code>을 가능한 한 없애라</a> </ol> </li> <li><a href="#document-metadata">문서 메타데이터</a> <ol> <li><a href="#add-title-element"><code>title</code> 요소를 넣어라</a> <li><a href="#dont-use-base-element"><code>base</code> 요소를 쓰지 마라</a> <li><a href="#specify-mime-type-of-minor-linked-resources">마이너한 링크 리소스에 MIME 타입을 정의해라</a> <li><a href="#dont-link-to-faviconico"><code>favicon.ico</code> 링크하지 마라</a> <li><a href="#add-apple-touch-icon-link">Add <code>apple-touch-icon</code> link</a> <li><a href="#add-title-attribute-to-alternate-stylesheets">대체 스타일시트에 <code>title</code> 속성을 넣어라</a> <li><a href="#for-url-use-link-element">URL을 위해서 <code>link</code> 요소를 써라</a> <li><a href="#specify-document-character-encoding">문서의 문자 인코딩을 정의해라</a> <li><a href="#dont-use-legacy-character-encoding-format">레거시 인코딩 포맷을 쓰지 마라</a> <li><a href="#specify-character-encoding-at-first">문자 인코딩을 처음으로 선언해라</a> <li><a href="#use-utf-8">UTF-8을 써라</a> <li><a href="#omit-type-attribute-for-css">CSS를 위한 <code>type</code> 속성을 생략해라</a> <li><a href="#dont-comment-out-contents-of-style-element"><code>style</code> 요소의 내용을 주석처리하지 마라</a> <li><a href="#dont-mix-tag-for-css-and-javascript">CSS와 JavaScript 태그를 섞지 말아라</a> </ol> </li> <li><a href="#sections">섹션</a> <ol> <li><a href="#add-body-element"><code>body</code> 요소를 넣어라</a> <li><a href="#forget-about-hgroup-element"><code>hgroup</code> 요소는 잊어라</a> <li><a href="#use-address-element-only-for-contact-information"><code>address</code> 요소는 콘택트 정보를 제공하는 데만 써라</a> </ol> </li> <li><a href="#grouping-content">그룹 콘텐츠</a> <ol> <li><a href="#dont-start-with-newline-in-pre-element"><code>pre</code> 요소에서 새 줄로 시작하지 말아라</a> <li><a href="#use-appropriate-element-in-blockquote-element"><code>blockquote</code> 요소에 적절한 요소를 써라</a> <li><a href="#dont-include-attribution-directly-in-blockquote-element"><code>blockquote</code> 요소 안에 직접 포함하지 마라</a> <li><a href="#write-one-list-item-per-line">한 줄에 한 리스트 아이템을 써라</a> <li><a href="#use-type-attribute-for-ol-element"><code>ol</code> 요소에 <code>type</code> 속성을 써라</a> <li><a href="#dont-use-dl-for-dialogue">다이얼로그를 위해 <code>dl</code>을 쓰지 마라</a> <li><a href="#place-figcaption-element-as-first-or-last-child-of-figure-element"><code>figcaption</code> 요소를 <code>figure</code> 요소의 첫째 or 마지막 자식요소로 써라</a> <li><a href="#use-main-element"><code>main</code> 요소를 써라</a> <li><a href="#avoid-div-element-as-much-as-possible"><code>div</code> 요소를 가능한 한 많이 없애라</a> </ol> </li> <li><a href="#text-level-semantics">Text-level 시맨틱</a> <ol> <li><a href="#dont-split-same-link-that-can-be-grouped">그룹 가능한 동일 링크를 분리하지 마라</a> <li><a href="#use-download-attribute-for-downloading-a-resource">리소스를 다운하고자 할 때 <code>download</code> 속성을 사용하라</a> <li><a href="#use-rel-hreflang-and-type-attribute-if-needed">필요하다면 <code>rel</code>, <code>hreflang</code>, <code>type</code> 속성을 사용해라</a> <li><a href="#clear-link-text">링크 텍스트를 명확히 하라</a> <li><a href="#dont-use-em-element-for-warning-or-caution">경고나 주의를 위해 <code>em</code>을 사용하지 말아라</a> <li><a href="#avoid-s-i-b-and-u-element-as-much-as-possible"><code>s</code>, <code>i</code>, <code>b</code>, <code>u</code> 요소를 가능한 한 없애라</a> <li><a href="#dont-put-quotes-to-q-element"><code>q</code> 요소에 따옴표를 넣지 말아라</a> <li><a href="#add-title-attribute-to-abbr-element"><code>abbr</code> 요소에 <code>title</code> 속성을 써라</a> <li><a href="#markup-ruby-element-verbosely"><code>ruby</code> 요소를 자세히 마크업해라</a> <li><a href="#add-datetime-attribute-to-non-machine-readable-time-element">기계가 읽을 수 없는 <code>time</code> 요소에 <code>datetime</code> 속성을 추가해라</a> <li><a href="#specify-code-language-with-class-attribute-prefixed-with-language"><code>class</code> 속성 접두어로 <code>language-</code>를 넣어 code 언어를 정의하라</a> <li><a href="#keep-kbd-element-as-simple-as-possible"><code>kbd</code> 요소를 가능한 한 단순하게 둬라</a> <li><a href="#avoid-span-element-as-much-as-possible"><code>span</code> 요소를 가능한 한 많이 제거해라.</a> <li><a href="#break-after-br-element"><code>br</code> 요소 뒤에 줄바꿈해라</a> <li><a href="#dont-use-br-element-only-for-presentational-purpose">프레젠테이션 목적으로만 <code>br</code> 요소를 쓰지 마라</a> </ol> </li> <li><a href="#edits">에디트</a> <ol> <li><a href="#dont-stride-ins-and-del-element-over-other-elements"><code>ins</code>와 <code>del</code> 요소로 다른 요소를 뛰어넘지 마라</a> </ol> </li> <li><a href="#embedded-content">Embedded 콘텐츠</a> <ol> <li><a href="#provide-fallback-img-element-for-picture-element"><code>picture</code> 요소의 폴백으로 <code>img</code> 요소를 제공해라</a> <li><a href="#add-alt-attrbute-to-img-element-if-needed">만약 필요하다면 <code>img</code> 요소에 <code>alt</code> 속성을 추가해라</a> <li><a href="#empty-alt-attribute-if-possible">가능한 경우 <code>alt</code> 속성을 비워둬라</a> <li><a href="#omit-alt-attribute-if-possible">가능한 경우 <code>alt</code> 속성을 생략해라</a> <li><a href="#empty-iframe-element"><code>iframe</code> 요소를 비워둬라</a> <li><a href="#markup-map-element-content"><code>map</code> 요소 콘텐츠도 마크업해라</a> <li><a href="#provide-fallback-content-for-audio-or-video-element"><code>audio</code>나 <code>video</code> 요소를 위한 폴백 콘텐츠를 제공해라.</a> </ol> </li> <li><a href="#tabular-data">테이블 데이터</a> <ol> <li><a href="#write-one-cell-per-line">한 줄에 한 셀만 써라</a> <li><a href="#use-th-element-for-header-cell"><code>th</code> 요소를 헤더 셀로 써라</a> </ol> </li> <li><a href="#forms">폼</a> <ol> <li><a href="#wrap-form-control-with-label-element">폼 컨트롤을 <code>label</code> 요소로 감싸라</a> <li><a href="#omit-for-attribute-if-possible">가능한 경우 <code>for</code> 속성을 생략해라</a> <li><a href="#use-appropriate-type-attribute-for-input-element"><code>input</code> 요소에 적절한 <code>type</code> 속성을 사용해라</a> <li><a href="#add-value-attribute-to-input-typesubmit"><code>input type=&quot;submit&quot;</code>에 <code>value</code> 속성을 넣어라</a> <li><a href="#add-title-attribute-to-input-element-when-there-is-pattern-attribute"><code>input</code> 요소에 <code>pattern</code> 속성이 있는 경우 <code>title</code> 속성을 추가해라</a> <li><a href="#dont-use-placeholder-attribute-for-labeling">레이블하기 위해 <code>placeholder</code> 속성을 쓰지 마라</a> <li><a href="#write-one-option-element-per-line">한 줄에 한 <code>option</code> 요소만 사용해라</a> <li><a href="#add-max-attribute-to-progress-element"><code>progress</code> 요소에 <code>max</code> 속성을 추가해라</a> <li><a href="#add-min-and-max-attribute-to-meter-element"><code>meter</code> 요소에 <code>min</code>, <code>max</code> 속성을 추가해라</a> <li><a href="#place-legend-element-as-the-first-child-of-fieldset-element"><code>legend</code> 요소를 <code>fieldset</code> 요소의 첫번째 자식으로 둬라.</a> </ol> </li> <li><a href="#scripting">스크립트</a> <ol> <li><a href="#omit-type-attribute-for-javascript">자바스크립트를 위한 <code>type</code> 속성을 생략해라</a> <li><a href="#dont-comment-out-contents-of-script-element"><code>script</code> 요소의 내용을 주석처리하지 마라</a> <li><a href="#dont-use-script-injected-script-element">스크립트가 삽입된 <code>script</code> 요소를 쓰지 마라</a> </ol> </li> <li><a href="#other">기타</a> <ol> <li><a href="#indent-consistently">일관된 들여쓰기</a> <li><a href="#use-absolute-path-for-internal-links">내부 링크에 절대 경로를 사용해라</a> <li><a href="#dont-use-protocol-relative-url-for-external-resources">Don’t use protocol-relative URL for external resources</a> </ol> </li> <li><a href="#contributors">Contributors</a></li> <li><a href="#translators">Translators</a></li> <li><a href="#license">License</a></li> </ol> </nav> <main> <section id="general"> <h2>공통</h2> <section id="start-with-doctype"> <h3>DOCTYPE으로 시작해라</h3> <p>DOCTYPE은 표준 모드를 활성화하기 위해 필요하다.</p> <p>Bad:</p> <pre><code>&lt;html&gt; ... &lt;/html&gt;</code></pre><p>Good:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; ... &lt;/html&gt;</code></pre> </section> <section id="dont-use-legacy-or-obsolete-doctype"> <h3>레거시 혹은 폐기된 DOCTYPE을 쓰지 마라</h3> <p>DOCTYPE은 더 이상 DTD가 아니다, 간단해져라</p> <p>Bad:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;!DOCTYPE html&gt;</code></pre> </section> <section id="dont-use-xml-declaration"> <h3>XML 선언을 쓰지 말아라</h3> <p>정말 XHTML을 쓸거니?</p> <p>Bad:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt; &lt;!DOCTYPE html&gt;</code></pre><p>Good:</p> <pre><code>&lt;!DOCTYPE html&gt;</code></pre> </section> <section id="dont-use-character-references-as-much-as-possible"> <h3>문자 레퍼런스를 가능한 한 사용하지 말아라</h3> <p>만약 HTML문서를 UTF-8로 작성하고 있다면, 대부분의 문자(이모티콘 포함)를 직접적으로 쓸 수 있다.</p> <p>Bad:</p> <pre><code>&lt;p&gt;&lt;small&gt;Copyright &amp;copy; 2014 W3C&lt;sup&gt;&amp;reg;&lt;/sup&gt;&lt;/small&gt;&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;&lt;small&gt;Copyright © 2014 W3C&lt;sup&gt;®&lt;/sup&gt;&lt;/small&gt;&lt;/p&gt;</code></pre> </section> <section id="escape-amp-lt-gt-quot-and-apos-with-named-character-references"> <h3><code>&amp;</code>, <code>&lt;</code>, <code>&gt;</code>, <code>&quot;</code>, <code>&#39;</code>를 문자 레퍼런스로 변환해라</h3> <p>이 문자들은 버그가 없는 HTML 문서를 만들기위해 반드시 변환해두어야한다.</p> <p>Bad:</p> <pre><code>&lt;h1&gt;The &quot;&amp;&quot; character&lt;/h1&gt;</code></pre><p>Good:</p> <pre><code>&lt;h1&gt;The &amp;quot;&amp;amp;&amp;quot; character&lt;/h1&gt;</code></pre> </section> <section id="use-numeric-character-references-for-control-or-invisible-characters"> <h3>제어 문자나 보이지 않는 문자를 제어하기 위해 숫자 문자 레퍼런스를 사용하라</h3> <p>이 문자들은 다른 문자로 쉽게 오인된다. spec은 이러한 문자에 대해 사람이 읽을 수 있는 이름을 정의하는 걸 보장하지 않는다.</p> <p>Bad:</p> <pre><code>&lt;p&gt;This book can read in 1 hour.&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;This book can read in 1&amp;#xA0;hour.&lt;/p&gt;</code></pre> </section> <section id="put-white-spaces-around-comment-contents"> <h3>주석 내용 주위에 공백을 넣어라</h3> <p>일부 문자는 주석의 여는 태그 바로 뒤나 닫는 태그 바로 앞에 붙어서 넣을 수 없다.</p> <p>Bad:</p> <pre><code>&lt;!--This section is non-normative--&gt;</code></pre><p>Good:</p> <pre><code>&lt;!-- This section is non-normative --&gt;</code></pre> </section> <section id="dont-omit-closing-tag"> <h3>닫는 태그를 생략하지 말아라</h3> <p>내 생각엔 닫는 태그 생략 룰에 대해 이해하지 못했을 가능성이 높다.</p> <p>Bad:</p> <pre><code>&lt;html&gt; &lt;body&gt; ...</code></pre><p>Good:</p> <pre><code>&lt;html&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre> </section> <section id="dont-mix-empty-element-format"> <h3>빈 요소 포맷을 섞지 마라</h3> <p>일관성은 가독성의 핵심이다.</p> <p>Bad:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot;&gt; &lt;hr /&gt;</code></pre><p>Good:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot;&gt; &lt;hr&gt;</code></pre> </section> <section id="dont-put-white-spaces-around-tags-and-attribute-values"> <h3>태그 및 속성 값 사이에 공백문자를 넣지 말아라</h3> <p>그럴 이유가 없다.</p> <p>Bad:</p> <pre><code>&lt;h1 class=&quot; title &quot; &gt;HTML Best Practices&lt;/h1&gt;</code></pre><p>Good:</p> <pre><code>&lt;h1 class=&quot;title&quot;&gt;HTML Best Practices&lt;/h1&gt;</code></pre> </section> <section id="dont-mix-character-cases"> <h3>대소문자를 섞지 말아라</h3> <p>일관성을 줄거다.</p> <p>Bad:</p> <pre><code>&lt;a HREF=&quot;#general&quot;&gt;General&lt;/A&gt;</code></pre><p>Good:</p> <pre><code>&lt;a href=&quot;#general&quot;&gt;General&lt;/a&gt;</code></pre><p>Also Good:</p> <pre><code>&lt;A HREF=&quot;#general&quot;&gt;General&lt;/A&gt;</code></pre> </section> <section id="dont-mix-quotation-marks"> <h3>인용 부호를 섞지 말아라</h3> <p>위와 같다.</p> <p>Bad:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&#39;/img/logo.jpg&#39;&gt;</code></pre><p>Good:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.jpg&quot;&gt;</code></pre> </section> <section id="dont-separate-attributes-with-two-or-more-white-spaces"> <h3>속성을 두개 이상의 공백 문자로 나누지 마라</h3> <p>이상한 규칙이 누군가를 혼란하게 한다.</p> <p>Bad:</p> <pre><code>&lt;input name=&quot;q&quot; type=&quot;search&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;input name=&quot;q&quot; type=&quot;search&quot;&gt;</code></pre> </section> <section id="omit-boolean-attribute-value"> <h3>불리언 속성값을 생략해라</h3> <p>작성하기 쉽다, 안그래?</p> <p>Bad:</p> <pre><code>&lt;audio autoplay=&quot;autoplay&quot; src=&quot;/audio/theme.mp3&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;audio autoplay src=&quot;/audio/theme.mp3&quot;&gt;</code></pre> </section> <section id="omit-namespaces"> <h3>네임스페이스를 생략해라</h3> <p>HTML 문서에서 SVG와 MathML은 바로 쓸 수 있다.</p> <p>Bad:</p> <pre><code>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt; ... &lt;/svg&gt;</code></pre><p>Good:</p> <pre><code>&lt;svg&gt; ... &lt;/svg&gt;</code></pre> </section> <section id="dont-use-xml-attributes"> <h3>XML 속성을 쓰지 마라</h3> <p>우린 HTML 문서를 쓰고있다.</p> <p>Bad:</p> <pre><code>&lt;span lang=&quot;ja&quot; xml:lang=&quot;ja&quot;&gt;...&lt;/span&gt;</code></pre><p>Good:</p> <pre><code>&lt;span lang=&quot;ja&quot;&gt;...&lt;/span&gt;</code></pre> </section> <section id="dont-mix-data-microdata-and-rdfa-lite-attributes-with-common-attributes"> <h3><code>data-*</code>, 마이크로데이터, RDFa Lite 속성을 일반 속성과 섞어쓰지 마라</h3> <p>태그 문자열이 아주 복잡할 수 있다. 이 간단한 규칙은 태그 문자열을 더 읽기 쉽게한다.</p> <p>Bad:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; data-height=&quot;31&quot; data-width=&quot;88&quot; itemprop=&quot;image&quot; src=&quot;/img/logo.png&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot; data-width=&quot;88&quot; data-height=&quot;31&quot; itemprop=&quot;image&quot;&gt;</code></pre> </section> <section id="prefer-default-implicit-aria-semantics"> <h3>기본 암시적 ARIA 시맨틱을 선호하라</h3> <p>일부 요소에서는 HTML 문서에서 ARIA <code>role</code>을 가지므로 지정하지 마라.</p> <p>Bad:</p> <pre><code>&lt;nav role=&quot;navigation&quot;&gt; ... &lt;/nav&gt; &lt;hr role=&quot;separator&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;nav&gt; ... &lt;/nav&gt; &lt;hr&gt;</code></pre> </section> </section> <section id="the-root-element"> <h2>루트 요소</h2> <section id="add-lang-attribute"> <h3><code>lang</code> 속성을 추가해라</h3> <p><code>lang</code> 속성이 HTML 문서를 번역하는 데 도움을 줄거다.</p> <p>Bad:</p> <pre><code>&lt;html&gt;</code></pre><p>Good:</p> <pre><code>&lt;html lang=&quot;en-US&quot;&gt;</code></pre> </section> <section id="keep-lang-attribute-value-as-short-as-possible"> <h3><code>lang</code> 속성을 가능하면 짧게 유지해라</h3> <p>일본어는 Japan만 사용해라. 국가 코드는 필요없다.</p> <p>Bad:</p> <pre><code>&lt;html lang=&quot;ja-JP&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;html lang=&quot;ja&quot;&gt;</code></pre> </section> <section id="avoid-data-as-much-as-possible"> <h3><code>data-*</code>을 가능한 한 없애라</h3> <p>적절한 속성은 브라우저에서 처리할 수 있다.</p> <p>Bad:</p> <pre><code>&lt;span data-language=&quot;french&quot;&gt;chemises&lt;/span&gt; ... &lt;strong data-type=&quot;warning&quot;&gt;Do not wash!&lt;/strong&gt;</code></pre><p>Good:</p> <pre><code>&lt;span title=&quot;French&quot;&gt;&lt;span lang=&quot;fr-FR&quot;&gt;chemises&lt;/span&gt;&lt;/span&gt; ... &lt;strong class=&quot;warning&quot;&gt;Do not wash!&lt;/strong&gt;</code></pre> </section> </section> <section id="document-metadata"> <h2>문서 메타데이터</h2> <section id="add-title-element"> <h3><code>title</code> 요소를 넣어라</h3> <p><code>title</code> 요소 값은 브라우저뿐만 아니라 다양한 어플리케이션에서 사용한다.</p> <p>Bad:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;/head&gt;</code></pre><p>Good:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;HTML Best Practices&lt;/title&gt; &lt;/head&gt;</code></pre> </section> <section id="dont-use-base-element"> <h3><code>base</code> 요소를 쓰지 마라</h3> <p>절대 경로나 URL은 개발자와 유저 모두에게 안전하다</p> <p>Bad:</p> <pre><code>&lt;head&gt; ... &lt;base href=&quot;/blog/&quot;&gt; &lt;link href=&quot;hello-world&quot; rel=&quot;canonical&quot;&gt; ... &lt;/head&gt;</code></pre><p>Good:</p> <pre><code>&lt;head&gt; ... &lt;link href=&quot;/blog/hello-world&quot; rel=&quot;canonical&quot;&gt; ... &lt;/head&gt;</code></pre> </section> <section id="specify-mime-type-of-minor-linked-resources"> <h3>마이너한 링크 리소스에 MIME 타입을 정의해라</h3> <p>어플리케이션에서 리소스를 어떻게 처리하는 가에 대한 힌트다.</p> <p>Bad:</p> <pre><code>&lt;link href=&quot;/pdf&quot; rel=&quot;alternate&quot;&gt; &lt;link href=&quot;/feed&quot; rel=&quot;alternate&quot;&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;link href=&quot;/pdf&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt; &lt;link href=&quot;/feed&quot; rel=&quot;alternate&quot; type=&quot;application/rss+xml&quot;&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt;</code></pre> </section> <section id="dont-link-to-faviconico"> <h3><code>favicon.ico</code> 링크하지 마라</h3> <p>대부분의 브라우저에서 <code>/favicon.ico</code>를 자동으로 비동기방식으로 가져온다.</p> <p>Bad:</p> <pre><code>&lt;link href=&quot;/favicon.ico&quot; rel=&quot;icon&quot; type=&quot;image/vnd.microsoft.icon&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;!-- Place `favicon.ico` in the root directory. --&gt;</code></pre> </section> <section id="add-apple-touch-icon-link"> <h3>Add <code>apple-touch-icon</code> link</h3> <p>A default request path for touch icon was changed suddenly.</p> <p>Bad:</p> <pre><code>&lt;!-- Hey Apple! Please download `/apple-touch-icon.png`! --&gt;</code></pre><p>Good:</p> <pre><code>&lt;link href=&quot;/apple-touch-icon.png&quot; rel=&quot;apple-touch-icon&quot;&gt;</code></pre> </section> <section id="add-title-attribute-to-alternate-stylesheets"> <h3>대체 스타일시트에 <code>title</code> 속성을 넣어라</h3> <p>사람이 읽을 수 있는 레이블은 스타일시트를 선택하는 데 도움을 줄거다.</p> <p>Bad:</p> <pre><code>&lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;link href=&quot;/css/high-contrast.css&quot; rel=&quot;alternate stylesheet&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;link href=&quot;/css/high-contrast.css&quot; rel=&quot;alternate stylesheet&quot; title=&quot;High contrast&quot;&gt;</code></pre> </section> <section id="for-url-use-link-element"> <h3>URL을 위해서 <code>link</code> 요소를 써라</h3> <p><code>href</code> 속성 값이 URL로 해석된다.</p> <p>Bad:</p> <pre><code>&lt;section itemscope itemtype=&quot;http://schema.org/BlogPosting&quot;&gt; &lt;meta content=&quot;https://example.com/blog/hello&quot; itemprop=&quot;url&quot;&gt; ... &lt;/section&gt;</code></pre><p>Good:</p> <pre><code>&lt;section itemscope itemtype=&quot;http://schema.org/BlogPosting&quot;&gt; &lt;link href=&quot;/blog/hello&quot; itemprop=&quot;url&quot;&gt; ... &lt;/section&gt;</code></pre> </section> <section id="specify-document-character-encoding"> <h3>문서의 문자 인코딩을 정의해라</h3> <p>아직 UTF-8이 모든 브라우저에서 기본이 아니다.</p> <p>Bad:</p> <pre><code>&lt;head&gt; &lt;title&gt;HTML Best Practices&lt;/title&gt; &lt;/head&gt;</code></pre><p>Good:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;HTML Best Practices&lt;/title&gt; &lt;/head&gt;</code></pre> </section> <section id="dont-use-legacy-character-encoding-format"> <h3>레거시 인코딩 포맷을 쓰지 마라</h3> <p>HTTP 헤더는 서버에서 정의해야하며, 아주 쉽다.</p> <p>Bad:</p> <pre><code>&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;meta charset=&quot;UTF-8&quot;&gt;</code></pre> </section> <section id="specify-character-encoding-at-first"> <h3>문자 인코딩을 처음으로 선언해라</h3> <p>스펙상 문자 인코딩이 문서의 첫 1024 바이트 내에 지정되어있어야 한다.</p> <p>Bad:</p> <pre><code>&lt;head&gt; &lt;meta content=&quot;width=device-width&quot; name=&quot;viewport&quot;&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; ... &lt;/head&gt;</code></pre><p>Good:</p> <pre><code>&lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta content=&quot;width=device-width&quot; name=&quot;viewport&quot;&gt; ... &lt;/head&gt;</code></pre> </section> <section id="use-utf-8"> <h3>UTF-8을 써라</h3> <p>UTF-8과 함께라면, 이모티콘을 자유롭게 쓸 수 있다.</p> <p>Bad:</p> <pre><code>&lt;meta charset=&quot;Shift_JIS&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;meta charset=&quot;UTF-8&quot;&gt;</code></pre> </section> <section id="omit-type-attribute-for-css"> <h3>CSS를 위한 <code>type</code> 속성을 생략해라</h3> <p>HTML에서, <code>style</code> 요소의 기본 <code>type</code> 속성 값은 <code>text/css</code>다.</p> <p>Bad:</p> <pre><code>&lt;style type=&quot;text/css&quot;&gt; ... &lt;/style&gt;</code></pre><p>Good:</p> <pre><code>&lt;style&gt; ... &lt;/style&gt;</code></pre> </section> <section id="dont-comment-out-contents-of-style-element"> <h3><code>style</code> 요소의 내용을 주석처리하지 마라</h3> <p>이는 오랜 브라우저를 위한 것이다.</p> <p>Bad:</p> <pre><code>&lt;style&gt; &lt;!-- ... --&gt; &lt;/style&gt;</code></pre><p>Good:</p> <pre><code>&lt;style&gt; ... &lt;/style&gt;</code></pre> </section> <section id="dont-mix-tag-for-css-and-javascript"> <h3>CSS와 JavaScript 태그를 섞지 말아라</h3> <p>때론 <code>script</code> 요소가 DOM 구성을 막기도 한다.</p> <p>Bad:</p> <pre><code>&lt;script src=&quot;/js/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;script src=&quot;/js/main.js&quot;&gt;&lt;/script&gt;</code></pre><p>Good:</p> <pre><code>&lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;script src=&quot;/js/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;/js/main.js&quot;&gt;&lt;/script&gt;</code></pre><p>Also good:</p> <pre><code>&lt;script src=&quot;/js/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;/js/main.js&quot;&gt;&lt;/script&gt; &lt;link href=&quot;/css/screen.css&quot; rel=&quot;stylesheet&quot;&gt;</code></pre> </section> </section> <section id="sections"> <h2>섹션</h2> <section id="add-body-element"> <h3><code>body</code> 요소를 넣어라</h3> <p>때로 <code>body</code>를 브라우저에서 넣을 때 원치 않은 위치에 있기도 한다.</p> <p>Bad:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; ... &lt;/html&gt;</code></pre><p>Good:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre> </section> <section id="forget-about-hgroup-element"> <h3><code>hgroup</code> 요소는 잊어라</h3> <p>W3C 스펙에서 삭제되었다.</p> <p>Bad:</p> <pre><code>&lt;hgroup&gt; &lt;h1&gt;HTML Best Practices&lt;/h1&gt; &lt;h2&gt;For writing maintainable and scalable HTML documents.&lt;/h2&gt; &lt;/hgroup&gt;</code></pre><p>Good:</p> <pre><code>&lt;h1&gt;HTML Best Practices&lt;/h1&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt;</code></pre> </section> <section id="use-address-element-only-for-contact-information"> <h3><code>address</code> 요소는 콘택트 정보를 제공하는 데만 써라</h3> <p><code>address</code> 요소는 이메일 주소, 소셜 네트워크 계정, 주소, 전화번호 등 직접 연락할 수 있는 항목이다.</p> <p>Bad:</p> <pre><code>&lt;address&gt;No rights reserved.&lt;/address&gt;</code></pre><p>Good:</p> <pre><code>&lt;address&gt;Contact: &lt;a href=&quot;https://twitter.com/hail2u_&quot;&gt;Kyo Nagashima&lt;/a&gt;&lt;/address&gt;</code></pre> </section> </section> <section id="grouping-content"> <h2>그룹 콘텐츠</h2> <section id="dont-start-with-newline-in-pre-element"> <h3><code>pre</code> 요소에서 새 줄로 시작하지 말아라</h3> <p>첫번째 줄바꿈은 브라우저에서 무시하지만, 두번째부터는 렌더링된다.</p> <p>Bad:</p> <pre><code>&lt;pre&gt; &amp;lt;!DOCTYPE html&amp;gt; &lt;/pre&gt;</code></pre><p>Good:</p> <pre><code>&lt;pre&gt;&amp;lt;!DOCTYPE html&amp;gt; &lt;/pre&gt;</code></pre> </section> <section id="use-appropriate-element-in-blockquote-element"> <h3><code>blockquote</code> 요소에 적절한 요소를 써라</h3> <p><code>blockquote</code> 요소의 콘텐츠는 인용한 내용이지, 문장 덩어리가 아니다.</p> <p>Bad:</p> <pre><code>&lt;blockquote&gt;For writing maintainable and scalable HTML documents.&lt;/blockquote&gt;</code></pre><p>Good:</p> <pre><code>&lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;/blockquote&gt;</code></pre> </section> <section id="dont-include-attribution-directly-in-blockquote-element"> <h3><code>blockquote</code> 요소 안에 직접 포함하지 마라</h3> <p><code>blockquote</code> 요소의 콘텐츠는 인용구다.</p> <p>Bad:</p> <pre><code>&lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;p&gt;— HTML Best Practices&lt;/p&gt; &lt;/blockquote&gt;</code></pre><p>Good:</p> <pre><code>&lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;/blockquote&gt; &lt;p&gt;— HTML Best Practices&lt;/p&gt;</code></pre><p>Also good (recommended by WHATWG):</p> <pre><code>&lt;figure&gt; &lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;/blockquote&gt; &lt;figcaption&gt;— HTML Best Practices&lt;/figcaption&gt; &lt;/figure&gt;</code></pre><p>Also good too (recommended by W3C):</p> <pre><code>&lt;blockquote&gt; &lt;p&gt;For writing maintainable and scalable HTML documents.&lt;/p&gt; &lt;footer&gt;— HTML Best Practices&lt;/footer&gt; &lt;/blockquote&gt;</code></pre> </section> <section id="write-one-list-item-per-line"> <h3>한 줄에 한 리스트 아이템을 써라</h3> <p>기이ㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣㅣ인 라인은 너무ㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜ 읽기 힘들다.</p> <p>Bad:</p> <pre><code>&lt;ul&gt; &lt;li&gt;General&lt;/li&gt;&lt;li&gt;The root Element&lt;/li&gt;&lt;li&gt;Sections&lt;/li&gt;... &lt;/ul&gt;</code></pre><p>Good:</p> <pre><code>&lt;ul&gt; &lt;li&gt;General&lt;/li&gt; &lt;li&gt;The root Element&lt;/li&gt; &lt;li&gt;Sections&lt;/li&gt; ... &lt;/ul&gt;</code></pre> </section> <section id="use-type-attribute-for-ol-element"> <h3><code>ol</code> 요소에 <code>type</code> 속성을 써라</h3> <p>때로는 주변 콘텐츠에 의해 마커가 참조된다. 만약 <code>type</code> 속성으로 마커를 변경한다면, 참조하는 것이 안전하다.</p> <p>Bad:</p> <pre><code>&lt;head&gt; &lt;style&gt; .toc { list-style-type: upper-roman; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;ol class=&quot;toc&quot;&gt; &lt;li&gt;General&lt;/li&gt; &lt;li&gt;The root Element&lt;/li&gt; &lt;li&gt;Sections&lt;/li&gt; ... &lt;/ol&gt; &lt;/body&gt;</code></pre><p>Good:</p> <pre><code>&lt;body&gt; &lt;ol type=&quot;I&quot;&gt; &lt;li&gt;General&lt;/li&gt; &lt;li&gt;The root Element&lt;/li&gt; &lt;li&gt;Sections&lt;/li&gt; ... &lt;/ol&gt; &lt;/body&gt;</code></pre> </section> <section id="dont-use-dl-for-dialogue"> <h3>다이얼로그를 위해 <code>dl</code>을 쓰지 마라</h3> <p><code>dl</code> 요소는 HTML의 연결 목록으로 제한한다.</p> <p>Bad:</p> <pre><code>&lt;dl&gt; &lt;dt&gt;Costello&lt;/dt&gt; &lt;dd&gt;Look, you gotta first baseman?&lt;/dd&gt; &lt;dt&gt;Abbott&lt;/dt&gt; &lt;dd&gt;Certainly.&lt;/dd&gt; &lt;dt&gt;Costello&lt;/dt&gt; &lt;dd&gt;Who’s playing first?&lt;/dd&gt; &lt;dt&gt;Abbott&lt;/dt&gt; &lt;dd&gt;That’s right.&lt;/dd&gt; &lt;dt&gt;Costello becomes exasperated.&lt;/dd&gt; &lt;dt&gt;Costello&lt;/dt&gt; &lt;dd&gt;When you pay off the first baseman every month, who gets the money?&lt;/dd&gt; &lt;dt&gt;Abbott&lt;/dt&gt; &lt;dd&gt;Every dollar of it.&lt;/dd&gt; &lt;/dl&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;Costello: Look, you gotta first baseman?&lt;/p&gt; &lt;p&gt;Abbott: Certainly.&lt;/p&gt; &lt;p&gt;Costello: Who’s playing first?&lt;/p&gt; &lt;p&gt;Abbott: That’s right.&lt;/p&gt; &lt;p&gt;Costello becomes exasperated.&lt;/p&gt; &lt;p&gt;Costello: When you pay off the first baseman every month, who gets the money?&lt;/p&gt; &lt;p&gt;Abbott: Every dollar of it.&lt;/p&gt;</code></pre> </section> <section id="place-figcaption-element-as-first-or-last-child-of-figure-element"> <h3><code>figcaption</code> 요소를 <code>figure</code> 요소의 첫째 or 마지막 자식요소로 써라</h3> <p>스펙 (WHATWG 버전)에서 <code>figcaption</code> 요소를 <code>figure</code> 요소 중간에 두는 걸 허용하지 않는다.</p> <p>Bad:</p> <pre><code>&lt;figure&gt; &lt;img alt=&quot;Front cover of the “HTML Best Practices” book&quot; src=&quot;/img/front-cover.png&quot;&gt; &lt;figcaption&gt;“HTML Best Practices” Cover Art&lt;/figcaption&gt; &lt;img alt=&quot;Back cover of the “HTML Best Practices” book&quot; src=&quot;/img/back-cover.png&quot;&gt; &lt;/figure&gt;</code></pre><p>Good:</p> <pre><code>&lt;figure&gt; &lt;img alt=&quot;Front cover of the “HTML Best Practices” book&quot; src=&quot;/img/front-cover.png&quot;&gt; &lt;img alt=&quot;Back cover of the “HTML Best Practices” book&quot; src=&quot;/img/back-cover.png&quot;&gt; &lt;figcaption&gt;“HTML Best Practices” Cover Art&lt;/figcaption&gt; &lt;/figure&gt;</code></pre> </section> <section id="use-main-element"> <h3><code>main</code> 요소를 써라</h3> <p><code>main</code> 요소는 콘텐츠를 감쌀 때 쓸 수 있다.</p> <p>Bad:</p> <pre><code>&lt;div id=&quot;content&quot;&gt; ... &lt;/div&gt;</code></pre><p>Good:</p> <pre><code>&lt;main&gt; ... &lt;/main&gt;</code></pre> </section> <section id="avoid-div-element-as-much-as-possible"> <h3><code>div</code> 요소를 가능한 한 많이 없애라</h3> <p><code>div</code> 요소는 최후의 수단이다.</p> <p>Bad:</p> <pre><code>&lt;div class=&quot;chapter&quot;&gt; ... &lt;/div&gt;</code></pre><p>Good:</p> <pre><code>&lt;section&gt; ... &lt;/section&gt;</code></pre> </section> </section> <section id="text-level-semantics"> <h2>Text-level 시맨틱</h2> <section id="dont-split-same-link-that-can-be-grouped"> <h3>그룹 가능한 동일 링크를 분리하지 마라</h3> <p><code>a</code> 요소는 대부분의 요소를 감쌀 수 있다. (<code>a</code> 요소 자신이나 컨트롤같은 인터렉티브 요소는 제외한다)</p> <p>Bad:</p> <pre><code>&lt;h1&gt;&lt;a href=&quot;https://whatwg.org/&quot;&gt;WHATWG&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;&lt;a href=&quot;https://whatwg.org/&quot;&gt;A community maintaining and evolving HTML since 2004.&lt;/a&gt;&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;a href=&quot;https://whatwg.org/&quot;&gt; &lt;h1&gt;WHATWG&lt;/h1&gt; &lt;p&gt;A community maintaining and evolving HTML since 2004.&lt;/p&gt; &lt;/a&gt;</code></pre> </section> <section id="use-download-attribute-for-downloading-a-resource"> <h3>리소스를 다운하고자 할 때 <code>download</code> 속성을 사용하라</h3> <p>브라우저에서 연결된 리소스를 스토리지에서 다운받으려 할거다.</p> <p>Bad:</p> <pre><code>&lt;a href=&quot;/downloads/offline.zip&quot;&gt;offline version&lt;/a&gt;</code></pre><p>Good:</p> <pre><code>&lt;a download href=&quot;/downloads/offline.zip&quot;&gt;offline version&lt;/a&gt;</code></pre> </section> <section id="use-rel-hreflang-and-type-attribute-if-needed"> <h3>필요하다면 <code>rel</code>, <code>hreflang</code>, <code>type</code> 속성을 사용해라</h3> <p>이러한 힌트는 어플리케이션에서 연결된 리소스를 제어하는 데 사용한다.</p> <p>Bad:</p> <pre><code>&lt;a href=&quot;/ja/pdf&quot;&gt;Japanese PDF version&lt;/a&gt;</code></pre><p>Good:</p> <pre><code>&lt;a href=&quot;/ja/pdf&quot; hreflang=&quot;ja&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt;Japanese PDF version&lt;/a&gt;</code></pre> </section> <section id="clear-link-text"> <h3>링크 텍스트를 명확히 하라</h3> <p>링크 텍스트는 연결된 리소스의 레이블이어야한다.</p> <p>Bad:</p> <pre><code>&lt;p&gt;&lt;a href=&quot;/pdf&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt;Click here&lt;/a&gt; to view PDF version.&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;&lt;a href=&quot;/pdf&quot; rel=&quot;alternate&quot; type=&quot;application/pdf&quot;&gt;PDF version&lt;/a&gt; is also available.&lt;/p&gt;</code></pre> </section> <section id="dont-use-em-element-for-warning-or-caution"> <h3>경고나 주의를 위해 <code>em</code>을 사용하지 말아라</h3> <p>이것들은 심각하다. 따라서 <code>storng</code> 요소가 더 적절하다.</p> <p>Bad:</p> <pre><code>&lt;em&gt;Caution!&lt;/em&gt;</code></pre><p>Good:</p> <pre><code>&lt;strong&gt;Caution!&lt;/strong&gt;</code></pre> </section> <section id="avoid-s-i-b-and-u-element-as-much-as-possible"> <h3><code>s</code>, <code>i</code>, <code>b</code>, <code>u</code> 요소를 가능한 한 없애라</h3> <p>이 요소의 시맨틱은 사람과 아주 다르다.</p> <p>Bad:</p> <pre><code>&lt;i class=&quot;icon-search&quot;&gt;&lt;/i&gt;</code></pre><p>Good:</p> <pre><code>&lt;span class=&quot;icon-search&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt;</code></pre> </section> <section id="dont-put-quotes-to-q-element"> <h3><code>q</code> 요소에 따옴표를 넣지 말아라</h3> <p>브라우저에서 제공한다.</p> <p>Bad:</p> <pre><code>&lt;q&gt;“For writing maintainable and scalable HTML documents”&lt;/q&gt;</code></pre><p>Good:</p> <pre><code>&lt;q&gt;For writing maintainable and scalable HTML documents&lt;/q&gt;</code></pre><p>Also good:</p> <pre><code>“For writing maintainable and scalable HTML documents”</code></pre> </section> <section id="add-title-attribute-to-abbr-element"> <h3><code>abbr</code> 요소에 <code>title</code> 속성을 써라</h3> <p>무엇의 함축어인 지 달리 설명할 길이 없다.</p> <p>Bad:</p> <pre><code>&lt;abbr&gt;HBP&lt;/abbr&gt;</code></pre><p>Good:</p> <pre><code>&lt;abbr title=&quot;HTML Best Practices&quot;&gt;HBP&lt;/abbr&gt;</code></pre> </section> <section id="markup-ruby-element-verbosely"> <h3><code>ruby</code> 요소를 자세히 마크업해라</h3> <p><code>ruby</code> 요소를 모든 모던 브라우저에서 완전하게 지원하는 게 아니다.</p> <p>Bad:</p> <pre><code>&lt;ruby&gt;HTML&lt;rt&gt;えいちてぃーえむえる&lt;/ruby&gt;</code></pre><p>Good:</p> <pre><code>&lt;ruby&gt;HTML&lt;rp&gt; (&lt;/rp&gt;&lt;rt&gt;えいちてぃーえむえる&lt;/rt&gt;&lt;rp&gt;) &lt;/rp&gt;&lt;/ruby&gt;</code></pre> </section> <section id="add-datetime-attribute-to-non-machine-readable-time-element"> <h3>기계가 읽을 수 없는 <code>time</code> 요소에 <code>datetime</code> 속성을 추가해라</h3> <p><code>datetime</code> 속성이 없을 때, <code>time</code> 요소의 포맷은 제한된다.</p> <p>Bad:</p> <pre><code>&lt;time&gt;Dec 19, 2014&lt;/time&gt;</code></pre><p>Good:</p> <pre><code>&lt;time datetime=&quot;2014-12-19&quot;&gt;Dec 19, 2014&lt;/time&gt;</code></pre> </section> <section id="specify-code-language-with-class-attribute-prefixed-with-language"> <h3><code>class</code> 속성 접두어로 <code>language-</code>를 넣어 code 언어를 정의하라</h3> <p>일반적이진 않지만, spec에 언급되어있다.</p> <p>Bad:</p> <pre><code>&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;/code&gt;</code></pre><p>Good:</p> <pre><code>&lt;code class=&quot;language-html&quot;&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;/code&gt;</code></pre> </section> <section id="keep-kbd-element-as-simple-as-possible"> <h3><code>kbd</code> 요소를 가능한 한 단순하게 둬라</h3> <p><code>kbd</code> 요소를 감싸는 건 사람과 다르다.</p> <p>Bad:</p> <pre><code>&lt;kbd&gt;&lt;kbd&gt;Ctrl&lt;/kbd&gt;+&lt;kbd&gt;F5&lt;/kbd&gt;&lt;/kbd&gt;</code></pre><p>Good:</p> <pre><code>&lt;kbd&gt;Ctrl+F5&lt;/kbd&gt;</code></pre> </section> <section id="avoid-span-element-as-much-as-possible"> <h3><code>span</code> 요소를 가능한 한 많이 제거해라.</h3> <p><code>span</code> 요소는 최후의 수단이다.</p> <p>Bad:</p> <pre><code>HTML &lt;span class=&quot;best&quot;&gt;Best&lt;/span&gt; Practices</code></pre><p>Good:</p> <pre><code>HTML &lt;em&gt;Best&lt;/em&gt; Practices</code></pre> </section> <section id="break-after-br-element"> <h3><code>br</code> 요소 뒤에 줄바꿈해라</h3> <p><code>br</code> 요소를 사용하면 줄바꿈 하는 게 좋다.</p> <p>Bad:</p> <pre><code>&lt;p&gt;HTML&lt;br&gt;Best&lt;br&gt;Practices&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;HTML&lt;br&gt; Best&lt;br&gt; Practices&lt;/p&gt;</code></pre> </section> <section id="dont-use-br-element-only-for-presentational-purpose"> <h3>프레젠테이션 목적으로만 <code>br</code> 요소를 쓰지 마라</h3> <p><code>br</code> 요소는 줄바꿈을 위해서가 아니라, 콘텐츠의 라인 구분을 위해 사용한다.</p> <p>Bad:</p> <pre><code>&lt;p&gt;&lt;label&gt;Rule name: &lt;input name=&quot;rule-name&quot; type=&quot;text&quot;&gt;&lt;/label&gt;&lt;br&gt; &lt;label&gt;Rule description:&lt;br&gt; &lt;textarea name=&quot;rule-description&quot;&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;&lt;label&gt;Rule name: &lt;input name=&quot;rule-name&quot; type=&quot;text&quot;&gt;&lt;/label&gt;&lt;/p&gt; &lt;p&gt;&lt;label&gt;Rule description:&lt;br&gt; &lt;textarea name=&quot;rule-description&quot;&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;/p&gt;</code></pre> </section> </section> <section id="edits"> <h2>에디트</h2> <section id="dont-stride-ins-and-del-element-over-other-elements"> <h3><code>ins</code>와 <code>del</code> 요소로 다른 요소를 뛰어넘지 마라</h3> <p>요소는 다른 요소를 넘을 수 없다.</p> <p>Bad:</p> <pre><code>&lt;p&gt;For writing maintainable and scalable HTML documents.&lt;del&gt; And for mental stability.&lt;/p&gt; &lt;p&gt;Don’t trust!&lt;/p&gt;&lt;/del&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;For writing maintainable and scalable HTML documents.&lt;del&gt; And for mental stability.&lt;/del&gt;&lt;/p&gt; &lt;del&gt;&lt;p&gt;Don’t trust!&lt;/p&gt;&lt;/del&gt;</code></pre> </section> </section> <section id="embedded-content"> <h2>Embedded 콘텐츠</h2> <section id="provide-fallback-img-element-for-picture-element"> <h3><code>picture</code> 요소의 폴백으로 <code>img</code> 요소를 제공해라</h3> <p><code>picture</code> 요소 지원율이 아직 그렇게 높지 않다.</p> <p>Bad:</p> <pre><code>&lt;picture&gt; &lt;source srcset=&quot;/img/logo.webp&quot; type=&quot;image/webp&quot;&gt; &lt;source srcset=&quot;/img/logo.hdp&quot; type=&quot;image/vnd.ms-photo&quot;&gt; &lt;source srcset=&quot;/img/logo.jp2&quot; type=&quot;image/jp2&quot;&gt; &lt;source srcset=&quot;/img/logo.jpg&quot; type=&quot;image/jpg&quot;&gt; &lt;/picture&gt;</code></pre><p>Good:</p> <pre><code>&lt;picture&gt; &lt;source srcset=&quot;/img/logo.webp&quot; type=&quot;image/webp&quot;&gt; &lt;source srcset=&quot;/img/logo.hdp&quot; type=&quot;image/vnd.ms-photo&quot;&gt; &lt;source srcset=&quot;/img/logo.jp2&quot; type=&quot;image/jp2&quot;&gt; &lt;img src=&quot;/img/logo.jpg&quot;&gt; &lt;/picture&gt;</code></pre> </section> <section id="add-alt-attrbute-to-img-element-if-needed"> <h3>만약 필요하다면 <code>img</code> 요소에 <code>alt</code> 속성을 추가해라</h3> <p><code>alt</code> 속성은 이미지를 처리할 수 없거나 불러오지 못했을 때 도움을 준다.</p> <p>Bad:</p> <pre><code>&lt;img src=&quot;/img/logo.png&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;img alt=&quot;HTML Best Practices&quot; src=&quot;/img/logo.png&quot;&gt;</code></pre> </section> <section id="empty-alt-attribute-if-possible"> <h3>가능한 경우 <code>alt</code> 속성을 비워둬라</h3> <p>본문을 보충하는 이미지라면, 근처에 동일한 콘텐츠가 있다.</p> <p>Bad:</p> <pre><code>&lt;img alt=&quot;Question mark icon&quot; src=&quot;/img/icon/help.png&quot;&gt; Help</code></pre><p>Good:</p> <pre><code>&lt;img alt=&quot;&quot; src=&quot;/img/icon/help.png&quot;&gt; Help</code></pre> </section> <section id="omit-alt-attribute-if-possible"> <h3>가능한 경우 <code>alt</code> 속성을 생략해라</h3> <p>때때로 어떤 텍스트가 alt 속성에 적합한 지 모를 수 있다. (역주) spec에서 <code>alt</code> 속성은 특수한 케이스가 아니라면 필수 속성이므로 빈값으로 넣어주세요.</p> <p>Bad:</p> <pre><code>&lt;img alt=&quot;CAPTCHA&quot; src=&quot;captcha.cgi?id=82174&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;img src=&quot;captcha.cgi?id=82174&quot; title=&quot;CAPTCHA&quot;&gt; (If you cannot see the image, you can use an &lt;a href=&quot;?audio&quot;&gt;audio&lt;/a&gt; test instead.)</code></pre> </section> <section id="empty-iframe-element"> <h3><code>iframe</code> 요소를 비워둬라</h3> <p>콘텐츠에 몇가지 제한사항이 있다. 비워두면 항상 안전하다.</p> <p>Bad:</p> <pre><code>&lt;iframe src=&quot;/ads/default.html&quot;&gt; &lt;p&gt;If your browser support inline frame, ads are displayed here.&lt;/p&gt; &lt;/iframe&gt;</code></pre><p>Good:</p> <pre><code>&lt;iframe src=&quot;/ads/default.html&quot;&gt;&lt;/iframe&gt;</code></pre> </section> <section id="markup-map-element-content"> <h3><code>map</code> 요소 콘텐츠도 마크업해라</h3> <p>스크린 리더의 콘텐츠 프리셋으로 쓰인다.</p> <p>Bad:</p> <pre><code>&lt;map name=&quot;toc&quot;&gt; &lt;a href=&quot;#general&quot;&gt;General&lt;/a&gt; &lt;area alt=&quot;General&quot; coords=&quot;0, 0, 40, 40&quot; href=&quot;#General&quot;&gt; | &lt;a href=&quot;#the_root_element&quot;&gt;The root element&lt;/a&gt; &lt;area alt=&quot;The root element&quot; coords=&quot;50, 0, 90, 40&quot; href=&quot;#the_root_element&quot;&gt; | &lt;a href=&quot;#sections&quot;&gt;Sections&lt;/a&gt; &lt;area alt=&quot;Sections&quot; coords=&quot;100, 0, 140, 40&quot; href=&quot;#sections&quot;&gt; &lt;/map&gt;</code></pre><p>Good:</p> <pre><code>&lt;map name=&quot;toc&quot;&gt; &lt;p&gt; &lt;a href=&quot;#general&quot;&gt;General&lt;/a&gt; &lt;area alt=&quot;General&quot; coords=&quot;0, 0, 40, 40&quot; href=&quot;#General&quot;&gt; | &lt;a href=&quot;#the_root_element&quot;&gt;The root element&lt;/a&gt; &lt;area alt=&quot;The root element&quot; coords=&quot;50, 0, 90, 40&quot; href=&quot;#the_root_element&quot;&gt; | &lt;a href=&quot;#sections&quot;&gt;Sections&lt;/a&gt; &lt;area alt=&quot;Sections&quot; coords=&quot;100, 0, 140, 40&quot; href=&quot;#sections&quot;&gt; &lt;/p&gt; &lt;/map&gt;</code></pre> </section> <section id="provide-fallback-content-for-audio-or-video-element"> <h3><code>audio</code>나 <code>video</code> 요소를 위한 폴백 콘텐츠를 제공해라.</h3> <p>HTML에 새로 추가된 요소들을 위해 폴백 콘텐츠가 필요하다.</p> <p>Bad:</p> <pre><code>&lt;video&gt; &lt;source src=&quot;/mov/theme.mp4&quot; type=&quot;video/mp4&quot;&gt; &lt;source src=&quot;/mov/theme.ogv&quot; type=&quot;video/ogg&quot;&gt; ... &lt;/video&gt;</code></pre><p>Good:</p> <pre><code>&lt;video&gt; &lt;source src=&quot;/mov/theme.mp4&quot; type=&quot;video/mp4&quot;&gt; &lt;source src=&quot;/mov/theme.ogv&quot; type=&quot;video/ogg&quot;&gt; ... &lt;iframe src=&quot;//www.youtube.com/embed/...&quot; allowfullscreen&gt;&lt;/iframe&gt; &lt;/video&gt;</code></pre> </section> </section> <section id="tabular-data"> <h2>테이블 데이터</h2> <section id="write-one-cell-per-line"> <h3>한 줄에 한 셀만 써라</h3> <p>긴 라인은 스캔하기 힘들다.</p> <p>Bad:</p> <pre><code>&lt;tr&gt; &lt;td&gt;General&lt;/td&gt;&lt;td&gt;The root Element&lt;/td&gt;&lt;td&gt;Sections&lt;/td&gt; &lt;/tr&gt;</code></pre><p>Good:</p> <pre><code>&lt;tr&gt; &lt;td&gt;General&lt;/td&gt; &lt;td&gt;The root Element&lt;/td&gt; &lt;td&gt;Sections&lt;/td&gt; &lt;/tr&gt;</code></pre> </section> <section id="use-th-element-for-header-cell"> <h3><code>th</code> 요소를 헤더 셀로 써라</h3> <p>안 쓸 이유가 없다.</p> <p>Bad:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;Element&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;Empty&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;Tag omission&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;&lt;code&gt;pre&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;No&lt;/td&gt; &lt;td&gt;Neither tag is omissible&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;&lt;code&gt;img&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;Yes&lt;/td&gt; &lt;td&gt;No end tag&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre><p>Good:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Element&lt;/th&gt; &lt;th&gt;Empty&lt;/th&gt; &lt;th&gt;Tag omission&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;&lt;code&gt;pre&lt;/code&gt;&lt;/th&gt; &lt;td&gt;No&lt;/td&gt; &lt;td&gt;Neither tag is omissible&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&lt;code&gt;img&lt;/code&gt;&lt;/th&gt; &lt;td&gt;Yes&lt;/td&gt; &lt;td&gt;No end tag&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </section> </section> <section id="forms"> <h2>폼</h2> <section id="wrap-form-control-with-label-element"> <h3>폼 컨트롤을 <code>label</code> 요소로 감싸라</h3> <p><code>label</code> 요소가 폼 요소에 포커스를 주는 데 도움을 준다</p> <p>Bad:</p> <pre><code>&lt;p&gt;Query: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;p&gt;&lt;label&gt;Query: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/label&gt;&lt;/p&gt;</code></pre> </section> <section id="omit-for-attribute-if-possible"> <h3>가능한 경우 <code>for</code> 속성을 생략해라</h3> <p><code>label</code> 요소는 몇가지 폼 요소를 감쌀 수 있다.</p> <p>Bad:</p> <pre><code>&lt;label for=&quot;q&quot;&gt;Query: &lt;/label&gt;&lt;input id=&quot;q&quot; name=&quot;q&quot; type=&quot;text&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;label&gt;Query: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/label&gt;</code></pre> </section> <section id="use-appropriate-type-attribute-for-input-element"> <h3><code>input</code> 요소에 적절한 <code>type</code> 속성을 사용해라</h3> <p>적절한 <code>type</code>을 사용하면, 브라우저에서 <code>input</code> 요소에 작은 기능을 제공한다.</p> <p>Bad:</p> <pre><code>&lt;label&gt;Search keyword: &lt;input name=&quot;q&quot; type=&quot;text&quot;&gt;&lt;/label&gt;</code></pre><p>Good:</p> <pre><code>&lt;label&gt;Search keyword: &lt;input name=&quot;q&quot; type=&quot;search&quot;&gt;&lt;/label&gt;</code></pre> </section> <section id="add-value-attribute-to-input-typesubmit"> <h3><code>input type=&quot;submit&quot;</code>에 <code>value</code> 속성을 넣어라</h3> <p>submit 버튼의 기본 레이블은 브라우저 및 언어 사이 표준이 없다.</p> <p>Bad:</p> <pre><code>&lt;input type=&quot;submit&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;input type=&quot;submit&quot; value=&quot;Search&quot;&gt;</code></pre> </section> <section id="add-title-attribute-to-input-element-when-there-is-pattern-attribute"> <h3><code>input</code> 요소에 <code>pattern</code> 속성이 있는 경우 <code>title</code> 속성을 추가해라</h3> <p>입력한 텍스트가 <code>pattern</code> 속성과 매치하지 않는 경우, <code>title</code> 속성의 값이 힌트가 될거다.</p> <p>Bad:</p> <pre><code>&lt;input name=&quot;security-code&quot; pattern=&quot;[0-9]{3}&quot; type=&quot;text&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;input name=&quot;security-code&quot; pattern=&quot;[0-9]{3}&quot; title=&quot;A security code is a number in three figures.&quot; type=&quot;text&quot;&gt;</code></pre> </section> <section id="dont-use-placeholder-attribute-for-labeling"> <h3>레이블하기 위해 <code>placeholder</code> 속성을 쓰지 마라</h3> <p><code>label</code> 요소가 레이블을 위한 요소고, <code>placeholder</code> 속성은 짧은 힌트를 위한 속성이다.</p> <p>Bad:</p> <pre><code>&lt;input name=&quot;email&quot; placeholder=&quot;Email&quot; type=&quot;text&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;label&gt;Email: &lt;input name=&quot;email&quot; placeholder=&quot;<EMAIL>&quot; type=&quot;text&quot;&gt;&lt;/label&gt;</code></pre> </section> <section id="write-one-option-element-per-line"> <h3>한 줄에 한 <code>option</code> 요소만 사용해라</h3> <p>긴 라인은 읽기 힘들다.</p> <p>Bad:</p> <pre><code>&lt;datalist id=&quot;toc&quot;&gt; &lt;option label=&quot;General&quot;&gt;&lt;option label=&quot;The root element&quot;&gt;&lt;option label=&quot;Sections&quot;&gt; &lt;/datalist&gt;</code></pre><p>Good:</p> <pre><code>&lt;datalist id=&quot;toc&quot;&gt; &lt;option label=&quot;General&quot;&gt; &lt;option label=&quot;The root element&quot;&gt; &lt;option label=&quot;Sections&quot;&gt; &lt;/datalist&gt;</code></pre> </section> <section id="add-max-attribute-to-progress-element"> <h3><code>progress</code> 요소에 <code>max</code> 속성을 추가해라</h3> <p><code>max</code> 속성을 통해, <code>value</code> 속성을 쉬운 포맷으로 쓸 수 있다.</p> <p>Bad:</p> <pre><code>&lt;progress value=&quot;0.5&quot;&gt; 50%&lt;/progress&gt;</code></pre><p>Good:</p> <pre><code>&lt;progress max=&quot;100&quot; value=&quot;50&quot;&gt; 50%&lt;/progress&gt;</code></pre> </section> <section id="add-min-and-max-attribute-to-meter-element"> <h3><code>meter</code> 요소에 <code>min</code>, <code>max</code> 속성을 추가해라</h3> <p><code>min</code>, <code>max</code> 속성을 통해, <code>value</code> 속성을 쉬운 포맷으로 쓸 수 있다.</p> <p>Bad:</p> <pre><code>&lt;meter value=&quot;0.5&quot;&gt; 512GB used (1024GB total)&lt;/meter&gt;</code></pre><p>Good:</p> <pre><code>&lt;meter min=&quot;0&quot; max=&quot;1024&quot; value=&quot;512&quot;&gt; 512GB used (1024GB total)&lt;/meter&gt;</code></pre> </section> <section id="place-legend-element-as-the-first-child-of-fieldset-element"> <h3><code>legend</code> 요소를 <code>fieldset</code> 요소의 첫번째 자식으로 둬라.</h3> <p>스펙 필수 사항이다.</p> <p>Bad:</p> <pre><code>&lt;fieldset&gt; &lt;p&gt;&lt;label&gt;Is this section is useful?: &lt;input name=&quot;usefulness-general&quot; type=&quot;checkbox&quot;&gt;&lt;/label&gt;&lt;/p&gt; ... &lt;legend&gt;About &quot;General&quot;&lt;/legend&gt; &lt;/fieldset&gt;</code></pre><p>Good:</p> <pre><code>&lt;fieldset&gt; &lt;legend&gt;About &quot;General&quot;&lt;/legend&gt; &lt;p&gt;&lt;label&gt;Is this section is useful?: &lt;input name=&quot;usefulness-general&quot; type=&quot;checkbox&quot;&gt;&lt;/label&gt;&lt;/p&gt; ... &lt;/fieldset&gt;</code></pre> </section> </section> <section id="scripting"> <h2>스크립트</h2> <section id="omit-type-attribute-for-javascript"> <h3>자바스크립트를 위한 <code>type</code> 속성을 생략해라</h3> <p>HTML에서, <code>script</code> 요소의 기본 <code>type</code> 속성값은 <code>text/javascript</code>다.</p> <p>Bad:</p> <pre><code>&lt;script type=&quot;text/javascript&quot;&gt; ... &lt;/script&gt;</code></pre><p>Good:</p> <pre><code>&lt;script&gt; ... &lt;/script&gt;</code></pre> </section> <section id="dont-comment-out-contents-of-script-element"> <h3><code>script</code> 요소의 내용을 주석처리하지 마라</h3> <p>이는 오랜 브라우저를 위한 것이다.</p> <p>Bad:</p> <pre><code>&lt;script&gt; /*&lt;![CDATA[*/ ... /*]]&gt;*/ &lt;/script&gt;</code></pre><p>Also bad:</p> <pre><code>&lt;script&gt; &lt;!-- ... // --&gt; &lt;/script&gt;</code></pre><p>Good:</p> <pre><code>&lt;script&gt; ... &lt;/script&gt;</code></pre> </section> <section id="dont-use-script-injected-script-element"> <h3>스크립트가 삽입된 <code>script</code> 요소를 쓰지 마라</h3> <p><code>async</code> 속성은 성능면으로나 단순성면으로나 최고다.</p> <p>Bad:</p> <pre><code>&lt;script&gt; var script = document.createElement(&quot;script&quot;); script.async = true; script.src = &quot;//example.com/widget.js&quot;; document.getElementsByTagName(&quot;head&quot;)[0].appendChild(script); &lt;/script&gt;</code></pre><p>Good:</p> <pre><code>&lt;script async defer src=&quot;https://example.com/widget.js&quot;&gt;&lt;/script&gt;</code></pre> </section> </section> <section id="other"> <h2>기타</h2> <section id="indent-consistently"> <h3>일관된 들여쓰기</h3> <p>일관성은 가독성에 중요하다.</p> <p>Bad:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre><p>Good:</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; &lt;body&gt; ... &lt;/body&gt; &lt;/html&gt;</code></pre> </section> <section id="use-absolute-path-for-internal-links"> <h3>내부 링크에 절대 경로를 사용해라</h3> <p>절대 경로는 인터넷 연결 없이도 localhost에서도 동작한다.</p> <p>Bad:</p> <pre><code>&lt;link rel=&quot;apple-touch-icon&quot; href=&quot;http://you.example.com/apple-touch-icon-precomposed.png&quot;&gt; ... &lt;p&gt;You can find more at &lt;a href=&quot;//you.example.com/contact.html&quot;&gt;contact page&lt;/a&gt;.&lt;/p&gt;</code></pre><p>Good:</p> <pre><code>&lt;link rel=&quot;apple-touch-icon&quot; href=&quot;/apple-touch-icon-precomposed.png&quot;&gt; ... &lt;p&gt;You can find more at &lt;a href=&quot;/contact.html&quot;&gt;contact page&lt;/a&gt;.&lt;/p&gt;</code></pre> </section> <section id="dont-use-protocol-relative-url-for-external-resources"> <h3>Don’t use protocol-relative URL for external resources</h3> <p>With protocol, you can load external resources reliably and safely.</p> <p>Bad:</p> <pre><code>&lt;script src=&quot;//example.com/js/library.js&quot;&gt;</code></pre><p>Good:</p> <pre><code>&lt;script src=&quot;https://example.com/js/library.js&quot;&gt;</code></pre> </section> </section> <section id="contributors"> <h2>Contributors</h2> <ul> <li><a href="https://github.com/@hail2u_">hail2u_</a></li> <li><a href="https://github.com/@momdo">momdo</a></li> </ul> </section> <section id="translators"> <h2>Translators</h2> <ul> <li><a href="https://github.com/@techhtml">techhtml</a></li> <li><a href="https://github.com/@umutphp">umutphp</a></li> </ul> </section> <sections id="license"> <h2>License</h2> <p><a href="http:&#x2F;&#x2F;creativecommons.org&#x2F;publicdomain&#x2F;zero&#x2F;1.0&#x2F;">CC0</a></p> </section> </main> </body> </html>
ustab/html-best-practices
<|start_filename|>cli.js<|end_filename|> #!/usr/bin/env node const meow = require("meow") const updateNotifier = require("update-notifier") const KnownError = require("./lib/error") const initCommand = require("./lib/cli/init-command") const deployCommand = require("./lib/cli/deploy-command") const distributeCommand = require("./lib/cli/distribute-command") const ConfigurationPath = ".discharge.json" const cli = meow(` Usage $ discharge init $ discharge deploy $ discharge distribute `) updateNotifier({ pkg: cli.pkg }).notify() let command = cli.input[0] switch (command) { case undefined: return cli.showHelp() case "init": return initCommand(ConfigurationPath).catch(KnownError.catch) case "deploy": return deployCommand(ConfigurationPath).catch(KnownError.catch) case "distribute": return distributeCommand(ConfigurationPath).catch(KnownError.catch) } <|start_filename|>lib/configuration.js<|end_filename|> const fs = require("fs") const KnownError = require("./error").error const logSymbols = require("log-symbols") const read = (configurationPath) => { if (!fs.existsSync(configurationPath)) { throw new KnownError("No configuration file, run `discharge init` first") } let file = fs.readFileSync(configurationPath) try { let configuration = JSON.parse(file) if (configuration.hasOwnProperty("trailing_slashes")) { delete configuration["trailing_slashes"] write(configurationPath, configuration) console.log( `\n${logSymbols.warning}`, "Removing unused `trailing_slashes` configuration option", "\n", ) } return configuration } catch (error) { throw new KnownError("Configuration file cannot be parsed—ensure the JSON is valid") } } module.exports.read = read const write = (configurationPath, configuration) => { let json = JSON.stringify(configuration, null, 2) return fs.writeFileSync(configurationPath, `${json}\n`) } module.exports.write = write module.exports.update = (configurationPath, updatedConfiguration) => { let configuration = read(configurationPath) configuration = Object.assign(configuration, updatedConfiguration) return write(configurationPath, configuration) } <|start_filename|>lib/configure.js<|end_filename|> const AWS = require("./aws") const inquirer = require("inquirer") const intersperse = require("./utilities").intersperse const flatten = require("./utilities").flatten let choices = Object.values(AWS.regionsGroupedByPrefix()).map((regionGroup) => { return regionGroup.map((region) => { return { name: region.name, value: region.key } }) }) let choicesWithSeparators = flatten(intersperse(choices, new inquirer.Separator())) let redirectsPrompt = async (array) => { let answers = await inquirer.prompt([ { name: "prefix_match", message: "Prefix to match on?", type: "input", }, { name: "destination", message: "Destination to redirect to?", type: "input", }, { name: "again", message: "Do you want to setup another redirect?", default: true, type: "confirm", }, ]) array.push({ prefix_match: answers.prefix_match, destination: answers.destination }) if (answers.again) { return redirectsPrompt(array) } else { return array } } module.exports = async () => { let configuration = {} let answers answers = await inquirer.prompt([ { name: "domain", message: "Domain name:", default: "example.com", type: "input", }, { name: "build_command", message: "Build command", default: "npm run build", type: "input", }, { name: "upload_directory", message: "Directory to upload", default: "build", type: "input", }, { name: "index_key", message: "Index key", default: "index.html", type: "input", }, { name: "error_key", message: "Error key", default: "404.html", type: "input", }, { name: "cache", message: "Number of seconds to cache pages for?", default: 3600, type: "number", }, { name: "redirects", message: "Do you want to setup redirects?", default: false, type: "confirm", }, ]) configuration = Object.assign(configuration, answers) if (configuration.redirects) { configuration.redirects = await redirectsPrompt([]) } else { delete configuration.redirects } answers = await inquirer.prompt([ { name: "aws_profile", message: "AWS credentials profile", default: "default", type: "input", }, { name: "aws_region", message: "AWS region", type: "list", choices: choicesWithSeparators, pageSize: choicesWithSeparators.length, }, { name: "cdn", message: "Use a CDN for performance and HTTPS/TLS for security?", default: true, type: "confirm", }, { name: "dns_configured", message: "Is your DNS configured?", default: false, type: "confirm", }, ]) configuration = Object.assign(configuration, answers) return configuration } <|start_filename|>lib/deploy/synchronize-website.js<|end_filename|> const glob = require("glob") const fs = require("fs") const CacheControl = require("../cache-control") const mime = require("mime") const crypto = require("crypto") const diff = require("../diff") const flatMap = require("lodash.flatmap") module.exports = { title: "Synchronize website", task: async (context, task) => { let domain = context.config.domain let uploadDirectory = context.config.upload_directory let paths = glob.sync("**/*", { cwd: uploadDirectory, nodir: true, }) let cacheControl = CacheControl.build( context.config.cache, context.config.cache_control, context.config.cdn, ) let source = flatMap(paths, (path) => { let fullPath = `${uploadDirectory}/${path}` let content = fs.readFileSync(fullPath) let md5Hash = `"${crypto .createHash("md5") .update(content) .digest("hex")}"` let files = [ { path: path, key: path, md5Hash: md5Hash, }, ] if (path.endsWith(".html")) { files.push({ path: path, key: path.replace(/\.html$/, ""), md5Hash: md5Hash, }) } return files }) let response = await context.s3.listObjectsV2({ Bucket: domain }) let target = response.Contents.map((object) => { return { key: object.Key, md5Hash: object.ETag, } }) let changes = diff({ source: source, target: target, locationProperty: "key", contentsHashProperty: "md5Hash", }) for (let change of changes.add) { task.output = `Adding ${change.path} as ${change.key}` let fullPath = `${uploadDirectory}/${change.path}` await context.s3.putObject({ Bucket: domain, Body: fs.readFileSync(fullPath), Key: change.key, ACL: "public-read", CacheControl: cacheControl, ContentType: mime.getType(fullPath), }) } for (let change of changes.update) { task.output = `Updating ${change.path} as ${change.key}` let fullPath = `${uploadDirectory}/${change.path}` await context.s3.putObject({ Bucket: domain, Body: fs.readFileSync(fullPath), Key: change.key, ACL: "public-read", CacheControl: cacheControl, ContentType: mime.getType(fullPath), }) } for (let change of changes.remove) { task.output = `Removing ${change.key}` await context.s3.deleteObject({ Bucket: domain, Key: change.key, }) } }, } <|start_filename|>test/diff.js<|end_filename|> import test from "ava" import diff from "../lib/diff" test("a file is in the source but not the target", (t) => { let a = { path: "foo/bar", md5: "abc123" } let source = [a] let target = [] let changes = diff({ source, target, locationProperty: "path", contentsHashProperty: "md5" }) t.deepEqual(changes, { add: [a], remove: [], update: [], ignore: [], }) }) test("a file is in the target but not the source", (t) => { let a = { path: "foo/bar", md5: "abc123" } let source = [] let target = [a] let changes = diff({ source, target, locationProperty: "path", contentsHashProperty: "md5" }) t.deepEqual(changes, { add: [], remove: [a], update: [], ignore: [], }) }) test("a file is in both the target and the source but the hashes are different", (t) => { let aSource = { path: "foo/bar", md5: "abc123" } let aTarget = { path: "foo/bar", md5: "def456" } let source = [aSource] let target = [aTarget] let changes = diff({ source, target, locationProperty: "path", contentsHashProperty: "md5" }) t.deepEqual(changes, { add: [], remove: [], update: [aSource], ignore: [], }) }) test("a file is in both the target and the source and the hashes are the same", (t) => { let aSource = { path: "foo/bar", md5: "abc123" } let aTarget = { path: "foo/bar", md5: "abc123" } let source = [aSource] let target = [aTarget] let changes = diff({ source, target, locationProperty: "path", contentsHashProperty: "md5" }) t.deepEqual(changes, { add: [], remove: [], update: [], ignore: [aSource], }) }) test("a combination of files in different states", (t) => { let a = { path: "only/in/source" } let b = { path: "only/in/target" } let cSource = { path: "in/both/but/changed", md5: "abc123" } let cTarget = { path: "in/both/but/changed", md5: "def456" } let dSource = { path: "in/both/and/same", md5: "abc123" } let dTarget = { path: "in/both/and/same", md5: "abc123" } let source = [a, cSource, dSource] let target = [b, cTarget, dTarget] let changes = diff({ source, target, locationProperty: "path", contentsHashProperty: "md5" }) t.deepEqual(changes, { add: [a], remove: [b], update: [cSource], ignore: [dSource], }) }) <|start_filename|>lib/deploy/expire-cache.js<|end_filename|> const delay = require("../utilities").delay const suppressConnectionErrors = require("../utilities").suppressConnectionErrors const isInvalidationCompleted = async (context, distributionId, invalidationId) => { let data = await context.cloudFront.getInvalidation({ DistributionId: distributionId, Id: invalidationId, }) let status = data.Invalidation.Status return status === "Completed" } module.exports = { title: "Expire cache", enabled: (context) => context.config && context.config.cdn, skip: async (context) => { let domain = context.config.domain let data = await context.cloudFront.listDistributions({ MaxItems: "100" }) let distributions = data.DistributionList.Items let distribution = distributions.find((distribution) => distribution.Aliases.Items.includes(domain)) if (distribution) { context.distributionId = distribution.Id return false } else { return "Distribution not set up yet" } }, task: async (context, task) => { let distributionId = context.distributionId let domain = context.config.domain let currentTime = new Date().toISOString() let data = await context.cloudFront.createInvalidation({ DistributionId: distributionId, InvalidationBatch: { CallerReference: `${domain.replace(/\W/g, "_")}_${currentTime}`, Paths: { Items: ["/*"], Quantity: 1, }, }, }) let invalidationId = data.Invalidation.Id let invalidationIsCompleted = false while (!invalidationIsCompleted) { await delay(5000) task.output = "This can take a few minutes" await suppressConnectionErrors(async () => { invalidationIsCompleted = await isInvalidationCompleted(context, distributionId, invalidationId) }) } }, } <|start_filename|>lib/distribute/load-configuration.js<|end_filename|> const configuration = require("../configuration") const AWS = require("../aws") module.exports = { title: "Load configuration", task: (context) => { let configurationPath = context.configurationPath let config = configuration.read(configurationPath) let credentials = AWS.credentials(config.aws_profile) context.acm = AWS.acm({ credentials: credentials, region: "us-east-1", }) context.cloudFront = AWS.cloudFront({ credentials: credentials, }) context.config = config }, } <|start_filename|>lib/routing-rules.js<|end_filename|> const URL = require("url") const removeRootForwardSlash = (path) => { return path.replace(/^\//, "") } module.exports = (redirects, routingRules) => { if (routingRules) { return routingRules } return redirects.map((redirect) => { let redirectOptions = { HttpRedirectCode: "301", } let url = URL.parse(redirect.destination) if (url.protocol && url.hostname) { redirectOptions.Protocol = url.protocol.replace(":", "") redirectOptions.HostName = url.hostname } redirectOptions.ReplaceKeyWith = removeRootForwardSlash(url.path) return { Condition: { KeyPrefixEquals: removeRootForwardSlash(redirect.prefix_match), }, Redirect: redirectOptions, } }) } <|start_filename|>lib/cli/distribute-command.js<|end_filename|> const distribute = require("../distribute") const logSymbols = require("log-symbols") const configuration = require("../configuration") module.exports = async (configurationPath) => { let context = await distribute.run({ configurationPath: configurationPath, }) let dnsNotConfigured = !context.config.dns_configured let cdnNotEnabled = !context.config.cdn let cdnDomain = context.cdnDomain let domain = context.config.domain let url = `https://${dnsNotConfigured ? cdnDomain : domain}` console.log(`\n${logSymbols.success}`, `Distribution deployed! You can see it at ${url}`) if (dnsNotConfigured || cdnNotEnabled) { console.log(`\n${logSymbols.info}`, `Make sure you configure your DNS—add an ALIAS or CNAME from your domain to \`${cdnDomain}\``) console.log(`${logSymbols.info}`, "This reminder won’t show again.") configuration.update(configurationPath, { cdn: true, dns_configured: true, }) } } <|start_filename|>lib/utilities.js<|end_filename|> const path = require("path") module.exports.intersperse = (array, separator) => { return array.reduce((newArray, item, index) => { newArray.push(item) if (index !== array.length - 1) { newArray.push(separator) } return newArray }, []) } module.exports.flatten = (arrayOfArrays) => { return [].concat(...arrayOfArrays) } module.exports.delay = (duration) => { return new Promise((resolve) => setTimeout(resolve, duration)) } module.exports.suppressConnectionErrors = (callback) => { try { return callback() } catch (error) { if (error.message.startsWith("connect")) { throw error } } } module.exports.untildify = (string) => { if (string.substr(0, 1) === "~") { string = process.env.HOME + string.substr(1) } return path.resolve(string) } <|start_filename|>lib/distribute.js<|end_filename|> const Listr = require("listr") const loadConfigurationTask = require("./distribute/load-configuration") const createCertificateTask = require("./distribute/create-certificate") const verifyCertificateTask = require("./distribute/verify-certificate") const createDistributionTask = require("./distribute/create-distribution") const deployDistributionTask = require("./distribute/deploy-distribution") module.exports = new Listr([ loadConfigurationTask, createCertificateTask, verifyCertificateTask, createDistributionTask, deployDistributionTask, ]) <|start_filename|>lib/distribute/verify-certificate.js<|end_filename|> const delay = require("../utilities").delay const suppressConnectionErrors = require("../utilities").suppressConnectionErrors const isCertificateVerified = async (context, certificateARN) => { let data = await context.acm.describeCertificate({ CertificateArn: certificateARN }) let status = data.Certificate.Status return status === "ISSUED" } module.exports = { title: "Verify certificate", task: async (context, task) => { let certificateARN = context.certificateARN if (await isCertificateVerified(context, certificateARN)) { return } let certificateIsVerified = false while (!certificateIsVerified) { task.output = "A verification email has been sent to an email address associated with your domain" await delay(5000) await suppressConnectionErrors(async () => { certificateIsVerified = await isCertificateVerified(context, certificateARN) }) } }, } <|start_filename|>lib/deploy.js<|end_filename|> const Listr = require("listr") const loadConfigurationTask = require("./deploy/load-configuration") const buildWebsiteTask = require("./deploy/build-website") const createBucketTask = require("./deploy/create-bucket") const configureBucketAsWebsiteTask = require("./deploy/configure-bucket-as-website") const synchronizeWebsiteTask = require("./deploy/synchronize-website") const expireCacheTask = require("./deploy/expire-cache") module.exports = new Listr([ loadConfigurationTask, buildWebsiteTask, createBucketTask, configureBucketAsWebsiteTask, synchronizeWebsiteTask, expireCacheTask, ]) <|start_filename|>lib/cli/init-command.js<|end_filename|> const logSymbols = require("log-symbols") const configure = require("../configure") const configuration = require("../configuration") module.exports = async (configurationPath) => { let data = await configure() configuration.write(configurationPath, data) console.log(`\n${logSymbols.success}`, `Configuration written to \`${configurationPath}\`!`) console.log(`${logSymbols.info}`, "Run `discharge deploy` to deploy your website.") } <|start_filename|>lib/deploy/create-bucket.js<|end_filename|> module.exports = { title: "Create bucket", skip: async (context) => { let bucketExists = false try { bucketExists = await context.s3.headBucket({ Bucket: context.config.domain }) } catch(error) {} if (bucketExists) { return "Bucket already exists" } else { return false } }, task: (context) => { return context.s3.createBucket({ ACL: "public-read", Bucket: context.config.domain, }) }, } <|start_filename|>lib/error.js<|end_filename|> class KnownError extends Error { constructor(...args) { super(...args) Error.captureStackTrace(this, KnownError) } } module.exports.error = KnownError module.exports.catch = (error) => { let errorIsKnown = error instanceof KnownError if (!errorIsKnown) { throw error } } <|start_filename|>lib/distribute/deploy-distribution.js<|end_filename|> const delay = require("../utilities").delay const suppressConnectionErrors = require("../utilities").suppressConnectionErrors const findDistributionByDomain = async (context, domain) => { let data = await context.cloudFront.listDistributions({ MaxItems: "100" }) let distributions = data.DistributionList.Items return distributions.find((distribution) => distribution.Aliases.Items.includes(domain)) } const findDistributionById = async (context, id) => { let data = await context.cloudFront.getDistribution({ Id: id }) return data.Distribution } const isDistributionDeployed = (distribution) => distribution.Status === "Deployed" module.exports = { title: "Deploy distribution", task: async (context, task) => { let domain = context.config.domain let distribution = await findDistributionByDomain(context, domain) context.cdnDomain = distribution.DomainName if (isDistributionDeployed(distribution)) { return } let distributionIsDeployed = false while (!distributionIsDeployed) { await delay(5000) task.output = "This can take a while (~5–15 minutes)" await suppressConnectionErrors(async () => { distribution = await findDistributionById(context, distribution.Id) distributionIsDeployed = isDistributionDeployed(distribution) }) } }, } <|start_filename|>lib/distribute/create-distribution.js<|end_filename|> const AWS = require("../aws") module.exports = { title: "Create distribution", skip: async (context) => { let domain = context.config.domain let data = await context.cloudFront.listDistributions({ MaxItems: "100" }) let distributions = data.DistributionList.Items let distribution = distributions.find((distribution) => distribution.Aliases.Items.includes(domain)) if (distribution) { return "Distribution already exists" } else { return false } }, task: async (context) => { let domain = context.config.domain let endpoint = AWS.findEndpointByRegionKey(context.config.aws_region) let origin = `${domain}.${endpoint}` let certificateARN = context.certificateARN await context.cloudFront.createDistribution({ DistributionConfig: { Aliases: { Items: [ domain, `www.${domain}`, ], Quantity: 2, }, CallerReference: new Date().toISOString(), Comment: context.config.domain, DefaultCacheBehavior: { AllowedMethods: { Items: [ "GET", "HEAD", ], Quantity: 2, }, Compress: true, ForwardedValues: { Cookies: { Forward: "none", }, QueryString: false, }, MinTTL: 0, TargetOriginId: domain, TrustedSigners: { Enabled: false, Quantity: 0, }, ViewerProtocolPolicy: "redirect-to-https", }, Enabled: true, Origins: { Items: [{ CustomOriginConfig: { HTTPPort: 80, HTTPSPort: 443, OriginProtocolPolicy: "http-only", }, DomainName: origin, Id: domain, }], Quantity: 1, }, PriceClass: "PriceClass_100", ViewerCertificate: { ACMCertificateArn: certificateARN, CloudFrontDefaultCertificate: false, MinimumProtocolVersion: "TLSv1", SSLSupportMethod: "sni-only", }, }, }) }, } <|start_filename|>lib/cli/deploy-command.js<|end_filename|> const deploy = require("../deploy") const AWS = require("../aws") const logSymbols = require("log-symbols") const configuration = require("../configuration") module.exports = async (configurationPath) => { let context = await deploy.run({ configurationPath: configurationPath, }) let dnsNotConfigured = !context.config.dns_configured let domain = context.config.domain let url = `http://${domain}` let endpoint = AWS.findEndpointByRegionKey(context.config.aws_region) if (dnsNotConfigured) { url = `${url}.${endpoint}` } console.log(`\n${logSymbols.success}`, `Website deployed! You can see it at ${url}`) if (dnsNotConfigured) { if (!context.config.cdn) { console.log(`\n${logSymbols.info}`, `Make sure you configure your DNS—add an ALIAS or CNAME from your domain to \`${domain}.${endpoint}\``) console.log(`${logSymbols.info}`, "This reminder won’t show again.") configuration.update(configurationPath, { dns_configured: true }) } else { console.log(`\n${logSymbols.info}`, "Run `discharge distribute` to configure the CDN") } } } <|start_filename|>lib/diff.js<|end_filename|> const intersectionBy = require("lodash.intersectionby") const differenceBy = require("lodash.differenceby") const intersectionWith = require("lodash.intersectionwith") module.exports = ({ source = [], target = [], locationProperty, contentsHashProperty }) => { let filesInBothSourceAndTarget = intersectionBy(source, target, locationProperty) let filesInSourceButNotTarget = differenceBy(source, target, locationProperty) let filesInTargetButNotSource = differenceBy(target, source, locationProperty) let filesInBothSourceAndTargetWithDifferentHashes = intersectionWith(source, target, (a, b) => { let locationsMatch = a[locationProperty] === b[locationProperty] let hashesDoNotMatch = a[contentsHashProperty] !== b[contentsHashProperty] return locationsMatch && hashesDoNotMatch }) let filesInBothSourceAndTargetWithIdenticalHashes = differenceBy( filesInBothSourceAndTarget, filesInBothSourceAndTargetWithDifferentHashes, locationProperty, ) return { add: filesInSourceButNotTarget, remove: filesInTargetButNotSource, update: filesInBothSourceAndTargetWithDifferentHashes, ignore: filesInBothSourceAndTargetWithIdenticalHashes, } } <|start_filename|>lib/distribute/create-certificate.js<|end_filename|> module.exports = { title: "Create certificate", skip: async (context) => { let domain = context.config.domain let data = await context.acm.listCertificates({ MaxItems: 100 }) let certificates = data.CertificateSummaryList let certificate = certificates.find((certificate) => certificate.DomainName === domain) if (certificate) { context.certificateARN = certificate.CertificateArn return "Certificate already exists" } else { return false } }, task: async (context) => { let domain = context.config.domain let certificate = await context.acm.requestCertificate({ DomainName: domain, IdempotencyToken: domain.replace(/\W/g, "_"), SubjectAlternativeNames: [`*.${domain}`], }) context.certificateARN = certificate.CertificateArn }, }
frsgrn/discharge
<|start_filename|>app/src/main/kotlin/com/werb/g_trending/adapter/RepositoryViewHolder.kt<|end_filename|> package com.werb.g_trending.adapter import android.app.Activity import android.content.Intent import android.graphics.Color import android.graphics.PorterDuff import android.net.Uri import android.text.TextUtils import android.view.View import com.werb.g_trending.R import com.werb.g_trending.activity.WebActivity import com.werb.g_trending.model.Repository import com.werb.library.MoreViewHolder import kotlinx.android.synthetic.main.item_trending.* /** Created by wanbo <<EMAIL>> on 2017/9/21. */ class RepositoryViewHolder(containerView: View) : MoreViewHolder<Repository>(containerView) { private val context = containerView.context override fun bindData(data: Repository) { title.text = data.title description.text = data.description forks.text = data.forks starsToday.text = data.todayStars starsAll.text = data.stars languageType.text = data.language avatars.setData(data.users) if (TextUtils.isEmpty(data.color)) { colorType.visibility = View.GONE } else { colorType.visibility = View.VISIBLE data.color?.let { if (it.length == 7) { val drawable = context.resources.getDrawable(R.drawable.oval_drawable) drawable.setColorFilter(Color.parseColor(it), PorterDuff.Mode.SRC) colorType.setBackgroundDrawable(drawable) } } } if (TextUtils.isEmpty(data.todayStars)) { starsToday.text = "no stars today" } if (TextUtils.isEmpty(data.description)) { description.text = "no description" } containerView.setOnClickListener { WebActivity.startActivity(context as Activity, "https://github.com" + data.url, data.title) } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/api/TrendingService.kt<|end_filename|> package com.werb.g_trending.api import io.reactivex.Observable import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query /** Created by wanbo <<EMAIL>> on 2017/9/13. */ interface TrendingService { @GET("{lan}") fun getTrending(@Path("lan") lan: String?, @Query("since") since: String?): Observable<String> } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/utils/ResourcesUtils.kt<|end_filename|> package com.werb.g_trending.utils import android.content.Context import java.io.BufferedReader import java.io.InputStreamReader /** * Created by liuxi on 2017/9/7. */ object ResourcesUtils { fun dp2px(context: Context, dipValue: Float): Int { val scale = context.resources.displayMetrics.density return (dipValue * scale + 0.5f).toInt() } fun getFromAssets(context: Context, fileName: String): String { var Result = "" try { val inputReader = InputStreamReader(context.resources.assets.open(fileName)) val bufReader = BufferedReader(inputReader) bufReader.readLines().forEach { Result += it } bufReader.close() inputReader.close() } catch (e: Exception) { } return Result } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/view/AvatarsView.kt<|end_filename|> package com.werb.g_trending.view import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.LinearLayout import com.facebook.drawee.view.SimpleDraweeView import com.werb.g_trending.R import com.werb.g_trending.model.Repository import com.werb.g_trending.model.User /** * * 用户图标列表 * Created by liuxi on 2017/9/7. */ class AvatarsView : LinearLayout { constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) init { orientation = LinearLayout.HORIZONTAL } fun setData(data: MutableList<User>) { removeAllViews() for (user in data) { user.avatar?.let { addChildView(it) } } } private fun addChildView(imageUrl: String) { val layout = LayoutInflater.from(context).inflate(R.layout.item_avatar, this, false) as LinearLayout val avatar = layout.findViewById<SimpleDraweeView>(R.id.itemAvatar) avatar.setImageURI(imageUrl) addView(layout) } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/adapter/ThemeAdapter.kt<|end_filename|> package com.werb.g_trending.adapter import android.content.Context import android.support.v4.app.DialogFragment import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.werb.eventbus.EventBus import com.werb.g_trending.R import com.werb.g_trending.model.ThemeModel import com.werb.g_trending.utils.Preference import com.werb.g_trending.utils.Theme import com.werb.g_trending.utils.event.ThemeEvent import kotlinx.android.synthetic.main.item_theme.view.* /** Created by wanbo <<EMAIL>> on 2017/9/8. */ class ThemeAdapter(private val context: Context, private val dialog: DialogFragment) : RecyclerView.Adapter<ThemeAdapter.ThemeViewHolder>() { private val list: List<ThemeModel> by lazy { initData() } private var lastPosition = 0 private fun initData(): List<ThemeModel> { val themes = arrayListOf<ThemeModel>() val names = context.resources.getStringArray(R.array.theme) val colors = context.resources.getIntArray(R.array.theme_color) return names.mapTo(themes) { ThemeModel(it, colors[names.indexOf(it)]).apply { select = it == Preference.getTheme(context).name } } } override fun getItemCount(): Int = list.size override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ThemeViewHolder { return ThemeViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item_theme, parent, false)) } override fun onBindViewHolder(holder: ThemeViewHolder?, position: Int) { if (holder is ThemeViewHolder) { holder.bindData(list[position]) } } inner class ThemeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val color = itemView.color private val str = itemView.str private val select = itemView.select private lateinit var themeModel: ThemeModel fun bindData(themeModel: ThemeModel) { this.themeModel = themeModel color.setColor(themeModel.color) str.text = themeModel.name select.isChecked = themeModel.select if (themeModel.select) lastPosition = layoutPosition select.setOnClickListener(clickListener) itemView.setOnClickListener(clickListener) } private val clickListener = View.OnClickListener { if (lastPosition == layoutPosition) { select.isChecked = true return@OnClickListener } list.forEach { if (list.indexOf(it) == layoutPosition) { select.isChecked = true list[lastPosition].select = false } } notifyItemChanged(lastPosition) lastPosition = layoutPosition itemView.postDelayed({ dialog.dismiss() Preference.setTheme(context, Theme.valueOf(themeModel.name)) EventBus.post(ThemeEvent()) }, 250) } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/utils/RxHelper.kt<|end_filename|> package com.werb.g_trending.utils import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.Consumer import io.reactivex.schedulers.Schedulers object RxHelper { fun <T> getObservable(observable: Observable<T>): Observable<T> { return observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun <T> getPostObservable(observable: Observable<T>): Observable<T> { return observable .subscribeOn(Schedulers.io()) } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/adapter/LanguageViewHolder.kt<|end_filename|> package com.werb.g_trending.adapter import android.content.Intent import android.graphics.Color import android.graphics.PorterDuff import android.view.View import com.werb.g_trending.R import com.werb.g_trending.model.Language import com.werb.library.MoreViewHolder import kotlinx.android.synthetic.main.item_language.* /** Created by wanbo <<EMAIL>> on 2017/9/18. */ class LanguageViewHolder(containerView: View) : MoreViewHolder<Language>(containerView) { private val context = containerView.context override fun bindData(data: Language) { name.text = data.name data.color?.let { val drawable = containerView.context.resources.getDrawable(R.drawable.oval_drawable) drawable.setColorFilter(Color.parseColor(data.color), PorterDuff.Mode.SRC) colorType.setBackgroundDrawable(drawable) } containerView.tag = this addOnLongClickListener(containerView) delete.tag = data addOnClickListener(delete) } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/api/TrendingRequest.kt<|end_filename|> package com.werb.g_trending.api import com.werb.g_trending.model.Repository import com.werb.g_trending.model.Developer import com.werb.g_trending.model.User import com.werb.g_trending.utils.RxHelper import io.reactivex.Observable import io.reactivex.ObservableOnSubscribe import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.select.Elements /** Created by wanbo <<EMAIL>> on 2017/9/6. */ object TrendingRequest { enum class DailyType { TODAY, WEEK, MONTH } private val baseUrl = "https://github.com/trending" fun repository(lang: String?, daily: DailyType = DailyType.TODAY): Observable<List<Repository>> { return RxHelper.getObservable(JSoupProvider.getTrendingService().getTrending(lang, buildDaily(daily))) .flatMap { RxHelper.getObservable(requestRepos(it)) } } fun developer(lang: String?, daily: DailyType = DailyType.TODAY): Observable<List<Developer>> { val url = buildUrl("$baseUrl/developers", lang, daily) return Observable.create(ObservableOnSubscribe<List<Developer>> { val users = requestUsers(url) it.onNext(users) it.onComplete() }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } private fun buildUrl(url: String, lang: String?, daily: DailyType): String { return when (daily) { DailyType.TODAY -> "$url/$lang?since=daily" DailyType.WEEK -> "$url/$lang?since=weekly" DailyType.MONTH -> "$url/$lang?since=monthly" } } private fun buildDaily(daily: DailyType): String { return when (daily) { DailyType.TODAY -> "daily" DailyType.WEEK -> "weekly" DailyType.MONTH -> "monthly" } } private fun requestRepos(url: String): Observable<List<Repository>> { return Observable.fromPublisher { s -> val trendingList = mutableListOf<Repository>() val document: Document = Jsoup.parse(url) val repoList = document.select(".repo-list") if (repoList.isNotEmpty()) { val list: Elements? = repoList.select("li") list?.let { if (list.isNotEmpty()) { it.onEach { val title = it.select(".d-inline-block > h3 > a").text() val url = it.select(".d-inline-block > h3 > a").attr("href") val description = it.select(".py-1 > p").text() val stars = it.select(".f6 > a[href*=/stargazers]").text() val forks = it.select(".f6 > a[href*=/network]").text() val color = it.select(".f6 .mr-3 > span.repo-language-color").attr("style") .replace("background-color:", "").replace(";", "") var todayStars = it.select(".f6 > span.float-right").text() if (todayStars.isNullOrBlank()) { todayStars = it.select(".f6 > span.float-sm-right").text() } var language = it.select(".f6 .mr-3 > span[itemprop=programmingLanguage]").text() if (language.isNullOrBlank()) { language = it.select(".f6 span[itemprop=programmingLanguage]").text() } val aTag = it.select(".f6 span a.no-underline") val contributors = aTag.attr("href") val users = arrayListOf<User>() if (aTag.isNotEmpty()) { val images = aTag.select("img") images.onEach { val name = it.attr("title") val avatar = it.attr("src") users.add(User(name, avatar)) } } val repos = Repository(title, description, url, stars, forks, color, todayStars, language, contributors, users) trendingList.add(repos) } } } } s.onNext(trendingList) s.onComplete() } } private fun requestUsers(url: String): List<Developer> { val userList = mutableListOf<Developer>() val document: Document = Jsoup.connect(url).get() val list = document.select("div.explore-content ol") if (list.isNotEmpty()) { val li: Elements? = list.select("li") li?.let { if (li.isNotEmpty()) { it.onEach { val avatar = it.select(".d-flex div.mx-2 a:eq(0) img.rounded-1").attr("src") val name = it.select(".d-flex div.mx-2 h2 a").text() val url = it.select(".d-flex div.mx-2 h2 a").attr("href") val repositoryUrl = it.select(".d-flex div.mx-2 a:eq(1)").attr("href") val repositoryName = it.select(".d-flex div.mx-2 a:eq(1) span.repo-snipit-name span.repo").text() val repositoryDesc = it.select(".d-flex div.mx-2 a:eq(1) span.repo-snipit-description ").text() val user = Developer(name, avatar, url, repositoryUrl, repositoryName, repositoryDesc) userList.add(user) } } } } return userList } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/activity/AboutActivity.kt<|end_filename|> package com.werb.g_trending.activity import android.app.Activity import android.content.Intent import android.os.Bundle import com.werb.g_trending.R import com.werb.g_trending.adapter.AboutInfoViewHolder import com.werb.g_trending.adapter.AboutUserViewHolder import com.werb.g_trending.model.User import com.werb.library.MoreAdapter import com.werb.library.link.MultiLink import com.werb.library.link.RegisterItem import kotlinx.android.synthetic.main.activity_about.* /** Created by wanbo <<EMAIL>> on 2017/9/27. */ class AboutActivity : BaseActivity() { private val adapter: MoreAdapter by lazy { MoreAdapter() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowTitleEnabled(false) toolbar.setNavigationOnClickListener { finish() } adapter.apply { register(RegisterItem(R.layout.item_view_about_developer, AboutUserViewHolder::class.java)) register(RegisterItem(R.layout.item_view_about_title, AboutInfoViewHolder::class.java)) attachTo(recyclerView) } adapter.loadData("Developer & Designer") adapter.loadData(User("wanbo", "https://avatars1.githubusercontent.com/u/12763277?v=4&s=460", "https://github.com/Werb")) adapter.loadData(User("liuxi", "https://avatars2.githubusercontent.com/u/26291475?v=4&s=460", "https://github.com/LiuXi0314")) adapter.loadData("Open source") adapter.loadData(User("Werb/MoreType", null, url = "https://github.com/Werb/MoreType")) adapter.loadData(User("Werb/EventBusKotlin", null, url = "https://github.com/Werb/EventBusKotlin")) adapter.loadData(User("jhy/jsoup", null, url = "https://github.com/jhy/jsoup")) adapter.loadData(User("facebook/fresco", null, url = "https://github.com/facebook/fresco")) adapter.loadData(User("ReactiveX/RxJava", null, url = "https://github.com/ReactiveX/RxJava")) adapter.loadData(User("ReactiveX/RxAndroid", null, url = "https://github.com/ReactiveX/RxAndroid")) adapter.loadData(User("square/retrofit", null, url = "https://github.com/square/retrofit")) adapter.loadData(User("markzhai/AndroidPerformanceMonitor", null, url = "https://github.com/markzhai/AndroidPerformanceMonitor")) } override fun finish() { super.finish() overridePendingTransition(R.anim.activity_anim_not_change, R.anim.activity_anim_current_to_right) } companion object { fun startActivity(activity: Activity) { val intent = Intent(activity, AboutActivity::class.java) activity.startActivity(intent) activity.overridePendingTransition(R.anim.activity_anim_right_to_current, R.anim.activity_anim_not_change) } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/api/TrendingFactory.kt<|end_filename|> package com.werb.g_trending.api import com.google.gson.Gson import okhttp3.RequestBody import okhttp3.ResponseBody import retrofit2.Converter import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.io.IOException import java.lang.reflect.Type /** Created by wanbo <<EMAIL>> on 2017/9/13. */ class TrendingFactory : Converter.Factory() { private val gson = Gson() override fun responseBodyConverter(type: Type?, annotations: Array<out Annotation>?, retrofit: Retrofit?): Converter<ResponseBody, *>? { return if (type === String::class.java) { StringResponseConverter() } else GsonConverterFactory.create(gson).responseBodyConverter(type, annotations, retrofit) } override fun requestBodyConverter(type: Type?, parameterAnnotations: Array<out Annotation>?, methodAnnotations: Array<out Annotation>?, retrofit: Retrofit?): Converter<*, RequestBody>? { return GsonConverterFactory.create(gson).requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit) } private class StringResponseConverter : Converter<ResponseBody, String> { @Throws(IOException::class) override fun convert(value: ResponseBody): String { return value.string() } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/adapter/AboutUserViewHolder.kt<|end_filename|> package com.werb.g_trending.adapter import android.app.Activity import android.content.Intent import android.net.Uri import android.view.View import com.werb.g_trending.activity.WebActivity import com.werb.g_trending.model.User import com.werb.library.MoreViewHolder import kotlinx.android.synthetic.main.item_view_about_developer.* /** Created by wanbo <<EMAIL>> on 2017/9/27. */ class AboutUserViewHolder(containerView: View) : MoreViewHolder<User>(containerView) { private val context = containerView.context override fun bindData(data: User) { icon.visibility = View.GONE data.avatar?.let { icon.visibility = View.VISIBLE icon.setImageURI(data.avatar) } name.text = data.name url.text = data.url containerView.setOnClickListener { WebActivity.startActivity(context as Activity, data.url, data.name) } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/activity/BaseActivity.kt<|end_filename|> package com.werb.g_trending.activity import android.os.Build import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import com.werb.eventbus.EventBus import com.werb.eventbus.Subscriber import com.werb.g_trending.R import com.werb.g_trending.utils.Preference import com.werb.g_trending.utils.Theme import com.werb.g_trending.utils.event.ThemeEvent import io.reactivex.android.schedulers.AndroidSchedulers /** Created by wanbo <<EMAIL>> on 2017/9/10. */ open class BaseActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { initTheme() super.onCreate(savedInstanceState) } private fun initTheme() { val theme = Preference.getTheme(this) when (theme) { Theme.Default -> this.setTheme(R.style.DefaultTheme) Theme.Blue -> this.setTheme(R.style.BlueTheme) Theme.Indigo -> this.setTheme(R.style.IndigoTheme) Theme.Green -> this.setTheme(R.style.GreenTheme) Theme.Red -> this.setTheme(R.style.RedTheme) Theme.BlueGrey -> this.setTheme(R.style.BlueGreyTheme) Theme.Black -> this.setTheme(R.style.BlackTheme) Theme.Purple -> this.setTheme(R.style.PurpleTheme) Theme.Orange -> this.setTheme(R.style.OrangeTheme) Theme.Pink -> this.setTheme(R.style.PinkTheme) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (theme == Theme.Default) { window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE } } } @Subscriber private fun theme(event: ThemeEvent) { recreate() } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/Config.kt<|end_filename|> package com.werb.g_trending /** Created by wanbo <<EMAIL>> on 2017/9/25. */ object Config { var TRENDING_TAG = "repos" fun repos(){ TRENDING_TAG = "repos" } fun developer() { TRENDING_TAG = "developer" } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/model/Developer.kt<|end_filename|> package com.werb.g_trending.model /** Created by wanbo <<EMAIL>> on 2017/9/6. */ data class Developer(val name: String, val avatar: String, val url: String, val repositoryUrl: String, val repositoryName: String, val repositoryDesc: String) <|start_filename|>app/src/main/kotlin/com/werb/g_trending/utils/Extensions.kt<|end_filename|> package com.werb.g_trending.utils /** Created by wanbo <<EMAIL>> on 2017/9/22. */ fun Array<*>.list(): MutableList<String> { val list = arrayListOf<String>() forEach { list.add(it as String) } return list } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/api/JSoupProvider.kt<|end_filename|> package com.werb.g_trending.api import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory /** Created by wanbo <<EMAIL>> on 2017/9/13. */ object JSoupProvider { private var okHttpClient: OkHttpClient? = null private fun provideOkHttpClient(): OkHttpClient? { if (okHttpClient == null) { val client = OkHttpClient.Builder() okHttpClient = client.build() } return okHttpClient } fun getTrendingService(): TrendingService { return Retrofit.Builder() .baseUrl("https://github.com/trending/") .client(provideOkHttpClient()) .addConverterFactory(TrendingFactory()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(TrendingService::class.java) } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/utils/event/LanguageEvent.kt<|end_filename|> package com.werb.g_trending.utils.event import com.werb.eventbus.IEvent import com.werb.g_trending.model.Language /** Created by wanbo <<EMAIL>> on 2017/9/21. */ class LanguageEvent(val language: Language?): IEvent <|start_filename|>app/src/main/kotlin/com/werb/g_trending/extensions/ToolbarExtendion.kt<|end_filename|> package com.werb.g_trending.extensions import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle /** Created by wanbo <<EMAIL>> on 2017/9/5. */ /** Toolbar icon 切换 */ fun ActionBarDrawerToggle.switch(position: Float) { if (position == 1f) { drawerArrowDrawable.setVerticalMirror(true) } else if (position == 0f) { drawerArrowDrawable.setVerticalMirror(false) } drawerArrowDrawable.progress = position } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/utils/ColorUtils.kt<|end_filename|> package com.werb.g_trending.utils import android.content.Context import com.google.gson.Gson import com.werb.g_trending.model.Language import io.reactivex.Observable /** Created by wanbo <<EMAIL>> on 2017/9/18. */ object ColorUtils { lateinit var colors: Colors fun load(context: Context) { RxHelper.getObservable(Observable.create<String> { val json = ResourcesUtils.getFromAssets(context, "colors.json") it.onNext(json) }).subscribe { colors = Gson().fromJson(it, Colors::class.java) } } fun getLanguage(languageName: String): Language? { val language = colors.colors[languageName] language?.name = languageName return language } data class Colors(var colors: Map<String, Language> = hashMapOf()) } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/activity/MainActivity.kt<|end_filename|> package com.werb.g_trending.activity import android.app.Activity import android.content.Intent import android.os.Build import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v7.app.ActionBarDrawerToggle import com.werb.eventbus.EventBus import com.werb.eventbus.Subscriber import com.werb.g_trending.Config import com.werb.g_trending.R import com.werb.g_trending.adapter.TabLayoutAdapter import com.werb.g_trending.utils.Preference import com.werb.g_trending.utils.event.LanguageEvent import com.werb.g_trending.utils.list import kotlinx.android.synthetic.main.activity_main.* class MainActivity : BaseActivity() { private lateinit var adapter: TabLayoutAdapter private lateinit var toggle: ActionBarDrawerToggle override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = resources.getColor(android.R.color.transparent) } setContentView(R.layout.activity_main) initToolbar() initTabLayout() } override fun onStart() { super.onStart() EventBus.register(this) } private fun initToolbar() { toolbar.title = getString(R.string.app_name) toolbar.inflateMenu(R.menu.toolbar) mainDrawer.setNavigationItemSelectedListener(drawerItemClick) mainDrawer.menu.getItem(0).isChecked = true setSupportActionBar(toolbar) toggle = ActionBarDrawerToggle(this, mainDrawerLayout, toolbar, R.string.open, R.string.close) mainDrawerLayout.setDrawerListener(toggle) toggle.syncState() } private fun initTabLayout() { var list = Preference.getLanguage(this) if (list.isEmpty()) { list = resources.getStringArray(R.array.trending).list() Preference.setLanguage(this, list) } content_viewPager.offscreenPageLimit = list.size adapter = TabLayoutAdapter(supportFragmentManager, list) content_viewPager.adapter = adapter tabLayout.setupWithViewPager(content_viewPager) } @Subscriber(tag = "move") private fun languageMove(event: LanguageEvent) { initTabLayout() } @Subscriber(tag = "add") private fun languageAdd(event: LanguageEvent) { event.language?.let { adapter.addPage(content_viewPager, it) } } @Subscriber(tag = "delete") private fun languageDelete(event: LanguageEvent) { event.language?.let { adapter.removePage(content_viewPager, it) } } private val drawerItemClick = NavigationView.OnNavigationItemSelectedListener { when (it.itemId) { R.id.repos -> { if (Config.TRENDING_TAG != "repos") { Config.repos() initTabLayout() } mainDrawerLayout.closeDrawer(GravityCompat.START) } R.id.developer -> { if (Config.TRENDING_TAG != "developer") { Config.developer() initTabLayout() } mainDrawerLayout.closeDrawer(GravityCompat.START) } R.id.language -> { LanguageActivity.startActivity(this) } R.id.theme -> { ThemeDialog().show(supportFragmentManager, "theme") } R.id.about -> { AboutActivity.startActivity(this) } } return@OnNavigationItemSelectedListener true } companion object { fun startActivity(activity: Activity) { val intent = Intent(activity, MainActivity::class.java) activity.startActivity(intent) activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/model/Language.kt<|end_filename|> package com.werb.g_trending.model /** * Created by wanbo <werbhelius></<EMAIL>> on 2017/9/22. */ data class Language(var name: String, var color: String?, var url: String, var check: Boolean = false) <|start_filename|>app/src/main/kotlin/com/werb/g_trending/view/CircleView.kt<|end_filename|> package com.werb.g_trending.view import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import android.view.View import com.werb.g_trending.R /** Created by wanbo <<EMAIL>> on 2017/9/10. */ class CircleView : View { constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private val paint: Paint by lazy { Paint() } private val paintBorder: Paint by lazy { Paint() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) var board = width.toFloat() if (width != height) { val min = Math.min(width, height) board = min.toFloat() } paint.isAntiAlias = true paint.strokeWidth = 10f paint.style = Paint.Style.FILL canvas.drawCircle(board / 2, board / 2, board / 2 - .5f, paint) paintBorder.isAntiAlias = true paintBorder.strokeWidth = 2f paintBorder.style = Paint.Style.FILL paintBorder.color = resources.getColor(R.color.colorWhite) canvas.drawCircle(board / 2, board / 2 , 15f, paintBorder) } fun setColor(color: Int) { if (color == -1){ paint.color = resources.getColor(R.color.colorAccent) }else { paint.color = color } invalidate() } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/activity/ChooseActivity.kt<|end_filename|> package com.werb.g_trending.activity import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import com.werb.g_trending.R import com.werb.g_trending.adapter.ChooseViewHolder import com.werb.g_trending.utils.ColorUtils import com.werb.g_trending.utils.Preference import com.werb.library.MoreAdapter import com.werb.library.link.RegisterItem import kotlinx.android.synthetic.main.activity_choose.* /** Created by wanbo <<EMAIL>> on 2017/9/23. */ class ChooseActivity : BaseActivity() { private val adapter: MoreAdapter by lazy { MoreAdapter() } private var handler = Handler(Looper.getMainLooper()) private val languages = ColorUtils.colors.colors private lateinit var saveLanguages: MutableList<String> private var keyChat: String = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_choose) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowTitleEnabled(false) toolbar.setNavigationOnClickListener { finish() } search.addTextChangedListener(watcher) saveLanguages = Preference.getLanguage(this) adapter.apply { register(RegisterItem(R.layout.item_view_choose, ChooseViewHolder::class.java)) attachTo(recyclerView) } loadData() } private fun loadData(){ adapter.removeAllData() languages.keys .map { val name = it languages[it]?.let { it.name = name it } } .forEach { it?.let { it.check = saveLanguages.contains(it.name) adapter.loadData(it) } } } private val watcher = object: TextWatcher{ override fun afterTextChanged(p0: Editable?) { keyChat = p0.toString() if (TextUtils.isEmpty(keyChat)){ loadData() }else { updateList() } } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} } private fun updateList() { handler.removeCallbacks(runnable) handler.postDelayed(runnable, 750) } private var runnable: Runnable = Runnable { adapter.removeAllData() languages.keys .map { val name = it languages[it]?.let { it.name = name it } } .forEach { it?.let { if (it.name.toUpperCase().contains(keyChat.toUpperCase())) { it.check = saveLanguages.contains(it.name) adapter.loadData(it) } } } } override fun finish() { super.finish() overridePendingTransition(R.anim.activity_anim_not_change, R.anim.activity_anim_current_to_right) } companion object { fun startActivity(activity: Activity) { val intent = Intent(activity, ChooseActivity::class.java) activity.startActivity(intent) activity.overridePendingTransition(R.anim.activity_anim_right_to_current, R.anim.activity_anim_not_change) } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/utils/Preference.kt<|end_filename|> package com.werb.g_trending.utils import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import com.google.gson.Gson /** Created by wanbo <<EMAIL>> on 2017/9/10. */ object Preference { private val THEME = "theme" private val LANGUAGE = "language" private fun getSharedPreferences(context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) fun setTheme(context: Context, theme: Theme) { val editor = getSharedPreferences(context).edit() editor.putString(THEME, theme.name) editor.apply() } fun getTheme(context: Context): Theme = Theme.valueOf(getSharedPreferences(context).getString(THEME, Theme.Default.name)) fun setLanguage(context: Context, languages: MutableList<String>){ val editor = getSharedPreferences(context).edit() editor.putString(LANGUAGE, Gson().toJson(languages)) editor.apply() } @Suppress("UNCHECKED_CAST") fun getLanguage(context: Context): MutableList<String> { val str = getSharedPreferences(context).getString(LANGUAGE, "") val fromJson = Gson().fromJson(str, MutableList::class.java) return fromJson?.let { it } as MutableList<String>? ?: mutableListOf() } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/fragment/LazyLoadFragment.kt<|end_filename|> package com.werb.g_trending.fragment import android.support.v4.app.Fragment import android.os.Bundle /** Created by wanbo <<EMAIL>> on 2017/9/13. */ abstract class LazyLoadFragment: Fragment() { private var isViewInitiated: Boolean = false private var isDataLoaded: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) isViewInitiated = true prepareRequestData() } override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) prepareRequestData() } abstract fun requestData() private fun prepareRequestData(): Boolean { return prepareRequestData(false) } private fun prepareRequestData(forceUpdate: Boolean): Boolean { if (userVisibleHint && isViewInitiated && (!isDataLoaded || forceUpdate)) { requestData() isDataLoaded = true return true } return false } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/MyApp.kt<|end_filename|> package com.werb.g_trending import android.app.Application import android.content.Context import android.support.multidex.MultiDexApplication import android.util.Log import com.crashlytics.android.Crashlytics import com.facebook.drawee.backends.pipeline.Fresco import com.werb.g_trending.utils.ColorUtils import io.fabric.sdk.android.Fabric /** Created by wanbo <<EMAIL>> on 2017/9/10. */ class MyApp: MultiDexApplication() { override fun onCreate() { super.onCreate() Log.e("app", System.currentTimeMillis().toString()) sContext = applicationContext // BlockCanary.install(this, AppContext()).start() Fresco.initialize(this) ColorUtils.load(applicationContext) Fabric.with(this, Crashlytics()) } companion object { private var sContext: Context? = null fun getAppContext(): Context? { return sContext } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/extensions/KeyBoardExtension.kt<|end_filename|> package com.werb.g_trending.extensions import android.content.Context import android.view.inputmethod.InputMethodManager import android.widget.EditText /** * Created by wanbo on 2017/2/4. */ fun EditText.showKeyboard() { requestFocus() val inputManager = context.getSystemService( Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManager.showSoftInput(this, 0) } fun EditText.hideKeyboard() { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(windowToken, 0) } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/adapter/AboutInfoViewHolder.kt<|end_filename|> package com.werb.g_trending.adapter import android.view.View import com.werb.library.MoreViewHolder import kotlinx.android.synthetic.main.item_view_about_title.* /** Created by wanbo <<EMAIL>> on 2017/9/27. */ class AboutInfoViewHolder(containerView: View) : MoreViewHolder<String>(containerView) { override fun bindData(data: String) { title.text = data } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/activity/SplashActivity.kt<|end_filename|> package com.werb.g_trending.activity import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import android.util.Log /** Created by wanbo <<EMAIL>> on 2017/9/28. */ class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.e("SplashActivity", System.currentTimeMillis().toString()) Handler().postDelayed({ MainActivity.startActivity(this) finish() }, 300) } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/activity/LanguageActivity.kt<|end_filename|> package com.werb.g_trending.activity import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import android.support.design.widget.Snackbar import android.support.v4.graphics.drawable.DrawableCompat import android.support.v7.app.AlertDialog import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import android.util.TypedValue import android.view.View import android.widget.Toast import com.werb.eventbus.EventBus import com.werb.eventbus.Subscriber import com.werb.g_trending.R import com.werb.g_trending.adapter.LanguageViewHolder import com.werb.g_trending.model.Language import com.werb.g_trending.utils.ColorUtils import com.werb.g_trending.utils.Preference import com.werb.g_trending.utils.event.LanguageEvent import com.werb.library.MoreAdapter import com.werb.library.action.MoreClickListener import com.werb.library.link.RegisterItem import kotlinx.android.synthetic.main.activity_language.* import java.util.* /** Created by wanbo <<EMAIL>> on 2017/9/15. */ class LanguageActivity : BaseActivity() { private val adapter: MoreAdapter by lazy { MoreAdapter() } private var handler = Handler(Looper.getMainLooper()) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_language) toolbar.title = getString(R.string.menu_language) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) toolbar.setNavigationOnClickListener { finish() } val drawable = resources.getDrawable(R.drawable.ic_add_black_24dp) val typedValue = TypedValue() theme.resolveAttribute(R.attr.colorPrimaryLight, typedValue, true) val wrappedDrawable = DrawableCompat.wrap(drawable) DrawableCompat.setTint(wrappedDrawable, resources.getColor(typedValue.resourceId)) add.setBackgroundDrawable(wrappedDrawable) add.setOnClickListener { add() } itemTouchHelper.attachToRecyclerView(recyclerView) adapter.apply { register(RegisterItem(R.layout.item_language, LanguageViewHolder::class.java, itemClickListener)) attachTo(recyclerView) } val languages = Preference.getLanguage(this) languages.forEach { val language = ColorUtils.getLanguage(it) language?.let { adapter.loadData(it) } } } override fun onStart() { super.onStart() EventBus.register(this) } override fun onDestroy() { super.onDestroy() EventBus.unRegister(this) } private fun add() { ChooseActivity.startActivity(this) } @Subscriber(tag = "add") private fun languageAdd(event: LanguageEvent) { event.language?.let { adapter.loadData(it) } } @Subscriber(tag = "delete") private fun languageDelete(event: LanguageEvent) { event.language?.let { adapter.removeData(it) } } private val itemClickListener = object : MoreClickListener() { override fun onItemClick(view: View, position: Int) { val language = view.tag as Language val alertDialog = AlertDialog.Builder(this@LanguageActivity) alertDialog.setMessage(R.string.delete_language) alertDialog.setPositiveButton(R.string.delete, { _, _ -> if (adapter.itemCount > 1) { adapter.removeData(position) EventBus.post(LanguageEvent(language), "delete") } else { Toast.makeText(this@LanguageActivity, getString(R.string.size_up_one), Toast.LENGTH_SHORT).show() } }) alertDialog.setNegativeButton(R.string.cancel, { dialog, _ -> dialog.dismiss() }) alertDialog.show() } override fun onItemLongClick(view: View, position: Int): Boolean { val holder = view.tag as LanguageViewHolder itemTouchHelper.startDrag(holder) return true } } private val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.Callback() { override fun isLongPressDragEnabled(): Boolean { return false } override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN return makeMovementFlags(dragFlags, 0) } override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { val fromPosition = viewHolder.adapterPosition val toPosition = target.adapterPosition if (fromPosition < toPosition) { for (i in fromPosition until toPosition) { Collections.swap(adapter.list, i, i + 1) } } else { for (i in fromPosition downTo toPosition + 1) { Collections.swap(adapter.list, i, i - 1) } } adapter.notifyItemMoved(fromPosition, toPosition) updateList() return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {} }) private fun updateList() { handler.removeCallbacks(runnable) handler.postDelayed(runnable, 750) } private var runnable: Runnable = Runnable { val languages = arrayListOf<String>() adapter.list.forEach { if (it is Language) { languages.add(it.name) } } if (languages.isNotEmpty()) { Preference.setLanguage(this, languages) EventBus.post(LanguageEvent(null), "move") } } override fun finish() { super.finish() overridePendingTransition(R.anim.activity_anim_not_change, R.anim.activity_anim_current_to_right) } companion object { fun startActivity(activity: Activity) { val intent = Intent(activity, LanguageActivity::class.java) activity.startActivity(intent) activity.overridePendingTransition(R.anim.activity_anim_right_to_current, R.anim.activity_anim_not_change) } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/model/Repository.kt<|end_filename|> package com.werb.g_trending.model /** Created by wanbo <<EMAIL>> on 2017/9/6. */ data class Repository(val title: String?, val description: String, val url: String, val stars: String?, val forks: String?, var color: String?, val todayStars: String?, val language: String?, val contributors: String, var users: MutableList<User>) data class User(val name: String, val avatar: String?, val url: String? = "") <|start_filename|>app/src/main/kotlin/com/werb/g_trending/adapter/DeveloperViewHolder.kt<|end_filename|> package com.werb.g_trending.adapter import android.app.Activity import android.content.Intent import android.net.Uri import android.view.View import com.werb.g_trending.activity.WebActivity import com.werb.g_trending.model.Developer import com.werb.library.MoreViewHolder import kotlinx.android.synthetic.main.item_view_developer.* /** Created by wanbo <<EMAIL>> on 2017/9/25. */ class DeveloperViewHolder(containerView: View) : MoreViewHolder<Developer>(containerView) { private val context = containerView.context override fun bindData(data: Developer) { icon.setImageURI(data.avatar) name.text = data.name repos.text = data.repositoryName desc.text = data.repositoryDesc containerView.setOnClickListener { WebActivity.startActivity(context as Activity, "https://github.com" + data.url, data.name) } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/adapter/TabLayoutAdapter.kt<|end_filename|> package com.werb.g_trending.adapter import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentStatePagerAdapter import com.werb.g_trending.fragment.TrendingFragment import android.support.v4.view.PagerAdapter import android.support.v4.view.ViewPager import com.werb.g_trending.model.Language import com.werb.g_trending.utils.Preference /** Created by wanbo <<EMAIL>> on 2017/9/6. */ class TabLayoutAdapter(fm: FragmentManager, private val titles: MutableList<String>) : FragmentStatePagerAdapter(fm) { override fun getItem(position: Int): Fragment = TrendingFragment.newInstance(titles[position]) override fun getCount(): Int = titles.size override fun getPageTitle(position: Int): CharSequence = titles[position] override fun getItemPosition(`object`: Any?): Int { return PagerAdapter.POSITION_NONE } fun removePage(pager: ViewPager, language: Language) { val indexOf = titles.indexOf(language.name) val view = pager.getChildAt(indexOf) view?.let { pager.removeViewAt(indexOf) titles.removeAt(indexOf) notifyDataSetChanged() pager.offscreenPageLimit = titles.size Preference.setLanguage(pager.context, titles) } } fun addPage(pager: ViewPager, language: Language) { titles.add(language.name) notifyDataSetChanged() pager.offscreenPageLimit = titles.size Preference.setLanguage(pager.context, titles) } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/utils/event/ThemeEvent.kt<|end_filename|> package com.werb.g_trending.utils.event import com.werb.eventbus.IEvent /** Created by wanbo <<EMAIL>> on 2017/9/10. */ class ThemeEvent: IEvent <|start_filename|>app/src/main/kotlin/com/werb/g_trending/extensions/ViewExtension.kt<|end_filename|> package com.werb.g_trending.extensions import android.animation.Animator import android.animation.ValueAnimator import android.content.res.Configuration import android.support.v7.app.ActionBarDrawerToggle import android.view.View import android.view.animation.AccelerateInterpolator fun View.dp2px(dpValue: Float): Int { val scale = context.resources.displayMetrics.density return (dpValue * scale + 0.5f).toInt() } val View.density: Int get() { val density = context.resources.displayMetrics.density return (density + 0.5f).toInt() } fun View.px2dp(pxValue: Float): Int { val scale = context.resources.displayMetrics.density return (pxValue / scale + 0.5f).toInt() } val View.isLowDesity: Boolean get() = context.resources.displayMetrics.widthPixels < 1080 val View.widthPixels: Int get() { val displayMetrics = context.resources.displayMetrics val cf = context.resources.configuration val ori = cf.orientation if (ori == Configuration.ORIENTATION_LANDSCAPE) { return displayMetrics.heightPixels } else if (ori == Configuration.ORIENTATION_PORTRAIT) { return displayMetrics.widthPixels } return 0 } val View.heightPixels: Int get() { val displayMetrics = context.resources.displayMetrics val cf = context.resources.configuration val ori = cf.orientation if (ori == Configuration.ORIENTATION_LANDSCAPE) { return displayMetrics.widthPixels } else if (ori == Configuration.ORIENTATION_PORTRAIT) { return displayMetrics.heightPixels } return 0 } fun View.getDimen(resId: Int): Int { return context.resources.getDimensionPixelSize(resId) } fun View.getMeasureWidth(): Int { val w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) val h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) measure(w, h) return measuredWidth } fun View.getMeasureHeight(): Int { val w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) val h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) measure(w, h) return measuredHeight } fun View.createDropAnim(start: Int, end: Int, duration: Long, animEnd: () -> Unit): ValueAnimator { val va = ValueAnimator.ofInt(start, end) va.interpolator = AccelerateInterpolator() val max = Math.max(start, end) va.addUpdateListener { animation -> val value = animation.animatedValue as Int layoutParams.height = value layoutParams = layoutParams } va.duration = duration va.addListener(object: Animator.AnimatorListener { override fun onAnimationRepeat(p0: Animator?) {} override fun onAnimationCancel(p0: Animator?) {} override fun onAnimationStart(p0: Animator?) {} override fun onAnimationEnd(p0: Animator?) { animEnd() } }) return va } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/adapter/ChooseViewHolder.kt<|end_filename|> package com.werb.g_trending.adapter import android.view.View import com.werb.eventbus.EventBus import com.werb.g_trending.model.Language import com.werb.g_trending.utils.event.LanguageEvent import com.werb.library.MoreViewHolder import kotlinx.android.synthetic.main.item_view_choose.* /** Created by wanbo <<EMAIL>> on 2017/9/23. */ class ChooseViewHolder(containerView: View) : MoreViewHolder<Language>(containerView) { override fun bindData(data: Language) { name.text = data.name check.isChecked = data.check check.setOnClickListener { if (check.isChecked) { EventBus.post(LanguageEvent(data), "add") } else { EventBus.post(LanguageEvent(data), "delete") } } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/utils/Theme.kt<|end_filename|> package com.werb.g_trending.utils /** Created by wanbo <<EMAIL>> on 2017/9/8. */ enum class Theme { Default, Blue, Indigo, Green, Red, BlueGrey, Black, Purple, Orange, Pink } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/activity/ThemeDialog.kt<|end_filename|> package com.werb.g_trending.activity import android.app.Dialog import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v7.app.AlertDialog import android.support.v7.widget.RecyclerView import com.werb.g_trending.R import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.werb.g_trending.adapter.ThemeAdapter /** Created by wanbo <<EMAIL>> on 2017/9/12. */ class ThemeDialog: DialogFragment() { override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { dialog.setCanceledOnTouchOutside(true) return super.onCreateView(inflater, container, savedInstanceState) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val view = LayoutInflater.from(context).inflate(R.layout.widget_view_theme, null) val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView) recyclerView.adapter = ThemeAdapter(context, this) return AlertDialog.Builder(context) .setView(view) .create() } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/activity/WebActivity.kt<|end_filename|> package com.werb.g_trending.activity import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import com.werb.g_trending.R import kotlinx.android.synthetic.main.activity_web.* import android.webkit.WebView import android.webkit.WebViewClient /** * Created by wanbo on 2018/3/13. */ class WebActivity: BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_web) val url = intent.getStringExtra("url") val title = intent.getStringExtra("title") setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowTitleEnabled(false) toolbar.setNavigationOnClickListener { finish() } toolbar.title = title refresh.setColorSchemeResources(R.color.refresh_progress_1, R.color.refresh_progress_2, R.color.refresh_progress_3); setWebView(url) } private fun setWebView(url: String) { webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { view.loadUrl(url) return super.shouldOverrideUrlLoading(view, url) } override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { super.onPageStarted(view, url, favicon) refresh.isRefreshing = true } override fun onPageFinished(view: WebView?, url: String?) { super.onPageFinished(view, url) refresh.isRefreshing = false } } webView.loadUrl(url) } override fun finish() { super.finish() overridePendingTransition(R.anim.activity_anim_not_change, R.anim.activity_anim_top_to_bottom) } companion object { fun startActivity(activity: Activity, url: String?, title: String?) { val intent = Intent(activity, WebActivity::class.java) intent.putExtra("url", url) intent.putExtra("title", title) activity.startActivity(intent) activity.overridePendingTransition(R.anim.activity_anim_bottom_to_top, R.anim.activity_anim_not_change) } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/fragment/TrendingFragment.kt<|end_filename|> package com.werb.g_trending.fragment import android.content.Context import android.graphics.Rect import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.werb.g_trending.Config import com.werb.g_trending.R import com.werb.g_trending.adapter.DeveloperViewHolder import com.werb.g_trending.adapter.RepositoryViewHolder import com.werb.g_trending.api.TrendingRequest import com.werb.g_trending.utils.ResourcesUtils import com.werb.library.MoreAdapter import com.werb.library.link.RegisterItem import kotlinx.android.synthetic.main.fragment_trending.* /** Created by wanbo <<EMAIL>> on 2017/9/6. */ class TrendingFragment : LazyLoadFragment() { private val adapter: MoreAdapter by lazy { MoreAdapter() } private var language = "" private var refresh: SwipeRefreshLayout? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true language = arguments.getString(ARG_LANGUAGE) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_trending, container, false).apply { refresh = this?.findViewById(R.id.refresh) } } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recyclerView.addItemDecoration(ItemDecoration(context)) when (Config.TRENDING_TAG) { "repos" -> { adapter.register(RegisterItem(R.layout.item_trending, RepositoryViewHolder::class.java)) } "developer" -> { adapter.register(RegisterItem(R.layout.item_view_developer, DeveloperViewHolder::class.java)) } } adapter.attachTo(recyclerView) refresh?.setOnRefreshListener { requestData() } } override fun requestData() { when (Config.TRENDING_TAG) { "repos" -> { repos() } "developer" -> { developer() } } } private fun repos() { TrendingRequest.repository(language) .doOnSubscribe { refresh?.isRefreshing = true } .subscribe({ adapter.removeAllData() adapter.loadData(it) }, { it.printStackTrace() }, { refresh?.isRefreshing = false }) } private fun developer() { TrendingRequest.developer(language) .doOnSubscribe { refresh?.isRefreshing = true } .subscribe({ adapter.removeAllData() adapter.loadData(it) }, { it.printStackTrace() }, { refresh?.isRefreshing = false }) } companion object { private const val ARG_LANGUAGE = "LANGUAGE" fun newInstance(name: String): TrendingFragment { return TrendingFragment().apply { arguments = Bundle().apply { putString(ARG_LANGUAGE, name) } } } } private inner class ItemDecoration(private val context: Context) : RecyclerView.ItemDecoration() { override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) { super.getItemOffsets(outRect, view, parent, state) outRect?.bottom = ResourcesUtils.dp2px(context, 3f) } } } <|start_filename|>app/src/main/kotlin/com/werb/g_trending/model/ThemeModel.kt<|end_filename|> package com.werb.g_trending.model /** Created by wanbo <<EMAIL>> on 2017/9/8. */ data class ThemeModel(val name: String, val color: Int) { var select: Boolean = false }
Werb/G-Trending
<|start_filename|>lib/serialize-dom.js<|end_filename|> 'use strict' /** * Walk through the dom and create a json snapshot. * * @param {Element} element * @return {Object} * @api private */ module.exports = function serialize(element) { var json = { name: element.nodeName.toLowerCase(), element: element } if (json.name == '#text') { json.text = element.textContent return json } var attr = element.attributes if (attr && attr.length) { json.attributes = {} var attrLength = attr.length for (var i = 0; i < attrLength; i++) { json.attributes[attr[i].name] = attr[i].value } } var childNodes = element.childNodes if (childNodes && childNodes.length) { json.children = {length: childNodes.length} var childNodesLength = childNodes.length for (var i = 0; i < childNodesLength; i++) { json.children[i] = serialize(childNodes[i]) } } return json } <|start_filename|>lib/keypath.js<|end_filename|> 'use strict' /** * Find value in json obj using array or dot path notation. * * http://docs.mongodb.org/manual/core/document/#document-dot-notation * * {a: {b: {c: 3}}} * 'a.b.c' // 3 * * {a: {b: {c: [1,2,3]}}} * 'a.b.c.1' // 2 * * @param {Object|Array} obj * @param {String|Array} path * @return {Mixed} */ module.exports = function(obj, path) { var parts, i if (!obj || !path) return obj parts = typeof path == 'string' ? path.split('.') : path for (i = 0; i < parts.length; i++) { obj = obj[parts[i]] } return obj } <|start_filename|>profile/html-parser.js<|end_filename|> var serializeHtml = require('../lib/serialize-html') var html = require('fs').readFileSync(__dirname + '/../bench/test.html', 'utf8') var i = 10000 var now = Date.now() while (i > 0) { serializeHtml(html) i-- } console.log(Date.now() - now) <|start_filename|>lib/hashify.js<|end_filename|> 'use strict' var adler32 = require('./adler32') /** * Add hashes to every node. * Hash is calculated using node name, text, attributes and child nodes. * * @param {Object} node * @return {String} str which is used to generate a hash * @api private */ module.exports = function hashify(node) { var attr, i var str = '' var nodes if (!node) return str if (node.name) { str += node.name if (node.text) str += node.text for (attr in node.attributes) { str += attr + node.attributes[attr] } nodes = node.children // Its a collection. } else { nodes = node } for (i in nodes) { str += hashify(nodes[i]) } node.hash = adler32(str) return str } <|start_filename|>test/renderer.js<|end_filename|> function getView() { var element = document.createElement('div') var renderer = new DiffRenderer(element) return { render: function(html) { renderer.update(html) DiffRenderer.render() }, element: element } } module('DiffRenderer') test('render a tag', function() { var view = getView() view.render('<a/>') equal(view.element.innerHTML, '<a></a>', 'self closing') view.render('<a></a>') equal(view.element.innerHTML, '<a></a>', 'not self closing') }) test('render a text node', function() { var view = getView() view.render('abc') equal(view.element.innerHTML, 'abc', 'without spaces') view.render(' abc ') equal(view.element.innerHTML, ' abc ', 'with spaces') }) test('add an attribute', function() { var view = getView() view.render('<a/>') view.render('<a class="b"/>') equal(view.element.innerHTML, '<a class="b"></a>', 'add class') view.render('<a class="b" id="c"/>') equal(view.element.innerHTML, '<a class="b" id="c"></a>', 'add id') view.render('<a class="b" id="c" href=""/>') equal(view.element.innerHTML, '<a class="b" id="c" href=""></a>', 'add empty href') view.render('<a class="b" id="c" href="" disabled/>') equal(view.element.innerHTML, '<a class="b" id="c" href="" disabled=""></a>', 'add disabled') }) test('add an attribute', function() { var view = getView() view.render('<a/>') view.render('<a class="b"/>') equal(view.element.innerHTML, '<a class="b"></a>', 'add class') view.render('<a class="b" id="c"/>') equal(view.element.innerHTML, '<a class="b" id="c"></a>', 'add id') view.render('<a class="b" id="c" href=""/>') equal(view.element.innerHTML, '<a class="b" id="c" href=""></a>', 'add empty href') view.render('<a class="b" id="c" href="" disabled/>') equal(view.element.innerHTML, '<a class="b" id="c" href="" disabled=""></a>', 'add disabled') }) test('change an attribute', function() { var view = getView() view.render('<a class="b"/>') view.render('<a class="c d"/>') equal(view.element.innerHTML, '<a class="c d"></a>') }) test('change an attributes', function() { var view = getView() view.render('<a class="b" id="e"/>') view.render('<a class="c d" id="f"/>') equal(view.element.innerHTML, '<a class="c d" id="f"></a>') }) test('remove an attribute', function() { var view = getView() view.render('<a class="b"/>') view.render('<a/>') equal(view.element.innerHTML, '<a></a>') }) test('remove all attributes', function() { var view = getView() view.render('<a class="b" id="c"/>') view.render('<a/>') equal(view.element.innerHTML, '<a></a>') }) test('remove one of attributes', function() { var view = getView() view.render('<a class="b" id="c"/>') view.render('<a id="c"/>') equal(view.element.innerHTML, '<a id="c"></a>') }) test('change text node text', function() { var view = getView() view.render('abc') view.render('a') equal(view.element.innerHTML, 'a') }) test('change text node text within a tag', function() { var view = getView() view.render('<a>aaa</a>') view.render('<a>a</a>') equal(view.element.innerHTML, '<a>a</a>') }) test('replace tag by another tag', function() { var view = getView() view.render('<a/>') view.render('<b/>') equal(view.element.innerHTML, '<b></b>') }) test('replace multiple tags by 1 other tag', function() { var view = getView() view.render('<a/><b/>') view.render('<c/>') equal(view.element.innerHTML, '<c></c>') }) test('replace multiple tags by 1 text node', function() { var view = getView() view.render('<a/><b/>') view.render('aaa') equal(view.element.innerHTML, 'aaa') }) test('replace multiple tags by multiple tags', function() { var view = getView() view.render('<a/><b/>') view.render('<c/><d/>') equal(view.element.innerHTML, '<c></c><d></d>') }) test('replace first tag by another one', function() { var view = getView() view.render('<a/><b/>') view.render('<c/><b/>') equal(view.element.innerHTML, '<c></c><b></b>') }) test('replace first tag by text node', function() { var view = getView() view.render('<a/><b/>') view.render('a<b/>') equal(view.element.innerHTML, 'a<b></b>') }) test('replace last tag by another one', function() { var view = getView() view.render('<a/><b/>') view.render('<a/><c/>') equal(view.element.innerHTML, '<a></a><c></c>') }) test('replace middle tag by another one', function() { var view = getView() view.render('<a/><b/><c/>') view.render('<a/><d/><c/>') equal(view.element.innerHTML, '<a></a><d></d><c></c>') }) test('append a tag', function() { var view = getView() view.render('<a/>') view.render('<a><b/></a>') equal(view.element.innerHTML, '<a><b></b></a>') }) test('append a text node', function() { var view = getView() view.render('<a/>') view.render('<a>b</a>') equal(view.element.innerHTML, '<a>b</a>') }) test('prepend a tag', function() { var view = getView() view.render('<a/>') view.render('<b/><a/>') equal(view.element.innerHTML, '<b></b><a></a>') }) test('prepend multiple tags', function() { var view = getView() view.render('<a/>') view.render('<d/><c/><b/><a/>') equal(view.element.innerHTML, '<d></d><c></c><b></b><a></a>') }) test('prepend a text node', function() { var view = getView() view.render('<a c="b"/>') view.render('b<a c="b"/>') equal(view.element.innerHTML, 'b<a c="b"></a>') }) test('insert a tag after', function() { var view = getView() view.render('<a/>') view.render('<a/><b/>') equal(view.element.innerHTML, '<a></a><b></b>') }) test('insert multiple tags after', function() { var view = getView() view.render('<a/>') view.render('<a/><b/><c/><d/>') equal(view.element.innerHTML, '<a></a><b></b><c></c><d></d>') }) test('insert multiple tags in the middle', function() { var view = getView() view.render('<a/><b/>') view.render('<a/><c/><d/><b/>') equal(view.element.innerHTML, '<a></a><c></c><d></d><b></b>') }) test('migrate children', function() { var view = getView() view.render('<a>a</a><b/>') view.render('<b>a</b><a/>') equal(view.element.innerHTML, '<b>a</b><a></a>') }) test('remove text node within a tag', function() { var view = getView() view.render('<a>abc</a>') view.render('<a></a>') equal(view.element.innerHTML, '<a></a>') }) test('remove text node', function() { var view = getView() view.render('abc') view.render('') equal(view.element.innerHTML, '') }) test('remove first tag', function() { var view = getView() view.render('<a/><b/><c/>') view.render('<b/><c/>') equal(view.element.innerHTML, '<b></b><c></c>') }) test('remove middle tag', function() { var view = getView() view.render('<a/><b/><c/>') view.render('<a/><c/>') equal(view.element.innerHTML, '<a></a><c></c>') }) test('remove last tag', function() { var view = getView() view.render('<a/><b/><c/>') view.render('<a/><b/>') equal(view.element.innerHTML, '<a></a><b></b>') }) test('remove last tag', function() { var view = getView() view.render('<a/><b/><c/>') view.render('<a/><b/>') equal(view.element.innerHTML, '<a></a><b></b>') }) test('allow nesting of renderers', function() { var element1 = document.createElement('div') element1.className = '1' var element2 = document.createElement('div') element2.className = '2' var element3 = document.createElement('div') element3.className = '3' element1.appendChild(element2) element2.appendChild(element3) var renderer1 = new DiffRenderer(element1) var renderer2 = new DiffRenderer(element2) ok(renderer1.node.children[0] === renderer2.node) ok(renderer1.node.children[0].children[0] === renderer2.node.children[0]) }) <|start_filename|>Makefile<|end_filename|> build: node_modules/browserify/bin/cmd.js -e ./index.js -o dist/diff-renderer.js -s DiffRenderer xpkg . bench: node bench test: node_modules/.bin/qunit -c DiffRenderer:./index.js -t ./test/serialize-html.js --cov .PHONY: build bench test <|start_filename|>bench/index.js<|end_filename|> var html = require('fs').readFileSync(__dirname + '/test.html', 'utf8'), serializeHtml = require('../lib/serialize-html'), htmlParser = require('html-minifier/src/htmlparser'), htmltree = require('htmltree') var noop = function() {} exports.compare = {} exports.compare.diffRenderer = function() { serializeHtml(html) } exports.compare.htmlParser = function() { htmlParser.HTMLParser(html, {}) } exports.compare.htmltree = function() { htmltree(html, noop) } exports.stepsPerLap = 10 require('bench').runMain() <|start_filename|>lib/render-queue.js<|end_filename|> 'use strict' /** * Any changed nodes land here to get considered for rendering. * * @type {Array} * @api private */ var queue = module.exports = [] /** * Add node to the queue. * * @param {Node} node * @api private */ queue.enqueue = function(node) { queue.push(node) } /** * Empty the queue. * * @param {Node} node * @api private */ queue.empty = function() { queue.splice(0) } <|start_filename|>lib/modifier.js<|end_filename|> 'use strict' var keypath = require('./keypath') var Node = require('./node') /** * Modifier applies changes to the node. * * @param {Node} node * @api private */ function Modifier(node) { this.node = node } module.exports = Modifier /** * Exclude properties from applying the diff. * * @type {Object} * @api private */ Modifier.EXCLUDE = { length: true, parent: true } /** * Apply the changes to the node. * * @param {Array} changes * @api private */ Modifier.prototype.apply = function(changes) { for (var i = 0; i < changes.length; i++) { var change = changes[i] var prop = change.path[change.path.length - 1] if (Modifier.EXCLUDE[prop]) continue var propIsNum = false if (!isNaN(prop)) { propIsNum = true prop = Number(prop) } var method = this[prop] if (!method) { if (propIsNum) method = this['children'] else method = this['attributes'] } method.call(this, change, prop) } } /** * Modify a text node. * * @param {Change} change * @param {String} prop * @api private */ Modifier.prototype.text = function(change, prop) { var path = change.path.slice(0, change.path.length - 1) var now = change.values.now var node = keypath(this.node.children, path) node.setText(now) } /** * Insert/remove child nodes. * * @param {Change} change * @param {String|Number} prop * @api private */ Modifier.prototype.children = function(change, prop) { var now = change.values.now var node var path if (change.change == 'add') { // Insert node at specific position. if (typeof prop == 'number') { // Find a path to the parent node. if (change.path.length > 1) { path = change.path.slice(0, change.path.length - 1) path.push(prop - 1) node = keypath(this.node.children, path) } else { node = this.node } node.insertAt(prop, Node.create(now, node)) // Append children. } else { path = change.path.slice(0, change.path.length - 1) node = keypath(this.node.children, path) for (var key in now) { if (!Modifier.EXCLUDE[key]) node.append(Node.create(now[key], node)) } } } else if (change.change == 'remove') { // Remove all children. if (prop == 'children') { path = change.path.slice(0, change.path.length - 1) node = keypath(this.node.children, path) node.removeChildren() } else { path = change.path node = keypath(this.node.children, path) if (node) node.parent.removeChild(node) } } } /** * Modify attributes. * * @param {Change} change * @param {String} prop * @api private */ Modifier.prototype.attributes = function(change, prop) { var now = change.values.now var path var node if (change.change == 'add') { if (prop == 'attributes') { path = change.path.slice(0, change.path.length - 1) node = keypath(this.node.children, path) node.setAttributes(now) } else { path = change.path.slice(0, change.path.length - 2) node = keypath(this.node.children, path) node.setAttribute(prop, now) } } else if (change.change == 'update') { path = change.path.slice(0, change.path.length - 2) node = keypath(this.node.children, path) node.setAttribute(prop, now) } else if (change.change == 'remove') { if (prop == 'attributes') { path = change.path.slice(0, change.path.length - 1) node = keypath(this.node.children, path) for (prop in change.values.original) { node.removeAttribute(prop) } } else { path = change.path.slice(0, change.path.length - 2) node = keypath(this.node.children, path) node.removeAttribute(prop) } } } /** * Change tag name. * * @param {Change} change * @param {String} prop * @api private */ Modifier.prototype.name = function(change, prop) { var path = change.path.slice(0, change.path.length - 1) var node = keypath(this.node.children, path) var now = change.values.now node.setName(now) } <|start_filename|>lib/renderer.js<|end_filename|> 'use strict' var docdiff = require('docdiff') var keypath = require('./keypath') var Node = require('./node') var Modifier = require('./modifier') var serializeDom = require('./serialize-dom') var serializeHtml = require('./serialize-html') var renderQueue = require('./render-queue') var hashify = require('./hashify') /** * Renderer constructor. * * @param {Element} element dom node for serializing and updating. * @api public */ function Renderer(element) { if (!element) throw new TypeError('DOM element required') if (!(this instanceof Renderer)) return new Renderer(element) this.node = null this.modifier = null this.refresh(element) } module.exports = Renderer Renderer.serializeDom = serializeDom Renderer.serializeHtml = serializeHtml Renderer.keypath = keypath Renderer.docdiff = docdiff Renderer.hashify = hashify /** * Start checking render queue and render. * * @api public */ Renderer.start = function() { function check() { if (!Renderer.running) return Renderer.render() requestAnimationFrame(check) } Renderer.running = true requestAnimationFrame(check) } /** * Stop checking render queue and render. * * @api public */ Renderer.stop = function() { Renderer.running = false } /** * Render all queued nodes. * * @api public */ Renderer.render = function() { if (!renderQueue.length) return for (var i = 0; i < renderQueue.length; i++) { renderQueue[i].render() } renderQueue.empty() return this } /** * Create a snapshot from the dom. * * @param {Element} [element] * @return {Renderer} this * @api public */ Renderer.prototype.refresh = function(element) { if (!element && this.node) element = this.node.target if (this.node) this.node.unlink() var json = serializeDom(element) this.node = Node.create(json) this.modifier = new Modifier(this.node) return this } /** * Find changes and apply them to virtual nodes. * * @param {String} html * @return {Renderer} this * @api public */ Renderer.prototype.update = function(html) { var next = serializeHtml(html).children // Everything has been removed. if (!next) { this.node.removeChildren() return this } var current = this.node.toJSON().children || {} var diff = docdiff(current, next) this.modifier.apply(diff) return this } <|start_filename|>lib/node.js<|end_filename|> 'use strict' var ElementsPool = require('./elements-pool') var queue = require('./render-queue') // Global elements pool for all nodes and all renderer instances. var pool = new ElementsPool() var counter = 0 var nodesMap = {} var ID_NAMESPACE = '__diffRendererId__' /** * Abstract node which can be rendered to a dom node. * * @param {Object} options * @param {String} options.name tag name * @param {String} [options.text] text for the text node * @param {Object} [options.attributes] key value hash of name/values * @param {Element} [options.element] if element is passed, node is already rendered * @param {Object} [options.children] NodeList like collection * @param {Node} [parent] * @api private */ function Node(options, parent) { this.id = counter++ this.name = options.name this.parent = parent if (options.text) this.text = options.text if (options.attributes) this.attributes = options.attributes if (options.element) { this.setTarget(options.element) // Not dirty if element passed. } else { this.dirty('name', true) if (this.text) this.dirty('text', true) if (this.attributes) this.dirty('attributes', this.attributes) } if (options.children) { this.children = [] for (var i in options.children) { if (i != 'length') { this.children[i] = Node.create(options.children[i], this) if (this.children[i].dirty()) this.dirty('children', true) } } } nodesMap[this.id] = this } module.exports = Node /** * Create Node instance, check if passed element has already a Node. * * @see {Node} * @api private * @return {Node} */ Node.create = function(options, parent) { if (options.element && options.element[ID_NAMESPACE]) { return nodesMap[options.element[ID_NAMESPACE]] } return new Node(options, parent) } /** * Serialize instance to json data. * * @return {Object} * @api private */ Node.prototype.toJSON = function() { var json = {name: this.name} if (this.text) json.text = this.text if (this.attributes) json.attributes = this.attributes if (this.children) { json.children = {length: this.children.length} for (var i = 0; i < this.children.length; i++) { json.children[i] = this.children[i].toJSON() } } return json } /** * Allocate, setup current target, insert children to the dom. * * @api private */ Node.prototype.render = function() { if (!this._dirty) return if (this.dirty('name')) { if (this.target) this.migrate() else this.setTarget(pool.allocate(this.name)) this.dirty('name', null) } // Handle children if (this.dirty('children') && this.children) { var newChildren = [] for (var i = 0; i < this.children.length; i++) { var child = this.children[i] // Children can be dirty for removal or for insertions only. // All other changes are handled by the child.render. if (child.dirty()) { if (child.dirty('remove')) { this.removeChildAt(i) child.dirty('remove', null) delete nodesMap[child.id] // Handle insert. } else { var next = this.children[i + 1] child.render() this.target.insertBefore(child.target, next && next.target) newChildren.push(child) child.dirty('insert', null) child.dirty('name', null) } } else { newChildren.push(child) } } // We migrate children to the new array because some of them might be removed // and if we splice them directly, we will remove wrong elements. if (newChildren) this.children = newChildren this.dirty('children', null) } // Handle textContent. if (this.dirty('text') && this.text) { this.target.textContent = this.text this.dirty('text', null) } // Handle attribtues. if (this.dirty('attributes')) { var attributes = this.dirty('attributes') for (var attrName in attributes) { var value = attributes[attrName] if (value == null) { delete this.attributes[attrName] if (this.name != '#text') this.target.removeAttribute(attrName) } else { if (!this.attributes) this.attributes = {} this.attributes[attrName] = value this.target.setAttribute(attrName, value) } } this.dirty('attributes', null) } } /** * Remove child DOM element at passed position without removing from children array. * * @param {Number} position * @api private */ Node.prototype.removeChildAt = function(position) { var child = this.children[position] child.detach() child.cleanup() if (child.children) { for (var i = 0; i < child.children.length; i++) { child.removeChildAt(i) } } pool.deallocate(child.target) child.unlink() } /** * Migrate target DOM element and its children to a new DOM element. * F.e. because tagName changed. * * @api private */ Node.prototype.migrate = function() { this.detach() this.cleanup() var oldTarget = this.target this.setTarget(pool.allocate(this.name)) // Migrate children. if (this.name == '#text') { this.children = null } else { this.text = null while (oldTarget.hasChildNodes()) { this.target.appendChild(oldTarget.removeChild(oldTarget.firstChild)) } } pool.deallocate(oldTarget) this.dirty('insert', true) } /** * Remove target DOM element from the render tree. * * @api private */ Node.prototype.detach = function() { var parentNode = this.target.parentNode if (parentNode) parentNode.removeChild(this.target) } /** * Clean up everything changed on the target DOM element. * * @api private */ Node.prototype.cleanup = function() { if (this.attributes) { for (var attrName in this.attributes) this.target.removeAttribute(attrName) } if (this.text) this.target.textContent = '' delete this.target[ID_NAMESPACE] } /** * Set all child nodes set dirty for removal. * * @api private */ Node.prototype.removeChildren = function() { if (!this.children) return for (var i = 0; i < this.children.length; i++) { this.children[i].dirty('remove', true) } this.dirty('children', true) } /** * Set child element as dirty for removal. * * @param {Node} node * @api private */ Node.prototype.removeChild = function(child) { child.dirty('remove', true) this.dirty('children', true) } /** * Clean up all references for current and child nodes. * * @api private */ Node.prototype.unlink = function() { if (this.children) { for (var i = 0; i < this.children.length; i++) { this.children[i].unlink() } } delete this.id delete this.name delete this.text delete this.attributes delete this.parent delete this.children delete this.target delete this._dirty } /** * Insert a node at specified position. * * @param {Number} position * @param {Node} node * @api private */ Node.prototype.insertAt = function(position, node) { this.dirty('children', true) node.dirty('insert', true) if (!this.children) this.children = [] this.children.splice(position, 0, node) } /** * Insert a node at the end. * * @param {Node} node * @api private */ Node.prototype.append = function(node) { var position = this.children ? this.children.length : 0 this.insertAt(position, node) } /** * Set nodes attributes. * * @param {Object} attribtues * @api private */ Node.prototype.setAttributes = function(attributes) { for (var name in attributes) { this.setAttribute(name, attributes[name]) } } /** * Set nodes attribute. * * @param {String} name * @param {String|Boolean|Null} value, use null to remove * @api private */ Node.prototype.setAttribute = function(name, value) { if (this.attributes && this.attributes[name] == value) return var attributes = this.dirty('attributes') || {} attributes[name] = value this.dirty('attributes', attributes) } /** * Remove nodes attribute. * @param {String} name * @api private */ Node.prototype.removeAttribute = function(name) { if (this.attributes && this.attributes[name] != null) this.setAttribute(name, null) } /** * Set text content. * * @param {String} content * @api private */ Node.prototype.setText = function(text) { if (this.name != '#text' || text == this.text) return this.dirty('text', true) this.text = text } /** * Element name can't be set, we need to swap out the element. * * @param {String} name * @api private */ Node.prototype.setName = function(name) { if (name == this.name) return this.dirty('name', true) this.parent.dirty('children', true) this.name = name } /** * Set target element. * * @param {Element} element * @api private */ Node.prototype.setTarget = function(element) { element[ID_NAMESPACE] = this.id this.target = element } /** * Get/set/unset a dirty flag, add to render queue. * * @param {String} name * @param {Mixed} [value] * @api private */ Node.prototype.dirty = function(name, value) { // Get flag. if (value === undefined) { return this._dirty && name ? this._dirty[name] : this._dirty } // Unset dirty flag. if (value === null) { if (this._dirty) { delete this._dirty[name] // If if its not empty object - exist. for (name in this._dirty) return // For quick check. delete this._dirty } // Set dirty flag. } else { if (!this._dirty) { this._dirty = {} // Only enqueue if its the first flag. queue.enqueue(this) } this._dirty[name] = value } } <|start_filename|>test/serialize-html.js<|end_filename|> var serializeHtml = DiffRenderer.serializeHtml var hashify = DiffRenderer.hashify QUnit.module('serialize-html') test('text node 0', function() { var doc = serializeHtml('a') var node = doc.children[0] hashify(node) equal(doc.name, 'root', 'root name') equal(node.name, '#text', 'node name') equal(node.text, 'a', 'node text') equal(node.hash, 123798090, 'node hash') }) test('text node 1', function() { var node = serializeHtml(' abc ').children[0] hashify(node) equal(node.name, '#text', 'node name') equal(node.text, ' abc ', 'node text') equal(node.hash, 315884367, 'node hash') }) test('empty node 0', function() { var node = serializeHtml('<a/>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 6422626, 'node hash') }) test('empty node 1', function() { var node = serializeHtml('< a/>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 6422626, 'node hash') }) test('empty node 2', function() { var node = serializeHtml('< a / >').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 6422626, 'node hash') }) test('empty node 3', function() { var node = serializeHtml('<\na\n/\n>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 6422626, 'node hash') }) test('closing tag', function() { deepEqual(serializeHtml('</a>'), {name: 'root'}) deepEqual(serializeHtml('< / a\n >'), {name: 'root'}) deepEqual(serializeHtml('<\n/\n a\n >'), {name: 'root'}) }) test('attributes 0', function() { var node = serializeHtml('<a id/>').children[0] hashify(node) equal(node.name, 'a', 'node name') deepEqual(node.attributes, {id: ''}, 'attributes') equal(node.hash, 39584047, 'node hash') }) test('attributes 1', function() { var node = serializeHtml('<a id=""/>').children[0] hashify(node) equal(node.name, 'a', 'node name') deepEqual(node.attributes, {id: ''}, 'attributes') equal(node.hash, 39584047, 'node hash') }) test('attributes 2', function() { var node = serializeHtml('<a id=\'\'/>').children[0] hashify(node) equal(node.name, 'a', 'node name') deepEqual(node.attributes, {id: ''}, 'attribtues') equal(node.hash, 39584047, 'node hash') }) test('attributes 3', function() { var node = serializeHtml('<a id="a"/>').children[0] hashify(node) equal(node.name, 'a', 'node name') deepEqual(node.attributes, {id: 'a'}, 'attributes') equal(node.hash, 65798544, 'node hash') }) test('attributes 4', function() { var node = serializeHtml('<a id = \'a\'/>').children[0] hashify(node) equal(node.name, 'a', 'node name') deepEqual(node.attributes, {id: 'a'}, 'attributes') equal(node.hash, 65798544, 'node hash') }) test('attributes 5', function() { var node = serializeHtml('<a id\n=\n"a\'"/>').children[0] hashify(node) equal(node.name, 'a', 'node name') deepEqual(node.attributes, {id: "a'"}, 'attributes') equal(node.hash, 94568887, 'node hash') }) test('attributes 6', function() { var node = serializeHtml('<a id\n=\n"a=\'b\'"\n/>').children[0] hashify(node) equal(node.name, 'a', 'node name') deepEqual(node.attributes, {id: "a='b'"}, 'attributes') equal(node.hash, 209715837, 'node hash') }) test('attributes 7', function() { var node = serializeHtml('<a id="a" class="\nb "/>').children[0] hashify(node) equal(node.name, 'a', 'node name') deepEqual(node.attributes, {id: 'a', class: '\nb '}, 'attributes') equal(node.hash, 499844146, 'node hash') }) test('attributes 8', function() { var node = serializeHtml('<a attr1="first"attr2="second"/>').children[0] hashify(node) equal(node.name, 'a', 'node name') deepEqual(node.attributes, {attr1: 'first', attr2: 'second'}, 'attributes') equal(node.hash, 1708460255, 'node hash') }) test('attributes 9', function() { var node = serializeHtml('<a attr="<p>"/>').children[0] hashify(node) equal(node.name, 'a', 'node name') deepEqual(node.attributes, {attr: '<p>'}, 'attributes') equal(node.hash, 239928071, 'node hash') }) test('children 0', function() { var node = serializeHtml('<a>a</a>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 168362667, 'node hash') equal(node.children[0].name, '#text', 'child name') equal(node.children[0].text, 'a', 'child text') equal(node.children.length, 1, 'children length') }) test('children 1', function() { var node = serializeHtml('<a>\n</a>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 162660948, 'node hash') equal(node.children[0].name, '#text', 'child 0 name') equal(node.children[0].text, '\n', 'child 0 text') equal(node.children[0].hash, 118096371, 'child 0 hash') equal(node.children.length, 1, 'children length') }) test('children 2', function() { var node = serializeHtml('<a> a \n b </a>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 479593367, 'node hash') equal(node.children[0].name, '#text', 'child 0 name') equal(node.children[0].text, ' a \n b ', 'child 0 text') equal(node.children[0].hash, 396886838, 'child 0 hash') equal(node.children.length, 1, 'children length') }) test('children 3', function() { var node = serializeHtml('<a>\n<b></b></a>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 208143030, 'node hash') equal(node.children[0].name, '#text', 'child 0 name') equal(node.children[0].text, '\n', 'child 0 text') equal(node.children[0].hash, 118096371, 'child 0 hash') equal(node.children[1].name, 'b', 'child 1 name') equal(node.children[1].hash, 6488163, 'child 1 hash') equal(node.children.length, 2, 'children length') }) test('children 4', function() { var node = serializeHtml('<a>\n<b/>\n\n<c/></a>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 762774805, 'node hash') equal(node.children[0].name, '#text', 'child 0 name') equal(node.children[0].text, '\n', 'child 0 text') equal(node.children[0].hash, 118096371, 'child 0 hash') equal(node.children[1].name, 'b', 'child 1 name') equal(node.children[1].hash, 6488163, 'child 1 hash') equal(node.children[2].name, '#text', 'child 2 name') equal(node.children[2].text, '\n\n', 'child 2 text') equal(node.children[2].hash, 151454205, 'child 2 hash') equal(node.children[3].name, 'c', 'child 3 name') equal(node.children[3].hash, 6553700, 'child 3 hash') equal(node.children.length, 4, 'children length') }) test('children 5', function() { var node = serializeHtml('<a><a/></a>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 19202243, 'node hash') equal(node.children[0].name, 'a', 'child 0 name') equal(node.children[0].hash, 6422626, 'child 0 hash') equal(node.children.length, 1, 'children length') }) test('children 6', function() { var node = serializeHtml('<a><b></b></a>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 19267780, 'node hash') equal(node.children[0].name, 'b', 'child 0 name') equal(node.children[0].hash, 6488163, 'child 0 hash') equal(node.children.length, 1, 'children length') }) test('children 7', function() { var node = serializeHtml('<a><b class="c"></b></a>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 240255805, 'node hash') equal(node.children[0].name, 'b', 'child 0 name') equal(node.children[0].hash, 189334236, 'child 0 hash') deepEqual(node.children[0].attributes, {class: 'c'}, 'child 0 attributes') equal(node.children.length, 1, 'children length') }) test('collection 0', function() { var nodes = serializeHtml('<a/><b/><c/>').children hashify(nodes) equal(nodes[0].name, 'a', 'node 0 name') equal(nodes[0].hash, 6422626, 'node 0 hash') equal(nodes[0].parent.name, 'root' , 'node 0 parent') equal(nodes[1].name, 'b', 'node 1 name') equal(nodes[1].hash, 6488163, 'node 1 hash') equal(nodes[1].parent.name, 'root' , 'node 1 parent') equal(nodes[2].name, 'c', 'node 2 name') equal(nodes[2].hash, 6553700, 'node 2 hash') equal(nodes[2].parent.name, 'root' , 'node 2 parent') equal(nodes.length, 3, 'nodes length') }) test('collection 1', function() { var nodes = serializeHtml('<a></a><b></b><c></c>').children hashify(nodes) equal(nodes[0].name, 'a', 'node 0 name') equal(nodes[0].hash, 6422626, 'node 0 hash') equal(nodes[0].parent.name, 'root' , 'node 0 parent') equal(nodes[1].name, 'b', 'node 1 name') equal(nodes[1].hash, 6488163, 'node 1 hash') equal(nodes[1].parent.name, 'root' , 'node 1 parent') equal(nodes[2].name, 'c', 'node 2 name') equal(nodes[2].hash, 6553700, 'node 2 hash') equal(nodes[2].parent.name, 'root' , 'node 2 parent') equal(nodes.length, 3, 'nodes length') }) test('collection 2', function() { var node = serializeHtml('<a><b/><c/></a>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 38600999, 'node hash') equal(node.children[0].name, 'b', 'child 0 name') equal(node.children[0].hash, 6488163, 'child 0 hash') equal(node.children[1].name, 'c', 'child 1 name') equal(node.children[1].hash, 6553700, 'child 1 hash') equal(node.children.length, 2, 'children length') }) test('collection 3', function() { var node = serializeHtml('<a><b></b><c/></a>').children[0] hashify(node) equal(node.name, 'a', 'node name') equal(node.hash, 38600999, 'node hash') equal(node.children[0].name, 'b', 'child 0 name') equal(node.children[0].hash, 6488163, 'child 0 hash') equal(node.children[1].name, 'c', 'child 1 name') equal(node.children[1].hash, 6553700, 'child 1 hash') equal(node.children.length, 2, 'children length') }) <|start_filename|>lib/elements-pool.js<|end_filename|> 'use strict' /** * Dom nodes pool for dom reuse. * * @api private */ function ElementsPool() { this.store = {} } module.exports = ElementsPool /** * Get a dom element. Create if needed. * * @param {String} name * @return {Node} * @api private */ ElementsPool.prototype.allocate = function(name) { var nodes = this.store[name] return nodes && nodes.length ? nodes.shift() : this.createElement(name) } /** * Release a dom element. * * @param {Node} element * @api private */ ElementsPool.prototype.deallocate = function(element) { var name = element.nodeName.toLowerCase() if (this.store[name]) this.store[name].push(element) else this.store[name] = [element] } /** * Create dom element. * * @param {String} name - #text, div etc. * @return {Element} * @api private */ ElementsPool.prototype.createElement = function(name) { return name == '#text' ? document.createTextNode('') : document.createElement(name) } <|start_filename|>dist/diff-renderer.js<|end_filename|> !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.DiffRenderer=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ module.exports = _dereq_('./lib/renderer') },{"./lib/renderer":9}],2:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * 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. * * @providesModule adler32 */ /* jslint bitwise:true */ "use strict"; var MOD = 65521; // This is a clean-room implementation of adler32 designed for detecting // if markup is not what we expect it to be. It does not need to be // cryptographically strong, only reasonable good at detecting if markup // generated on the server is different than that on the client. function adler32(data) { var a = 1; var b = 0; for (var i = 0; i < data.length; i++) { a = (a + data.charCodeAt(i)) % MOD; b = (b + a) % MOD; } return a | (b << 16); } module.exports = adler32; },{}],3:[function(_dereq_,module,exports){ 'use strict' /** * Dom nodes pool for dom reuse. * * @api private */ function ElementsPool() { this.store = {} } module.exports = ElementsPool /** * Get a dom element. Create if needed. * * @param {String} name * @return {Node} * @api private */ ElementsPool.prototype.allocate = function(name) { var nodes = this.store[name] return nodes && nodes.length ? nodes.shift() : this.createElement(name) } /** * Release a dom element. * * @param {Node} element * @api private */ ElementsPool.prototype.deallocate = function(element) { var name = element.nodeName.toLowerCase() if (this.store[name]) this.store[name].push(element) else this.store[name] = [element] } /** * Create dom element. * * @param {String} name - #text, div etc. * @return {Element} * @api private */ ElementsPool.prototype.createElement = function(name) { return name == '#text' ? document.createTextNode('') : document.createElement(name) } },{}],4:[function(_dereq_,module,exports){ 'use strict' var adler32 = _dereq_('./adler32') /** * Add hashes to every node. * Hash is calculated using node name, text, attributes and child nodes. * * @param {Object} node * @return {String} str which is used to generate a hash * @api private */ module.exports = function hashify(node) { var attr, i var str = '' var nodes if (!node) return str if (node.name) { str += node.name if (node.text) str += node.text for (attr in node.attributes) { str += attr + node.attributes[attr] } nodes = node.children // Its a collection. } else { nodes = node } for (i in nodes) { str += hashify(nodes[i]) } node.hash = adler32(str) return str } },{"./adler32":2}],5:[function(_dereq_,module,exports){ 'use strict' /** * Find value in json obj using array or dot path notation. * * http://docs.mongodb.org/manual/core/document/#document-dot-notation * * {a: {b: {c: 3}}} * 'a.b.c' // 3 * * {a: {b: {c: [1,2,3]}}} * 'a.b.c.1' // 2 * * @param {Object|Array} obj * @param {String|Array} path * @return {Mixed} */ module.exports = function(obj, path) { var parts, i if (!obj || !path) return obj parts = typeof path == 'string' ? path.split('.') : path for (i = 0; i < parts.length; i++) { obj = obj[parts[i]] } return obj } },{}],6:[function(_dereq_,module,exports){ 'use strict' var keypath = _dereq_('./keypath') var Node = _dereq_('./node') /** * Modifier applies changes to the node. * * @param {Node} node * @api private */ function Modifier(node) { this.node = node } module.exports = Modifier /** * Exclude properties from applying the diff. * * @type {Object} * @api private */ Modifier.EXCLUDE = { length: true, parent: true } /** * Apply the changes to the node. * * @param {Array} changes * @api private */ Modifier.prototype.apply = function(changes) { for (var i = 0; i < changes.length; i++) { var change = changes[i] var prop = change.path[change.path.length - 1] if (Modifier.EXCLUDE[prop]) continue var propIsNum = false if (!isNaN(prop)) { propIsNum = true prop = Number(prop) } var method = this[prop] if (!method) { if (propIsNum) method = this['children'] else method = this['attributes'] } method.call(this, change, prop) } } /** * Modify a text node. * * @param {Change} change * @param {String} prop * @api private */ Modifier.prototype.text = function(change, prop) { var path = change.path.slice(0, change.path.length - 1) var now = change.values.now var node = keypath(this.node.children, path) node.setText(now) } /** * Insert/remove child nodes. * * @param {Change} change * @param {String|Number} prop * @api private */ Modifier.prototype.children = function(change, prop) { var now = change.values.now var node var path if (change.change == 'add') { // Insert node at specific position. if (typeof prop == 'number') { // Find a path to the parent node. if (change.path.length > 1) { path = change.path.slice(0, change.path.length - 1) path.push(prop - 1) node = keypath(this.node.children, path) } else { node = this.node } node.insertAt(prop, Node.create(now, node)) // Append children. } else { path = change.path.slice(0, change.path.length - 1) node = keypath(this.node.children, path) for (var key in now) { if (!Modifier.EXCLUDE[key]) node.append(Node.create(now[key], node)) } } } else if (change.change == 'remove') { // Remove all children. if (prop == 'children') { path = change.path.slice(0, change.path.length - 1) node = keypath(this.node.children, path) node.removeChildren() } else { path = change.path node = keypath(this.node.children, path) if (node) node.parent.removeChild(node) } } } /** * Modify attributes. * * @param {Change} change * @param {String} prop * @api private */ Modifier.prototype.attributes = function(change, prop) { var now = change.values.now var path var node if (change.change == 'add') { if (prop == 'attributes') { path = change.path.slice(0, change.path.length - 1) node = keypath(this.node.children, path) node.setAttributes(now) } else { path = change.path.slice(0, change.path.length - 2) node = keypath(this.node.children, path) node.setAttribute(prop, now) } } else if (change.change == 'update') { path = change.path.slice(0, change.path.length - 2) node = keypath(this.node.children, path) node.setAttribute(prop, now) } else if (change.change == 'remove') { if (prop == 'attributes') { path = change.path.slice(0, change.path.length - 1) node = keypath(this.node.children, path) for (prop in change.values.original) { node.removeAttribute(prop) } } else { path = change.path.slice(0, change.path.length - 2) node = keypath(this.node.children, path) node.removeAttribute(prop) } } } /** * Change tag name. * * @param {Change} change * @param {String} prop * @api private */ Modifier.prototype.name = function(change, prop) { var path = change.path.slice(0, change.path.length - 1) var node = keypath(this.node.children, path) var now = change.values.now node.setName(now) } },{"./keypath":5,"./node":7}],7:[function(_dereq_,module,exports){ 'use strict' var ElementsPool = _dereq_('./elements-pool') var queue = _dereq_('./render-queue') // Global elements pool for all nodes and all renderer instances. var pool = new ElementsPool() var counter = 0 var nodesMap = {} var ID_NAMESPACE = '__diffRendererId__' /** * Abstract node which can be rendered to a dom node. * * @param {Object} options * @param {String} options.name tag name * @param {String} [options.text] text for the text node * @param {Object} [options.attributes] key value hash of name/values * @param {Element} [options.element] if element is passed, node is already rendered * @param {Object} [options.children] NodeList like collection * @param {Node} [parent] * @api private */ function Node(options, parent) { this.id = counter++ this.name = options.name this.parent = parent if (options.text) this.text = options.text if (options.attributes) this.attributes = options.attributes if (options.element) { this.setTarget(options.element) // Not dirty if element passed. } else { this.dirty('name', true) if (this.text) this.dirty('text', true) if (this.attributes) this.dirty('attributes', this.attributes) } if (options.children) { this.children = [] for (var i in options.children) { if (i != 'length') { this.children[i] = Node.create(options.children[i], this) if (this.children[i].dirty()) this.dirty('children', true) } } } nodesMap[this.id] = this } module.exports = Node /** * Create Node instance, check if passed element has already a Node. * * @see {Node} * @api private * @return {Node} */ Node.create = function(options, parent) { if (options.element && options.element[ID_NAMESPACE]) { return nodesMap[options.element[ID_NAMESPACE]] } return new Node(options, parent) } /** * Serialize instance to json data. * * @return {Object} * @api private */ Node.prototype.toJSON = function() { var json = {name: this.name} if (this.text) json.text = this.text if (this.attributes) json.attributes = this.attributes if (this.children) { json.children = {length: this.children.length} for (var i = 0; i < this.children.length; i++) { json.children[i] = this.children[i].toJSON() } } return json } /** * Allocate, setup current target, insert children to the dom. * * @api private */ Node.prototype.render = function() { if (!this._dirty) return if (this.dirty('name')) { if (this.target) this.migrate() else this.setTarget(pool.allocate(this.name)) this.dirty('name', null) } // Handle children if (this.dirty('children') && this.children) { var newChildren = [] for (var i = 0; i < this.children.length; i++) { var child = this.children[i] // Children can be dirty for removal or for insertions only. // All other changes are handled by the child.render. if (child.dirty()) { if (child.dirty('remove')) { this.removeChildAt(i) child.dirty('remove', null) delete nodesMap[child.id] // Handle insert. } else { var next = this.children[i + 1] child.render() this.target.insertBefore(child.target, next && next.target) newChildren.push(child) child.dirty('insert', null) child.dirty('name', null) } } else { newChildren.push(child) } } // We migrate children to the new array because some of them might be removed // and if we splice them directly, we will remove wrong elements. if (newChildren) this.children = newChildren this.dirty('children', null) } // Handle textContent. if (this.dirty('text') && this.text) { this.target.textContent = this.text this.dirty('text', null) } // Handle attribtues. if (this.dirty('attributes')) { var attributes = this.dirty('attributes') for (var attrName in attributes) { var value = attributes[attrName] if (value == null) { delete this.attributes[attrName] if (this.name != '#text') this.target.removeAttribute(attrName) } else { if (!this.attributes) this.attributes = {} this.attributes[attrName] = value this.target.setAttribute(attrName, value) } } this.dirty('attributes', null) } } /** * Remove child DOM element at passed position without removing from children array. * * @param {Number} position * @api private */ Node.prototype.removeChildAt = function(position) { var child = this.children[position] child.detach() child.cleanup() if (child.children) { for (var i = 0; i < child.children.length; i++) { child.removeChildAt(i) } } pool.deallocate(child.target) child.unlink() } /** * Migrate target DOM element and its children to a new DOM element. * F.e. because tagName changed. * * @api private */ Node.prototype.migrate = function() { this.detach() this.cleanup() var oldTarget = this.target this.setTarget(pool.allocate(this.name)) // Migrate children. if (this.name == '#text') { this.children = null } else { this.text = null while (oldTarget.hasChildNodes()) { this.target.appendChild(oldTarget.removeChild(oldTarget.firstChild)) } } pool.deallocate(oldTarget) this.dirty('insert', true) } /** * Remove target DOM element from the render tree. * * @api private */ Node.prototype.detach = function() { var parentNode = this.target.parentNode if (parentNode) parentNode.removeChild(this.target) } /** * Clean up everything changed on the target DOM element. * * @api private */ Node.prototype.cleanup = function() { if (this.attributes) { for (var attrName in this.attributes) this.target.removeAttribute(attrName) } if (this.text) this.target.textContent = '' delete this.target[ID_NAMESPACE] } /** * Set all child nodes set dirty for removal. * * @api private */ Node.prototype.removeChildren = function() { if (!this.children) return for (var i = 0; i < this.children.length; i++) { this.children[i].dirty('remove', true) } this.dirty('children', true) } /** * Set child element as dirty for removal. * * @param {Node} node * @api private */ Node.prototype.removeChild = function(child) { child.dirty('remove', true) this.dirty('children', true) } /** * Clean up all references for current and child nodes. * * @api private */ Node.prototype.unlink = function() { if (this.children) { for (var i = 0; i < this.children.length; i++) { this.children[i].unlink() } } delete this.id delete this.name delete this.text delete this.attributes delete this.parent delete this.children delete this.target delete this._dirty } /** * Insert a node at specified position. * * @param {Number} position * @param {Node} node * @api private */ Node.prototype.insertAt = function(position, node) { this.dirty('children', true) node.dirty('insert', true) if (!this.children) this.children = [] this.children.splice(position, 0, node) } /** * Insert a node at the end. * * @param {Node} node * @api private */ Node.prototype.append = function(node) { var position = this.children ? this.children.length : 0 this.insertAt(position, node) } /** * Set nodes attributes. * * @param {Object} attribtues * @api private */ Node.prototype.setAttributes = function(attributes) { for (var name in attributes) { this.setAttribute(name, attributes[name]) } } /** * Set nodes attribute. * * @param {String} name * @param {String|Boolean|Null} value, use null to remove * @api private */ Node.prototype.setAttribute = function(name, value) { if (this.attributes && this.attributes[name] == value) return var attributes = this.dirty('attributes') || {} attributes[name] = value this.dirty('attributes', attributes) } /** * Remove nodes attribute. * @param {String} name * @api private */ Node.prototype.removeAttribute = function(name) { if (this.attributes && this.attributes[name] != null) this.setAttribute(name, null) } /** * Set text content. * * @param {String} content * @api private */ Node.prototype.setText = function(text) { if (this.name != '#text' || text == this.text) return this.dirty('text', true) this.text = text } /** * Element name can't be set, we need to swap out the element. * * @param {String} name * @api private */ Node.prototype.setName = function(name) { if (name == this.name) return this.dirty('name', true) this.parent.dirty('children', true) this.name = name } /** * Set target element. * * @param {Element} element * @api private */ Node.prototype.setTarget = function(element) { element[ID_NAMESPACE] = this.id this.target = element } /** * Get/set/unset a dirty flag, add to render queue. * * @param {String} name * @param {Mixed} [value] * @api private */ Node.prototype.dirty = function(name, value) { // Get flag. if (value === undefined) { return this._dirty && name ? this._dirty[name] : this._dirty } // Unset dirty flag. if (value === null) { if (this._dirty) { delete this._dirty[name] // If if its not empty object - exist. for (name in this._dirty) return // For quick check. delete this._dirty } // Set dirty flag. } else { if (!this._dirty) { this._dirty = {} // Only enqueue if its the first flag. queue.enqueue(this) } this._dirty[name] = value } } },{"./elements-pool":3,"./render-queue":8}],8:[function(_dereq_,module,exports){ 'use strict' /** * Any changed nodes land here to get considered for rendering. * * @type {Array} * @api private */ var queue = module.exports = [] /** * Add node to the queue. * * @param {Node} node * @api private */ queue.enqueue = function(node) { queue.push(node) } /** * Empty the queue. * * @param {Node} node * @api private */ queue.empty = function() { queue.splice(0) } },{}],9:[function(_dereq_,module,exports){ 'use strict' var docdiff = _dereq_('docdiff') var keypath = _dereq_('./keypath') var Node = _dereq_('./node') var Modifier = _dereq_('./modifier') var serializeDom = _dereq_('./serialize-dom') var serializeHtml = _dereq_('./serialize-html') var renderQueue = _dereq_('./render-queue') var hashify = _dereq_('./hashify') /** * Renderer constructor. * * @param {Element} element dom node for serializing and updating. * @api public */ function Renderer(element) { if (!element) throw new TypeError('DOM element required') if (!(this instanceof Renderer)) return new Renderer(element) this.node = null this.modifier = null this.refresh(element) } module.exports = Renderer Renderer.serializeDom = serializeDom Renderer.serializeHtml = serializeHtml Renderer.keypath = keypath Renderer.docdiff = docdiff Renderer.hashify = hashify /** * Start checking render queue and render. * * @api public */ Renderer.start = function() { function check() { if (!Renderer.running) return Renderer.render() requestAnimationFrame(check) } Renderer.running = true requestAnimationFrame(check) } /** * Stop checking render queue and render. * * @api public */ Renderer.stop = function() { Renderer.running = false } /** * Render all queued nodes. * * @api public */ Renderer.render = function() { if (!renderQueue.length) return for (var i = 0; i < renderQueue.length; i++) { renderQueue[i].render() } renderQueue.empty() return this } /** * Create a snapshot from the dom. * * @param {Element} [element] * @return {Renderer} this * @api public */ Renderer.prototype.refresh = function(element) { if (!element && this.node) element = this.node.target if (this.node) this.node.unlink() var json = serializeDom(element) this.node = Node.create(json) this.modifier = new Modifier(this.node) return this } /** * Find changes and apply them to virtual nodes. * * @param {String} html * @return {Renderer} this * @api public */ Renderer.prototype.update = function(html) { var next = serializeHtml(html).children // Everything has been removed. if (!next) { this.node.removeChildren() return this } var current = this.node.toJSON().children || {} var diff = docdiff(current, next) this.modifier.apply(diff) return this } },{"./hashify":4,"./keypath":5,"./modifier":6,"./node":7,"./render-queue":8,"./serialize-dom":10,"./serialize-html":11,"docdiff":13}],10:[function(_dereq_,module,exports){ 'use strict' /** * Walk through the dom and create a json snapshot. * * @param {Element} element * @return {Object} * @api private */ module.exports = function serialize(element) { var json = { name: element.nodeName.toLowerCase(), element: element } if (json.name == '#text') { json.text = element.textContent return json } var attr = element.attributes if (attr && attr.length) { json.attributes = {} var attrLength = attr.length for (var i = 0; i < attrLength; i++) { json.attributes[attr[i].name] = attr[i].value } } var childNodes = element.childNodes if (childNodes && childNodes.length) { json.children = {length: childNodes.length} var childNodesLength = childNodes.length for (var i = 0; i < childNodesLength; i++) { json.children[i] = serialize(childNodes[i]) } } return json } },{}],11:[function(_dereq_,module,exports){ 'use strict' /** * Simplified html parser. The fastest one written in javascript. * It is naive and requires valid html. * You might want to validate your html before to pass it here. * * @param {String} html * @param {Object} [parent] * @return {Object} * @api private */ module.exports = function serialize(str, parent) { if (!parent) parent = {name: 'root'} if (!str) return parent var i = 0 var end = false var added = false var current var isWhite, isSlash, isOpen, isClose var inTag = false var inTagName = false var inAttrName = false var inAttrValue = false var inCloser = false var inClosing = false var isQuote, openQuote var attrName, attrValue var inText = false var json = { parent: parent, name: '' } while (!end) { current = str[i] isWhite = current == ' ' || current == '\t' || current == '\r' || current == '\n' isSlash = current == '/' isOpen = current == '<' isClose = current == '>' isQuote = current == "'" || current == '"' if (isSlash) inClosing = true if (isClose) inCloser = false if (current == null) { end = true } else { if (inTag) { if (inCloser) { delete json.name // Tag name } else if (inTagName || !json.name) { inTagName = true if ((json.name && isWhite) || isSlash) { inTagName = false if (!json.name) { inCloser = true if (parent.parent) parent = parent.parent } } else if (isClose) { serialize(str.substr(i + 1), inClosing || inCloser ? parent : json) return parent } else if (!isWhite) { json.name += current } // Attribute name } else if (inAttrName || !attrName) { inAttrName = true if (attrName == null) attrName = '' if (isSlash || (attrName && isWhite) || (attrName && current == '=')) { inAttrName = false if (attrName) { if (!json.attributes) json.attributes = {} json.attributes[attrName] = '' } } else if (isClose) { serialize(str.substr(i + 1), inClosing || inCloser ? parent : json) return parent } else if (!isWhite) { attrName += current } // Attribute value } else if (inAttrValue || attrName) { if (attrValue == null) attrValue = '' if (isQuote) { if (inAttrValue) { if (current == openQuote) { if (attrValue) json.attributes[attrName] = attrValue inAttrValue = false attrName = attrValue = null } else { attrValue += current } } else { inAttrValue = true openQuote = current } } else if (inAttrValue) { attrValue += current } } } else if (isOpen) { if (inText) { serialize(str.substr(i), parent) return parent } inTag = true } else if (isSlash && !inAttrValue) { end = true } else { inText = true inTag = false if (!json.name) json.name = '#text' if (json.text == null) json.text = '' json.text += current } if (json.name && !added) { if (!parent.children) parent.children = {length: 0} parent.children[parent.children.length] = json parent.children.length++ added = true } } if (isClose) inClosing = false ++i } return parent } },{}],12:[function(_dereq_,module,exports){ var utils = _dereq_('./utils'); /** * Diff Arrays * * @param {Array} one * @param {Array} two * @return {Array} Array with values in one but not in two */ var diffArrays = function (one, two) { return one.filter(function (val) { return two.indexOf(val) === -1; }); }; /** * Extract Type * * Returns a function that can be passed to an iterator (forEach) that will * correctly update all.primitives and all.documents based on the values it * iteraties over * * @param {Object} all Object on which primitives/documents will be set * @return {Object} The all object, updated based on the looped values */ var extractType = function (all) { return function (val) { if (utils.isObject(val)) { all.primitives = false; } else { all.documents = false; } if (Array.isArray(val)) all.primitives = false; } }; /** * ArrayDiff * * @param {Array} original * @param {Array} now * @return {Object} */ module.exports = function (original, now) { var all = { primitives: true, documents: true }; original.forEach(extractType(all)); now.forEach(extractType(all)); var diff = { change: null, now: now, original: original }; if (all.primitives) { diff.change = 'primitiveArray'; diff.added = diffArrays(now, original); diff.removed = diffArrays(original, now); } else { diff.change = all.documents ? 'documentArray' : 'mixedArray'; } return diff; }; },{"./utils":14}],13:[function(_dereq_,module,exports){ var arraydiff = _dereq_('./arraydiff'); var utils = _dereq_('./utils'); /** * DocDiff * * @param {Object} original * @param {Object} now * @param {Array} path * @param {Array} changes * @return {Array} Array of changes */ module.exports = function docdiff (original, now, path, changes) { if (!original || !now) return false; if (!path) path = []; if (!changes) changes = []; var keys = Object.keys(now); keys.forEach(function (key) { var newVal = now[key]; var origVal = original[key]; // Recurse if (utils.isObject(newVal) && utils.isObject(origVal)) { return docdiff(origVal, newVal, path.concat(key), changes); } // Array diff if (Array.isArray(newVal) && Array.isArray(origVal)) { var diff = arraydiff(origVal, newVal); return changes.push(new Change(path, key, 'update', diff.change, diff.now, diff.original, diff.added, diff.removed)); } // Primitive updates and additions if (origVal !== newVal) { var type = origVal === undefined ? 'add' : 'update'; changes.push(new Change(path, key, type, 'primitive', newVal, origVal)); } }); // Primitve removals Object.keys(original).forEach(function (key) { if (keys.indexOf(key) === -1) changes.push(new Change(path, key, 'remove', 'primitive', null, original[key])); }); return changes; } /** * Change * * @param {Array} path * @param {String} key * @param {String} change * @param {String} type * @param {Mixed} now * @param {Mixed} original * @param {Array} added * @param {Array} removed */ function Change (path, key, change, type, now, original, added, removed) { this.path = path.concat(key); this.change = change; this.type = type; this.values = {}; if (change !== 'remove') this.values.now = now; if (change !== 'add') this.values.original = original; if (type === 'primitiveArray') { this.values.added = added; this.values.removed = removed; } } },{"./arraydiff":12,"./utils":14}],14:[function(_dereq_,module,exports){ /** * isObject * * @param {Mixed} arg * @return {Boolean} If arg is an object */ exports.isObject = function (arg) { return typeof arg === 'object' && arg !== null && !Array.isArray(arg); }; },{}]},{},[1]) (1) }); <|start_filename|>lib/serialize-html.js<|end_filename|> 'use strict' /** * Simplified html parser. The fastest one written in javascript. * It is naive and requires valid html. * You might want to validate your html before to pass it here. * * @param {String} html * @param {Object} [parent] * @return {Object} * @api private */ module.exports = function serialize(str, parent) { if (!parent) parent = {name: 'root'} if (!str) return parent var i = 0 var end = false var added = false var current var isWhite, isSlash, isOpen, isClose var inTag = false var inTagName = false var inAttrName = false var inAttrValue = false var inCloser = false var inClosing = false var isQuote, openQuote var attrName, attrValue var inText = false var json = { parent: parent, name: '' } while (!end) { current = str[i] isWhite = current == ' ' || current == '\t' || current == '\r' || current == '\n' isSlash = current == '/' isOpen = current == '<' isClose = current == '>' isQuote = current == "'" || current == '"' if (isSlash) inClosing = true if (isClose) inCloser = false if (current == null) { end = true } else { if (inTag) { if (inCloser) { delete json.name // Tag name } else if (inTagName || !json.name) { inTagName = true if ((json.name && isWhite) || isSlash) { inTagName = false if (!json.name) { inCloser = true if (parent.parent) parent = parent.parent } } else if (isClose) { serialize(str.substr(i + 1), inClosing || inCloser ? parent : json) return parent } else if (!isWhite) { json.name += current } // Attribute name } else if (inAttrName || !attrName) { inAttrName = true if (attrName == null) attrName = '' if (isSlash || (attrName && isWhite) || (attrName && current == '=')) { inAttrName = false if (attrName) { if (!json.attributes) json.attributes = {} json.attributes[attrName] = '' } } else if (isClose) { serialize(str.substr(i + 1), inClosing || inCloser ? parent : json) return parent } else if (!isWhite) { attrName += current } // Attribute value } else if (inAttrValue || attrName) { if (attrValue == null) attrValue = '' if (isQuote) { if (inAttrValue) { if (current == openQuote) { if (attrValue) json.attributes[attrName] = attrValue inAttrValue = false attrName = attrValue = null } else { attrValue += current } } else { inAttrValue = true openQuote = current } } else if (inAttrValue) { attrValue += current } } } else if (isOpen) { if (inText) { serialize(str.substr(i), parent) return parent } inTag = true } else if (isSlash && !inAttrValue) { end = true } else { inText = true inTag = false if (!json.name) json.name = '#text' if (json.text == null) json.text = '' json.text += current } if (json.name && !added) { if (!parent.children) parent.children = {length: 0} parent.children[parent.children.length] = json parent.children.length++ added = true } } if (isClose) inClosing = false ++i } return parent }
kof/diff-renderer
<|start_filename|>packages/sql/package.json<|end_filename|> { "name": "prettier-plugin-sql", "version": "0.4.1", "type": "module", "description": "An opinionated sql formatter plugin for Prettier", "repository": "<EMAIL>/rx-ts/prettier.git", "homepage": "https://github.com/rx-ts/prettier/blob/master/packages/sql", "author": "JounQin <<EMAIL>>", "license": "MIT", "main": "./lib/index.cjs", "module": "./lib/index.js", "exports": { "import": "./lib/index.js", "require": "./lib/index.cjs" }, "jsdelivr": "./lib/umd.min.js", "unpkg": "./lib/umd.min.js", "types": "./lib/index.d.ts", "files": [ "lib" ], "keywords": [ "sql", "big-query", "db2", "flink-sql", "hive", "maria-db", "mysql", "n1ql", "pl-sql", "postgre-sql", "redshift", "transact-sql", "tsql", "plugin", "prettier", "prettier-plugin" ], "peerDependencies": { "prettier": "^2.0.0" }, "dependencies": { "node-sql-parser": "^4.0.0", "sql-formatter": "^4.0.2" }, "publishConfig": { "access": "public" } } <|start_filename|>packages/pkg/test/fixtures/fixture2.json<|end_filename|> { "name": "@rxts/prettier-plugin-pkg", "version": "0.0.0", "description": "An opinionated package.json formatter plugin for Prettier", "license": "MPL-2.0", "repository": "<EMAIL>/rx-ts/prettier.git", "author": "JounQin <<EMAIL>>", "scripts": { "bootstrap": "yarn build && tsc --module commonjs --outDir lib/cjs", "build": "ts-node -O '{\"module\":\"commonjs\"}' build" }, "homepage": "https://github.com/rx-ts/prettier/blob/master/packages/pkg", "main": "lib/cjs", "engines": { "node": ">= 8.0.0" }, "files": [ "lib", "rules", "LICENSE", "README.md" ], "keywords": [ "package", "package.json", "pkg", "plugin", "prettier", "prettier-plugin" ], "peerDependencies": { "prettier": "^1.18.2" }, "es2015": "lib/es2015", "module": "lib/esm" } <|start_filename|>tsconfig.base.json<|end_filename|> { // used by ESLint "extends": "./tsconfig.lib", "compilerOptions": { "baseUrl": ".", "strictFunctionTypes": false } } <|start_filename|>packages/sh/test/fixtures/Dockerfile<|end_filename|> FROM node:lts-alpine as builder # 安装与编译代码 COPY . /app WORKDIR /app RUN yarn --frozen-lockfile && \ yarn build && \ find . -name '*.map' -type f -exec rm -f {} \; # 最终的应用 FROM abiosoft/caddy COPY --from=builder /app/packages/ufc-host-app/build /srv EXPOSE 2015 <|start_filename|>.eslintrc.js<|end_filename|> require('ts-node').register() module.exports = { extends: '@1stg', } <|start_filename|>package.json<|end_filename|> { "name": "@rxts/prettier", "version": "0.0.0", "description": "Opinionated but Incredible Prettier plugins.", "repository": "<EMAIL>:rx-ts/prettier.git", "author": "JounQin <<EMAIL>>", "license": "MIT", "private": true, "workspaces": [ "packages/*" ], "scripts": { "build": "run-p build:*", "build:r": "r -f cjs,umd -g \"{'mvdan-sh':'sh','prettier/parser-babel':'prettierPlugins.babel','prettier-plugin-pkg':'prettierPlugins.pkg','prettier-plugin-sh':'prettierPlugins.sh','prettier-plugin-sql':'prettierPlugins.sql','node-sql-parser':'NodeSQLParser','sql-formatter':'sqlFormatter'}\" -x mvdan-sh,node-sql-parser,sql-formatter -p", "build:ts": "tsc -b", "clean": "rimraf 'packages/*/{lib,*.tsbuildinfo}'", "format": "ts-node scripts/format", "languages": "ts-node scripts/languages", "lint": "run-p lint:*", "lint:es": "eslint . --cache -f friendly", "prepare": "simple-git-hooks && yarn languages && yarn-deduplicate --strategy fewer || exit 0", "release": "changeset publish", "test": "jest", "typecov": "type-coverage" }, "devDependencies": { "@1stg/lib-config": "^4.1.2", "@babel/types": "^7.16.0", "@changesets/changelog-github": "^0.4.2", "@changesets/cli": "^2.18.1", "@pkgr/imagemin": "^2.1.0", "@types/jest": "^27.0.3", "@types/js-yaml": "^4.0.5", "@types/lodash": "^4.14.177", "@types/mvdan-sh": "^0.5.1", "@types/prettier": "^2.4.2", "https-proxy-agent": "^5.0.0", "js-yaml": "^4.1.0", "lodash": "^4.17.21", "ts-jest": "^27.0.7", "ts-node": "^10.4.0", "type-coverage": "^2.19.0", "typescript": "^4.5.2" }, "resolutions": { "prettier": "^2.4.1" }, "commitlint": { "extends": [ "@1stg" ] }, "eslintIgnore": [ "coverage", "**/fixtures", "**/lib", "**/CHANGELOG.md", "packages/*/src/languages.ts", "!/.*.js" ], "jest": { "preset": "ts-jest", "collectCoverage": true }, "renovate": { "extends": [ "@1stg" ] }, "typeCoverage": { "atLeast": 98.21, "cache": true, "detail": true, "ignoreAsAssertion": true, "ignoreFiles": [ "**/*.d.ts" ], "showRelativePath": true, "strict": true, "update": true } } <|start_filename|>packages/pkg/package.json<|end_filename|> { "name": "prettier-plugin-pkg", "version": "0.11.1", "type": "module", "description": "An opinionated package.json formatter plugin for Prettier", "repository": "<EMAIL>/rx-ts/prettier.git", "homepage": "https://github.com/rx-ts/prettier/blob/master/packages/pkg", "author": "JounQin <<EMAIL>>", "license": "MPL-2.0", "main": "./lib/index.cjs", "module": "./lib/index.js", "exports": { "import": "./lib/index.js", "require": "./lib/index.cjs" }, "jsdelivr": "./lib/umd.min.js", "unpkg": "./lib/umd.min.js", "types": "./lib/index.d.ts", "files": [ "lib" ], "keywords": [ "package", "package.json", "pkg", "plugin", "prettier", "prettier-plugin" ], "peerDependencies": { "prettier": "^2.0.0" }, "publishConfig": { "access": "public" } }
maxmilton/prettier
<|start_filename|>examples/main/main.cpp<|end_filename|> /* ========================================================================= The MIT License (MIT) Copyright 2017 <NAME>. 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 <stdio.h> #include <stdint.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_log.h" #include "esp_err.h" #include "SPIbus.hpp" #define SPI_MODE 0 #define MISO_PIN 17 #define MOSI_PIN 5 #define SCLK_PIN 23 #define CS_PIN 16 #define SPI_CLOCK 1000000 // 1 MHz extern "C" void app_main() { printf("SPIbus Example \n"); fflush(stdout); SPI_t &mySPI = vspi; // vspi and hspi are the default objects spi_device_handle_t device; ESP_ERROR_CHECK( mySPI.begin(MOSI_PIN, MISO_PIN, SCLK_PIN)); ESP_ERROR_CHECK( mySPI.addDevice(SPI_MODE, SPI_CLOCK, CS_PIN, &device)); uint8_t buffer[6]; while (1) { ESP_ERROR_CHECK(mySPI.readBytes(device, 0x3B, 6, buffer)); vTaskDelay(1000 / portTICK_PERIOD_MS); } mySPI.removeDevice(device); mySPI.close(); vTaskDelay(portMAX_DELAY); }
sdkrach/esp32-SPIbus
<|start_filename|>src/day_07/arrowFunctions.test.js<|end_filename|> describe('DAY 7: arrow functions', () => { it(`complete the function code to pass the test`, () => { let myArrowFunction = () => { }; expect(myArrowFunction(1, 2)).toEqual({ first: 1, second: 2 }); }); }); <|start_filename|>src/day_05/grouping.test.js<|end_filename|> describe('DAY 5: Test Grouping', () => { it('change the code to make the second expect throw and error', () => { let a; let b; expect(a).toBe(undefined); expect(() => b).toThrow(`b is not defined`); }); }); <|start_filename|>src/day_09/callback.test.js<|end_filename|> describe('DAY 9: Callback', () => { it(`(Synchronous callback) create a function named caller deduce the rest of the implementation reading the 2 expects`, () => { let callback = jest.fn(); let callbackArgument = Symbol('callbackArgument'); /** * * @param {function} callback * @returns {undefined} */ let caller = () => {}; let result = caller(callback); expect(callback).toBeCalledWith(callbackArgument); expect(result).toBe(callback); }); it(`(Asynchronous callback) change the function "caller" deduce the implementation reading the 2 expects`, done => { let callback = jest.fn(); let callbackArgument = Symbol('callbackArgument'); // @see https://jestjs.io/docs/en/asynchronous let caller = () => {}; setTimeout(() => expect(callback).toBeCalledWith(callbackArgument), 1000); setTimeout(() => caller(callback), 50); }, 2000); }); <|start_filename|>src/day_06/scope.test.js<|end_filename|> describe('DAY 6: Test Scope', () => { it(`n to be available outside of the block scope`, () => { { // change the declaration statement to accomplish the task let n = 5; } expect(n).toBe(5); }); it(`outer n to be 5 inner IIFE n var to be 4 (hint: add the missing code)`, () => { let n = 5; (function () { expect(n).toBe(4); }()); expect(n).toBe(5); }); it(`inner most IIFE to have access to the outer most n var (hint: change the expect statement)`, () => { let n = 5; (function () { (function () { (function () { (function () { (function () { expect(n).not.toBe(5); }()); }()); }()); }()); }()); }); }); <|start_filename|>src/day_04/arrays.test.js<|end_filename|> let hotPeppers = [ '<NAME>', '<NAME>', 'White Habanero', 'Habanero', 'Fatalii', 'Devil’s Tongue', 'Tigerpaw', 'Chocolate Habanero (aka Congo Black)', 'Caribbean Red Habanero', 'Red Savina', 'Naga Morich (aka Dorset Naga)', 'Trinidad Scorpion CARDI', 'Bhut Jolokia Chocolate', 'Bhut Jolokia (aka Ghost Pepper)', '7 Pot Chili ', 'Gibraltar (aka Spanish Naga)', 'Infinity Chili', 'Naga Viper', '7 Pod Douglah (aka Chocolate 7 Pot)', 'Trinidad Scorpion Butch T', 'Trinidad Moruga Scorpion', 'Carolina Reaper' ]; describe('DAY 4: Test Arrays', () => { it('Array to be instance of Array (literal)', () => { // use literal notation let array; expect(array).toBeInstanceOf(Array); }); it('Array to be instance of Array (constructor)', () => { // use constructor let array; expect(array).toBeInstanceOf(Array); }); it('Array to be instance of Object and Array', () => { // use any of the previous let array; expect(array).toBeInstanceOf(Array); expect(array).toBeInstanceOf(Object); }); it('Initialize Array with length of 4 (literal)', () => { // use literal let array; expect(array.length).toBe(4); }); it('Initialize Array with length of 4 (constructor)', () => { // use constructor let array; expect(array.length).toBe(4); }); it('Initialize Array with length of 1 (constructor), and first entry value to be 4', () => { // use constructor let array; expect(array.length).toBe(1); expect(array[0]).toBe(4); }); it('Mutate Array length to be 4', () => { let array = []; // use a mutator method to add elements expect(array.length).toBe(4); }); it('Mutate Array length to be 5', () => { let array = [42, 42, 42, 42, 42, 42]; // use a mutator method to remove elements expect(array.length).toBe(5); }); it('Remove the first element of the array', () => { let array = ['a', 'b', 'c', 'd']; // use a method to remove it expect(array.indexOf('a')).toBe(-1); }); it('Remove the last element of the array', () => { let array = ['a', 'b', 'c', 'd']; // use a method to remove it expect(array.indexOf('d')).toBe(-1); }); it('Remove an element off from inner boundaries of the array', () => { let array = ['a', 'b', 'c', 'd']; // use a method to remove it expect(array.indexOf('b')).toBe(-1); }); it('Create a new array containing the values of 2 different arrays (method)', () => { let array1 = ['a', 'b', 'c', 'd']; let array2 = [1, 2, 3, 4, 5]; // use a method to create it let array3; expect(array3).toEqual([1, 2, 3, 4, 5, 'a', 'b', 'c', 'd']); }); it('Create a new array containing the values of 2 different arrays (operator)', () => { let array1 = ['a', 'b', 'c', 'd']; let array2 = [1, 2, 3, 4, 5]; // use an operator to create it let array3; expect(array3).toEqual(['a', 'b', 'c', 'd', 1, 2, 3, 4, 5]); }); it('Create a string from an array (method)', () => { let array = ['a', 'b', 'c', 'd']; // use a method to create it let string; expect(string).toBe('a-b-c-d'); }); it('Create an array from a string (method)', () => { let string = 'a-b-c-d'; // use a method to create it let array; expect(array).toEqual(['a', 'b', 'c', 'd']); }); it('Create an array from a string (operator)', () => { let string = 'abcd'; // use an operator to create it let array; expect(array).toEqual(['a', 'b', 'c', 'd']); }); it('Reverse the a string using the learned techniques', () => { let string = 'abcd'; // use available method for strings an arrays let reversed; expect(reversed).toEqual('dcba'); }); it('Copy the values of array a to array b using an iteration', () => { let a = [1, 2, 'a', 'b', 'c', [6, 7]]; let b = []; /** * * iterate over a ( you can use an iteration statement or an array method ) * validate each value has been correctly copied * */ //! add your code here // ? why a IS NOT b? explain expect(a).not.toBe(b); // ? but IS EQUAL to b? explain expect(a).toEqual(b); // ? then why a[5] ACTUALLY IS b[5] expect(a[5]).toBe(b[5]); }); it('Find an element by value using an array method', () => { let array = hotPeppers; let myFavorite = 'Habanero'; // use an array method let found; expect(found).toBe(myFavorite); }); }); <|start_filename|>src/day_05/branching.test.js<|end_filename|> describe('DAY 5: Test Branching - if...else', () => { it('b to be true if a is truthy', () => { let a; let b; if (a) { // } else { // } expect(b).toBe(true); }); it('b to be false if a is truthy', () => { let a; let b; if (a) { // } else { // } expect(b).toBe(false); }); it('b to be 1 if a is truthy ( use postfix unary operator )', () => { let a; let b = 0; if (a) { // } else { // } // are prefix and postfix interchangeable here? expect(b).toBe(1); }); it('b to be -1 if a is truthy ( use prefix unary operator )', () => { let a; let b = 0; if (a) { // } else { // } // are prefix and postfix interchangeable here? expect(b).toBe(-1); }); }); describe('DAY 5: Test Branching - switch/break', () => { it('found to be true when number 7 is the first item of array', () => { let array = []; let found = false; switch (array.indexOf(7)) { case -1: break; case 0: break; case 1: break; default: break; } expect(found).toBe(true); }); it('found to be true when number 7 is not an item of array', () => { let array = []; let found = false; switch (array.indexOf(7)) { case -1: break; case 0: break; case 1: break; default: break; } expect(found).toBe(true); }); it('found to be true when number 7 is at index 4 of array', () => { let array = []; let found = false; switch (array.indexOf(7)) { case -1: break; case 0: break; case 1: break; default: found = true; break; } expect(found).toBe(true); }); it('found to be true when number 7 is at index 2 or 3 or 4 of array ( wanna try Fallthrough? )', () => { let array = []; let found = false; switch (array.indexOf(7)) { case -1: break; case 0: break; case 1: break; default: found = true; break; } expect(found).toBe(true); }); }); describe('DAY 5: Test Branching - short circuit', () => { it('c to be "hell yeah" using logical AND to evaluate a AND b, AND the value assigned to c', () => { let a; let b; let c = a && b && 'hell yeah'; expect(c).toBe('hell yeah'); }); it('c to be "hell yeah" using logical OR to evaluate a OR b, AND the value assigned to c ( find the error and fix it )', () => { let a = 1; let b; let c = a || b && 'hell yeah'; expect(c).toBe('hell yeah'); }); it('c to be true IF a AND b are numbers and > than 42', () => { // read the test spec carefully before start coding ;) let a; let b; let c = false; expect(c).toBe(true); }); }); describe('DAY 5: Test Branching - conditional operator ( ternary )', () => { it('c to be true IF a AND b are numbers and > than 42, else it should be false', () => { let a = null; let b = null; let c = null; // use ternary operator during assignment expect(c).toBe(true); a = null; b = null; c = null; // use ternary operator during assignment expect(c.toString()).toBe('Error: Not valid values for a and b'); }); it(`if speed is faster than 140, traffic ticket should be 8000, else if, it's faster than 130, traffic ticket should be 3000 else, traffic ticket should be 0`, () => { let speed; let trafficTicket; // use ternary operator during assignment expect(trafficTicket).toBe(8000); // change the values so the test may pass ( use ternary operator for trafficTicket ) expect(trafficTicket).toBe(3000); // change the values so the test may pass ( use ternary operator for trafficTicket ) expect(trafficTicket).toBe(0); /** * it seems we had to do some repetitive work here * any clue about how to avoid it? */ }); }); <|start_filename|>src/day_06/hoisting.test.js<|end_filename|> describe('DAY 6: Test Hoisting', () => { it(`myHoistedVariable should be hoisted as undefined, NOT to throw a reference error`, () => { expect(myHoistedVariable).toBeUndefined(); // change the declaration statement to complete the test let myHoistedVariable = 3; }); it(`myHoistedFunctionExpression should be hoisted as undefined, NOT to throw a reference error`, () => { expect(myHoistedFunctionExpression).toBeUndefined(); // change the declaration statement to complete the test const myHoistedFunctionExpression = function () { }; }); it(`myHoistedFunctionDeclaration should be hoisted together with its body, NOT to throw a reference error`, () => { // change the expect clause to complete the test // @see https://jestjs.io/docs/en/expect documentation for help expect(myHoistedFunctionDeclaration).toThrow(); /** * @returns {undefined} */ function myHoistedFunctionDeclaration () { } }); }); <|start_filename|>src/day_05/exceptionHandling.test.js<|end_filename|> describe('DAY 5: Test Exception Handling', () => { it('throw explicitly an error and on catch define a as true', () => { let a; expect(a).toBe(true); }); it('throw explicitly an error and assign the error to a, make the verification of the message', () => { let a; expect(a.toString()).toBe(`Error: I'm an error`); }); it('throw explicitly an error and assign the error to a, make the verification of type', () => { let a; expect(a).toBeInstanceOf(Error); }); });
danichim/a-walk-in-javascript
<|start_filename|>agent/http/push.go<|end_filename|> package http import ( "encoding/json" "github.com/leancloud/satori/agent/g" "github.com/leancloud/satori/common/model" "net/http" ) func httpPush(w http.ResponseWriter, req *http.Request) { if req.ContentLength == 0 { http.Error(w, "body is blank", http.StatusBadRequest) return } decoder := json.NewDecoder(req.Body) var metrics []*model.MetricValue err := decoder.Decode(&metrics) if err != nil { http.Error(w, "cannot decode body", http.StatusBadRequest) return } g.SendToTransfer(metrics) w.Write([]byte("success")) } <|start_filename|>satori-rules/rules/infra/tcp.clj<|end_filename|> (ns infra.tcp (:require [riemann.streams :refer :all] [agent-plugin :refer :all] [alarm :refer :all] [lib :refer :all])) (def infra-tcp-rules (->waterfall (by :host) (where (service "TcpExt.ListenOverflows")) (moving-event-window 4) (->difference) (aggregate max) (judge (> 100)) (changed :state) (! {:note "有进程的 Listen 队列爆了" :level 5 :expected 0 :groups [:operation]}))) <|start_filename|>common/utils/map.go<|end_filename|> package utils // TODO 以下的部分, 考虑放到公共组件库 func KeysOfMap(m map[string]string) []string { keys := make([]string, len(m)) i := 0 for key, _ := range m { keys[i] = key i++ } return keys } <|start_filename|>frontend/view/top-nav.js<|end_filename|> var template = ` <div id="top_nav" class="top_nav"> <div class="nav_menu"> <!--<nav class="" role="navigation"> <div class="nav toggle"> <a id="menu_toggle"><i class="fa fa-bars"></i></a> </div> <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> <img src="images/img.jpg" alt=""><NAME> <span class=" fa fa-angle-down"></span> </a> <ul class="dropdown-menu dropdown-usermenu pull-right"> <li><a href="javascript:;"> Profile</a></li> <li> <a href="javascript:;"> <span class="badge bg-red pull-right">50%</span> <span>Settings</span> </a> </li> <li><a href="javascript:;">Help</a></li> <li><a href="login.html"><i class="fa fa-sign-out pull-right"></i> Log Out</a></li> </ul> </li> <li role="presentation" class="dropdown"> <a href="javascript:;" class="dropdown-toggle info-number" data-toggle="dropdown" aria-expanded="false"> <i class="fa fa-envelope-o"></i> <span class="badge bg-green">6</span> </a> <ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu"> <li> <a> <span class="image"><img src="images/img.jpg" alt="Profile Image" /></span> <span> <span><NAME></span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="images/img.jpg" alt="Profile Image" /></span> <span> <span><NAME></span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="images/img.jpg" alt="Profile Image" /></span> <span> <span><NAME></span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="images/img.jpg" alt="Profile Image" /></span> <span> <span><NAME></span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <div class="text-center"> <a> <strong>See All Alerts</strong> <i class="fa fa-angle-right"></i> </a> </div> </li> </ul> </li> </ul> </nav>--> </div> </div> `; <|start_filename|>agent/funcs/funcs.go<|end_filename|> package funcs import ( "log" "github.com/leancloud/satori/agent/g" "github.com/leancloud/satori/common/model" ) type FuncsAndInterval struct { Fs []func() []*model.MetricValue Interval int } var Mappers []FuncsAndInterval func BuildMappers() { if g.Config().NoBuiltin { log.Println("Container mode specified, disable built-in metrics except `agent.container-alive`") Mappers = []FuncsAndInterval{ FuncsAndInterval{ Fs: []func() []*model.MetricValue{ ContainerAliveMetrics, }, Interval: 60, }, } } else { Mappers = []FuncsAndInterval{ FuncsAndInterval{ Fs: []func() []*model.MetricValue{ AgentMetrics, CpuMetrics, NetMetrics, KernelMetrics, LoadAvgMetrics, MemMetrics, DiskIOMetrics, IOStatsMetrics, UdpMetrics, DeviceMetrics, SocketStatSummaryMetrics, }, Interval: 60, }, } } } <|start_filename|>frontend/css/custom-satori.css<|end_filename|> @charset "UTF-8"; html, body, .container, .main_container, .right_col { height: 100%; } .left_col { overflow-x: hidden; overflow-y: auto; } .right_col { overflow-y: auto; } .no-left-radius { border-top-left-radius: 0; border-bottom-left-radius: 0; } .no-right-radius { border-top-right-radius: 0; border-bottom-right-radius: 0; } .events-row td { vertical-align: middle !important; } .events-row .status { font-size: 20pt; } .icheck { -webkit-appearance: none; -moz-appearance: none; -o-appearance: none; appearance: none; *display: inline; background: url(icheck-green.png) no-repeat; border: none; cursor: pointer; display: inline-block; height: 20px; top: 0%; left: 0%; margin: 0 !important; padding: 0 !important; vertical-align: middle; width: 20px; transition: background-position 0.2s; } .icheck:checked { background-position: -22px 0; } .icheck:disabled { background-position: -44px 0; cursor: default; } .icheck:checked:disabled { background-position: -66px 0; } <|start_filename|>master/http/http.go<|end_filename|> package http import ( "encoding/json" "log" "net/http" "github.com/leancloud/satori/master/g" "github.com/leancloud/satori/master/state" ) func addHandlers() { http.HandleFunc("/state", func(w http.ResponseWriter, r *http.Request) { state.StateLock.RLock() s, err := json.Marshal(state.State) state.StateLock.RUnlock() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.Write(s) }) } func Start() { listen := g.Config().HTTP if listen == "" { return } addHandlers() s := &http.Server{ Addr: listen, MaxHeaderBytes: 1 << 30, } log.Println("starting REST API on", listen) log.Fatalln(s.ListenAndServe()) } <|start_filename|>common/cpool/clustered.go<|end_filename|> package cpool import ( "fmt" "sync" ) // ConnPools Manager type ClusteredConnPool struct { sync.RWMutex M map[string]*ConnPool } func CreateClusteredConnPool(connPoolFactory func(addr string) *ConnPool, cluster []string) *ClusteredConnPool { cp := &ClusteredConnPool{M: make(map[string]*ConnPool)} for _, addr := range cluster { cp.M[addr] = connPoolFactory(addr) } return cp } // 同步发送, 完成发送或超时后 才能返回 func (this *ClusteredConnPool) Call(addr string, arg interface{}) (interface{}, error) { connPool, exists := this.Get(addr) if !exists { return nil, fmt.Errorf("%s has no connection pool", addr) } return connPool.Call(arg) } func (this *ClusteredConnPool) Get(address string) (*ConnPool, bool) { this.RLock() defer this.RUnlock() p, exists := this.M[address] return p, exists } func (this *ClusteredConnPool) Destroy() { this.Lock() defer this.Unlock() addresses := make([]string, 0, len(this.M)) for address := range this.M { addresses = append(addresses, address) } for _, address := range addresses { this.M[address].Destroy() delete(this.M, address) } } func (this *ClusteredConnPool) Stats() []*ConnPoolStats { rst := make([]*ConnPoolStats, 0, 5) for _, p := range this.M { rst = append(rst, p.Stats()) } return rst } <|start_filename|>transfer/sender/sender.go<|end_filename|> package sender import ( cmodel "github.com/leancloud/satori/common/model" "github.com/leancloud/satori/transfer/g" "log" "time" ) var Backends = make([]Backend, 0, 5) var BackendConstructors = []func(cfg *BackendConfig) Backend{ newRiemannBackend, newInfluxdbBackend, newTsdbBackend, newTransferBackend, } // 连接池 // 初始化数据发送服务, 在main函数中调用 func Start() { // 初始化默认参数 for _, s := range g.Config().Backends { cfg := parseBackendUrl(s) for _, f := range BackendConstructors { b := f(cfg) if b != nil { Backends = append(Backends, b) break } } } for _, b := range Backends { err := b.Start() if err == nil { log.Printf("Started backend %s\n", b.GetConfig().Name) } else { log.Printf("Backend %s not started: %s\n", b.GetConfig().Name, err) } } go periodicallyPrintBackendStats() log.Println("send.Start, ok") } func Send(items []*cmodel.MetricValue) { for _, b := range Backends { b.Send(items) } } func periodicallyPrintBackendStats() { for { time.Sleep(120 * time.Second) log.Println(">>>>>------------------------------------") for _, b := range Backends { stats := b.GetStats() log.Printf("Backend %s: Send: %d, Drop: %d, Fail: %d, QueueLength: %d\n", b.GetConfig().Name, stats.Send.Qps, stats.Drop.Qps, stats.Fail.Qps, stats.QueueLength.Cnt, ) for _, s := range stats.ConnPoolStats { log.Printf(" - ConnPool: %s\n", s) } log.Printf("\n") } } } <|start_filename|>agent/http/plugin.go<|end_filename|> package http import ( "net/http" "github.com/leancloud/satori/agent/plugins" ) func httpPluginReset(w http.ResponseWriter, r *http.Request) { err := plugins.ForceResetPlugin() if err != nil { w.Write([]byte(err.Error())) } else { w.Write([]byte("success")) } } <|start_filename|>swcollector/funcs/custom.go<|end_filename|> package funcs import ( "errors" "log" "strconv" "strings" "time" go_snmp "github.com/gaochao1/gosnmp" "github.com/gaochao1/sw" "github.com/leancloud/satori/common/model" "github.com/leancloud/satori/swcollector/config" ) var ( customMetricIp = map[string]map[string]bool{} ) func CustomMetrics(ch chan *model.MetricValue) { customMetrics := config.Config().CustomMetrics if len(customMetrics) <= 0 { return } AliveIpLock.RLock() defer AliveIpLock.RUnlock() for _, metric := range customMetrics { key := strings.Join(metric.IpRange, "|") ips := customMetricIp[key] if ips == nil { ipsSlice := ExpandIpRanges(metric.IpRange) ips = map[string]bool{} for _, v := range ipsSlice { ips[v] = true } customMetricIp[key] = ips } for ip := range AliveIp { if ips[ip] { go collectMetric(ip, &metric, ch) } } } } func collectMetric(ip string, metric *config.CustomMetric, ch chan *model.MetricValue) { cfg := config.Config() log.Println("Collect custom metric", metric.Metric, "for", ip) value, err := snmpGet(ip, cfg.SnmpCommunity, metric.Oid, cfg.SnmpTimeout, cfg.SnmpRetry) if err != nil { log.Println("Error collectiing custom metric", metric.Metric, ip, metric.Oid, err) return } ch <- &model.MetricValue{ Endpoint: ReverseLookup(ip), Metric: metric.Metric, Value: value, Timestamp: time.Now().Unix(), Tags: metric.Tags, } } func snmpGet(ip, community, oid string, timeout, retry int) (float64, error) { defer func() { if r := recover(); r != nil { log.Println(ip, "recovered in CustomMetric, Oid is", oid, r) } }() method := "get" var value float64 var err error var snmpPDUs []go_snmp.SnmpPDU for i := 0; i < retry; i++ { snmpPDUs, err = sw.RunSnmp(ip, community, oid, method, timeout) if len(snmpPDUs) > 0 && err == nil { value, err = interfaceTofloat64(snmpPDUs[0].Value) break } time.Sleep(100 * time.Millisecond) } return value, err } func interfaceTofloat64(v interface{}) (float64, error) { var err error switch value := v.(type) { case int: return float64(value), nil case int8: return float64(value), nil case int16: return float64(value), nil case int32: return float64(value), nil case int64: return float64(value), nil case uint: return float64(value), nil case uint8: return float64(value), nil case uint16: return float64(value), nil case uint32: return float64(value), nil case uint64: return float64(value), nil case float32: return float64(value), nil case float64: return value, nil case string: value_parsed, err := strconv.ParseFloat(value, 64) if err != nil { return 0, err } else { return value_parsed, nil } default: err = errors.New("value cannot not Parse to digital") return 0, err } } <|start_filename|>master/state/state.go<|end_filename|> package state import ( "github.com/leancloud/satori/common/model" "sync" ) type AgentInfo struct { Hostname string `json:"hostname"` IP string `json:"ip"` AgentVersion string `json:"agent-version"` PluginVersion string `json:"plugin-version"` LastSeen int64 `json:"lastseen"` } type MsgType struct { Type string `json:"type"` } // Hear these from Riemann type PluginDirInfo struct { // type = plugin-dir Hostname string `json:"hostname"` Dirs []string `json:"dirs"` } type PluginInfo struct { // type = plugin Hostname string `json:"hostname"` Params []model.PluginParam `json:"plugins"` } type PluginVersionInfo struct { // type = plugin-version Version string `json:"version"` } type MasterState struct { PluginVersion string `json:"plugin-version"` ConfigVersions map[string]int64 `json:"config-version"` Agents map[string]AgentInfo `json:"agents"` PluginDirs map[string][]string `json:"plugin-dirs"` Plugin map[string][]model.PluginParam `json:"plugins"` } var StateLock = new(sync.RWMutex) var State = MasterState{ PluginVersion: "", ConfigVersions: make(map[string]int64), Agents: make(map[string]AgentInfo), PluginDirs: make(map[string][]string), Plugin: make(map[string][]model.PluginParam), } func Start() { go notifyRestart() go receiveAgentStates() go purgeStaleNodes() } <|start_filename|>transfer/sender/tsdb.go<|end_filename|> package sender import ( "bytes" "fmt" "log" "net" "strings" "time" nsema "github.com/toolkits/concurrent/semaphore" "github.com/leancloud/satori/common/cpool" cmodel "github.com/leancloud/satori/common/model" ) type TsdbBackend struct { BackendCommon } func newTsdbBackend(cfg *BackendConfig) Backend { if cfg.Engine == "tsdb" { return &TsdbBackend{*newBackendCommon(cfg)} } else { return nil } } type TsdbItem struct { Metric string `json:"metric"` Tags map[string]string `json:"tags"` Value float64 `json:"value"` Timestamp int64 `json:"timestamp"` } func (this *TsdbItem) String() string { return fmt.Sprintf( "<Metric:%s, Tags:%v, Value:%v, TS:%d>", this.Metric, this.Tags, this.Value, this.Timestamp, ) } func (this *TsdbItem) TsdbString() (s string) { s = fmt.Sprintf("put %s %d %.3f ", this.Metric, this.Timestamp, this.Value) for k, v := range this.Tags { key := strings.ToLower(strings.Replace(k, " ", "_", -1)) value := strings.Replace(v, " ", "_", -1) s += key + "=" + value + " " } return s } type TsdbClient struct { cli net.Conn name string } func (this TsdbClient) Name() string { return this.name } func (this TsdbClient) Closed() bool { return this.cli == nil } func (this TsdbClient) Close() error { if this.cli != nil { err := this.cli.Close() this.cli = nil return err } return nil } func (this TsdbClient) Call(items interface{}) (interface{}, error) { return this.cli.Write(items.([]byte)) } func (this *TsdbBackend) tsdbConnect(name string, p *cpool.ConnPool) (cpool.PoolClient, error) { addr := p.Address _, err := net.ResolveTCPAddr("tcp", addr) if err != nil { return nil, err } connTimeout := time.Duration(p.ConnTimeout) * time.Millisecond conn, err := net.DialTimeout("tcp", addr, connTimeout) if err != nil { return nil, err } return TsdbClient{conn, name}, nil } func (this *TsdbBackend) createConnPool() *cpool.ConnPool { cfg := this.config p := cpool.NewConnPool( cfg.Name, cfg.Url.Host, cfg.MaxConn, cfg.MaxIdle, cfg.ConnTimeout, cfg.CallTimeout, this.tsdbConnect, ) return p } func (this *TsdbBackend) Start() error { this.pool = this.createConnPool() go this.sendProc() return nil } func (this *TsdbBackend) sendProc() { cfg := this.config sema := nsema.NewSemaphore(cfg.MaxConn) for { items := this.queue.PopBackBy(cfg.Batch) if len(items) == 0 { time.Sleep(DefaultSendTaskSleepInterval) continue } // 同步Call + 有限并发 进行发送 sema.Acquire() go func(itemList []interface{}) { defer sema.Release() var tsdbBuffer bytes.Buffer for i := 0; i < len(itemList); i++ { tsdbItem := itemList[i].(*TsdbItem) tsdbBuffer.WriteString(tsdbItem.TsdbString()) tsdbBuffer.WriteString("\n") } var err error for i := 0; i < cfg.Retry; i++ { _, err = this.pool.Call(tsdbBuffer.Bytes()) if err == nil { this.sendCounter.IncrBy(int64(len(itemList))) break } time.Sleep(100 * time.Millisecond) } if err != nil { this.failCounter.IncrBy(int64(len(itemList))) log.Println(err) return } }(items) } } // 将原始数据入到tsdb发送缓存队列 func (this *TsdbBackend) Send(items []*cmodel.MetricValue) { for _, item := range items { tsdbItem := convert2TsdbItem(item) isSuccess := this.queue.PushFront(tsdbItem) if !isSuccess { this.dropCounter.Incr() } } } // 转化为tsdb格式 func convert2TsdbItem(d *cmodel.MetricValue) *TsdbItem { t := TsdbItem{Tags: make(map[string]string)} for k, v := range d.Tags { t.Tags[k] = v } t.Tags["endpoint"] = d.Endpoint t.Metric = d.Metric t.Timestamp = d.Timestamp t.Value = d.Value return &t } <|start_filename|>common/model/transfer.go<|end_filename|> package model import ( "fmt" ) type TransferResponse struct { Message string Total int Invalid int Latency int64 } func (this *TransferResponse) String() string { return fmt.Sprintf( "<Total=%v, Invalid:%v, Latency=%vms, Message:%s>", this.Total, this.Invalid, this.Latency, this.Message, ) } <|start_filename|>satori-rules/rules/mysql/query.clj<|end_filename|> (ns mysql.query (:require [clojure.string :as string] [riemann.streams :refer :all] [alarm :refer :all] [agent-plugin :refer :all] [lib :refer :all])) (def mysql-query-rules (sdo (where (host "db-sms02") ; 更多用法看源码: plugins/mysql.query ; 要注意安全问题 (plugin "mysql.query" 60 {:name "bad-user-count" :host "localhost" :port 3306 :user "user_for_monitor" :password "<PASSWORD>!" :database "awesome_app" :sql "SELECT count(*) FROM user WHERE bad = 1"}) (plugin "mysql.query" 60 {:name "total-user-count" :host "localhost" :port 3306 :user "user_for_monitor" :password "<PASSWORD>!" :database "awesome_app" :sql "SELECT count(*) FROM user"})) (where (service "mysql.query.bad-user-count") (judge (> 50) (runs 2 :state (alarm-every 5 :min (! {:note "坏用户太多了!" :level 3 :groups [:operation]}))))) (where (service #"^mysql\.query\..*-user-count$") (slot-window :service {:total "mysql.query.total-user-count", :bad "mysql.query.bad-user-count"} (slot-coalesce {:service "app.sms.bad-user-percent", :metric (if (> bad 5) (/ bad total) -1)} (judge (> 0.5) (runs 2 :state (alarm-every 5 :min (! {:note "坏用户占比过高!" :level 3 :groups [:operation]}))))))))) <|start_filename|>swcollector/funcs/funcs.go<|end_filename|> package funcs import ( "encoding/json" "log" "os" "time" "github.com/leancloud/satori/common/model" "github.com/leancloud/satori/swcollector/config" ) var Collectors = []func(chan *model.MetricValue){ SwIfMetrics, CpuMemMetrics, PingMetrics, CustomMetrics, } func StartCollect() { ch := make(chan *model.MetricValue, 30) go doCollect(ch) go doOutput(ch) } func doCollect(ch chan *model.MetricValue) { step := config.Config().Interval for { log.Println("doCollect round started") for _, f := range Collectors { go f(ch) } time.Sleep(time.Duration(step) * time.Second) } } func doOutput(ch chan *model.MetricValue) { emptyTags := map[string]string{} cook := func(m *model.MetricValue) *model.MetricValue { if m.Tags == nil { m.Tags = emptyTags } return m } for { L := []*model.MetricValue{} v := cook(<-ch) L = append(L, v) for i := 0; i < len(ch); i++ { L = append(L, cook(<-ch)) } s, _ := json.Marshal(L) os.Stdout.Write(s) os.Stdout.WriteString("\n") } } <|start_filename|>satori-rules/rules/agent_plugin.clj<|end_filename|> (ns agent-plugin (:require [clojure.set :as cset] [clojure.string :as string] [clojure.stacktrace :as st] [clojure.data.json :as json] [clojure.tools.logging :refer [info error]] [clojure.java.shell :refer [sh *sh-dir*]] [clojure.core.async :refer [chan go-loop <! >! <!! >!! mix admix timeout alts!]] [riemann.service :as service] [riemann.config :refer :all] [riemann.common :refer [event]] [riemann.test :refer [io]] [riemann.bin :refer [reload!]] [taoensso.carmine :as car]) (:import (java.util.concurrent.locks LockSupport))) (defmacro def- [& forms] `(def ^{:private true} ~@forms)) (def- state (atom {})) #_({"dns1" {:dirs #{"a" "b"} :plugins #{{:_metric "a", :_step 30 :a 1} {:_metric "b", :_step 30 :b 2}}}}) (def- masters (atom nil)) (defn- debounce [in ms] (let [out (chan)] (go-loop [last-val nil] (let [val (if (nil? last-val) (<! in) last-val) timer (timeout ms) [new-val ch] (alts! [in timer])] (condp = ch timer (do (>! out val) (recur nil)) in (if new-val (recur new-val))))) out)) (def- update-channel (chan)) (def- update-channel-mix (mix update-channel)) (def- debouncers (atom {})) (def- master-informer (go-loop [] (let [v (json/write-str (<! update-channel))] (doseq [m @masters] (car/wcar m (car/publish "satori:master-state" v)))) (recur))) (defn- inform-master [state] (let [k (str (:type state) ":" (:hostname state)) ch (or (get @debouncers k) (let [ch' (chan)] (admix update-channel-mix (debounce ch' 3000)) (swap! debouncers (fn [v v'] (merge v' v)) {k ch'}) (get @debouncers k)))] (>!! ch state))) (defn- update-plugin-dirs! [host dirs] (inform-master {:type "plugin-dir", :hostname host, :dirs dirs})) (defn- update-plugins! [host plugins] (inform-master {:type "plugin", :hostname host, :plugins plugins})) (defn watch-for-master-restart! [uri] (service! (service/thread-service ::watch-for-master-restart uri (fn [_] (as-> nil listener (car/with-new-pubsub-listener {:uri uri} {"satori:component-started" (fn [[_ _ component]] (when (= component "master") (info "Master restart detected, reloading...") (future (reload!))))} (car/subscribe "satori:component-started")) (try (LockSupport/park) (finally (car/close-listener listener)))))))) (defn set-master-redis! "指定 master 的 redis 地址,可以指定多个" [& uris] (when (not= @masters nil) (throw (Exception. "Masters already set"))) (doseq [uri uris] (watch-for-master-restart! uri)) (reset! masters (for [uri uris] {:pool {}, :spec {:uri uri}}))) (defn set-plugin-version! "指定插件的版本,需要是完整的 git commit hash" [v] (inform-master {:type "plugin-version", :version v})) (defn watch-for-update! [path old] (service! (service/thread-service ::watch-for-update [path old] (fn [_] (binding [*sh-dir* path] (Thread/sleep 5000) (let [r (sh "git" "rev-parse" "HEAD")] (if (not= 0 (:exit r)) (do (error "Can't determine plugin version in watch-for-update:\n" (:err r)) (Thread/sleep 30000)) (let [commit (string/trim (:out r))] (when (not= old commit) (info "Rules repo updated, reloading...") (sh "git" "reset" "--hard") (sh "git" "clean" "-f" "-d") (future (let [rst (reload!)] (if (= rst :reloaded) (do (info "Report reload success") (reinject (event {:service ".satori.riemann.newconf" :host "Satori" :metric 1 :description commit}))) (let [ex (with-out-str (st/print-stack-trace rst))] (info "Report reload failure") (reinject (event {:service ".satori.riemann.reload-failed" :host "Satori" :metric 1 :description ex})))))) (Thread/sleep 120000)))))))))) (defn set-plugin-repo! "指定插件的版本,需要指定 git 仓库的地址,需要是本地地址" [path] (io (binding [*sh-dir* path] (let [r (sh "git" "rev-parse" "HEAD")] (when (not= 0 (:exit r)) (throw (Exception. (str "Can't determine plugin version:\n" (:err r))))) (let [commit (string/trim (:out r))] (set-plugin-version! commit) (watch-for-update! path commit)))))) (defn plugin-dir "为机器指定插件目录。所有流过这个 stream 的 event 中的 host 都会执行 dirs 里面的插件。" [& dirs] (let [dirs (set dirs)] (fn [ev] (let [h (:host ev)] (when-not (cset/subset? dirs (:dirs (get @state h))) (as-> nil rst (swap! state (fn [state'] (update-in state' [h :dirs] #(cset/union % dirs)))) (update-plugin-dirs! h (:dirs (get rst h))))))))) (defn plugin "为机器指定一个插件。 metric 就是类似于 net.port.listen 的,也就是 riemann 中的 service。 step 是收集的间隔。args 是个 map,会传给插件当做参数。" [metric step args] (let [m (conj {:_metric metric :_step step} args)] (fn [ev] (let [h (:host ev)] (when-not ((or (:plugins (get @state h)) #{}) m) (as-> nil rst (swap! state (fn [state'] (update-in state' [h :plugins] #(conj (or % #{}) m)))) (update-plugins! h (:plugins (get rst h))))))))) (def plugin-metric plugin) ; for backward compatibility <|start_filename|>agent/g/cfg.go<|end_filename|> package g import ( "log" "net" "os" "regexp" "strings" "sync" "github.com/toolkits/file" tknet "github.com/toolkits/net" "gopkg.in/yaml.v2" ) type GlobalConfig struct { Debug bool `yaml:"debug"` Hostname string `yaml:"hostname"` FQDN bool `yaml:"fqdn"` IP string `yaml:"ip"` Master string `yaml:"master"` Transfer []string `yaml:"transfer"` HTTP string `yaml:"http"` NoBuiltin bool `yaml:"noBuiltin"` Cgroups *struct { Memory int64 `yaml:"mem"` CPU float32 `yaml:"cpu"` Enforce bool `yaml:"enforce"` } `yaml:"cgroups"` Plugin struct { Enabled bool `yaml:"enabled"` SigningKeys []struct { Key string `yaml:"key"` } `yaml:"signingKeys"` AuthorizedKeys string `yaml:"authorizedKeys"` Update string `yaml:"update"` Git string `yaml:"git"` CheckoutPath string `yaml:"checkoutPath"` Subdir string `yaml:"subDir"` LogDir string `yaml:"logs"` } `yaml:"plugin"` Ignore []struct { Metric string `yaml:"metric"` Tag string `yaml:"tag"` TagValue string `yaml:"tagValue"` } `yaml:"ignore"` Collector *struct { IfacePrefix []string `yaml:"ifacePrefix"` } `yaml:"collector"` AddTags map[string]string `yaml:"addTags"` } var ( ConfigFile string config *GlobalConfig lock = new(sync.RWMutex) hostnameCache string ) func Config() *GlobalConfig { lock.RLock() defer lock.RUnlock() return config } func toFQDN(ip string) string { var err error hosts, err := net.LookupAddr(ip) if err != nil || len(hosts) == 0 { return "" } fqdn := hosts[0] return strings.TrimSuffix(fqdn, ".") // return fqdn without trailing dot } func Hostname() string { if hostnameCache != "" { return hostnameCache } hostname := Config().Hostname if hostname != "" { hostnameCache = hostname return hostname } hostname, err := os.Hostname() if err != nil { panic("ERROR: os.Hostname() fail") } hostnameCache = hostname if Config().FQDN { if fqdn := toFQDN(IP()); fqdn != "" { hostnameCache = fqdn return fqdn } } return hostname } func IP() string { ip := Config().IP if ip != "" { // use ip in configuration return ip } ips, err := tknet.IntranetIP() if err != nil { log.Fatalln("get intranet ip fail:", err) } if len(ips) > 0 { ip = ips[0] } else { ip = "127.0.0.1" } return ip } func ParseConfig(cfg string) { if cfg == "" { log.Fatalln("use -c to specify configuration file") } if !file.IsExist(cfg) { log.Fatalln("config file `", cfg, "` does not exist") } ConfigFile = cfg configContent, err := file.ToTrimString(cfg) if err != nil { log.Fatalln("read config file:", cfg, "fail:", err) } var c GlobalConfig err = yaml.Unmarshal([]byte(configContent), &c) if err != nil { log.Fatalln("parse config file:", cfg, "fail:", err) } for _, item := range c.Ignore { regexp.MustCompile(item.Metric) regexp.MustCompile(item.Tag) regexp.MustCompile(item.TagValue) } lock.Lock() defer lock.Unlock() config = &c log.Println("read config file:", cfg, "successfully") } <|start_filename|>common/utils/func.go<|end_filename|> package utils import ( "fmt" ) func PK(endpoint, metric string, tags map[string]string) string { if tags == nil || len(tags) == 0 { return fmt.Sprintf("%s/%s", endpoint, metric) } return fmt.Sprintf("%s/%s/%s", endpoint, metric, SortedTags(tags)) } func PK2(endpoint, counter string) string { return fmt.Sprintf("%s/%s", endpoint, counter) } func UUID(endpoint, metric string, tags map[string]string, dstype string, step int) string { if tags == nil || len(tags) == 0 { return fmt.Sprintf("%s/%s/%s/%d", endpoint, metric, dstype, step) } return fmt.Sprintf("%s/%s/%s/%s/%d", endpoint, metric, SortedTags(tags), dstype, step) } func Checksum(endpoint string, metric string, tags map[string]string) string { pk := PK(endpoint, metric, tags) return Md5(pk) } func ChecksumOfUUID(endpoint, metric string, tags map[string]string, dstype string, step int64) string { return Md5(UUID(endpoint, metric, tags, dstype, int(step))) } <|start_filename|>agent/test/test-plugin.go<|end_filename|> package main import ( "github.com/leancloud/satori/agent/g" "github.com/leancloud/satori/agent/plugins" "github.com/leancloud/satori/common/model" "time" ) // func RunPlugins(dirs []string, metrics []model.PluginParam) { func main() { g.ParseConfig("cfg.example.yaml") cfg := g.Config() cfg.Debug = true cfg.Plugin.Enabled = true cfg.Plugin.Subdir = "." cfg.Plugin.CheckoutPath = "." go func() { for { plugins.RunPlugins([]string{"test"}, []model.PluginParam{}) time.Sleep(time.Second * 2) } }() select {} } <|start_filename|>master/state/redis.go<|end_filename|> package state import ( "encoding/json" "log" "net" "net/url" "time" "github.com/garyburd/redigo/redis" "github.com/leancloud/satori/master/g" ) func connect() net.Conn { cfg := g.Config() for { u, err := url.Parse(cfg.Redis) if err != nil { panic("Malformed redis url") } dialer := net.Dialer{ Timeout: time.Second * 30, KeepAlive: time.Second * 120, } tc, err := dialer.Dial("tcp", u.Host) if err != nil { log.Println("Can't connect redis:", err) time.Sleep(time.Second) continue } return tc } } func notifyRestart() { tc := connect() c := redis.NewConn(tc, time.Hour*24, time.Second*10) _, _ = c.Do("PUBLISH", "satori:component-started", "master") _ = c.Close() } func receiveAgentStates() { for { tc := connect() c := redis.NewConn(tc, time.Hour*24, time.Second*10) pubsub := redis.PubSubConn{c} _ = pubsub.Subscribe("satori:master-state") for { switch n := pubsub.Receive().(type) { case redis.Message: doRecvState(n.Data) case error: log.Printf("pubsub error: %v\n", n) time.Sleep(time.Second) goto bail_out } } bail_out: } } func doRecvState(raw []byte) { debug := g.Config().Debug t := MsgType{} if err := json.Unmarshal(raw, &t); err != nil { log.Println("Can't decode: %s", raw) return } StateLock.Lock() defer StateLock.Unlock() switch t.Type { case "plugin-dir": dir := PluginDirInfo{} if err := json.Unmarshal(raw, &dir); err != nil { log.Printf("Can't unmarshal plugin-dir info: %s", err) break } if debug { log.Printf("New PluginDir: %s", dir) } State.PluginDirs[dir.Hostname] = dir.Dirs State.ConfigVersions[dir.Hostname] = time.Now().Unix() case "plugin": m := PluginInfo{} if err := json.Unmarshal(raw, &m); err != nil { log.Printf("Can't unmarshal plugin info: %s", err) break } if debug { log.Printf("New PluginMetric: %s", m) } State.Plugin[m.Hostname] = m.Params State.ConfigVersions[m.Hostname] = time.Now().Unix() case "plugin-version": v := PluginVersionInfo{} if err := json.Unmarshal(raw, &v); err != nil { log.Printf("Can't unmarshal plugin-version info: %s", err) break } if v.Version != "" { if debug { log.Printf("New PluginVersion: %s\n", v.Version) } State.PluginVersion = v.Version } } } <|start_filename|>common/cpool/interface.go<|end_filename|> package cpool import "io" type PoolClient interface { io.Closer Name() string Call(arg interface{}) (interface{}, error) Closed() bool } <|start_filename|>satori-rules/rules/nvgpu/nvgpu.clj<|end_filename|> (ns nvgpu.nvgpu (:require [clojure.tools.logging :refer [info error]] [riemann.streams :refer :all] [agent-plugin :refer :all] [alarm :refer :all] [lib :refer :all])) (def infra-common-rules (sdo (where (or (= (:region event) "office") (host "host1" "host2" "host3" "host4")) (plugin "nvgpu" 0 {:duration 5})) (->waterfall (where (service "nvgpu.gtemp")) (by :host) (copy :id :aggregate-desc-key) (group-window :id) (aggregate max) (judge-gapped (> 90) (< 86)) (alarm-every 2 :min) (! {:note "GPU 过热" :level 1 :expected 85 :outstanding-tags [:host] :groups [:operation :devs]})) #_(place holder))) <|start_filename|>transfer/g/git.go<|end_filename|> package g const ( COMMIT = "59272d0" ) <|start_filename|>transfer/g/cfg.go<|end_filename|> package g import ( "log" "sync" "github.com/toolkits/file" "gopkg.in/yaml.v2" ) type GlobalConfig struct { Debug bool `yaml:"debug"` Listen string `yaml:"listen"` Backends []string `yaml:"backends"` } var ( ConfigFile string config *GlobalConfig configLock = new(sync.RWMutex) ) func Config() *GlobalConfig { configLock.RLock() defer configLock.RUnlock() return config } func ParseConfig(cfg string) { if cfg == "" { log.Fatalln("use -c to specify configuration file") } if !file.IsExist(cfg) { log.Fatalln("config file:", cfg, "is not existent. maybe you need `mv cfg.example.yaml cfg.yaml`") } ConfigFile = cfg configContent, err := file.ToTrimString(cfg) if err != nil { log.Fatalln("read config file:", cfg, "fail:", err) } var c GlobalConfig err = yaml.Unmarshal([]byte(configContent), &c) if err != nil { log.Fatalln("parse config file:", cfg, "fail:", err) } configLock.Lock() defer configLock.Unlock() config = &c log.Println("g.ParseConfig ok, file ", cfg) } // CLUSTER NODE type ClusterNode struct { Addrs []string `yaml:"addrs"` } func NewClusterNode(addrs []string) *ClusterNode { return &ClusterNode{addrs} } <|start_filename|>swcollector/funcs/common.go<|end_filename|> package funcs import ( "log" "strings" "sync" "time" "github.com/gaochao1/sw" "github.com/miekg/dns" "github.com/leancloud/satori/swcollector/config" "github.com/leancloud/satori/swcollector/logging" ) var ( reverseLookups = map[string]string{} reverseLookupLock = sync.RWMutex{} dnsServer string AliveIp = map[string]bool{} AliveIpLock = sync.RWMutex{} ) func init() { dnsConfig, err := dns.ClientConfigFromFile("/etc/resolv.conf") if err != nil { logging.Fatalln("Failed to parse /etc/resolv.conf:", err) } dnsServer = dnsConfig.Servers[0] + ":" + dnsConfig.Port } func ExpandIpRanges(ipRange []string) []string { allIp := []string{} if len(ipRange) > 0 { for _, sip := range ipRange { aip := sw.ParseIp(sip) for _, ip := range aip { allIp = append(allIp, ip) } } } return allIp } func ReverseLookup(ip string) string { cfg := config.Config() if h := cfg.CustomHosts[ip]; h != "" { return h } if !cfg.ReverseLookup { return ip } reverseLookupLock.RLock() h := reverseLookups[ip] reverseLookupLock.RUnlock() if h != "" { return h } c := dns.Client{Timeout: 1 * time.Second} arpa, err := dns.ReverseAddr(ip) if err != nil { log.Println("ReverseLookup got invalid ip:", ip, ":", err) return ip } var host string for i := 0; i < 3; i++ { m := dns.Msg{} m.RecursionDesired = true m.SetQuestion(arpa, dns.TypePTR) r, _, err := c.Exchange(&m, dnsServer) if err != nil { log.Println("Failed to perform DNS query for", ip, ":", err) host = ip } else { host = r.Answer[0].(*dns.PTR).Ptr host = strings.TrimSuffix(host, ".") } } reverseLookupLock.Lock() reverseLookups[ip] = host reverseLookupLock.Unlock() return host } <|start_filename|>satori-rules/rules/once.clj<|end_filename|> (ns once (:require io.aviso.logging)) (io.aviso.logging/install-pretty-logging) <|start_filename|>agent/cron/collector.go<|end_filename|> package cron import ( "log" "time" "github.com/leancloud/satori/agent/funcs" "github.com/leancloud/satori/agent/g" "github.com/leancloud/satori/common/model" ) func StartCollect() { if len(g.Config().Transfer) == 0 { log.Fatalln("Transfer not configured!") } go collectCPUDisks() for _, v := range funcs.Mappers { go collect(int64(v.Interval), v.Fs) } } func collectCPUDisks() { for { _ = funcs.UpdateCpuStat() _ = funcs.UpdateDiskStats() time.Sleep(time.Second) } } func collect(sec int64, fns []func() []*model.MetricValue) { t := time.NewTicker(time.Second * time.Duration(sec)).C for { <-t hostname := g.Hostname() mvs := []*model.MetricValue{} debug := g.Config().Debug for _, fn := range fns { items := fn() if items == nil { continue } if len(items) == 0 { continue } if debug { log.Println(" -> collect ", len(items), " metrics") } mvs = append(mvs, items...) } now := time.Now().Unix() for j := 0; j < len(mvs); j++ { mvs[j].Endpoint = hostname mvs[j].Timestamp = now } g.SendToTransfer(mvs) } } <|start_filename|>satori-rules/rules/infra/ceph.clj<|end_filename|> (ns infra.ceph (:use riemann.streams agent-plugin lib alarm)) (def infra-ceph-rules (where (host "ceph-host-can-run-ceph-tool") (plugin "ceph.status" 10 {}) (where (service #"^ceph\.mon\.") (by :region (copy :region :host (slot-window :service {:quorum "ceph.mon.quorum" :total "ceph.mon.num"} (slot-coalesce {:service "ceph.mon.quorum_percent", :metric (/ quorum total)} (judge (< 1) (runs 2 :state (alarm-every 5 :min (! {:note "Ceph Mon 共识人数不满" :level 3 :groups [:operation]})))) (judge (< 0.5) (runs 2 :state (alarm-every 30 :secs (! {:note "Ceph Mon 无法形成共识" :level 0 :groups [:operation]}))))))))) (where (service #"^ceph\.osd\.") (by :region (copy :region :host (slot-window :service {:total "ceph.osd.num" :up "ceph.osd.up" :in "ceph.osd.in"} (slot-coalesce {:service "ceph.osd.up_percent" :metric (/ up total)} (judge (< 1) (runs 2 :state (alarm-every 5 :min (! {:note "有不在 UP 状态的 Ceph OSD" :level 3 :groups [:operation :devs]}))))) (slot-coalesce {:service "ceph.osd.in_percent" :metric (/ in total)} (judge (< 1) (runs 2 :state (alarm-every 5 :min (! {:note "有不在 IN 状态的 Ceph OSD" :level 3 :groups [:operation :devs]}))))))))) (where (and (service "ceph.pg.by_state") (#{"degraded" "unknown" "backfilling"} (:pg_state event))) (by [:region] (copy :region :host (where (= (:pg_state event) "degraded") (judge (> 0) (runs 2 :state (alarm-every 30 :min (! {:note "Ceph 中存在降级的 PG" :level 3 :groups [:operation :devs]}))))) (where (= (:pg_state event) "unknown") (judge (> 0) (runs 2 :state (alarm-every 5 :min (! {:note "Ceph 中存在失联的PG(丢失数据!)" :level 1 :groups [:operation :devs]}))))) #_(where (= (:pg_state event) "backfilling") (judge (> 0) (runs 2 :state (alarm-every 3 :hours (! {:note "Ceph 中正在修复降级的 PG" :level 5 :groups [:operation :devs]})))))))))) <|start_filename|>swcollector/main.go<|end_filename|> package main import ( "io/ioutil" "log" "os" "runtime" "github.com/leancloud/satori/swcollector/config" "github.com/leancloud/satori/swcollector/funcs" "github.com/leancloud/satori/swcollector/logging" ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) } func main() { buf, err := ioutil.ReadAll(os.Stdin) if err != nil { logging.Fatalln("Can't read config from stdin:", err) } config.ParseConfig(buf) cfg := config.Config() if cfg.LogFile != "" { logging.SetOutputFilename(cfg.LogFile) } funcs.StartCollect() log.Printf("swcollector started, config %+v\n", cfg) select {} } <|start_filename|>frontend/view/block.js<|end_filename|> (function(Vue){ var blockTemplate = ` <div class="x_panel"> <div class="x_title"> <h2>{{ title }}<small v:if="subtitle">{{ subtitle }}</small></h2> <ul class="nav navbar-right panel_toolbox"> <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a> <!-- <ul class="dropdown-menu" role="menu"> <li><a href="#">Settings 1</a> </li> <li><a href="#">Settings 2</a> </li> </ul> --> </li> <li><a class="close-link"><i class="fa fa-close"></i></a> </li> </ul> <div class="clearfix"></div> </div> <div class="x_content"> <slot> </div> </div> `; var Block = Vue.extend({ template: blockTemplate, props: ['title', 'subtitle'], }); Vue.component('block', Block); })(Vue); <|start_filename|>master/state/purge.go<|end_filename|> package state import ( "log" "time" "github.com/leancloud/satori/master/g" ) func purgeStaleNodes() { cfg := g.Config() deadline := cfg.PurgeSeconds if deadline <= 0 { log.Println("PurgeSeconds <= 0, not purging stale nodes") return } for { time.Sleep(time.Second * 10) now := time.Now().Unix() purging := []string{} StateLock.Lock() for k, v := range State.Agents { if now-v.LastSeen > deadline { purging = append(purging, k) } } for _, k := range purging { delete(State.Agents, k) } StateLock.Unlock() } } <|start_filename|>satori-rules/rules/hostgroup.clj<|end_filename|> (ns hostgroup) (defmacro is? [re] `(re-matches ~re ~'host)) (defn host->group [ev] (let [host (:host ev)] (cond (is? #"^docker\d+") [:operation :lean-engine] (is? #"^api\d+") [:operation :api] (is? #"^push\d+") [:operation :push] (is? #"^stats\d+") [:operation :stats] :else [:operation]))) <|start_filename|>swcollector/funcs/swcpumem.go<|end_filename|> package funcs import ( "log" "time" "github.com/gaochao1/sw" "github.com/leancloud/satori/common/model" "github.com/leancloud/satori/swcollector/config" ) func CpuMemMetrics(ch chan *model.MetricValue) { AliveIpLock.RLock() defer AliveIpLock.RUnlock() for ip := range AliveIp { go cpuMetrics(ip, ch) go memMetrics(ip, ch) } } func cpuMetrics(ip string, ch chan *model.MetricValue) { cfg := config.Config() util, err := sw.CpuUtilization(ip, cfg.SnmpCommunity, cfg.SnmpTimeout, cfg.SnmpRetry) if err != nil { log.Println("Error collecting cpuMetrics:", err) return } ch <- &model.MetricValue{ Endpoint: ReverseLookup(ip), Metric: "switch.CpuUtilization", Value: float64(util), Timestamp: time.Now().Unix(), } } func memMetrics(ip string, ch chan *model.MetricValue) { cfg := config.Config() util, err := sw.MemUtilization(ip, cfg.SnmpCommunity, cfg.SnmpTimeout, cfg.SnmpRetry) if err != nil { log.Println("Error collecting memMetrics:", err) return } ch <- &model.MetricValue{ Endpoint: ReverseLookup(ip), Metric: "switch.MemUtilization", Value: float64(util), Timestamp: time.Now().Unix(), } } <|start_filename|>satori-rules/rules/infra/mesos.clj<|end_filename|> (ns infra.mesos (:require [riemann.streams :refer :all] [agent-plugin :refer :all] [alarm :refer :all] [lib :refer :all])) (def infra-mesos-rules (where (host #"^mesos-slave\d+$") (plugin-dir "mesos") (where (service "mesos.master.elected") (by :host (changed :metric {:pairs? true} (smap (fn [[ev' ev]] (assoc ev :metric (map #(int (:metric % -1)) [ev' ev]))) (where (= metric [0 1]) (! {:note "切换成 Mesos Master 了" :event? true :level 1 :groups [:operation]})) (where (= metric [1 0]) (! {:note "不再是 Mesos Master 了" :event? true :level 1 :groups [:operation]})))))) (where (service "mesos.master.slave_active") (by :host (set-state-gapped (< 3) (> 4) (should-alarm-every 600 (! {:note "Mesos Slaves 不见了!" :level 1 :expected 5 :groups [:operation]}))))) (where (service "mesos.master.uptime_secs") (by :host (set-state (< 120) (changed :state (should-alarm-every 60 (! {:note "Mesos Master 重启了" :level 1 :expected 300 :groups [:operation]})))))) #_(place holder))) <|start_filename|>master/rpc/master.go<|end_filename|> package rpc import ( "github.com/leancloud/satori/common/model" "github.com/leancloud/satori/master/state" "time" ) func (t *Agent) Heartbeat(req *model.AgentHeartbeatRequest, resp *model.AgentHeartbeatResponse) error { host := req.Hostname if host == "" { return nil } state.StateLock.Lock() state.State.Agents[host] = state.AgentInfo{ Hostname: host, IP: req.IP, AgentVersion: req.AgentVersion, PluginVersion: req.PluginVersion, LastSeen: time.Now().Unix(), } state.StateLock.Unlock() state.StateLock.RLock() cfgVer := state.State.ConfigVersions[host] cfgModified := cfgVer != 0 && req.ConfigVersion != cfgVer resp.ConfigModified = cfgModified resp.PluginVersion = state.State.PluginVersion if cfgModified { resp.ConfigVersion = cfgVer resp.PluginDirs = state.State.PluginDirs[host] resp.Plugins = state.State.Plugin[host] } state.StateLock.RUnlock() return nil } <|start_filename|>transfer/sender/riemann.go<|end_filename|> package sender import ( "log" "time" "github.com/amir/raidman" nsema "github.com/toolkits/concurrent/semaphore" "github.com/leancloud/satori/common/cpool" cmodel "github.com/leancloud/satori/common/model" ) type RiemannBackend struct { BackendCommon } func newRiemannBackend(cfg *BackendConfig) Backend { if cfg.Engine == "riemann" { return &RiemannBackend{*newBackendCommon(cfg)} } else { return nil } } type RiemannClient struct { cli *raidman.Client name string } func (this RiemannClient) Name() string { return this.name } func (this RiemannClient) Closed() bool { return this.cli == nil } func (this RiemannClient) Close() error { if this.cli != nil { this.cli.Close() this.cli = nil } return nil } func (this RiemannClient) Call(items interface{}) (interface{}, error) { err := this.cli.SendMulti(items.([]*raidman.Event)) return nil, err } func (this *RiemannBackend) riemannConnect(name string, p *cpool.ConnPool) (cpool.PoolClient, error) { cfg := this.config u := cfg.Url proto := cfg.Protocol if proto == "" { proto = "tcp" } conn, err := raidman.DialWithTimeout( proto, u.Host, time.Duration(p.ConnTimeout)*time.Millisecond, ) if err != nil { return nil, err } return RiemannClient{conn, name}, nil } func (this *RiemannBackend) createConnPool() *cpool.ConnPool { cfg := this.config u := cfg.Url p := cpool.NewConnPool( cfg.Name, u.Host, cfg.MaxConn, cfg.MaxIdle, cfg.ConnTimeout, cfg.CallTimeout, this.riemannConnect, ) return p } func (this *RiemannBackend) Start() error { this.pool = this.createConnPool() go this.sendProc() return nil } func (this *RiemannBackend) sendProc() { cfg := this.config sema := nsema.NewSemaphore(cfg.MaxConn) for { items := this.queue.PopBackBy(cfg.Batch) if len(items) == 0 { time.Sleep(DefaultSendTaskSleepInterval) continue } // 同步Call + 有限并发 进行发送 sema.Acquire() go func(itemList []interface{}) { defer sema.Release() riemannItems := make([]*raidman.Event, len(itemList)) for i := range itemList { riemannItems[i] = itemList[i].(*raidman.Event) } var err error for i := 0; i < 3; i++ { _, err = this.pool.Call(riemannItems) if err == nil { this.sendCounter.IncrBy(int64(len(itemList))) break } time.Sleep(100 * time.Millisecond) } if err != nil { this.failCounter.IncrBy(int64(len(itemList))) log.Println(err) return } }(items) } } // 将原始数据入到riemann发送缓存队列 func (this *RiemannBackend) Send(items []*cmodel.MetricValue) { for _, item := range items { riemannItem := raidman.Event{ Service: item.Metric, Host: item.Endpoint, State: "", Metric: item.Value, Time: item.Timestamp, Description: item.Desc, Tags: nil, Attributes: make(map[string]string), } for k, v := range item.Tags { riemannItem.Attributes[k] = v } isSuccess := this.queue.PushFront(&riemannItem) if !isSuccess { this.dropCounter.Incr() } } } <|start_filename|>agent/funcs/dfstat.go<|end_filename|> package funcs import ( "github.com/leancloud/satori/common/model" "github.com/toolkits/nux" "log" ) func DeviceMetrics() (L []*model.MetricValue) { mountPoints, err := nux.ListMountPoint() if err != nil { log.Println(err) return } var diskTotal uint64 = 0 var diskUsed uint64 = 0 for idx := range mountPoints { var du *nux.DeviceUsage du, err = nux.BuildDeviceUsage(mountPoints[idx][0], mountPoints[idx][1], mountPoints[idx][2]) if err != nil { log.Println(err) continue } diskTotal += du.BlocksAll diskUsed += du.BlocksUsed tags := map[string]string{ "mount": du.FsFile, "fstype": du.FsVfstype, } L = append(L, VT("df.bytes.total", float64(du.BlocksAll), tags)) L = append(L, VT("df.bytes.used", float64(du.BlocksUsed), tags)) L = append(L, VT("df.bytes.free", float64(du.BlocksFree), tags)) L = append(L, VT("df.bytes.used.percent", du.BlocksUsedPercent, tags)) L = append(L, VT("df.bytes.free.percent", du.BlocksFreePercent, tags)) L = append(L, VT("df.inodes.total", float64(du.InodesAll), tags)) L = append(L, VT("df.inodes.used", float64(du.InodesUsed), tags)) L = append(L, VT("df.inodes.free", float64(du.InodesFree), tags)) L = append(L, VT("df.inodes.used.percent", du.InodesUsedPercent, tags)) L = append(L, VT("df.inodes.free.percent", du.InodesFreePercent, tags)) } if len(L) > 0 && diskTotal > 0 { L = append(L, V("df.statistics.total", float64(diskTotal))) L = append(L, V("df.statistics.used", float64(diskUsed))) L = append(L, V("df.statistics.used.percent", float64(diskUsed)*100.0/float64(diskTotal))) } return } <|start_filename|>agent/funcs/common.go<|end_filename|> package funcs import ( "github.com/leancloud/satori/common/model" ) func VT(metric string, val float64, tags map[string]string) *model.MetricValue { if tags == nil { tags = map[string]string{} } mv := model.MetricValue{ Metric: metric, Value: val, Tags: tags, } return &mv } func V(metric string, val float64) *model.MetricValue { return VT(metric, val, nil) } <|start_filename|>agent/g/lastmsg.go<|end_filename|> package g import ( "io/ioutil" "log" "os" "runtime/debug" "time" ) const LAST_MESSAGE_PATH = "/tmp/satori-last-message" func LastMessage(name string) { msg := "Goroutine:" + name + "\n" + "Time: " + time.Now().Format("2006-01-02 15:04:05.000000") + "\n" + string(debug.Stack()) log.Println("======== PANICKED! ========") log.Println(msg) log.Println("===========================") var f *os.File var err error if f, err = os.OpenFile(LAST_MESSAGE_PATH, os.O_WRONLY|os.O_CREATE, 0644); err != nil { log.Fatalln(err) } if _, err = f.WriteString(msg); err != nil { log.Fatalln(err) } _ = f.Close() log.Fatalln("Successfully left last message, die in peace.") } func ReportLastMessage() { time.Sleep(5 * time.Second) if _, err := os.Stat(LAST_MESSAGE_PATH); err == nil { log.Println("Found last message, reporting") if msg, err := ioutil.ReadFile(LAST_MESSAGE_PATH); err == nil { ReportFailure(".satori.agent.panic", string(msg), nil) _ = os.Remove(LAST_MESSAGE_PATH) } else { log.Println("Error reading last message:", err) } } } <|start_filename|>frontend/view/sidebar.js<|end_filename|> (function(Vue){ var sidebarTemplate = ` <div class="col-md-3 left_col"> <div class="left_col scroll-view"> <div class="navbar nav_title" style="border: 0;"> <a href="index.html" class="site_title"><i class="fa fa-eye"></i> <span>SATORI</span></a> </div> <div class="clearfix"></div> <br /> <!-- sidebar menu --> <div id="sidebar-menu" class="main_menu_side hidden-print main_menu"> <div class="menu_section"> <!--<h3>General</h3>--> <ul class="nav side-menu"> <li v-for="item in items" :class="current === item.id ? 'active-sm' : ''"> <a :href="item.url"><i class = "fa" :class="item.icon"></i> {{ item.text }}</a> </li> </ul> </div> </div> <!-- /sidebar menu --> </div> </div> `; var Sidebar = Vue.extend({ template: sidebarTemplate, props: ['current'], data: function() { return { items: [ { id: 'index', url: 'index.html', icon: 'fa-home', text: '首页'}, { id: 'events', url: 'events.html', icon: 'fa-bell', text: '报警'}, { id: 'nodes', url: 'nodes.html', icon: 'fa-server', text: '机器信息'}, { id: 'grafana', url: 'grafana/', icon: 'fa-area-chart', text: '图表'}, // { id: 'influxdb', url: 'influxdb/', icon: 'fa-database', text: 'InfluxDB'}, ], }; }, ready: function() { }, }); Vue.component('sidebar', Sidebar); })(Vue); <|start_filename|>transfer/receiver/rpc/rpc.go<|end_filename|> package rpc import ( "log" "net" "net/rpc" "net/rpc/jsonrpc" "time" "github.com/leancloud/satori/transfer/g" ) func StartRpc() { addr := g.Config().Listen tcpAddr, err := net.ResolveTCPAddr("tcp", addr) if err != nil { log.Fatalf("net.ResolveTCPAddr fail: %s", err) } listener, err := net.ListenTCP("tcp", tcpAddr) if err != nil { log.Fatalf("listen %s fail: %s", addr, err) } else { log.Println("rpc listening", addr) } server := rpc.NewServer() server.Register(new(Transfer)) for { conn, err := listener.AcceptTCP() if err != nil { log.Println("listener.Accept occur error:", err) continue } conn.SetDeadline(time.Now().Add(time.Second * 900)) go server.ServeCodec(jsonrpc.NewServerCodec(conn)) } } <|start_filename|>master/rpc/rpc.go<|end_filename|> package rpc import ( "log" "net" "net/rpc" "net/rpc/jsonrpc" "time" "github.com/leancloud/satori/master/g" ) type Agent int func Start() { addr := g.Config().Listen server := rpc.NewServer() server.Register(new(Agent)) l, e := net.Listen("tcp", addr) if e != nil { log.Fatalln("listen error:", e) } else { log.Println("listening", addr) } for { conn, err := l.Accept() if err != nil { log.Println("listener accept fail:", err) time.Sleep(time.Duration(100) * time.Millisecond) continue } go server.ServeCodec(jsonrpc.NewServerCodec(conn)) } } <|start_filename|>agent/funcs/kernel.go<|end_filename|> package funcs import ( "github.com/leancloud/satori/common/model" "github.com/toolkits/nux" "log" ) func KernelMetrics() (L []*model.MetricValue) { maxFiles, err := nux.KernelMaxFiles() if err != nil { log.Println(err) return } L = append(L, V("kernel.maxfiles", float64(maxFiles))) maxProc, err := nux.KernelMaxProc() if err != nil { log.Println(err) return } L = append(L, V("kernel.maxproc", float64(maxProc))) allocateFiles, err := nux.KernelAllocateFiles() if err != nil { log.Println(err) return } L = append(L, V("kernel.files.allocated", float64(allocateFiles))) L = append(L, V("kernel.files.left", float64(maxFiles-allocateFiles))) return } <|start_filename|>frontend/frontend-vars.js<|end_filename|> // This is an example, just for debugging // If you find your browser loading this file, it's a bug. var SatoriVars = { rulesRepo: '<EMAIL>:meh', } <|start_filename|>agent/g/version.go<|end_filename|> package g // changelog: // 3.1.3: code refactor // 3.1.4: bugfix ignore configuration // 5.0.0: 支持通过配置控制是否开启/run接口;收集udp流量数据;du某个目录的大小 // 5.1.0: 同步插件的时候不再使用checksum机制 // 5.1.1: 修复往多个transfer发送数据的时候crash的问题 // 6.0.0: 配合 satori master // 7.0.0: tags 改成 map[string]string 了,不兼容 // 7.0.3: 优化与 transfer 之间的数据传输 // 7.0.4: 报告执行失败的插件 // 7.0.5: 修复与 master 断线之后不能恢复的bug // 7.0.6: 增加 noBuiltIn 参数,打开后只采集插件参数。 // 7.0.7: 增加了 /v1/ping ,用来检测 agent 存活 // 7.0.8: 支持 long running 的插件 // 7.0.9: 补全插件上报的事件中的 endpoint // 7.0.10: 新增插件签名功能,无签名的规则仓库不会主动切换过去。 // 7.0.11: 新增 agent 自更新功能 // 7.0.12: 增加 alternative key file 功能,管理签名 key 更方便了 // 7.0.13: 自更新的 binary 放到仓库外,配置文件格式修改(YAML) // 7.0.14: 修复一个严重的bug // 7.0.15: 增加 cgroups 限制 // 7.0.16: 小 bug 修复 // 7.0.17: noBuiltin 为 true 时上报 agent.container-alive // 7.0.18: 修复了新部署的 agent 无法找到 authorized_keys 的问题 // 7.0.19: TcpExt 的收集转移到了插件中 // 8.0.0: `plugin-metric` 改名 `plugin` // 8.0.1: 支持获取 FQDN // 8.0.2: Mem 指标微调 // 8.0.4: 修复一个关于插件的 crash 问题 // 8.0.5: 增加了 agent crash 的报警 // 8.0.6: 增加了 cpu.free == cpu.idle + cpu.iowait const ( VERSION = "8.0.6" ) <|start_filename|>swcollector/logging/logging.go<|end_filename|> package logging import ( "fmt" "log" "os" ) const ( LOG_FLAGS = log.Ldate | log.Lmicroseconds | log.Lshortfile ) var ( file *log.Logger std = log.New(os.Stderr, "", LOG_FLAGS) ) func init() { log.SetFlags(LOG_FLAGS) f, _ := os.OpenFile("/dev/null", os.O_WRONLY, 0222) log.SetOutput(f) } func SetOutputFilename(fn string) { f, err := os.OpenFile(fn, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) if err != nil { log.Fatalf("Can't open log file %s for writing: %s", fn, err) } log.SetOutput(f) file = log.New(f, "", LOG_FLAGS) } func Fatalln(v ...interface{}) { s := fmt.Sprintln(v...) std.Output(2, s) file.Output(2, s) os.Exit(1) } <|start_filename|>satori-rules/rules/lib.clj<|end_filename|> (ns lib (:require [clojure.set :as cset] [clojure.string :as string] [clojure.walk :refer [postwalk macroexpand-all]] [riemann.config :refer :all] [riemann.streams :refer :all] [riemann.test :refer [tests io tap]]) (:import riemann.codec.Event)) (defmacro ->waterfall "接受一组 form,将后面的 form 插入到前面 form 的最后。 如果你的规则从上到下只有一条分支,用这个可以将缩进压平,变的好看些。" [& forms] `(->> ~@(reverse forms))) (defn aggregate* "接受事件的数组,变换成一个事件。 f 函数接受 metric 数组作为参数,返回一个 aggregate 过的 metric, 最后将 aggregate 过的 metric 放在最后一个事件中,向下传递这个事件。 常接在 (moving|fixed)-(time|event)-window 流后面。" [f & children] (fn [evts] (when-not (sequential? evts) (throw (Exception. "aggregate must accept list of events"))) (when (> (count evts) 0) (let [m (mapv :metric evts), v (f m) s (string/join "\n" (map #(str (or (:aggregate-desc-key %) (:host %)) "=" (:metric %)) evts)) s (if (> (count s) 3000) (subs s 0 3000) s) aggregated (into (last evts) {:metric v, :description s})] (call-rescue aggregated children))))) (defn aggregate [f & children] (apply aggregate* (fn [m] (apply f m)) children)) (defn copy "将事件的一个 field 复制到另一个 field。通常接在 aggregate 后面,用于修正 host。 (copy :region :host (...))" [from to & children] (apply smap #(assoc % to (from %)) children)) (defn ->difference "接受事件的数组,变换成另外一个事件数组。 新的事件数组中,每一个事件的 metric 是之前相邻两个事件 metric 的差。 如果你的事件是一个一直增长的计数器,那么用这个流可以将它变成每次实际增长的值。" [& children] (apply smap (fn [l] (map (fn [[ev' ev]] (assoc ev' :metric (- (:metric ev') (:metric ev)))) (map vector (rest l) l))) children)) (defn |>| [& args] (apply > (map #(Math/abs %) args))) (defn |<| [& args] (apply < (map #(Math/abs %) args))) (defn maxpdiff "计算列表中最后一个点相对之前的点的最大变化率(MAX Percentage DIFFerence), 与 aggregate 搭配使用。计算变化率时总是使用两个点中的最小值做分母, 所以由1变到2的变化率是 1.0, 由2变到1的变化率是 -1.0 (而不是 -0.5) " [& m] (let [m (filter pos? m) r (last m)] (if r (->> m (map #(/ (- r %) (min r %))) (reduce #(if (|>| %1 %2) %1 %2) 0)) 0.0))) (defn avgpdiff "计算最后一个点相比于之前的点的平均值的变化率" [& m] (let [r (last m) c (count m)] (if (not= r 0) (let [avg (/ (apply + (- r) m) (- c 1))] (/ (- r avg) (min avg r))) 0))) (defn group-window "将事件分组后向下传递,类似 fixed-time-window,但不使用时间切割, 而是通过 (group-fn event) 的值进行切割。(group-fn event) 的值会被记录下来, 每一次出现重复值的时候,会将当前缓存住的事件数组向下传递。 比如你有一组同质的机器,跑了相同的服务,但是机器名不一样,可以通过 (group-window :host ....) 将事件分组后处理(e.g. 对单台的容量求和获得总体容量) e.g.: 一个事件流中的事件先后到达,其中 :host 的值如下 a b c d b a c a b 那么会被这个流分成 [a b c d] [b a c] [a b] 分成 3 次向下游传递 " [group-fn & children] (let [buffer (ref []) group-keys (ref #{})] (fn stream [event] (let [evkey (group-fn event)] (as-> nil rst (dosync (if (@group-keys evkey) (let [events @buffer] (ref-set buffer [event]) (ref-set group-keys #{evkey}) events) (do (alter buffer conj event) (alter group-keys conj evkey) nil))) (when rst (call-rescue rst children))))))) (defn slot-window* [slot-fn fields children] (let [valid (set (vals fields)) invert (cset/map-invert fields) current (ref {}) remaining (ref (set (vals fields)))] (fn stream [event] (let [evkey (slot-fn event)] (as-> nil rst (when (valid evkey) (dosync (alter current assoc (invert evkey) event) (alter remaining disj evkey) (if (empty? @remaining) (let [r @current] (ref-set current {}) (ref-set remaining valid) r) nil))) (when rst (call-rescue rst children))))))) (def ^{:private true, :dynamic true} *slot-window-slots*) (defmacro slot-window "收集指定的几个事件并打包向下传递。事件的特征由 slot-fn 提取,并与 fields 中的 的定义匹配,如果 fields 中的所有条件匹配的事件都收集到了,则打包向下传递并开始下一轮收集。 与 group-window 相反,group-window 收集一组同质的事件,slot-window 用于收集一组异质的事件。 当 slot-window 遇到重复的事件但是还没有满足向下传递的条件时,新的事件会替换掉缓存住的已有事件。 常用于收集同一个资源不同的 metric 用于复杂的判定。 比如有一个服务,同时收集了错误请求量和总量,希望按照错误数量在一定之上后按照错误率报警 (slot-window :service {:error \"app.req.error\" :count \"app.req.count\"} ; 此时会有形如 {:error {:service \"app.req.error\", ...}, ; :count {:service \"app.req.count\", ...}} 的事件传递下来 ; 构造出想要的 event (slot-coalesce {:service \"app.req.error_rate\" :metric (if (> error 100) (/ error count) -1)} (judge (> 0.5) (runs :state 5 (alarm-every 2 :min (! {... ...})))))) " [slot-fn fields & children] (binding [*slot-window-slots* fields] `(slot-window* ~slot-fn ~fields ~(macroexpand-all (vec children))))) (defn- ev-rewrite-slot [varname form fields] (let [vars (->> fields (keys) (map name) (map symbol) (set)) evvars (->> fields (keys) (map #(vector (symbol (str "ev:" (name %))) (keyword %))) (into {}))] (postwalk (fn [node] (if (symbol? node) (cond (vars node) `(:metric (~(keyword node) ~varname)) (evvars node) (list (evvars node) varname) (= node 'event) varname :else node) node)) form))) (defmacro slot-coalesce "对 slot-window 的结果进行计算,并构造出单一的 event。 具体用法可以看 slot-window 的帮助 ev': 构造出的新 event 模板。表达式中可以直接用如下的约定引用 slot 中的值: ; 假设: (slot-window :service {:some-counter1 \"app.some_counter\"} ...) some-counter1 ; :some-counter1 的 metric 值 ev:some-counter1 ; :some-counter1 的整个 event event ; slot-window 整个传递下来的 {:some-counter1 ...} " [ev' & children] (if (bound? #'*slot-window-slots*) `(smap (fn [~'event] (conj (select-keys (first (vals ~'event)) [:host :time]) ~(ev-rewrite-slot 'event ev' *slot-window-slots*))) ~@children) (throw (Exception. "Could not find slot-window stream!")))) ; ------------------------------------------------------------------ (tests (deftest slot-window-test (let [s (lib/slot-window :service {:foo "bar" :baz "quux"} (tap :slot-window)) rst (inject! [s] [{:host "meh" :service "bar" :metric 10}, {:host "meh" :service "quux" :metric 20}, {:host "meh" :service "bar" :metric 30}, {:host "meh" :service "irrelevant" :metric 35}, {:host "meh" :service "bar" :metric 40}, {:host "meh" :service "quux" :metric 50}, {:host "meh" :service "quux" :metric 60}, {:host "meh" :service "bar" :metric 70}, {:host "meh" :service "bar" :metric 80}])] (is (= [{:foo {:host "meh" :service "bar" :metric 10} :baz {:host "meh" :service "quux" :metric 20}}, {:foo {:host "meh" :service "bar" :metric 40} :baz {:host "meh" :service "quux" :metric 50}}, {:foo {:host "meh" :service "bar" :metric 70} :baz {:host "meh" :service "quux" :metric 60}}] (:slot-window rst))))) (deftest slot-coalesce-test (let [s (lib/slot-window :service {:ev1 "metric.ev1" :ev2 "metric.ev2"} (lib/slot-coalesce {:service "metric.final" :metric [ev1 ev2 (:metric ev:ev1) (:metric ev:ev2) (:metric (:ev1 event)) (:metric (:ev2 event))]} (tap :slot-coalesce-test))) rst (inject! [s] [{:host "meh" :service "metric.ev1" :metric 10}, {:host "meh" :service "metric.ev2" :metric 20}])] (is (= [{:host "meh" :service "metric.final" :metric [10 20 10 20 10 20]}] (:slot-coalesce-test rst))))) (deftest maxpdiff-test (is (= (lib/maxpdiff 1.0 1.0 1.0 1.0 1.0 2.0) 1.0)) (is (= (lib/maxpdiff 2.0 1.0 1.0 1.0 1.0 1.0) -1.0)) (is (= (lib/maxpdiff 0.0 0.0 0.0 0.0 1.0 2.0) 1.0)) (is (= (lib/maxpdiff 0.0 0.0 0.0 0.0 0.0 0.0) 0.0))) (deftest aggregate-test (let [s (lib/aggregate + (tap :aggregate-test)) rst (inject! [s] [[{:host "meh" :service "bar" :metric 10}, {:host "meh" :service "bar" :metric 80}]])] (is (= 90 (get-in rst [:aggregate-test 0 :metric])))))) <|start_filename|>common/model/rpc.go<|end_filename|> package model import ( "fmt" ) // code == 0 => success // code == 1 => bad request type SimpleRpcResponse struct { Code int `json:"code"` } func (this *SimpleRpcResponse) String() string { return fmt.Sprintf("<Code: %d>", this.Code) } type NullRpcRequest struct { } <|start_filename|>agent/g/var.go<|end_filename|> package g import ( "crypto/sha256" "fmt" "io" "os" "github.com/kardianos/osext" ) var ( ConfigVersion int64 BinaryHash []byte BinaryPath string ) func init() { var err error BinaryPath, err = osext.Executable() if err != nil { panic(fmt.Errorf("Can't get binary path: %s", err.Error())) } h := sha256.New() self, err := os.Open(BinaryPath) if err != nil { panic(fmt.Errorf("Can't open self for read: %s", err.Error())) } if _, err := io.Copy(h, self); err != nil { panic(fmt.Errorf("Can't read contents of self: %s", err.Error())) } self.Close() BinaryHash = h.Sum(nil) } <|start_filename|>vendor/github.com/gaochao1/sw/modelstat.go<|end_filename|> package sw import ( "log" "strings" "time" "github.com/gaochao1/gosnmp" ) func SysModel(ip, community string, retry int, timeout int) (string, error) { vendor, err := SysVendor(ip, community, retry, timeout) method := "get" var oid string defer func() { if r := recover(); r != nil { log.Println("Recovered in sw.modelstat.go SysModel", r) } }() switch vendor { case "Cisco_NX", "Cisco", "Cisco_old", "Cisco_IOS_XR", "Cisco_IOS_XE", "Ruijie": method = "getnext" oid = "1.3.6.1.2.1.47.1.1.1.1.13" case "Huawei_ME60", "Huawei_V5.70", "Huawei_V5.130", "Huawei_V3.10": method = "getnext" oid = "1.3.6.1.2.1.47.1.1.1.1.2" case "H3c_V3.10", "H3C_S9500", "H3C", "H3C_V5", "H3C_V7", "Cisco_ASA": oid = "1.3.6.1.2.1.47.1.1.1.1.13" return getSwmodle(ip, community, oid, timeout, retry) case "Linux": return "Linux", nil default: return "", err } snmpPDUs, err := RunSnmp(ip, community, oid, method, timeout) if err == nil { for _, pdu := range snmpPDUs { return pdu.Value.(string), err } } return "", err } func getSwmodle(ip, community, oid string, timeout, retry int) (value string, err error) { defer func() { if r := recover(); r != nil { log.Println(ip+" Recovered in CPUtilization", r) } }() method := "getnext" oidnext := oid var snmpPDUs []gosnmp.SnmpPDU for { for i := 0; i < retry; i++ { snmpPDUs, err = RunSnmp(ip, community, oidnext, method, timeout) if len(snmpPDUs) > 0 { break } time.Sleep(100 * time.Millisecond) } oidnext = snmpPDUs[0].Name if strings.Contains(oidnext, oid) { if snmpPDUs[0].Value.(string) != "" { value = snmpPDUs[0].Value.(string) break } } else { break } } return value, err } <|start_filename|>agent/cgroups/cgroups_dummy.go<|end_filename|> // +build !linux package cgroups import "fmt" func JailMe(cgPath string, cpu float32, mem int64) error { return fmt.Errorf("Not on linux, cgroups not supported") } <|start_filename|>swcollector/config/cfg.go<|end_filename|> package config import ( "encoding/json" "sync" "github.com/leancloud/satori/swcollector/logging" ) type CustomMetric struct { IpRange []string `json:"ipRange"` Metric string `json:"metric"` Tags map[string]string `json:"tags"` Oid string `json:"oid"` } type GlobalConfig struct { Interval int64 `json:"interval" default:30` LogFile string `json:"logFile"` IpRange []string `json:"ipRange"` Gosnmp bool `json:"gosnmp" default:"true"` PingTimeout int `json:"pingTimeout" default:"300"` PingRetry int `json:"pingRetry" default:"4"` SnmpCommunity string `json:"snmpCommunity" default:"\"public\""` SnmpTimeout int `json:"snmpTimeout" default:"1000"` SnmpRetry int `json:"snmpRetry" default:"5"` IgnoreIface []string `json:"ignoreIface" default:"[\"Nu\", \"NU\", \"Vlan\", \"Vl\"]"` Ignore []string `json:"ignore"` FastPingMode bool `json:"fastPingMode"` ConcurrentQueriesPerHost int `json:"concurrentQueriesPerHost" default:"4"` ConcurrentCollectors int `json:"concurrentCollectors" default:"1000"` CustomMetrics []CustomMetric `json:"customMetrics"` ReverseLookup bool `json:"reverseLookup" default:"false"` CustomHosts map[string]string `json:"customHosts"` } var ( config *GlobalConfig cfgLock = new(sync.RWMutex) ) func Config() *GlobalConfig { cfgLock.RLock() defer cfgLock.RUnlock() return config } func ParseConfig(cfg []byte) { var c []GlobalConfig err := json.Unmarshal(cfg, &c) if err != nil { logging.Fatalln("parse config:", err) } if len(c) > 1 { logging.Fatalln("swcollector cannot handle multiple configs this time, please schedule each swcollector to a different node") } else if len(c) < 1 { logging.Fatalln("Missing config") } FillDefault(&c[0]) cfgLock.Lock() defer cfgLock.Unlock() config = &c[0] } <|start_filename|>agent/http/ping.go<|end_filename|> package http import ( "net/http" "github.com/leancloud/satori/agent/g" ) func httpPing(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte("{\"result\":\"pong\",\"version\":\"" + g.VERSION + "\"}")) } <|start_filename|>frontend/view/events/table.js<|end_filename|> (function(Vue){ var evTableTemplate = ` <div class="table-responsive"> <table class="table table-striped jambo_table bulk_action"> <thead> <tr> <!--<th></th>--> <th>状态</th> <th>级别</th> <th>节点</th> <th>事件</th> <th>通知组</th> <th>监控项</th> <th>监控值</th> <th>触发时间</th> <th>标签</th> <th class="no-link last"><span class="nobr">动作</span></th> </tr> </thead> <tbody> <tr v-if="alarms == null"> <td colspan="10">正在获取数据……</td> </tr> <tr v-if="_.isArray(alarms) && _.isEmpty(alarms)"> <td colspan="10">并没有什么大新闻😆</td> </tr> <tr v-if="alarms" v-for="(a, i) in alarms" :key="a.id" class="pointer events-row" :class="[i & 1 ? 'odd' : 'even', _.includes(checked, a.id) ? 'selected' : '']"> <!-- <td class="a-center"> <input type="checkbox" :value="a.id" class="icheck" v-model="checked"> </td> --> <td class="status" :title="stateDescription(a.status)">{{ stateEmoji(a.status) }}</td> <td class="status">{{ ['0⃣','1⃣','2⃣','3⃣','4⃣','5⃣','6⃣','7⃣','8⃣','9⃣'][parseInt(a.level)] }}</td> <td>{{ a.endpoint }}</td> <td>{{ a.note }}</td> <td><span class="label label-primary" style="margin: 0 3px 0 3px;" v-for="g in a.groups">{{ g }}</span></td> <td>{{ a.metric }}</td> <td>{{ _.round(a.actual, 3) }}</td> <td>{{ timeFromNow(a.time) }}</td> <td> <div style="margin: 5px 0 0 5px; display: inline-block;" v-for="(v, k) in a.tags"> <span class="label label-warning no-right-radius">{{ k }}</span><span class="label label-info no-left-radius">{{ v }}</span> </div> </td> <td class="last"> <button v-show="a.status == 'PROBLEM'" @click="toggleAck(a)" class="btn btn-warning">静音</button> <button v-show="a.status == 'ACK'" @click="toggleAck(a)" class="btn btn-info">解除静音</button> <button @click="remove(a, i)" class="btn btn-danger">删除</button> </td> </tr> <!-- <tr class="pointer events-row"> <td> <input type="checkbox" class="icheck" v-model="checkAll" @change="doCheckAll()"> </td> <td colspan="10"> <a class="antoo" style="font-weight:500;">批量操作 ( {{ checked.length }} 条记录)</a> <div style="display: inline-block; margin-left: 10px;"> <button @click="batchAck(true)" class="btn btn-warning">静音</button> <button @click="batchAck(false)" class="btn btn-info">解除静音</button> <button @click="batchRemove()" class="btn btn-danger">删除</button> </div> </td> </tr> --> </tbody> </table> </div> `; var EventsTable = Vue.extend({ template: evTableTemplate, props: ['api-endpoint', 'api-auth'], mounted() { this.refresh(); }, data() { return { checkAll: false, alarms: null, checked: [], } }, methods: { _getFetchHeaders() { var headers = new Headers(); if(this.apiAuth) { headers.append("Authorization", "Basic " + btoa(this.apiAuth)); } return headers; }, refresh() { var opts = { method: "GET", headers: this._getFetchHeaders(), credentials: 'include', }; var order = { 'PROBLEM': 'AAAA', 'FLAPPING': 'BBBB', 'ACK': 'CCCC', 'TIMEWAIT': 'ZZZZ', }; fetch(this.apiEndpoint, opts).then(resp => resp.json()).then((data) => { this.alarms = _.sortBy(data['alarms'], a => (order[a.status] + a.title)); }); }, stateEmoji(s) { var emoji = { "PROBLEM": "😱", "ACK": "🔕", "FLAPPING": "🎭", // 🔃 🔄 "TIMEWAIT": "⌛", "ERROR": "❌", }[s]; return emoji ? emoji : s; }, stateDescription(s) { var desc = { "PROBLEM": "现在存在的问题", "ACK": "静音的问题", "FLAPPING": "被静音后不停重复发生的问题", // 🔃 🔄 "TIMEWAIT": "被静音后解决了的问题(在观察期内,超时后会自己消失)", "ERROR": "错误", }[s]; return desc ? desc : s; }, toggleAck(item) { var opts = { method: "POST", headers: this._getFetchHeaders(), }; fetch(`${ this.apiEndpoint }/${ item.id }/toggle-ack`, opts).then(resp => resp.json()).then((data) => { item.status = data["new-state"]; }); }, batchAck(state) { _.each(this.alarms, (a) => { if((state == true && a.status == 'PROBLEM') || (state == false && a.status == 'ACK')) { if(_.includes(this.checked, a.id)) { this.toggleAck(a); } } }); }, remove(item, index) { var opts = { method: "DELETE", headers: this._getFetchHeaders(), }; //* fetch(`${ this.apiEndpoint }/${ item.id }`, opts).then(resp => resp.json()).then((data) => { this.alarms.splice(index, 1); }); // */ }, batchRemove() { // meh }, doCheckAll() { if(this.checkAll) { this.checked = _.map(this.alarms, (i) => i.id); } else { this.checked = []; } }, timeFromNow(ts) { return moment(new Date(ts * 1000)).locale('zh-cn').fromNow(); }, } }); Vue.component('events-table', EventsTable); })(Vue); <|start_filename|>agent/g/metric.go<|end_filename|> package g import ( "log" "regexp" "github.com/leancloud/satori/common/model" ) var cachedRegexp map[string]*regexp.Regexp = make(map[string]*regexp.Regexp) func cachedMatch(re string, v string) bool { r, ok := cachedRegexp[re] if !ok { r = regexp.MustCompile(re) cachedRegexp[re] = r } return r.MatchString(v) } func filterMetrics(metrics []*model.MetricValue) []*model.MetricValue { cfg := Config() addTags := cfg.AddTags ignore := cfg.Ignore debug := cfg.Debug hostname := Hostname() filtered := make([]*model.MetricValue, 0) metricsLoop: for _, mv := range metrics { for _, item := range ignore { if !cachedMatch(item.Metric, mv.Metric) { continue } for k, v := range mv.Tags { if cachedMatch(item.Tag, k) && cachedMatch(item.TagValue, v) { if debug { log.Println("=> Filtered metric", mv.Metric, "/", mv.Tags, "by rule ", item.Metric, " :: ", item.Tag, " :: ", item.TagValue) } continue metricsLoop } } } if mv.Tags == nil { mv.Tags = map[string]string{} } if addTags != nil { for k, v := range addTags { if _, ok := mv.Tags[k]; !ok { mv.Tags[k] = v } } } if mv.Endpoint == "" { mv.Endpoint = hostname } filtered = append(filtered, mv) } return filtered } <|start_filename|>agent/cgroups/cgroups_linux.go<|end_filename|> package cgroups import ( "os" cglib "github.com/containerd/cgroups" specs "github.com/opencontainers/runtime-spec/specs-go" ) func strippedHierarchy() ([]cglib.Subsystem, error) { ss, err := cglib.V1() if err != nil { return ss, err } rst := []cglib.Subsystem{} for _, i := range ss { s := i.Name() if s == "cpu" || s == "memory" { rst = append(rst, i) } } return rst, err } func JailMe(cgPath string, cpu float32, mem int64) error { mlimit := mem * 1024 * 1024 cpuPeriod := uint64(1e5) cpuQuota := int64(float32(cpuPeriod) * cpu / 100.0) ctrl, err := cglib.New(strippedHierarchy, cglib.NestedPath(cgPath), &specs.LinuxResources{ CPU: &specs.LinuxCPU{ Quota: &cpuQuota, Period: &cpuPeriod, }, Memory: &specs.LinuxMemory{ Limit: &mlimit, }, }) if err != nil { return err } err = ctrl.Add(cglib.Process{Pid: os.Getpid()}) if err != nil { return err } return nil } <|start_filename|>transfer/sender/transfer.go<|end_filename|> package sender import ( "log" "math/rand" "net" "net/rpc" "net/rpc/jsonrpc" "strings" "time" nsema "github.com/toolkits/concurrent/semaphore" "github.com/leancloud/satori/common/cpool" cmodel "github.com/leancloud/satori/common/model" nproc "github.com/toolkits/proc" ) type TransferBackend struct { BackendCommon ccp *cpool.ClusteredConnPool addrs []string } func newTransferBackend(cfg *BackendConfig) Backend { if cfg.Engine == "transfer" { return &TransferBackend{BackendCommon: *newBackendCommon(cfg), ccp: nil} } else { return nil } } type TransferClient struct { cli *rpc.Client name string } func (this *TransferClient) Name() string { return this.name } func (this *TransferClient) Closed() bool { return this.cli == nil } func (this *TransferClient) Close() error { if this.cli == nil { this.cli.Close() this.cli = nil } return nil } func (this *TransferClient) Call(metrics interface{}) (interface{}, error) { var resp cmodel.TransferResponse err := this.cli.Call("Transfer.Update", metrics, &resp) return resp, err } func (this *TransferBackend) transferConnect(name string, p *cpool.ConnPool) (cpool.PoolClient, error) { connTimeout := time.Duration(p.ConnTimeout) * time.Millisecond conn, err := net.DialTimeout("tcp", p.Address, connTimeout) if err != nil { log.Printf("Connect transfer %s fail: %v", p.Address, err) return nil, err } return &TransferClient{ cli: jsonrpc.NewClient(conn), name: name, }, nil } func (this *TransferBackend) Start() error { cfg := this.config u := cfg.Url addrs := strings.Split(u.Host, ",") this.addrs = addrs this.ccp = cpool.CreateClusteredConnPool(func(addr string) *cpool.ConnPool { return cpool.NewConnPool( addr, addr, cfg.MaxConn, cfg.MaxIdle, cfg.ConnTimeout, cfg.CallTimeout, this.transferConnect, ) }, addrs) go this.sendProc() return nil } func (this *TransferBackend) sendProc() { cfg := this.config sema := nsema.NewSemaphore(cfg.MaxConn) for { items := this.queue.PopBackBy(cfg.Batch) if len(items) == 0 { time.Sleep(DefaultSendTaskSleepInterval) continue } // 同步Call + 有限并发 进行发送 sema.Acquire() go func(itemList []interface{}) { defer sema.Release() addrs := this.addrs var err error for i := 0; i < 3; i++ { for _, i := range rand.Perm(len(addrs)) { _, err := this.ccp.Call(addrs[i], itemList) if err != nil { log.Println("sendMetrics fail", addrs[i], err) continue } break } if err == nil { this.sendCounter.IncrBy(int64(len(itemList))) break } time.Sleep(100 * time.Millisecond) } if err != nil { this.failCounter.IncrBy(int64(len(itemList))) log.Println(err) return } }(items) } } // 将原始数据入到riemann发送缓存队列 func (this *TransferBackend) Send(items []*cmodel.MetricValue) { for _, i := range items { if !this.queue.PushFront(i) { this.dropCounter.Incr() } } } func (this *TransferBackend) GetStats() *BackendStats { ql := nproc.NewSCounterBase("QueueLength") ql.SetCnt(int64(this.queue.Len())) return &BackendStats{ Send: this.sendCounter.Get(), Drop: this.dropCounter.Get(), Fail: this.failCounter.Get(), QueueLength: ql.Get(), ConnPoolStats: this.ccp.Stats(), } } <|start_filename|>satori/images/transfer/Dockerfile<|end_filename|> FROM satori:base ADD .build /app EXPOSE 8433 CMD exec /app/transfer -c /conf/transfer.yaml <|start_filename|>swcollector/funcs/swifstat.go<|end_filename|> package funcs import ( "log" "strconv" "time" "github.com/gaochao1/sw" "github.com/leancloud/satori/common/model" "github.com/leancloud/satori/swcollector/config" "github.com/leancloud/satori/swcollector/logging" ) var ( initialized = false ignores = map[string]bool{} allIps = []string{} ) func SwIfMetrics(ch chan *model.MetricValue) { cfg := config.Config() if len(cfg.IpRange) <= 0 { logging.Fatalln("No ipRange configured, aborting") } if !initialized { initialized = true for _, v := range cfg.Ignore { ignores[v] = true } allIps = ExpandIpRanges(cfg.IpRange) } sem := make(chan bool, cfg.ConcurrentCollectors) for _, ip := range allIps { sem <- true go coreSwIfMetrics(ip, ch, sem) time.Sleep(5 * time.Millisecond) } } func coreSwIfMetrics(ip string, ch chan *model.MetricValue, sem chan bool) { log.Println("Collect coreSwIfMetrics for", ip) startTime := time.Now().UnixNano() host := ReverseLookup(ip) cfg := config.Config() NM := func(m string, v float64) { ch <- &model.MetricValue{ Endpoint: host, Metric: m, Value: v, Timestamp: time.Now().Unix(), } } pingResult := false for i := 0; i < cfg.PingRetry; i++ { pingResult = sw.Ping(ip, cfg.PingTimeout, cfg.FastPingMode) if pingResult == true { break } } if !pingResult { <-sem return } AliveIpLock.Lock() if !AliveIp[ip] { AliveIp[ip] = true log.Println("Found alive IP:", ip) } AliveIpLock.Unlock() var ifList []sw.IfStats var err error if cfg.Gosnmp { ifList, err = sw.ListIfStats( ip, cfg.SnmpCommunity, cfg.SnmpTimeout, cfg.IgnoreIface, cfg.SnmpRetry, cfg.ConcurrentQueriesPerHost, ignores["packets"], ignores["operstatus"], ignores["broadcasts"], ignores["multicasts"], ignores["discards"], ignores["errors"], ignores["unknownprotos"], ignores["qlen"], ) } else { ifList, err = sw.ListIfStatsSnmpWalk( ip, cfg.SnmpCommunity, cfg.SnmpTimeout*5, cfg.IgnoreIface, cfg.SnmpRetry, ignores["packets"], ignores["operstatus"], ignores["broadcasts"], ignores["multicasts"], ignores["discards"], ignores["errors"], ignores["unknownprotos"], ignores["qlen"], ) } <-sem if err != nil { log.Printf(ip, err) NM("switch.CollectTime", -1.0) } else { NM("switch.CollectTime", float64(time.Now().UnixNano()-startTime)/float64(time.Millisecond)) } for _, ifStat := range ifList { ts := ifStat.TS tags := map[string]string{ "ifName": ifStat.IfName, "ifIndex": strconv.Itoa(ifStat.IfIndex), } M := func(m string, v float64, ignore string) { if !ignores[ignore] { ch <- &model.MetricValue{ Endpoint: ip, Metric: m, Value: v, Timestamp: ts, Tags: tags, } } } M("switch.if.OperStatus", float64(ifStat.IfOperStatus), "operstatus") M("switch.if.Speed", float64(ifStat.IfSpeed), "speed") M("switch.if.InBroadcastPkt", float64(ifStat.IfHCInBroadcastPkts), "broadcasts") M("switch.if.OutBroadcastPkt", float64(ifStat.IfHCOutBroadcastPkts), "broadcasts") M("switch.if.InMulticastPkt", float64(ifStat.IfHCInMulticastPkts), "multicasts") M("switch.if.OutMulticastPkt", float64(ifStat.IfHCOutMulticastPkts), "multicasts") M("switch.if.InDiscards", float64(ifStat.IfInDiscards), "discards") M("switch.if.OutDiscards", float64(ifStat.IfOutDiscards), "discards") M("switch.if.InErrors", float64(ifStat.IfInErrors), "errors") M("switch.if.OutErrors", float64(ifStat.IfOutErrors), "errors") M("switch.if.InUnknownProtos", float64(ifStat.IfInUnknownProtos), "unknownprotos") M("switch.if.OutQLen", float64(ifStat.IfOutQLen), "qlen") M("switch.if.InPkts", float64(ifStat.IfHCInUcastPkts), "packets") M("switch.if.OutPkts", float64(ifStat.IfHCOutUcastPkts), "packets") M("switch.if.In", float64(ifStat.IfHCInOctets), "octets") M("switch.if.Out", float64(ifStat.IfHCOutOctets), "octets") } } <|start_filename|>common/cpool/pool.go<|end_filename|> package cpool import ( "fmt" "sync" "time" ) //TODO: 保存所有的连接, 而不是只保存连接计数 var ErrMaxConn = fmt.Errorf("maximum connections reached") // type ConnPool struct { sync.RWMutex Name string Address string MaxConns int MaxIdle int ConnTimeout int CallTimeout int Cnt int64 New func(name string, pool *ConnPool) (PoolClient, error) active int free []PoolClient all map[string]PoolClient } type ConnPoolStats struct { Name string Count int64 Active int All int Free int } func (this *ConnPoolStats) String() string { return fmt.Sprintf("%s[Count: %d, Active: %d, All: %d, Free: %d]", this.Name, this.Count, this.Active, this.All, this.Free, ) } func NewConnPool(name string, address string, maxConns int, maxIdle int, connTimeout int, callTimeout int, new func(string, *ConnPool) (PoolClient, error)) *ConnPool { return &ConnPool{ Name: name, Address: address, MaxConns: maxConns, MaxIdle: maxIdle, CallTimeout: callTimeout, ConnTimeout: connTimeout, Cnt: 0, New: new, all: make(map[string]PoolClient), } } func (this *ConnPool) Stats() *ConnPoolStats { this.RLock() defer this.RUnlock() return &ConnPoolStats{ Name: this.Name, Count: this.Cnt, Active: this.active, All: len(this.all), Free: len(this.free), } } func (this *ConnPool) Fetch() (PoolClient, error) { this.Lock() defer this.Unlock() // get from free conn := this.fetchFree() if conn != nil { return conn, nil } if this.active >= this.MaxConns { return nil, ErrMaxConn } // create new conn conn, err := this.newConn() if err != nil { return nil, err } this.active += 1 return conn, nil } func (this *ConnPool) Call(arg interface{}) (interface{}, error) { conn, err := this.Fetch() if err != nil { return nil, fmt.Errorf("%s get connection fail: conn %v, err %v. stats: %s", this.Name, conn, err, this.Stats()) } callTimeout := time.Duration(this.CallTimeout) * time.Millisecond done := make(chan error) var resp interface{} go func() { resp, err = conn.Call(arg) done <- err }() select { case <-time.After(callTimeout): this.ForceClose(conn) return nil, fmt.Errorf("%s, call timeout", conn.Name()) case err = <-done: if err != nil { this.ForceClose(conn) err = fmt.Errorf("%s, call failed, err %v. stats: %s", this.Name, err, this.Stats()) } else { this.Release(conn) } return resp, err } } func (this *ConnPool) Release(conn PoolClient) { this.Lock() defer this.Unlock() if len(this.free) >= this.MaxIdle { this.deleteConn(conn) this.active -= 1 } else { this.addFree(conn) } } func (this *ConnPool) ForceClose(conn PoolClient) { this.Lock() defer this.Unlock() this.deleteConn(conn) this.active -= 1 } func (this *ConnPool) Destroy() { this.Lock() defer this.Unlock() for _, conn := range this.free { if conn != nil && !conn.Closed() { conn.Close() } } for _, conn := range this.all { if conn != nil && !conn.Closed() { conn.Close() } } this.active = 0 this.free = []PoolClient{} this.all = map[string]PoolClient{} } // internal, concurrently unsafe func (this *ConnPool) newConn() (PoolClient, error) { name := fmt.Sprintf("%s_%d_%d", this.Name, this.Cnt, time.Now().Unix()) conn, err := this.New(name, this) if err != nil { if conn != nil { conn.Close() } return nil, err } this.Cnt++ this.all[conn.Name()] = conn return conn, nil } func (this *ConnPool) deleteConn(conn PoolClient) { if conn != nil { conn.Close() } delete(this.all, conn.Name()) } func (this *ConnPool) addFree(conn PoolClient) { this.free = append(this.free, conn) } func (this *ConnPool) fetchFree() PoolClient { if len(this.free) == 0 { return nil } conn := this.free[0] this.free = this.free[1:] return conn } <|start_filename|>common/utils/md5.go<|end_filename|> package utils import ( "crypto/md5" "fmt" "io" ) func Md5(raw string) string { h := md5.New() io.WriteString(h, raw) return fmt.Sprintf("%x", h.Sum(nil)) } <|start_filename|>swcollector/funcs/swping.go<|end_filename|> package funcs import ( "log" "time" "github.com/gaochao1/sw" "github.com/leancloud/satori/common/model" "github.com/leancloud/satori/swcollector/config" ) func PingMetrics(ch chan *model.MetricValue) { AliveIpLock.RLock() defer AliveIpLock.RUnlock() for ip := range AliveIp { go pingMetrics(ip, ch) } } func pingMetrics(ip string, ch chan *model.MetricValue) { cfg := config.Config() timeout := cfg.PingTimeout * cfg.PingRetry fastPingMode := cfg.FastPingMode rtt, err := sw.PingRtt(ip, timeout, fastPingMode) if err != nil { log.Println(ip, err) return } ch <- &model.MetricValue{ Endpoint: ReverseLookup(ip), Metric: "switch.Ping", Value: float64(rtt), Timestamp: time.Now().Unix(), } } <|start_filename|>satori/images/redis/Dockerfile<|end_filename|> FROM satori:base EXPOSE 6379 ADD redis.conf /etc/redis/redis.conf CMD exec /usr/bin/redis-server /etc/redis/redis.conf <|start_filename|>agent/funcs/ifstat.go<|end_filename|> package funcs import ( "github.com/leancloud/satori/agent/g" "github.com/leancloud/satori/common/model" "github.com/toolkits/nux" "log" ) func NetMetrics() []*model.MetricValue { return CoreNetMetrics(g.Config().Collector.IfacePrefix) } func CoreNetMetrics(ifacePrefix []string) []*model.MetricValue { netIfs, err := nux.NetIfs(ifacePrefix) if err != nil { log.Println(err) return []*model.MetricValue{} } cnt := len(netIfs) ret := make([]*model.MetricValue, cnt*20) for idx, netIf := range netIfs { iface := map[string]string{ "iface": netIf.Iface, } ret[idx*20+0] = VT("net.if.in.bytes", float64(netIf.InBytes), iface) ret[idx*20+1] = VT("net.if.in.packets", float64(netIf.InPackages), iface) ret[idx*20+2] = VT("net.if.in.errors", float64(netIf.InErrors), iface) ret[idx*20+3] = VT("net.if.in.dropped", float64(netIf.InDropped), iface) ret[idx*20+4] = VT("net.if.in.fifo.errs", float64(netIf.InFifoErrs), iface) ret[idx*20+5] = VT("net.if.in.frame.errs", float64(netIf.InFrameErrs), iface) ret[idx*20+6] = VT("net.if.in.compressed", float64(netIf.InCompressed), iface) ret[idx*20+7] = VT("net.if.in.multicast", float64(netIf.InMulticast), iface) ret[idx*20+8] = VT("net.if.out.bytes", float64(netIf.OutBytes), iface) ret[idx*20+9] = VT("net.if.out.packets", float64(netIf.OutPackages), iface) ret[idx*20+10] = VT("net.if.out.errors", float64(netIf.OutErrors), iface) ret[idx*20+11] = VT("net.if.out.dropped", float64(netIf.OutDropped), iface) ret[idx*20+12] = VT("net.if.out.fifo.errs", float64(netIf.OutFifoErrs), iface) ret[idx*20+13] = VT("net.if.out.collisions", float64(netIf.OutCollisions), iface) ret[idx*20+14] = VT("net.if.out.carrier.errs", float64(netIf.OutCarrierErrs), iface) ret[idx*20+15] = VT("net.if.out.compressed", float64(netIf.OutCompressed), iface) ret[idx*20+16] = VT("net.if.total.bytes", float64(netIf.TotalBytes), iface) ret[idx*20+17] = VT("net.if.total.packets", float64(netIf.TotalPackages), iface) ret[idx*20+18] = VT("net.if.total.errors", float64(netIf.TotalErrors), iface) ret[idx*20+19] = VT("net.if.total.dropped", float64(netIf.TotalDropped), iface) } return ret } <|start_filename|>satori/images/base/Dockerfile<|end_filename|> FROM ubuntu:18.04 MAINTAINER <EMAIL> ARG USE_MIRROR ENV TERM xterm ADD sources.list /etc/apt/sources.list RUN rm -f /etc/localtime && ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime RUN adduser ubuntu RUN [ -z "$USE_MIRROR" ] || (sed -E -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list; touch /etc/use-mirror) RUN apt-get update && apt-get install -y curl fcgiwrap supervisor git python3 python3-pip python3-venv redis-server openjdk-11-jre-headless locales RUN locale-gen zh_CN.UTF-8 ENV LANG zh_CN.UTF-8 ENV LANGUAGE zh_CN:en ENV LC_ALL zh_CN.UTF-8 <|start_filename|>swcollector/config/util.go<|end_filename|> package config import ( "encoding/json" "reflect" ) func FillDefault(v interface{}) { iface := reflect.ValueOf(v) elem := iface.Elem() typ := elem.Type() for i := 0; i < elem.NumField(); i++ { f := elem.Field(i) ft := typ.Field(i) if v := ft.Tag.Get("default"); v != "" { var zero bool switch ft.Type.Kind() { case reflect.Chan, reflect.Func, reflect.Map: fallthrough case reflect.Ptr, reflect.Interface, reflect.Slice: zero = f.IsNil() default: zero = reflect.Zero(ft.Type).Interface() == f.Interface() } if zero { json.Unmarshal([]byte(v), f.Addr().Interface()) } } } } <|start_filename|>master/g/cfg.go<|end_filename|> package g import ( "log" "sync" "github.com/toolkits/file" "gopkg.in/yaml.v2" ) type GlobalConfig struct { Debug bool `yaml:"debug"` Redis string `yaml:"redis"` Listen string `yaml:"listen"` HTTP string `yaml:"http"` Transfer string `yaml:"transfer"` PurgeSeconds int64 `yaml:"purgeSeconds"` } var ( ConfigFile string config *GlobalConfig configLock = new(sync.RWMutex) ) func Config() *GlobalConfig { configLock.RLock() defer configLock.RUnlock() return config } func ParseConfig(cfg string) { if cfg == "" { log.Fatalln("use -c to specify configuration file") } if !file.IsExist(cfg) { log.Fatalln("config file:", cfg, "is not existent") } ConfigFile = cfg configContent, err := file.ToTrimString(cfg) if err != nil { log.Fatalln("read config file:", cfg, "fail:", err) } var c GlobalConfig err = yaml.Unmarshal([]byte(configContent), &c) if err != nil { log.Fatalln("parse config file:", cfg, "fail:", err) } configLock.Lock() defer configLock.Unlock() config = &c log.Println("read config file:", cfg, "successfully") } <|start_filename|>frontend/view/nodes/table.js<|end_filename|> (function(Vue){ var nodesTableTemplate = ` <div class="table-responsive"> <table class="table table-striped jambo_table"> <thead> <tr> <th>最新插件版本</th> <th>总机器数</th> <th>最后心跳在1h前的机器数</th> </tr> </thead> <tbody> <tr class="events-row"> <td><img width=32 height=32 :src="'https://www.gravatar.com/avatar/' + pluginVersion + '?s=64&d=identicon&r=PG'" :alt="pluginVersion"></td> <td class="status">{{ numNodes }}</td> <td class="status">{{ numInactiveNodes }}</td> </tr> </tbody> </table> <table class="table table-striped jambo_table"> <thead> <tr> <th>机器名</th> <th>IP</th> <th>Agent版本</th> <th>插件版本</th> <th>上次心跳</th> <th>插件项</th> </tr> </thead> <tbody> <tr v-if="nodes == null"> <td colspan="6">正在获取数据……</td> </tr> <tr v-if="_.isArray(nodes) && _.isEmpty(nodes)"> <td colspan="6">并没有机器,正确的安装 agent 了么?</td> </tr> <tr v-if="nodes" v-for="(n, i) in nodes" class="pointer events-row" :class="i & 1 ? 'odd' : 'even'"> <td>{{ n.hostname }}</td> <td>{{ n.ip }}</td> <td><img width=32 height=32 :src="'https://www.gravatar.com/avatar/' + n['agent-version'].replace(/\\./g, '0') + '?s=64&d=identicon&r=PG'" :alt="n['agent-version']">{{ n['agent-version'] }}</td> <td><img width=32 height=32 :src="'https://www.gravatar.com/avatar/' + n['plugin-version'] + '?s=64&d=identicon&r=PG'" :alt="n['plugin-version']"></td> <!--<td></td>--> <td>{{ timeFromNow(n.lastseen) }}</td> <td> <div style="margin: 5px 0 0 5px; display: inline-block;" v-for="v in n.pluginDirs"> <span class="label label-info">{{ v }}</span> </div> <div style="margin: 5px 0 0 5px; display: inline-block;" v-for="v in n.pluginMetrics"> <span class="label label-warning" style="cursor: pointer" @click="showMetric(v)">{{ v._metric }}</span> </div> </td> </tr> </tbody> </table> </div> `; var NodesTable = Vue.extend({ template: nodesTableTemplate, props: ['api-endpoint', 'api-auth'], mounted() { this.refresh(); }, data() { return { nodes: null, pluginVersion: '...', numNodes: '...', numInactiveNodes: '...', } }, methods: { _getFetchHeaders() { var headers = new Headers(); if(this.apiAuth) { headers.append("Authorization", "Basic " + btoa(this.apiAuth)); } return headers; }, refresh() { var opts = { method: "GET", headers: this._getFetchHeaders(), credentials: 'include', }; fetch(this.apiEndpoint, opts).then(resp => resp.json()).then((state) => { this.pluginVersion = state['plugin-version']; this.numNodes = Object.keys(state['agents']).length; this.numInactiveNodes = _.sum(_.map(state.agents, (a) => (new Date() / 1000 - a.lastseen > 3600) ? 1 : 0)); this.nodes = _.map(state.agents, (v, k) => { v.pluginDirs = _.sortBy(state['plugin-dirs'][k]); v.pluginMetrics = _.sortBy(state['plugins'][k], v => v._metric); return v; }); }); }, timeFromNow(ts) { return moment(new Date(ts * 1000)).locale('zh-cn').fromNow(); }, showMetric(m) { alert(JSON.stringify(m, null, 2)); }, } }); Vue.component('nodes-table', NodesTable); })(Vue); <|start_filename|>transfer/sender/common.go<|end_filename|> package sender import ( "log" "net/url" "strconv" "strings" "time" "github.com/leancloud/satori/common/cpool" cmodel "github.com/leancloud/satori/common/model" nlist "github.com/toolkits/container/list" nproc "github.com/toolkits/proc" ) const ( DefaultSendQueueMaxSize = 10240 DefaultSendTaskSleepInterval = time.Millisecond * 50 //默认睡眠间隔为50ms ) type BackendStats struct { Send *nproc.SCounterQps Drop *nproc.SCounterQps Fail *nproc.SCounterQps QueueLength *nproc.SCounterBase ConnPoolStats []*cpool.ConnPoolStats } type BackendConfig struct { Name string Engine string Protocol string ConnTimeout int CallTimeout int SendInterval int Batch int MaxConn int MaxIdle int Retry int Url url.URL } func parseBackendUrl(connString string) *BackendConfig { u, err := url.Parse(connString) if err != nil { log.Printf("Can't parse backend string %s: %s\n", connString, err.Error()) return nil } q := u.Query() getInt := func(f string, def int) int { v := q.Get(f) if v == "" { return def } intv, err := strconv.ParseInt(v, 10, 32) if err == nil { return int(intv) } else { return def } } name := q.Get("name") if name == "" { name = u.String() } v := strings.SplitN(u.Scheme, "+", 2) var engine, protocol string if len(v) > 1 { engine = v[0] protocol = v[1] } else { engine = v[0] protocol = "" } return &BackendConfig{ Name: name, Engine: engine, Protocol: protocol, ConnTimeout: getInt("connTimeout", 1000), CallTimeout: getInt("callTimeout", 5000), SendInterval: getInt("sendInterval", 1000), Batch: getInt("batch", 20), MaxConn: getInt("maxConn", 32), MaxIdle: getInt("maxIdle", 32), Retry: getInt("retry", 3), Url: *u, } } type Backend interface { GetConfig() *BackendConfig Start() error Send(items []*cmodel.MetricValue) GetStats() *BackendStats } type BackendCommon struct { config *BackendConfig pool *cpool.ConnPool queue *nlist.SafeListLimited sendCounter *nproc.SCounterQps dropCounter *nproc.SCounterQps failCounter *nproc.SCounterQps } func (this *BackendCommon) GetConfig() *BackendConfig { return this.config } func (this *BackendCommon) GetStats() *BackendStats { ql := nproc.NewSCounterBase("QueueLength") ql.SetCnt(int64(this.queue.Len())) return &BackendStats{ Send: this.sendCounter.Get(), Drop: this.dropCounter.Get(), Fail: this.failCounter.Get(), QueueLength: ql.Get(), ConnPoolStats: []*cpool.ConnPoolStats{this.pool.Stats()}, } } func newBackendCommon(cfg *BackendConfig) *BackendCommon { return &BackendCommon{ config: cfg, queue: nlist.NewSafeListLimited(DefaultSendQueueMaxSize), sendCounter: nproc.NewSCounterQps("Send"), dropCounter: nproc.NewSCounterQps("Drop"), failCounter: nproc.NewSCounterQps("Fail"), } } <|start_filename|>satori-rules/rules/project.clj<|end_filename|> (defproject satori-conf "0.3.1-satori-rules" :description "NOT FOR BUILD, this is used for making dev environment happy" :url "http://example.com/FIXME" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :plugins [[io.aviso/pretty "0.1.37"]] :middleware [io.aviso.lein-pretty/inject] :dependencies [[org.clojure/clojure "1.10.0"] [org.clojure/tools.reader "1.0.0-beta3"] [org.clojure/data.json "0.2.6"] [com.taoensso/carmine "2.19.1"] [io.aviso/pretty "0.1.37"] [riemann "0.3.1"]] :source-paths ["."]) <|start_filename|>satori/images/master/Dockerfile<|end_filename|> FROM satori:base ADD .build /app EXPOSE 6040 EXPOSE 6041 CMD exec /app/master -c /conf/master.yaml <|start_filename|>transfer/sender/influxdb.go<|end_filename|> package sender import ( "log" "net" "net/url" "strings" "time" influxdb "github.com/influxdata/influxdb/client/v2" nsema "github.com/toolkits/concurrent/semaphore" "github.com/leancloud/satori/common/cpool" cmodel "github.com/leancloud/satori/common/model" ) type InfluxdbBackend struct { BackendCommon } func newInfluxdbBackend(cfg *BackendConfig) Backend { if cfg.Engine == "influxdb" { return &InfluxdbBackend{*newBackendCommon(cfg)} } else { return nil } } type InfluxdbClient struct { cli influxdb.Client name string dbName string } func (this InfluxdbClient) Name() string { return this.name } func (this InfluxdbClient) Closed() bool { return this.cli == nil } func (this InfluxdbClient) Close() error { if this.cli != nil { err := this.cli.Close() this.cli = nil return err } return nil } func (this InfluxdbClient) Call(arg interface{}) (interface{}, error) { bp, err := influxdb.NewBatchPoints(influxdb.BatchPointsConfig{ Database: this.dbName, Precision: "s", }) if err != nil { return nil, err } items := arg.([]*cmodel.MetricValue) for _, item := range items { token := strings.SplitN(item.Metric, ".", 2) var measurement, field string if len(token) == 1 { measurement = "_other" field = token[0] } else if len(token) == 2 { measurement = token[0] field = token[1] } // Create a point and add to batch tags := map[string]string{ "host": item.Endpoint, } fields := map[string]interface{}{ field: item.Value, } for k, v := range item.Tags { tags[k] = v } pt, err := influxdb.NewPoint(measurement, tags, fields, time.Unix(item.Timestamp, 0)) if err != nil { return nil, err } bp.AddPoint(pt) } // Write the batch return nil, this.cli.Write(bp) } func (this *InfluxdbBackend) influxdbConnect(name string, p *cpool.ConnPool) (cpool.PoolClient, error) { cfg := this.config u := cfg.Url connTimeout := time.Duration(p.ConnTimeout) * time.Millisecond _, err := net.DialTimeout("tcp", u.Host, connTimeout) if err != nil { // log.Printf("new conn fail, addr %s, err %v", p.Address, err) return nil, err } pwd, _ := u.User.Password() proto := cfg.Protocol if proto == "" { proto = "http" } c, err := influxdb.NewHTTPClient( influxdb.HTTPConfig{ Addr: (&url.URL{Scheme: proto, Host: u.Host}).String(), Username: u.User.Username(), Password: <PASSWORD>, }, ) if err != nil { return nil, err } return InfluxdbClient{ cli: c, name: name, dbName: u.Path[1:], }, nil } func (this *InfluxdbBackend) createConnPool() *cpool.ConnPool { cfg := this.config return cpool.NewConnPool( cfg.Name, cfg.Url.Host, cfg.MaxConn, cfg.MaxIdle, cfg.ConnTimeout, cfg.CallTimeout, this.influxdbConnect, ) } func (this *InfluxdbBackend) Start() error { this.pool = this.createConnPool() go this.sendProc() return nil } func (this *InfluxdbBackend) sendProc() { cfg := this.config batch := cfg.Batch // 一次发送,最多batch条数据 sema := nsema.NewSemaphore(cfg.MaxConn) for { items := this.queue.PopBackBy(batch) count := len(items) if count == 0 { time.Sleep(DefaultSendTaskSleepInterval) continue } influxdbItems := make([]*cmodel.MetricValue, 0, count) for i := 0; i < count; i++ { m := items[i].(*cmodel.MetricValue) if m.Metric[0:7] == ".satori" { // skip internal events continue } influxdbItems = append(influxdbItems, m) } // 同步Call + 有限并发 进行发送 sema.Acquire() go func(influxdbItems []*cmodel.MetricValue, count int) { defer sema.Release() var err error sendOk := false for i := 0; i < cfg.Retry; i++ { _, err = this.pool.Call(influxdbItems) if err == nil { sendOk = true break } time.Sleep(time.Millisecond * 10) } // statistics if !sendOk { log.Printf("send influxdb %s fail: %v", cfg.Name, err) this.failCounter.IncrBy(int64(count)) } else { this.sendCounter.IncrBy(int64(count)) } }(influxdbItems, count) } } // Push data to 3rd-party database func (this *InfluxdbBackend) Send(items []*cmodel.MetricValue) { for _, item := range items { myItem := item myItem.Timestamp = item.Timestamp isSuccess := this.queue.PushFront(myItem) // statistics if !isSuccess { this.dropCounter.Incr() } } } <|start_filename|>agent/main.go<|end_filename|> package main import ( "flag" "fmt" "log" "os" "github.com/leancloud/satori/agent/cgroups" "github.com/leancloud/satori/agent/cron" "github.com/leancloud/satori/agent/funcs" "github.com/leancloud/satori/agent/g" "github.com/leancloud/satori/agent/http" ) func main() { cfg := flag.String("c", "agent-cfg.yaml", "configuration file") version := flag.Bool("v", false, "show version") flag.Parse() if *version { fmt.Println(g.VERSION) os.Exit(0) } g.ParseConfig(*cfg) funcs.BuildMappers() defer func() { if r := recover(); r != nil { g.LastMessage("main") } }() cg := g.Config().Cgroups if cg != nil { if err := cgroups.JailMe("satori", cg.CPU, cg.Memory); err != nil { log.Println("Can't setup cgroups:", err) if cg.Enforce { panic(err) } } } go cron.SyncWithMaster() go cron.StartCollect() go g.SendToTransferProc() go http.Start() go g.ReportLastMessage() select {} } <|start_filename|>satori-rules/rules/infra/cross.clj<|end_filename|> (ns infra.cross (:require [riemann.streams :refer :all] [agent-plugin :refer :all] [alarm :refer :all] [lib :refer :all])) (def infra-cross-rules (sdo ; Ping (where (host "office1" "office2") (plugin "cross.ping" 15 {:region "office"}) (plugin "cross.agent" 15 {:region "office"})) (where (host "stg1" "stg2") (plugin "cross.ping" 15 {:region "stg"}) (plugin "cross.agent" 15 {:region "stg"})) (where (host "prod1" "prod2") (plugin "cross.ping" 15 {:region "c1"}) (plugin "cross.agent" 15 {:region "c1"})) (where (service "cross.ping.alive") (by :host (judge (< 1) (runs 3 :state (alarm-every 2 :min (! {:note "Ping 不通了!" :level 1 :expected 1 :outstanding-tags [:region] :groups [:operation]})))))) (where (service "cross.agent.alive") (by :host (judge (< 1) (runs 3 :state (alarm-every 2 :min (! {:note "Satori Agent 不响应了!" :level 5 :expected 1 :outstanding-tags [:region] :groups [:operation]})))))) #_(place holder))) <|start_filename|>transfer/receiver/receiver.go<|end_filename|> package receiver import ( "github.com/leancloud/satori/transfer/receiver/rpc" ) func Start() { go rpc.StartRpc() } <|start_filename|>transfer/receiver/rpc/rpc_transfer.go<|end_filename|> package rpc import ( "fmt" cmodel "github.com/leancloud/satori/common/model" "github.com/leancloud/satori/transfer/receiver/core" ) type Transfer int type TransferResp struct { Msg string Total int ErrInvalid int Latency int64 } func (t *TransferResp) String() string { s := fmt.Sprintf("TransferResp total=%d, err_invalid=%d, latency=%dms", t.Total, t.ErrInvalid, t.Latency) if t.Msg != "" { s = fmt.Sprintf("%s, msg=%s", s, t.Msg) } return s } func (this *Transfer) Ping(req cmodel.NullRpcRequest, resp *cmodel.SimpleRpcResponse) error { return nil } func (t *Transfer) Update(args []*cmodel.MetricValue, reply *cmodel.TransferResponse) error { return core.RecvMetricValues(args, reply) }
cnof/satori
<|start_filename|>src/app/components/messages/messages.css<|end_filename|> .p-message-wrapper { display: flex; align-items: center; } .p-message-close { display: flex; align-items: center; justify-content: center; } .p-message-close.p-link { margin-left: auto; overflow: hidden; position: relative; } <|start_filename|>src/app/components/slider/slider.css<|end_filename|> .p-slider { position: relative; } .p-slider .p-slider-handle { position: absolute; cursor: grab; touch-action: none; display: block; } .p-slider-range { position: absolute; display: block; } .p-slider-horizontal .p-slider-range { top: 0; left: 0; height: 100%; } .p-slider-horizontal .p-slider-handle { top: 50%; } .p-slider-vertical { height: 100px; } .p-slider-vertical .p-slider-handle { left: 50%; } .p-slider-vertical .p-slider-range { bottom: 0; left: 0; width: 100%; } <|start_filename|>src/app/components/steps/steps.css<|end_filename|> .p-steps { position: relative; } .p-steps ul { padding: 0; margin: 0; list-style-type: none; display: flex; } .p-steps-item { position: relative; display: flex; justify-content: center; flex: 1 1 auto; } .p-steps-item .p-menuitem-link { display: inline-flex; flex-direction: column; align-items: center; overflow: hidden; text-decoration: none; } .p-steps.p-steps-readonly .p-steps-item { cursor: auto; } .p-steps-item.p-steps-current .p-menuitem-link { cursor: default; } .p-steps-title { white-space: nowrap; } .p-steps-number { display: flex; align-items: center; justify-content: center; } .p-steps-title { display: block; } <|start_filename|>src/app/components/panelmenu/panelmenu.css<|end_filename|> .p-panelmenu .p-panelmenu-header-link { display: flex; align-items: center; user-select: none; cursor: pointer; position: relative; text-decoration: none; } .p-panelmenu .p-panelmenu-header-link:focus { z-index: 1; } .p-panelmenu .p-submenu-list { margin: 0; padding: 0; list-style: none; } .p-panelmenu .p-menuitem-link { display: flex; align-items: center; user-select: none; cursor: pointer; text-decoration: none; } .p-panelmenu .p-menuitem-text { line-height: 1; } <|start_filename|>src/app/components/megamenu/megamenu.css<|end_filename|> .p-megamenu-root-list { margin: 0; padding: 0; list-style: none; } .p-megamenu-root-list > .p-menuitem { position: relative; } .p-megamenu .p-menuitem-link { cursor: pointer; display: flex; align-items: center; text-decoration: none; overflow: hidden; position: relative; } .p-megamenu .p-menuitem-text { line-height: 1; } .p-megamenu-panel { display: none; position: absolute; width: auto; z-index: 1; } .p-megamenu-root-list > .p-menuitem-active > .p-megamenu-panel { display: block; } .p-megamenu-submenu { margin: 0; padding: 0; list-style: none; } /* Horizontal */ .p-megamenu-horizontal .p-megamenu-root-list { display: flex; align-items: center; flex-wrap: wrap; } /* Vertical */ .p-megamenu-vertical .p-megamenu-root-list { flex-direction: column; } .p-megamenu-vertical .p-megamenu-root-list > .p-menuitem-active > .p-megamenu-panel { left: 100%; top: 0; } .p-megamenu-vertical .p-megamenu-root-list > .p-menuitem > .p-menuitem-link > .p-submenu-icon { margin-left: auto; } .p-megamenu-grid { display: flex; } .p-megamenu-col-2, .p-megamenu-col-3, .p-megamenu-col-4, .p-megamenu-col-6, .p-megamenu-col-12 { flex: 0 0 auto; padding: 0.5rem; } .p-megamenu-col-2 { width: 16.6667%; } .p-megamenu-col-3 { width: 25%; } .p-megamenu-col-4 { width: 33.3333%; } .p-megamenu-col-6 { width: 50%; } .p-megamenu-col-12 { width: 100%; } <|start_filename|>src/app/components/colorpicker/colorpicker-images.css<|end_filename|> .p-colorpicker-panel .p-colorpicker-color { background: transparent url("./images/color.png") no-repeat left top; } .p-colorpicker-panel .p-colorpicker-hue { background: transparent url("./images/hue.png") no-repeat left top; } <|start_filename|>src/app/components/fieldset/fieldset.css<|end_filename|> .p-fieldset-legend > a, .p-fieldset-legend > span { display: flex; align-items: center; justify-content: center; } .p-fieldset-toggleable .p-fieldset-legend a { cursor: pointer; user-select: none; overflow: hidden; position: relative; } .p-fieldset-legend-text { line-height: 1; } <|start_filename|>src/app/components/paginator/paginator.css<|end_filename|> .p-paginator { display: flex; align-items: center; justify-content: center; flex-wrap: wrap; } .p-paginator-left-content { margin-right: auto; } .p-paginator-right-content { margin-left: auto; } .p-paginator-page, .p-paginator-next, .p-paginator-last, .p-paginator-first, .p-paginator-prev, .p-paginator-current { cursor: pointer; display: inline-flex; align-items: center; justify-content: center; line-height: 1; user-select: none; overflow: hidden; position: relative; } .p-paginator-element:focus { z-index: 1; position: relative; } <|start_filename|>src/app/components/message/message.css<|end_filename|> .p-inline-message { display: inline-flex; align-items: center; justify-content: center; vertical-align: top; } .p-inline-message-icon-only .p-inline-message-text { visibility: hidden; width: 0; } .p-fluid .p-inline-message { display: flex; }
kunal-thakkar/primeng
<|start_filename|>examples/submodules/bundle.js<|end_filename|> (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ },{}],2:[function(require,module,exports){ 'use strict'; require('./app.css'); var foo = require('./modules/foo'); var bar = require('./modules/bar'); foo.init(); bar.init(); },{"./app.css":1,"./modules/bar":3,"./modules/foo":4}],3:[function(require,module,exports){ 'use strict'; module.exports = { init: function() { var container = document.getElementById('container'); var bar = document.createElement('div'); bar.setAttribute('class', 'bar'); bar.innerHTML = 'bar module'; container.appendChild(bar); } }; },{}],4:[function(require,module,exports){ 'use strict'; module.exports = { init: function() { var container = document.getElementById('container'); var foo = document.createElement('div'); foo.setAttribute('class', 'foo'); foo.innerHTML = 'foo module'; container.appendChild(foo); } }; },{}]},{},[2]);
DARKPROGRAMMER16/browserify-css
<|start_filename|>nebulalabs-phonehome/src/co/nebulabs/phonehome/PhoneHomeConfig.java<|end_filename|> package co.nebulabs.phonehome; import java.util.List; import android.util.Log; public final class PhoneHomeConfig { private boolean isEnabled; private PhoneHomeSink logSink; private int debugLogLevel; private int productionLogLevel; private int batchSize; private int flushIntervalSeconds; private PhoneHomeConfig() { this.isEnabled = false; this.logSink = new DefaultSink(); this.debugLogLevel = Log.VERBOSE; this.productionLogLevel = Log.INFO; this.batchSize = 100; this.flushIntervalSeconds = 1800; } private static volatile PhoneHomeConfig INSTANCE = null; public static synchronized PhoneHomeConfig getInstance() { if (INSTANCE == null) INSTANCE = new PhoneHomeConfig(); return INSTANCE; } /** * If enabled == true, you must provide a sink to accept the flushed logs. * * @return */ public boolean isEnabled() { return isEnabled; } public PhoneHomeConfig enabled(final boolean isEnabled) { this.isEnabled = isEnabled; return this; } /** * Configure the sink for flushing logs externally. Required if PhoneHome * is enabled. * * @return */ public PhoneHomeSink getLogSink() { return logSink; } public PhoneHomeConfig logSink(final PhoneHomeSink logSink) { this.logSink = logSink; return this; } /** * Lines at and above this log level will be written to logcat in debug * builds. * * Defaults to Log.VERBOSE. * * @return */ public int getDebugLogLevel() { return debugLogLevel; } public PhoneHomeConfig debugLogLevel(final int debugLogLevel) { this.debugLogLevel = debugLogLevel; return this; } /** * Lines at and above this log level will be written to logcat in non-debug * builds. * * Defaults to Log.INFO. * * @return */ public int getProductionLogLevel() { return productionLogLevel; } public PhoneHomeConfig productionLogLevel(final int productionLogLevel) { this.productionLogLevel = productionLogLevel; return this; } /** * Set batch size for log events before flushing. If your sink sends log * lines across a network, larger values send more data in fewer batches. * Smaller values send smaller, more-frequent bursts of data. * * Defaults to 100 log events. * * @return */ public int getBatchSize() { return batchSize; } public PhoneHomeConfig batchSize(final int batchSize) { this.batchSize = batchSize; return this; } /** * If we haven't sent a batch in IntervalSeconds seconds, flush logs, regardless * of whether we have a full batch. This way, we won't have logs linger on the * client, waiting to be sent. * * Defaults to 1800 seconds, or 30 minutes. * * @return */ public int getFlushIntervalSeconds() { return flushIntervalSeconds; } public PhoneHomeConfig flushIntervalSeconds(final int flushIntervalSeconds) { this.flushIntervalSeconds = flushIntervalSeconds; return this; } private static class DefaultSink implements PhoneHomeSink { @Override public void flushLogs(final List<PhoneHomeLogEvent> logEvents) { if (PhoneHomeConfig.getInstance().isEnabled()) throw new IllegalStateException( "You must provide a PhoneHomeSink if PhoneHome is enabled! See PhoneHomeConfig.logSink()"); } } } <|start_filename|>nebulalabs-phonehome/src/co/nebulabs/phonehome/PhoneHomeSink.java<|end_filename|> package co.nebulabs.phonehome; import java.util.List; public interface PhoneHomeSink { /** * Flush log events externally somewhere. * * You may want to send them to your own server or perhaps to some third * party. * * @param logEvents */ public void flushLogs(List<PhoneHomeLogEvent> logEvents); } <|start_filename|>nebulalabs-phonehome/src/co/nebulabs/phonehome/PhoneHomeLogQueue.java<|end_filename|> package co.nebulabs.phonehome; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import android.util.Log; public final class PhoneHomeLogQueue { private static final String TAG = PhoneHomeLogQueue.class.getSimpleName(); private final BlockingQueue<PhoneHomeLogEvent> queuedEvents = new LinkedBlockingQueue<PhoneHomeLogEvent>(); private Date lastFlush; private PhoneHomeLogQueue() { final long flushCheckIntervalMillis; if (BuildConfig.DEBUG) // 10 seconds while debugging flushCheckIntervalMillis = 10000; else // 1 minute in production flushCheckIntervalMillis = 300000; (new Timer()).scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { maybeFlushQueue(); } catch (RuntimeException ex) { Log.e(TAG, "Caught exception flushing log queue", ex); } } }, flushCheckIntervalMillis, flushCheckIntervalMillis); } private static PhoneHomeLogQueue INSTANCE = null; public static synchronized PhoneHomeLogQueue getInstance() { if (INSTANCE == null) INSTANCE = new PhoneHomeLogQueue(); return INSTANCE; } public void enqueue(final Date when, final int level, final String tag, final String message) { // initialize lastFlush so we know when to start our minimum flush // interval if (lastFlush == null) lastFlush = new Date(); queuedEvents.add(new PhoneHomeLogEvent(when, level, tag, message)); } private synchronized void maybeFlushQueue() { if (queuedEvents.isEmpty()) return; if (lastFlush == null) throw new IllegalStateException( "lastFlush should have been initialized by this point"); final Date now = new Date(); final int batchSize = PhoneHomeConfig.getInstance().getBatchSize(); final int flushTimeSeconds = PhoneHomeConfig.getInstance() .getFlushIntervalSeconds(); if (queuedEvents.size() >= batchSize || (now.getTime() - lastFlush.getTime()) > flushTimeSeconds * 1000) { flushQueue(batchSize); lastFlush = now; } } private void flushQueue(final int batchSize) { List<PhoneHomeLogEvent> logEventBatch = new ArrayList<PhoneHomeLogEvent>(); queuedEvents.drainTo(logEventBatch, batchSize); if (!logEventBatch.isEmpty()) { // don't use our PhoneHomeLogger, lest this queue up another batch Log.d(TAG, "Flushing: " + logEventBatch.size() + " log events."); PhoneHomeConfig.getInstance().getLogSink() .flushLogs(Collections.unmodifiableList(logEventBatch)); } } } <|start_filename|>example/PhoneHomeTest/src/com/example/phonehometest/example/ExampleSink.java<|end_filename|> package com.example.phonehometest.example; import java.util.List; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.net.http.AndroidHttpClient; import android.os.AsyncTask; import co.nebulabs.phonehome.PhoneHomeLogEvent; import co.nebulabs.phonehome.PhoneHomeSink; public class ExampleSink implements PhoneHomeSink { // matches with the example backend provided private static final String HTTP_ENDPOINT = Utils.HTTP_BASE + "/logevents"; private final Context context; private final AndroidHttpClient httpClient = AndroidHttpClient.newInstance("PhoneHomeTest"); public ExampleSink(final Context context) { this.context = context; } private String encodeLogEvents(final List<PhoneHomeLogEvent> logEvents) throws JSONException { // JSON-encoded the hard way; you're better off using something nice like Jackson or Gson JSONArray array = new JSONArray(); for (PhoneHomeLogEvent event : logEvents) { JSONObject eventObj = new JSONObject(); eventObj.put("ts", event.getTimestamp()); eventObj.put("lvl", event.getLevel()); eventObj.put("tag", event.getTag()); eventObj.put("msg", event.getMessage()); array.put(eventObj); } JSONObject obj = new JSONObject(); obj.put("events", array); return obj.toString(); } @Override public void flushLogs(final List<PhoneHomeLogEvent> logEvents) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(final Void... params) { try { String postBody = encodeLogEvents(logEvents); StringEntity postEntity = new StringEntity(postBody, "UTF-8"); postEntity.setContentType("application/json"); HttpPost httpPost = new HttpPost(HTTP_ENDPOINT); httpPost.setEntity(postEntity); httpPost.setHeaders(Utils.getAndroidHeaders(context)); httpClient.execute(httpPost); } catch (Exception ex) { throw new RuntimeException(ex); } return null; } }.execute(); } } <|start_filename|>example/PhoneHomeTest/src/com/example/phonehometest/MainActivity.java<|end_filename|> package com.example.phonehometest; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.View; import android.widget.TextView; import co.nebulabs.phonehome.PhoneHomeConfig; import co.nebulabs.phonehome.PhoneHomeLogger; import com.example.phonehometest.example.ExampleEligibilityChecker; import com.example.phonehometest.example.ExampleEligibilityChecker.EligibilityCallback; import com.example.phonehometest.example.ExampleSink; import com.example.phonehometest.example.Utils; import com.example.phonehometest.example.Utils.AndroidInfo; public class MainActivity extends Activity { private static final PhoneHomeLogger Log = PhoneHomeLogger.forClass(MainActivity.class); private ExampleEligibilityChecker eligibilityChecker; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PhoneHomeConfig.getInstance() // disable sending log flushing for now (eligibility checked by button below) .enabled(false) // wait until we have this many events to flush a batch of logs... .batchSize(100) // ... or until this many seconds have passed since our last flush .flushIntervalSeconds(1800) // when developing, log all messages to logcat (everything is flushed to our sink) .debugLogLevel(android.util.Log.VERBOSE) // in production, only log INFO messages and above to logcat (everything is flushed to our sink) .productionLogLevel(android.util.Log.INFO) // the actual sink used when it's time to flush logs (required if you ever enable log flushing!) .logSink(new ExampleSink(this)); eligibilityChecker = new ExampleEligibilityChecker(this); AndroidInfo androidInfo = Utils.getAndroidInfo(this); ((TextView) findViewById(R.id.model)).setText("Model: " + androidInfo.model); ((TextView) findViewById(R.id.sdkVersion)).setText("SDK version: " + Integer.toString(androidInfo.sdkVersion)); ((TextView) findViewById(R.id.appVersion)).setText("App version: " + Integer.toString(androidInfo.appVersion)); // queue up a handler to create logs final Handler handler = new Handler(); handler.post(new Runnable() { int debugCounter = 0; int infoCounter = 0; @Override public void run() { debugCounter++; Log.d("Debug event #" + debugCounter); if (debugCounter % 2 == 0) { infoCounter++; Log.d("Info event #" + infoCounter); } ((TextView) findViewById(R.id.counterText)).setText("Events: " + debugCounter + " debug, " + infoCounter + " info"); handler.postDelayed(this, 1000); } }); } @Override public boolean onCreateOptionsMenu(final Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public void checkEligibility(final View view) { eligibilityChecker.checkEligibility( new EligibilityCallback() { @Override public void handleEligibilty(final boolean isEligible) { PhoneHomeConfig.getInstance() .enabled(isEligible); String description; if (isEligible) { description = "Eligible to send logs! Make sure you're receiving them on the backend!"; } else { description = "NOT eligible to receive logs. Are you sure that the android info above matches one of your logcat criteria?"; } ((TextView) findViewById(R.id.description)).setText(description); } }); } } <|start_filename|>example/PhoneHomeTest/src/com/example/phonehometest/example/ExampleEligibilityChecker.java<|end_filename|> package com.example.phonehometest.example; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import android.content.Context; import android.net.http.AndroidHttpClient; import android.os.AsyncTask; public final class ExampleEligibilityChecker { // matches with the example backend provided private static final String HTTP_ENDPOINT = Utils.HTTP_BASE + "/eligibility"; private final Context context; private final AndroidHttpClient httpClient = AndroidHttpClient.newInstance("PhoneHomeTest"); public ExampleEligibilityChecker(final Context context) { this.context = context; } public interface EligibilityCallback { public void handleEligibilty(boolean isEligible); } public void checkEligibility(final EligibilityCallback eligibilityCallback) { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(final Void... params) { HttpGet httpGet = new HttpGet(HTTP_ENDPOINT); httpGet.setHeaders(Utils.getAndroidHeaders(context)); HttpResponse response; try { response = httpClient.execute(httpGet); String json = EntityUtils.toString(response.getEntity(), "UTF-8"); JSONObject obj = new JSONObject(json); return obj.getBoolean("is_eligible"); } catch (Exception ex) { throw new RuntimeException(ex); } } @Override protected void onPostExecute(final Boolean isEligible) { eligibilityCallback.handleEligibilty(isEligible); } }.execute(); } } <|start_filename|>nebulalabs-phonehome/src/co/nebulabs/phonehome/PhoneHomeLogEvent.java<|end_filename|> package co.nebulabs.phonehome; import java.util.Date; public final class PhoneHomeLogEvent { private final long timestamp; private final int level; private final String tag; private final String message; public PhoneHomeLogEvent(final long timestamp, final int level, final String tag, final String message) { this.timestamp = timestamp; this.level = level; this.tag = tag; this.message = message; } public PhoneHomeLogEvent(final Date when, final int level, final String tag, final String message) { this(when.getTime(), level, tag, message); } public long getTimestamp() { return timestamp; } public int getLevel() { return level; } public String getTag() { return tag; } public String getMessage() { return message; } @Override public String toString() { return "PhoneHomeLogEvent [timestamp=" + timestamp + ", level=" + level + ", tag=" + tag + ", message=" + message + "]"; } } <|start_filename|>example/PhoneHomeTest/src/com/example/phonehometest/example/Utils.java<|end_filename|> package com.example.phonehometest.example; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; public final class Utils { // this points at localhost on whatever machine the meulator's running on; obviously change this to suit your needs static final String HTTP_BASE = "http://10.0.2.2"; private Utils() {} public static class AndroidInfo { public final String model; public final int sdkVersion; public final int appVersion; private AndroidInfo(final String model, final int sdkVersion, final int appVersion) { this.model = model; this.sdkVersion = sdkVersion; this.appVersion = appVersion; } } public static AndroidInfo getAndroidInfo(final Context context) { int versionCode = -1; try { PackageManager manager = context.getPackageManager(); // FIXME point this at your own package! PackageInfo info = manager.getPackageInfo("com.example.phonehometest", 0); versionCode = info.versionCode; } catch (NameNotFoundException nnf) { throw new RuntimeException("Couldn't get package versionCode!", nnf); } return new AndroidInfo(Build.MODEL, Build.VERSION.SDK_INT, versionCode); } static Header[] getAndroidHeaders(final Context context) { // see backend example for how these are used to associate log events with users AndroidInfo androidInfo = getAndroidInfo(context); return new Header[] { new BasicHeader("X-Android-Model", androidInfo.model), new BasicHeader("X-Android-Sdk", Integer.toString(androidInfo.sdkVersion)), new BasicHeader("X-Android-AppVersion", Integer.toString(androidInfo.appVersion)) }; } } <|start_filename|>nebulalabs-phonehome/src/co/nebulabs/phonehome/PhoneHomeLogger.java<|end_filename|> package co.nebulabs.phonehome; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import android.util.Log; public final class PhoneHomeLogger { private final String TAG; private PhoneHomeLogger(final String tag) { this.TAG = tag; } public static PhoneHomeLogger forTag(final String tag) { return new PhoneHomeLogger(tag); } public static PhoneHomeLogger forClass(final Class<?> cls) { return new PhoneHomeLogger(cls.getSimpleName()); } private boolean logToLogcat(final int level) { PhoneHomeConfig config = PhoneHomeConfig.getInstance(); return (BuildConfig.DEBUG) ? level >= config.getDebugLogLevel() : level >= config.getProductionLogLevel(); } private boolean logToSink() { return PhoneHomeConfig.getInstance().isEnabled(); } public void v(final String msg) { if (logToLogcat(Log.VERBOSE)) Log.v(TAG, msg); maybeSendLog(Log.VERBOSE, msg); } public void v(final String msg, final Throwable throwable) { if (logToLogcat(Log.VERBOSE)) Log.v(TAG, msg, throwable); maybeSendLog(Log.VERBOSE, msg, throwable); } public void d(final String msg) { if (logToLogcat(Log.DEBUG)) Log.d(TAG, msg); maybeSendLog(Log.DEBUG, msg); } public void d(final String msg, final Throwable throwable) { if (logToLogcat(Log.DEBUG)) Log.d(TAG, msg, throwable); maybeSendLog(Log.DEBUG, msg, throwable); } public void i(final String msg) { if (logToLogcat(Log.INFO)) Log.i(TAG, msg); maybeSendLog(Log.INFO, msg); } public void i(final String msg, final Throwable throwable) { if (logToLogcat(Log.INFO)) Log.i(TAG, msg, throwable); maybeSendLog(Log.INFO, msg, throwable); } public void w(final String msg) { if (logToLogcat(Log.WARN)) Log.w(TAG, msg); maybeSendLog(Log.WARN, msg); } public void w(final String msg, final Throwable throwable) { if (logToLogcat(Log.WARN)) Log.w(TAG, msg, throwable); maybeSendLog(Log.WARN, msg, throwable); } public void e(final String msg) { if (logToLogcat(Log.ERROR)) Log.e(TAG, msg); maybeSendLog(Log.ERROR, msg); } public void e(final String msg, final Throwable throwable) { if (logToLogcat(Log.ERROR)) Log.e(TAG, msg, throwable); maybeSendLog(Log.ERROR, msg, throwable); } public void wtf(final String msg) { if (logToLogcat(Log.ASSERT)) Log.wtf(TAG, msg); maybeSendLog(Log.ASSERT, msg); } public void wtf(final String msg, final Throwable throwable) { if (logToLogcat(Log.ASSERT)) Log.wtf(TAG, msg, throwable); maybeSendLog(Log.ASSERT, msg, throwable); } private void maybeSendLog(final int level, final String message) { if (logToSink()) PhoneHomeLogQueue.getInstance().enqueue(new Date(), level, TAG, message); } private void maybeSendLog(final int level, final String message, final Throwable throwable) { maybeSendLog(level, message + "\n" + getStackTraceAsString(throwable)); } private static String getStackTraceAsString(final Throwable throwable) { // lifted from Guava's Throwables.getStackTraceAsString() StringWriter stringWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } }
nebulabsnyc/PhoneHome
<|start_filename|>SemanticData/AddressSpaceComplianceTestTool/CommandLineSyntax/Extensions.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2019, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using CommandLine; using System; using System.Collections.Generic; namespace UAOOI.SemanticData.AddressSpacePrototyping.CommandLineSyntax { internal static class Extensions { internal static void Parse<T>(this string[] args, Action<T> RunCommand, Action<IEnumerable<Error>> dump) { using (Parser parser = Parser.Default) { ParserResult<T> parserResult = parser.ParseArguments<T>(args).WithParsed<T>((T opts) => { RunCommand(opts); }).WithNotParsed<T>(dump); } } } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/ModelFactoryTestingFixture/DataTypeFieldFactoryBase.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System.Xml; using UAOOI.SemanticData.InformationModelFactory; namespace UAOOI.SemanticData.UANodeSetValidation.ModelFactoryTestingFixture { /// <summary> /// Class DataTypeFieldFactoryBase. /// Implements the <see cref="UAOOI.SemanticData.InformationModelFactory.IDataTypeFieldFactory" /> /// </summary> /// <seealso cref="UAOOI.SemanticData.InformationModelFactory.IDataTypeFieldFactory" /> internal class DataTypeFieldFactoryBase : IDataTypeFieldFactory { /// <summary> /// Sets the DataType name. /// </summary> /// <value>The type of the data.</value> public XmlQualifiedName DataType { set { } } /// <summary> /// Sets the identifier the value associated with the field. /// </summary> /// <value>The identifier.</value> public int? Identifier { set { } } /// <summary> /// Sets the name for the field that is unique within the <see cref="T:UAOOI.SemanticData.InformationModelFactory.IDataTypeDefinitionFactory" />. /// </summary> /// <value>The name for the field.</value> public string Name { set { } } /// <summary> /// Sets the value rank. It shall be Scalar (-1) or a fixed rank Array (&gt;=1). This field is not specified for subtypes of Enumeration. /// </summary> /// <value>The value rank.</value> public int? ValueRank { set { } } /// <summary> /// Creates new object of <see cref="T:UAOOI.SemanticData.InformationModelFactory.IDataTypeDefinitionFactory" /> for anonymous definition of the DatType. /// The field is a structure with a layout specified by the <see cref="T:UAOOI.SemanticData.InformationModelFactory.IDataTypeDefinitionFactory" />. /// This field is optional. /// This field allows designers to create nested structures without defining a new DataType Node for each structure. /// This field is not specified for subtypes of Enumeration. /// </summary> /// <returns>IDataTypeDefinitionFactory.</returns> /// <value>A new instance of <see cref="T:UAOOI.SemanticData.InformationModelFactory.IDataTypeDefinitionFactory" /> encapsulating the DatType definition.</value> public IDataTypeDefinitionFactory NewDefinition() { return new DataTypeDefinitionFactoryBase(); } /// <summary> /// The value associated with the field. This field is only specified for subtypes of Enumeration. /// For OptionSets the value is the number of the bit associated with the field. /// </summary> /// <value>The value.</value> public int Value { set { } } /// <summary> /// Sets the symbolic name of the field. A symbolic name for the field that can be used in auto-generated code. It should only be /// specified if the Name cannot be used for this purpose. Only letters, digits or the underscore (‘_’) are permitted. /// This value is not exposed in the OPC UA Address Space /// </summary> /// <value>The symbolic name to be used by the tool.</value> public string SymbolicName { set { } } /// <summary> /// Adds the description for the field in multiple locales /// </summary> /// <param name="localeField">The locale field specified as a string that is composed of a language component and a country/region component as specified by RFC 3066.</param> /// <param name="valueField">The localized text.</param> public void AddDescription(string localeField, string valueField) { } /// <summary> /// Adds the display name. /// </summary> /// <param name="localeField">The locale field specified as a string that is composed of a language component and a country/region component as specified by RFC 3066.</param> /// <param name="valueField">The localized text.</param> public void AddDisplayName(string localeField, string valueField) { } /// <summary> /// Creates new instance of <see cref="IDataTypeDefinitionFactory"/>. /// </summary> /// <returns>IDataTypeDefinitionFactory.</returns> public IDataTypeDefinitionFactory NewDataTypeDefinitionFactory() { return new DataTypeDefinitionFactoryBase(); } /// <summary> /// Gets the array dimensions. /// </summary> /// <value>The array dimensions.</value> /// <remarks>The maximum length of an array. This field is a comma separated list of unsigned integer values.The list has a number of elements equal to the ValueRank. /// The value is 0 if the maximum is not known for a dimension. This field is not specified if the ValueRank less or equal 0. /// This field is not specified for subtypes of Enumeration or for DataTypes</remarks> public string ArrayDimensions { set { } } /// <summary> /// Sets the maximum length of the string. /// </summary> /// <value>The maximum length of the string.</value> /// <remarks>The maximum length of a String or ByteString value. If not known the value is 0. The value is 0 if the DataType is not String or ByteString. /// If the ValueRank &gt; 0 the maximum applies to each element in the array. This field is not specified for subtypes of Enumeration or for DataTypes with /// the OptionSetValues Property.</remarks> public uint MaxStringLength { set { } } /// <summary> /// Sets a value indicating whether this instance is optional. /// </summary> /// <value><c>true</c> if this instance is optional; otherwise, <c>false</c>.</value> /// <remarks>The field indicates if a data type field in a structure is optional. This field is optional.The default value is false. This field is not specified for subtypes of Enumeration and Union.</remarks> public bool IsOptional { set { } } } } <|start_filename|>SemanticData/UANodeSetValidation/XML/UAMethod.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using UAOOI.SemanticData.BuildingErrorsHandling; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.SemanticData.UANodeSetValidation.XML { /// <summary> /// Class UAMethod /// Implements the <see cref="UAOOI.SemanticData.UANodeSetValidation.XML.UAInstance" /> /// </summary> /// <seealso cref="UAOOI.SemanticData.UANodeSetValidation.XML.UAInstance" /> public partial class UAMethod { internal override void RecalculateNodeIds(IUAModelContext modelContext, Action<TraceMessage> trace) { base.RecalculateNodeIds(modelContext, trace); MethodDeclarationNodeId = modelContext.ImportNodeId(this.MethodDeclarationId, trace); } internal NodeId MethodDeclarationNodeId { get; private set; } /// <summary> /// Indicates whether the inherited parent object is also equal to another object. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns><c>true</c> if the current object is equal to the <paramref name="other">other</paramref>; otherwise,, <c>false</c> otherwise.</returns> protected override bool ParentEquals(UANode other) { UAMethod _other = other as UAMethod; if (Object.ReferenceEquals(_other, null)) return false; return base.ParentEquals(_other) && // TODO compare ArgumentDescription this.Executable == _other.Executable && this.UserExecutable == _other.UserExecutable; // not exposed and must be excluded from the comparison this.MethodDeclarationId == _other.MethodDeclarationId; } /// <summary> /// Get the clone from the types derived from this one. /// </summary> /// <returns>An instance of <see cref="T:UAOOI.SemanticData.UANodeSetValidation.XML.UANode" />.</returns> protected override UANode ParentClone() { UAMethod _ret = new UAMethod { Executable = this.Executable, UserExecutable = this.UserExecutable }; base.CloneUAInstance(_ret); return _ret; } } } <|start_filename|>SemanticData/UAModelDesignExport/XML/UA_Model_Design.GoCS.cmd<|end_filename|> :: convert the scheme DomainDescriptor.xsd to cs code xsd.exe "UA Model Design.xsd" /N:UAOOI.SemanticData.UAModelDesignExport.XML /c <|start_filename|>SemanticData/UANodeSetValidation/XML/UAReferenceType.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using UAOOI.SemanticData.BuildingErrorsHandling; namespace UAOOI.SemanticData.UANodeSetValidation.XML { public partial class UAReferenceType { /// <summary> /// Get the clone from the types derived from this one. /// </summary> /// <returns>An instance of <see cref="T:UAOOI.SemanticData.UANodeSetValidation.XML.UANode" />.</returns> protected override UANode ParentClone() { UAReferenceType _ret = new UAReferenceType() { InverseName = this.InverseName, Symmetric = this.Symmetric }; base.CloneUAType(_ret); return _ret; } internal override void RecalculateNodeIds(IUAModelContext modelContext, Action<TraceMessage> trace) { base.RecalculateNodeIds(modelContext, trace); modelContext.RegisterUAReferenceType(BrowseNameQualifiedName); } } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/Helpers/TraceDiagnosticFixture.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System.Collections.Generic; using System.Diagnostics; using UAOOI.SemanticData.BuildingErrorsHandling; namespace UAOOI.SemanticData.UANodeSetValidation.Helpers { internal class TraceDiagnosticFixture { internal readonly List<TraceMessage> TraceList = new List<TraceMessage>(); internal int DiagnosticCounter = 0; internal void Clear() { DiagnosticCounter = 0; TraceList.Clear(); } internal void TraceDiagnostic(TraceMessage msg) { Debug.WriteLine(msg.ToString()); if (msg.BuildError.Focus == Focus.Diagnostic) DiagnosticCounter++; else TraceList.Add(msg); } } } <|start_filename|>SemanticData/UANodeSetValidation/XML/ReferenceChange.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.SemanticData.UANodeSetValidation.XML { public partial class ReferenceChange { internal void RecalculateNodeIds(Func<string, NodeId> importNodeId) { SourceNodeId = importNodeId(Source); ValueNodeId = importNodeId(Value); ReferenceTypeNodeId = importNodeId(Value); } internal NodeId SourceNodeId { get; private set; } internal NodeId ValueNodeId { get; private set; } internal NodeId ReferenceTypeNodeId { get; private set; } } } <|start_filename|>SemanticData/UANodeSetValidation/DataSerialization/NodeId.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using System.Globalization; using System.Text; using UAOOI.SemanticData.BuildingErrorsHandling; namespace UAOOI.SemanticData.UANodeSetValidation.DataSerialization { /// <summary> /// Stores an identifier for a node in a server's address space. /// </summary> /// <remarks> /// <para> /// <b>Please refer to OPC Specifications</b>: /// <list type="bullet"> /// <item><b>Address Space Model</b> section <b>8.2</b></item> /// <item><b>Address Space Model</b> section <b>5.2.2</b></item> /// </list> /// </para> /// <para> /// Stores the id of a Node, which resides within the server's address space. /// <br/></para> /// <para> /// The NodeId can be either: /// <list type="bullet"> /// <item><see cref="uint"/></item> /// <item><see cref="Guid"/></item> /// <item><see cref="string"/></item> /// <item><see cref="byte"/>[]</item> /// </list> /// <br/></para> /// <note> /// <b>Important:</b> Keep in mind that the actual ID's of nodes should be unique such that no two /// nodes within an address-space share the same ID's. /// </note> /// <para> /// The NodeId can be assigned to a particular namespace index. This index is merely just a number and does /// not represent some index within a collection that this node has any knowledge of. The assumption is /// that the host of this object will manage that directly. /// <br/></para> /// </remarks> public partial class NodeId : IFormattable, IEquatable<NodeId>, IComparable { #region constructors /// <summary> /// Initializes the object with default values. /// </summary> /// <remarks> /// Creates a new instance of the class which will have the default values. The actual /// NodeId will need to be defined as this constructor does not specify the id. /// </remarks> internal NodeId() { m_namespaceIndex = 0; m_identifierType = IdType.Numeric_0; m_identifierPart = null; m_GlobalHashCode++; } /// <summary> /// Creates a deep copy of the value. /// </summary> /// <remarks> /// Creates a new NodeId by copying the properties of the node specified in the parameter. /// </remarks> /// <param name="value">The NodeId object whose properties will be copied.</param> /// <exception cref="ArgumentNullException">Thrown when <i>value</i> is null</exception> public NodeId(NodeId value) { if (value == null) throw new ArgumentNullException("value"); m_namespaceIndex = value.m_namespaceIndex; m_identifierType = value.m_identifierType; m_identifierPart = value.MemberwiseClone(); } /// <summary> /// Initializes a numeric node identifier. /// </summary> /// <remarks> /// Creates a new NodeId that will have a numeric (unsigned-int) id /// </remarks> /// <param name="value">The numeric value of the id</param> public NodeId(uint value) { m_namespaceIndex = 0; m_identifierType = IdType.Numeric_0; m_identifierPart = value; } /// <summary> /// Initializes a guid node identifier with a namespace index. /// </summary> /// <remarks> /// Creates a new NodeId that will use a numeric (unsigned int) for its Id, but also /// specifies which namespace this node should belong to. /// </remarks> /// <param name="value">The new (numeric) Id for the node being created</param> /// <param name="namespaceIndex">The index of the namespace that this node should belong to</param> /// <seealso cref="SetNamespaceIndex"/> public NodeId(uint value, ushort namespaceIndex) { m_namespaceIndex = namespaceIndex; m_identifierType = IdType.Numeric_0; m_identifierPart = value; } /// <summary> /// Initializes a string node identifier with a namespace index. /// </summary> /// <remarks> /// Creates a new NodeId that will use a string for its Id, but also /// specifies if the Id is a URI, and which namespace this node belongs to. /// </remarks> /// <param name="value">The new (string) Id for the node being created</param> /// <param name="namespaceIndex">The index of the namespace that this node belongs to</param> public NodeId(string value, ushort namespaceIndex) { m_namespaceIndex = namespaceIndex; m_identifierType = IdType.String_1; m_identifierPart = value; } /// <summary> /// Initializes a guid node identifier. /// </summary> /// <remarks> /// Creates a new node whose Id will be a <see cref="Guid"/>. /// </remarks> /// <param name="value">The new Guid value of this nodes Id.</param> public NodeId(System.Guid value) { m_namespaceIndex = 0; m_identifierType = IdType.Guid_2; m_identifierPart = value; } /// <summary> /// Initializes a guid node identifier. /// </summary> /// <remarks> /// Creates a new node whose Id will be a <see cref="Guid"/>. /// </remarks> /// <param name="value">The new Guid value of this nodes Id.</param> /// <param name="namespaceIndex">The index of the namespace that this node belongs to</param> public NodeId(global::System.Guid value, ushort namespaceIndex) { m_namespaceIndex = namespaceIndex; m_identifierType = IdType.Guid_2; m_identifierPart = value; } /// <summary> /// Initializes a guid node identifier. /// </summary> /// <remarks> /// Creates a new node whose Id will be a series of <see cref="Byte"/>. /// </remarks> /// <param name="value">An array of <see cref="Byte"/> that will become this Node's ID</param> public NodeId(byte[] value) { m_namespaceIndex = 0; m_identifierType = IdType.Opaque_3; m_identifierPart = null; if (value != null) { byte[] copy = new byte[value.Length]; Array.Copy(value, copy, value.Length); m_identifierPart = copy; } } /// <summary> /// Initializes an opaque node identifier with a namespace index. /// </summary> /// <remarks> /// Creates a new node whose Id will be a series of <see cref="Byte"/>, while specifying /// the index of the namespace that this node belongs to. /// </remarks> /// <param name="value">An array of <see cref="Byte"/> that will become this Node's ID</param> /// <param name="namespaceIndex">The index of the namespace that this node belongs to</param> public NodeId(byte[] value, ushort namespaceIndex) { m_namespaceIndex = namespaceIndex; m_identifierType = IdType.Opaque_3; m_identifierPart = null; if (value != null) { byte[] copy = new byte[value.Length]; Array.Copy(value, copy, value.Length); m_identifierPart = copy; } } /// <summary> /// Initializes a node id by parsing a node id string. /// </summary> /// <remarks> /// Creates a new node with a String id. /// </remarks> /// <param name="text">The string id of this new node</param> public NodeId(string text) { NodeId nodeId = NodeId.Parse(text); m_namespaceIndex = nodeId.NamespaceIndex; m_identifierType = nodeId.IdType; m_identifierPart = nodeId.IdentifierPart; } /// <summary> /// Initializes a node identifier with a namespace index. /// </summary> /// <remarks> /// Throws an exception if the identifier type is not supported. /// </remarks> /// <param name="value">The identifier</param> /// <param name="namespaceIndex">The index of the namespace that qualifies the node</param> public NodeId(object value, ushort namespaceIndex) { m_namespaceIndex = namespaceIndex; if (value is uint) { SetIdentifier(IdType.Numeric_0, value); return; } if (value == null || value is string) { SetIdentifier(IdType.String_1, value); return; } if (value is System.Guid) { SetIdentifier(IdType.Guid_2, value); return; } if (value is byte[]) { SetIdentifier(IdType.Opaque_3, value); return; } } #endregion constructors #region public /// <summary> /// Converts an integer to a numeric node identifier. /// </summary> /// <param name="value">The <see cref="uint" /> to compare this node to.</param> /// <returns>The <see cref="NodeId"/> object as the result of the conversion.</returns> /// <remarks>Converts an integer to a numeric node identifier for comparisons.</remarks> public static implicit operator NodeId(uint value) { return new NodeId(value); } /// <summary> /// Returns an instance of a null NodeId. /// </summary> /// <summary> /// Checks if the node id represents a 'Null' node id. /// </summary> /// <remarks> /// Returns a true/false value to indicate if the specified NodeId is null. /// </remarks> /// <param name="nodeId">The NodeId to validate</param> public static bool IsNull(NodeId nodeId) { if (nodeId == null) return true; return nodeId.IsNullNodeId; } /// <summary> /// Gets the <see cref="NodeId"/> representing <b>null</b>. /// </summary> /// <value>The null.</value> public static NodeId Null => s_Null; /// <summary> /// Parses a node id string and returns a node id object. /// </summary> /// <remarks> /// Parses a NodeId String and returns a NodeId object /// </remarks> /// <param name="text">The NodeId value as a string.</param> /// <exception cref="ServiceResultException">Thrown under a variety of circumstances, each time with a specific message.</exception> public static NodeId Parse(string text) { try { if (String.IsNullOrEmpty(text)) return NodeId.Null; ushort namespaceIndex = 0; // parse the namespace index if present. if (text.StartsWith("ns=", StringComparison.Ordinal)) { int index = text.IndexOf(';'); if (index == -1) throw new ServiceResultException (TraceMessage.BuildErrorTraceMessage(BuildError.NodeIdInvalidSyntax, String.Format("Cannot parse node id text: '{0}'", text)), "BuildError_BadNodeIdInvalid"); namespaceIndex = Convert.ToUInt16(text.Substring(3, index - 3), CultureInfo.InvariantCulture); text = text.Substring(index + 1); } // parse numeric node identifier. if (text.StartsWith("i=", StringComparison.Ordinal)) return new NodeId(Convert.ToUInt32(text.Substring(2), CultureInfo.InvariantCulture), namespaceIndex); // parse string node identifier. if (text.StartsWith("s=", StringComparison.Ordinal)) return new NodeId(text.Substring(2), namespaceIndex); // parse GUID node identifier. if (text.StartsWith("g=", StringComparison.Ordinal)) return new NodeId(new System.Guid(text.Substring(2)), namespaceIndex); // parse opaque node identifier. if (text.StartsWith("b=", StringComparison.Ordinal)) return new NodeId(Convert.FromBase64String(text.Substring(2)), namespaceIndex); // treat as a string identifier if a namespace was specified. if (namespaceIndex != 0) return new NodeId(text, namespaceIndex); // treat as URI identifier. return new NodeId(text, 0); } catch (Exception e) { throw new ServiceResultException (TraceMessage.BuildErrorTraceMessage(BuildError.NodeIdInvalidSyntax, String.Format("Cannot parse node id text: '{0}'", text)), "BuildError_BadNodeIdInvalid", e); } } /// <summary> /// Updates the namespace index. /// </summary> internal void SetNamespaceIndex(ushort value) { m_namespaceIndex = value; } /// <summary> /// Updates the identifier. /// </summary> internal void SetIdentifier(IdType idType, object value) { m_identifierType = idType; switch (idType) { case IdType.Opaque_3: throw new NotImplementedException(" m_identifier = Utils.Clone(value);"); default: m_identifierPart = value; break; } } /// <summary> /// Updates the identifier. /// </summary> internal void SetIdentifier(string value, IdType idType) { m_identifierType = idType; SetIdentifier(IdType.String_1, value); } ///<summary> /// The index of the namespace URI in the server's namespace array. /// </summary> /// <remarks> /// The index of the namespace URI in the server's namespace array. /// </remarks> public ushort NamespaceIndex => m_namespaceIndex; /// <summary> /// The type of node identifier used. /// </summary> /// <remarks> /// Returns the type of Id, whether it is: /// <list type="bullet"> /// <item><see cref="uint"/></item> /// <item><see cref="Guid"/></item> /// <item><see cref="string"/></item> /// <item><see cref="byte"/>[]</item> /// </list> /// </remarks> /// <seealso cref="IdType"/> public IdType IdType => m_identifierType; /// <summary> /// The node identifier. /// </summary> /// <remarks> /// Returns the Id in its native format, i.e. UInt, GUID, String etc. /// </remarks> public object IdentifierPart { get { if (m_identifierPart == null) { switch (m_identifierType) { case IdType.Numeric_0: { return (uint)0; } case IdType.Guid_2: { return global::System.Guid.Empty; } } } return m_identifierPart; } } /// <summary> /// Whether the object represents a Null NodeId. /// </summary> /// <remarks> /// Whether the NodeId represents a Null NodeId. /// </remarks> public bool IsNullNodeId { get { // non-zero namespace means it can't be null. if (m_namespaceIndex != 0) return false; // the definition of a null identifier depends on the identifier type. if (IdentifierPart == null) return true; bool _ret = true; switch (m_identifierType) { case IdType.Numeric_0: _ret = !!IdentifierPart.Equals((uint)0); break; case IdType.String_1: _ret = String.IsNullOrEmpty((string)IdentifierPart); break; case IdType.Guid_2: _ret = IdentifierPart.Equals(System.Guid.Empty); break; case IdType.Opaque_3: _ret = !(IdentifierPart != null && ((byte[])IdentifierPart).Length > 0); break; } // must be null. return _ret; } } /// <summary> /// Returns true if the objects are equal. /// </summary> /// <remarks> /// Returns true if the objects are equal. /// </remarks> public static bool operator ==(NodeId value1, object value2) { if (Object.ReferenceEquals(value1, null)) return Object.ReferenceEquals(value2, null); return (value1.CompareTo(value2) == 0); } /// <summary> /// Returns true if the objects are not equal. /// </summary> /// <remarks> /// Returns true if the objects are not equal. /// </remarks> public static bool operator !=(NodeId value1, object value2) { if (Object.ReferenceEquals(value1, null)) return !Object.ReferenceEquals(value2, null); return (value1.CompareTo(value2) != 0); } /// <summary> /// Converts an identifier and a namespaceUri to a local NodeId using the namespaceTable. /// </summary> /// <param name="identifier">The identifier for the node.</param> /// <param name="namespaceUri">The URI to look up.</param> /// <param name="namespaceTable">The table to use for the URI lookup.</param> /// <returns>A local NodeId</returns> /// <exception cref="ServiceResultException">Thrown when the namespace cannot be found</exception> public static NodeId Create(object identifier, string namespaceUri, INamespaceTable namespaceTable) { int index = -1; if (namespaceTable != null) index = namespaceTable.GetURIIndex(new Uri(namespaceUri)); if (index < 0) throw new ServiceResultException(TraceMessage.BuildErrorTraceMessage(BuildError.NodeIdNotDefined, $"NamespaceUri ({namespaceUri}) is not in the namespace table."), "BuildError_BadNodeIdInvalid"); return new NodeId(identifier, (ushort)index); } #region Format() /// <summary> /// Formats a node id as a string. /// </summary> /// <remarks> /// <para> /// Formats a NodeId as a string. /// <br/></para> /// <para> /// An example of this would be: /// <br/></para> /// <para> /// NodeId = "hello123"<br/> /// NamespaceId = 1;<br/> /// <br/> This would translate into:<br/> /// ns=1;s=hello123 /// <br/></para> /// </remarks> public string Format() { StringBuilder buffer = new StringBuilder(); Format(buffer); return buffer.ToString(); } /// <summary> /// Formats the NodeId as a string and appends it to the buffer. /// </summary> public void Format(StringBuilder buffer) { Format(buffer, IdentifierPart, m_identifierType, m_namespaceIndex); } /// <summary> /// Formats the NodeId as a string and appends it to the buffer. /// </summary> public static void Format(StringBuilder buffer, object identifier, IdType identifierType, ushort namespaceIndex) { if (namespaceIndex != 0) buffer.AppendFormat(CultureInfo.InvariantCulture, "ns={0};", namespaceIndex); // add identifier type prefix. switch (identifierType) { case IdType.Numeric_0: buffer.Append("i="); break; case IdType.String_1: buffer.Append("s="); break; case IdType.Guid_2: buffer.Append("g="); break; case IdType.Opaque_3: buffer.Append("b="); break; } // add identifier. FormatIdentifier(buffer, identifier, identifierType); } #endregion Format() #endregion public #region IComparable /// <summary> /// Compares the current instance to the object. /// </summary> /// <remarks> /// Enables this object type to be compared to other types of object. /// </remarks> public int CompareTo(object obj) { // check for null. if (Object.ReferenceEquals(obj, null)) return -1; // check for reference comparisons. if (Object.ReferenceEquals(this, obj)) return 0; ushort namespaceIndex = this.m_namespaceIndex; IdType idType = this.m_identifierType; object id = null; // check for expanded node ids. NodeId nodeId = obj as NodeId; if (nodeId != null) { namespaceIndex = nodeId.NamespaceIndex; idType = nodeId.IdType; id = nodeId.IdentifierPart; } else { UInt32? uid = obj as UInt32?; // check for numeric contains. if (uid != null) { if (namespaceIndex != 0 || idType != IdType.Numeric_0) return -1; uint id1 = (uint)m_identifierPart; uint id2 = uid.Value; if (id1 == id2) return 0; return (id1 < id2) ? -1 : +1; } ExpandedNodeId expandedId = obj as ExpandedNodeId; if (!Object.ReferenceEquals(expandedId, null)) { if (expandedId.IsAbsolute) return -1; namespaceIndex = expandedId.NamespaceIndex; idType = expandedId.IdType; id = expandedId.IdentifierPart; } } // check for different namespace. if (namespaceIndex != m_namespaceIndex) return (m_namespaceIndex < namespaceIndex) ? -1 : +1; // check for different id type. if (idType != m_identifierType) return (m_identifierType < idType) ? -1 : +1; // check for two nulls. if (IdentifierPart == null && id == null) return 0; // check for a single null. if (IdentifierPart == null && id != null) { switch (idType) { case IdType.String_1: string stringId = id as string; if (stringId.Length == 0) return 0; break; case IdType.Opaque_3: byte[] opaqueId = id as byte[]; if (opaqueId.Length == 0) return 0; break; case IdType.Numeric_0: uint? numericId = id as uint?; if (numericId.Value == 0) return 0; break; } return -1; } else if (IdentifierPart != null && id == null) // check for a single null. { switch (idType) { case IdType.String_1: string stringId = IdentifierPart as string; if (stringId.Length == 0) return 0; break; case IdType.Opaque_3: byte[] opaqueId = IdentifierPart as byte[]; if (opaqueId.Length == 0) return 0; break; case IdType.Numeric_0: uint? numericId = IdentifierPart as uint?; if (numericId.Value == 0) return 0; break; } return +1; } // compare ids. switch (idType) { case IdType.Numeric_0: { uint id1 = (uint)IdentifierPart; uint id2 = (uint)id; if (id1 == id2) return 0; return (id1 < id2) ? -1 : +1; } case IdType.String_1: { string id1 = (string)IdentifierPart; string id2 = (string)id; return String.CompareOrdinal(id1, id2); } case IdType.Guid_2: { System.Guid id1 = (System.Guid)IdentifierPart; return id1.CompareTo(id); } case IdType.Opaque_3: { byte[] id1 = (byte[])IdentifierPart; byte[] id2 = (byte[])id; if (id1.Length == id2.Length) { for (int ii = 0; ii < id1.Length; ii++) if (id1[ii] != id2[ii]) return (id1[ii] < id2[ii]) ? -1 : +1; return 0; } return (id1.Length < id2.Length) ? -1 : +1; } } // invalid id type - should never get here. return +1; } #endregion IComparable #region IFormattable /// <summary> /// Returns the string representation of a NodeId. /// </summary> /// <remarks> /// Returns the string representation of a NodeId. This is the same as calling /// <see cref="Format()"/>. /// </remarks> /// <exception cref="FormatException">Thrown when the format is not null</exception> public string ToString(string format, IFormatProvider formatProvider) { if (format == null) return String.Format(formatProvider, "{0}", Format()); throw new FormatException(String.Format("Invalid format string: '{0}'.", format)); } #endregion IFormattable #region object /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { return m_HashCode; } /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns>A <see cref="System.String" /> that represents this instance.</returns> public override string ToString() { return Format(); } #endregion object #region private /// <summary> /// Formats a node id as a string. /// </summary> private static void FormatIdentifier(StringBuilder buffer, object identifier, IdType identifierType) { switch (identifierType) { case IdType.Numeric_0: if (identifier == null) { buffer.Append('0'); break; } buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", identifier); break; case IdType.String_1: buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", identifier); break; case IdType.Guid_2: if (identifier == null) { buffer.Append(System.Guid.Empty); break; } buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", identifier); break; case IdType.Opaque_3: if (identifier != null) buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", Convert.ToBase64String((byte[])identifier)); break; } } private ushort m_namespaceIndex; private IdType m_identifierType; private object m_identifierPart; private static NodeId s_Null = new NodeId(); private static int m_GlobalHashCode = 0; private int m_HashCode = m_GlobalHashCode; #endregion private #region IEquatable<NodeId> /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns> public bool Equals(NodeId other) { return this.CompareTo(other) == 0; } #endregion IEquatable<NodeId> } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/InformationModelFactoryUnitTest.cs<|end_filename|>  using Microsoft.VisualStudio.TestTools.UnitTesting; using UAOOI.SemanticData.InformationModelFactory; using UAOOI.SemanticData.UANodeSetValidation.InformationModelFactory; namespace UAOOI.SemanticData.UANodeSetValidation { [TestClass] public class InformationModelFactoryUnitTest { [ClassInitialize] public static void InformationModelFactoryClassInitialize(TestContext context) { m_FactoryBase = new InformationModelFactoryBase(); Assert.IsNotNull(m_FactoryBase); } [TestMethod] [TestCategory("Code")] public void InformationModelFactoryIExportReferenceTypeFactoryTestMethod() { IReferenceTypeFactory _new = m_FactoryBase.AddNodeFactory<IReferenceTypeFactory>(); Assert.IsNotNull(_new); } [TestMethod] [TestCategory("Code")] public void InformationModelFactoryIExportObjectTypeFactoryTestMethod2() { IObjectTypeFactory _new = m_FactoryBase.AddNodeFactory<IObjectTypeFactory>(); Assert.IsNotNull(_new); } [TestMethod] [TestCategory("Code")] public void InformationModelFactoryIExportVariableTypeFactoryTestMethod2() { IVariableTypeFactory _new = m_FactoryBase.AddNodeFactory<IVariableTypeFactory>(); Assert.IsNotNull(_new); } [TestMethod] [TestCategory("Code")] public void InformationModelIExportDataTypeFactoryFactoryTestMethod2() { IDataTypeFactory _new = m_FactoryBase.AddNodeFactory<IDataTypeFactory>(); Assert.IsNotNull(_new); } [TestMethod] [TestCategory("Code")] public void InformationModelFactoryIExportObjectInstanceFactoryTestMethod2() { IObjectInstanceFactory _new = m_FactoryBase.AddNodeFactory<IObjectInstanceFactory>(); Assert.IsNotNull(_new); } [TestMethod] [TestCategory("Code")] public void InformationModelFactoryIExportPropertyInstanceFactoryTestMethod2() { IPropertyInstanceFactory _new = m_FactoryBase.AddNodeFactory<IPropertyInstanceFactory>(); Assert.IsNotNull(_new); } [TestMethod] [TestCategory("Code")] public void InformationModelFactoryIExportVariableInstanceFactoryTestMethod2() { IVariableInstanceFactory _new = m_FactoryBase.AddNodeFactory<IVariableInstanceFactory>(); Assert.IsNotNull(_new); } [TestMethod] [TestCategory("Code")] public void InformationModelFactoryIExportMethodInstanceFactoryTestMethod2() { IMethodInstanceFactory _new = m_FactoryBase.AddNodeFactory<IMethodInstanceFactory>(); Assert.IsNotNull(_new); } [TestMethod] [TestCategory("Code")] public void InformationModelFactoryIExportViewInstanceFactoryTestMethod2() { IViewInstanceFactory _new = m_FactoryBase.AddNodeFactory<IViewInstanceFactory>(); Assert.IsNotNull(_new); } private static InformationModelFactoryBase m_FactoryBase = null; } } <|start_filename|>SemanticData/UANodeSetValidation/InformationModelFactory/NodesContainer.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using System.Collections.Generic; using UAOOI.SemanticData.InformationModelFactory; namespace UAOOI.SemanticData.UANodeSetValidation.InformationModelFactory { /// <summary> /// Class NodesContainer. /// Implements the <see cref="UAOOI.SemanticData.InformationModelFactory.INodeContainer" /> /// </summary> /// <seealso cref="UAOOI.SemanticData.InformationModelFactory.INodeContainer" /> internal abstract class NodesContainer : INodeContainer { /// <summary> /// Creates and adds a new node instance of the <see cref="T:UAOOI.SemanticData.InformationModelFactory.INodeFactory" />. /// </summary> /// <typeparam name="NodeFactory">The type of the node factory must inherit from <see cref="T:UAOOI.SemanticData.InformationModelFactory.INodeFactory" />.</typeparam> /// <returns>Returns new object implementing <see cref="T:UAOOI.SemanticData.InformationModelFactory.INodeFactory" />.</returns> /// <exception cref="NotImplementedException"></exception> public NodeFactory AddNodeFactory<NodeFactory>() where NodeFactory : INodeFactory { NodeFactoryBase _df = null; if (typeof(NodeFactory) == typeof(IReferenceTypeFactory)) _df = new ReferenceTypeFactoryBase(); else if (typeof(NodeFactory) == typeof(IObjectTypeFactory)) _df = new ObjectTypeFactoryBase(); else if (typeof(NodeFactory) == typeof(IVariableTypeFactory)) _df = new VariableTypeFactoryBase(); else if (typeof(NodeFactory) == typeof(IDataTypeFactory)) _df = new DataTypeFactoryBase(); else if (typeof(NodeFactory) == typeof(IObjectInstanceFactory)) _df = new ObjectInstanceFactoryBase(); else if (typeof(NodeFactory) == typeof(IPropertyInstanceFactory)) _df = new PropertyInstanceFactoryBase(); else if (typeof(NodeFactory) == typeof(IVariableInstanceFactory)) _df = new VariableInstanceFactoryBase(); else if (typeof(NodeFactory) == typeof(IMethodInstanceFactory)) _df = new MethodInstanceFactoryBase(); else if (typeof(NodeFactory) == typeof(IViewInstanceFactory)) _df = new ViewInstanceFactoryBase(); else throw new NotImplementedException(); m_Nodes.Add(_df); return (NodeFactory)(INodeFactory)_df; } protected List<NodeFactoryBase> m_Nodes = new List<NodeFactoryBase>(); } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/DataSerialization/QualifiedNameUnitTest.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2019, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UAOOI.SemanticData.UANodeSetValidation.DataSerialization { [TestClass] public class QualifiedNameUnitTest { [TestMethod] public void NotEqualOperatorTest() { QualifiedName _qualifiedName = null; Assert.IsFalse(_qualifiedName != null); _qualifiedName = new QualifiedName("name", 1); Assert.IsTrue(_qualifiedName != null); } [TestMethod] public void EqualOperatorTest() { QualifiedName _qualifiedName = null; Assert.IsTrue(_qualifiedName == null); _qualifiedName = new QualifiedName("name", 1); Assert.IsFalse(_qualifiedName == null); } [TestMethod] public void EqualsTest() { QualifiedName _qualifiedName = new QualifiedName("name", 1); Assert.IsTrue(_qualifiedName.NamespaceIndexSpecified); Assert.IsFalse(_qualifiedName.Equals(null)); Assert.IsTrue(_qualifiedName.Equals(_qualifiedName)); QualifiedName _qualifiedNameSecond = new QualifiedName("name", 1); Assert.IsTrue(_qualifiedName.Equals(_qualifiedNameSecond)); _qualifiedNameSecond = new QualifiedName("NAME", 1); Assert.IsFalse(_qualifiedName.Equals(_qualifiedNameSecond)); _qualifiedNameSecond = new QualifiedName("name", 0); Assert.IsFalse(_qualifiedName.Equals(_qualifiedNameSecond)); } [TestMethod] public void ToStringTest() { QualifiedName _qualifiedName = new QualifiedName("name", 1); Assert.AreEqual<string>($"1:name", _qualifiedName.ToString()); _qualifiedName = new QualifiedName("name"); Assert.AreEqual<string>("name", _qualifiedName.ToString()); _qualifiedName = new QualifiedName(); Assert.AreEqual<string>("", _qualifiedName.ToString()); } [TestMethod] public void QualifiedNameConstructorTest() { string name = "Default Binary"; QualifiedName _qn = new QualifiedName("Default Binary"); Assert.IsNotNull(_qn); //Assert.AreEqual<int>(_qn.NamespaceIndex, 0); Assert.IsFalse(_qn.NamespaceIndexSpecified); Assert.AreEqual<string>(_qn.Name, name); } [TestMethod] public void OperatorsTest() { QualifiedName _qn1 = new QualifiedName("Default Binary"); QualifiedName _qn2 = new QualifiedName("Default Binary"); Assert.IsTrue(_qn1 != null); Assert.IsTrue(null != _qn1); Assert.IsTrue(_qn1 == _qn2); Assert.IsTrue(_qn2 == _qn1); _qn2 = new QualifiedName("Something else"); Assert.IsTrue(_qn1 != _qn2); _qn2 = new QualifiedName("1:Default Binary"); Assert.IsTrue(_qn1 != _qn2); } [TestMethod] public void QualifiedNameParseTest() { QualifiedName _qn = QualifiedName.Parse("Name"); Assert.IsNotNull(_qn); Assert.AreEqual<int>(_qn.NamespaceIndex, 0); Assert.IsTrue(_qn.NamespaceIndexSpecified); Assert.AreEqual<string>(_qn.Name, "Name"); } [TestMethod] public void QualifiedNameParse0NamespaceIndexTest() { QualifiedName _qn = QualifiedName.Parse("0:Name"); Assert.IsNotNull(_qn); Assert.IsTrue(_qn.NamespaceIndexSpecified); Assert.AreEqual<int>(_qn.NamespaceIndex, 0); Assert.AreEqual<string>(_qn.Name, "Name"); } [TestMethod] public void QualifiedNameParseDefaultNamespaceTestMethod() { AssertQualifiedNameParse("0:http://opcfoundation.org/UA/", @"http://opcfoundation.org/UA/", 0); AssertQualifiedNameParse("Byte", "Byte", 0); AssertQualifiedNameParse("1:Default Binary", "Default Binary", 1); AssertQualifiedNameParse(":Default Binary", "Default Binary", 0); AssertQualifiedNameParse("1:Default Binary", "Default Binary", 1); AssertQualifiedNameParse("Default Binary", "Default Binary", 0); AssertQualifiedNameParse(" 1:Default Binary ", "Default Binary ", 1); AssertQualifiedNameParse(" Default Binary ", "Default Binary ", 0); AssertQualifiedNameParse(" Default Binary ", "Default Binary ", 0); AssertQualifiedNameParse(" 1:<Default Binary>", "<Default Binary>", 1); AssertQualifiedNameParse(" 1:[Default Binary]", "[Default Binary]", 1); AssertQualifiedNameParse(" 1:{Default Binary}", "{Default Binary}", 1); AssertQualifiedNameParse(" 1:Default Binary {n}", "Default Binary {n}", 1); } private void AssertQualifiedNameParse(string text, string expectedName, ushort expectedNamespaceIndex) { QualifiedName newQualifiedName = QualifiedName.Parse(text); Assert.IsNotNull(newQualifiedName); Assert.IsTrue(newQualifiedName.NamespaceIndexSpecified); Assert.AreEqual<int>(expectedNamespaceIndex, newQualifiedName.NamespaceIndex); Assert.AreEqual<string>(expectedName, newQualifiedName.Name); } } } <|start_filename|>Common/Tests/InfrastructureUnitTest/TraceSourceBaseUnitTest.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using UAOOI.Common.Infrastructure.Diagnostic; using UAOOI.Common.Infrastructure.UnitTest.Instrumentation; namespace UAOOI.Common.Infrastructure.UnitTest { [TestClass] public class TraceSourceBaseUnitTest { [TestMethod] public void ConstructorStateTestMethod() { TraceSourceBase _trace = new TraceSourceBase(); _trace.TraceData(TraceEventType.Critical, 0, "Message"); } [TestMethod] public void AssemblyTraceEventTestMethod() { TraceSourceBase _tracer = new TraceSourceBase(); Assert.AreEqual<string>("UAOOI.Common", _tracer.TraceSource.Name, $"Actual tracer name: {_tracer.TraceSource.Name}"); Assert.AreEqual(1, _tracer.TraceSource.Listeners.Count); Dictionary<string, TraceListener> _listeners = _tracer.TraceSource.Listeners.Cast<TraceListener>().ToDictionary<TraceListener, string>(x => x.Name); Assert.IsTrue(_listeners.ContainsKey("LogFile")); TraceListener _listener = _listeners["LogFile"]; Assert.IsNotNull(_listener); Assert.IsInstanceOfType(_listener, typeof(DelimitedListTraceListener)); DelimitedListTraceListener _advancedListener = _listener as DelimitedListTraceListener; Assert.IsNotNull(_advancedListener.Filter); Assert.IsInstanceOfType(_advancedListener.Filter, typeof(EventTypeFilter)); EventTypeFilter _eventTypeFilter = _advancedListener.Filter as EventTypeFilter; Assert.AreEqual(SourceLevels.All, _eventTypeFilter.EventType); string _testPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Assert.AreEqual<string>(Path.Combine(_testPath, @"UAOOI.Common.log"), _advancedListener.GetFileName()); } [TestMethod] public void LogFileExistsTest() { TraceSourceBase _tracer = new TraceSourceBase(); TraceListener _listener = _tracer.TraceSource.Listeners.Cast<TraceListener>().Where<TraceListener>(x => x.Name == "LogFile").First<TraceListener>(); Assert.IsNotNull(_listener); DelimitedListTraceListener _advancedListener = _listener as DelimitedListTraceListener; Assert.IsNotNull(_advancedListener); Assert.IsFalse(string.IsNullOrEmpty(_advancedListener.GetFileName())); FileInfo _logFileInfo = new FileInfo(_advancedListener.GetFileName()); long _startLength = _logFileInfo.Exists ? _logFileInfo.Length : 0; _tracer.TraceSource.TraceEvent(TraceEventType.Information, 0, "LogFileExistsTest is executed"); Assert.IsFalse(string.IsNullOrEmpty(_advancedListener.GetFileName())); _logFileInfo.Refresh(); Assert.IsTrue(_logFileInfo.Exists); Assert.IsTrue(_logFileInfo.Length > _startLength); } } } <|start_filename|>Networking/Simulator.Boiler/SimulatorDataManagementSetup.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2020, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using CommonServiceLocator; using System; using System.ComponentModel.Composition; using System.Diagnostics; using UAOOI.Networking.Core; using UAOOI.Networking.ReferenceApplication.Core; using UAOOI.Networking.ReferenceApplication.Core.Diagnostic; using UAOOI.Networking.SemanticData; namespace UAOOI.Networking.Simulator.Boiler { /// <summary> /// Class SimulatorDataManagementSetup represents a data producer in the Reference Application. It is responsible to compose all parts making up a producer. /// This class cannot be inherited. /// Implements the <see cref="DataManagementSetup" /> /// Implements the <see cref="IDataRepositoryStartup" /> /// Implements the <see cref="IDataRepositoryStartup" /> /// </summary> /// <seealso cref="IDataRepositoryStartup" /> /// <seealso cref="DataManagementSetup" /> [Export(typeof(IDataRepositoryStartup))] [PartCreationPolicy(CreationPolicy.Shared)] public sealed class SimulatorDataManagementSetup : DataManagementSetup, IDataRepositoryStartup { #region Composition /// <summary> /// Initializes a new instance of the <see cref="SimulatorDataManagementSetup"/> class. /// </summary> public SimulatorDataManagementSetup() { IServiceLocator _serviceLocator = ServiceLocator.Current; string _configurationFileName = _serviceLocator.GetInstance<string>(CompositionSettings.ConfigurationFileNameContract); m_ViewModel = _serviceLocator.GetInstance<ProducerViewModel>(); ConfigurationFactory = new ProducerConfigurationFactory(_configurationFileName); EncodingFactory = _serviceLocator.GetInstance<IEncodingFactory>(); BindingFactory = m_DataGenerator = new DataGenerator(); MessageHandlerFactory = _serviceLocator.GetInstance<IMessageHandlerFactory>(); } #endregion Composition #region IProducerDataManagementSetup /// <summary> /// Setups this instance. /// </summary> public void Setup() { try { ReferenceApplicationEventSource.Log.Initialization($"{nameof(SimulatorDataManagementSetup)}.{nameof(Setup)} starting"); m_ViewModel.ChangeProducerCommand(() => { m_ViewModel.ProducerErrorMessage = "Restarted"; }); Start(); m_ViewModel.ProducerErrorMessage = "Running"; ReferenceApplicationEventSource.Log.Initialization($" Setup of the producer engine has been accomplished and it starts sending data."); } catch (Exception _ex) { ReferenceApplicationEventSource.Log.LogException(_ex); m_ViewModel.ProducerErrorMessage = "ERROR"; throw; } } #endregion IProducerDataManagementSetup #region IDisposable /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { m_onDispose(disposing); base.Dispose(disposing); if (!disposing || m_disposed) return; m_disposed = true; m_DataGenerator.Dispose(); } #endregion IDisposable #region private /// <summary> /// Gets or sets the view model to be used for diagnostic purpose.. /// </summary> /// <value>The view model.</value> private ProducerViewModel m_ViewModel; private DataGenerator m_DataGenerator = null; /// <summary> /// Gets a value indicating whether this <see cref="LoggerManagementSetup"/> is disposed. /// </summary> /// <value><c>true</c> if disposed; otherwise, <c>false</c>.</value> private bool m_disposed = false; private Action<bool> m_onDispose = disposing => { }; #endregion private #region Unit tests instrumentation [Conditional("DEBUG")] internal void DisposeCheck(Action<bool> onDispose) { m_onDispose = onDispose; } #endregion Unit tests instrumentation } } <|start_filename|>DataDiscovery/DiscoveryServices/DataDiscoveryServices.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System; using System.Diagnostics; using System.IO; using System.Net.Http; using System.Threading.Tasks; using System.Xml.Serialization; using UAOOI.DataDiscovery.DiscoveryServices.Models; namespace UAOOI.DataDiscovery.DiscoveryServices { /// <summary> /// Class DataDiscoveryServices - provides functionality supporting Global Data Discovery resolution. /// </summary> public class DataDiscoveryServices : IDisposable { #region public API /// <summary> /// Resolves address and reads the <see cref="DomainModel"/> record as an asynchronous operation. /// </summary> /// <param name="modelUri">The model URI.</param> /// <param name="rootZoneUrl">The root zone URL where the resolving process shall start.</param> /// <param name="log"><see cref="Action{T1, T2, T3}"/> encapsulating tracing functionality .</param> /// <returns>Task{DomainModel}.</returns> /// <exception cref="InvalidOperationException">Too many iteration in the resolving process.</exception> public async Task<DomainModel> ResolveDomainModelAsync(Uri modelUri, Uri rootZoneUrl, Action<string, TraceEventType, Priority> log) { log($"Starting resolving address of the domain model descriptor for the model Uri {modelUri}", TraceEventType.Verbose, Priority.Low); DomainDescriptor lastDomainDescriptor = new DomainDescriptor() { NextStepRecordType = RecordType.DomainDescriptor }; Uri nextUri = rootZoneUrl; int iteration = 0; do { iteration++; log($"Resolving address iteration {iteration} address: {nextUri}", TraceEventType.Verbose, Priority.Low); if (iteration > 16) throw new InvalidOperationException("Too many iteration in the resolving process."); lastDomainDescriptor = await GetHTTPResponseAsync<DomainDescriptor>(nextUri, log); nextUri = lastDomainDescriptor.ResolveUri(modelUri); } while (lastDomainDescriptor.NextStepRecordType == RecordType.DomainDescriptor); log($"Reading DomainModel at: {nextUri}", TraceEventType.Verbose, Priority.Low); Task<DomainModel> _DomainModelTask = GetHTTPResponseAsync<DomainModel>(nextUri, log); DomainModel _model = await _DomainModelTask; _model.UniversalDiscoveryServiceLocator = nextUri.ToString(); log($"Successfully received and decoded the requested DomainModel record: {nextUri}", TraceEventType.Verbose, Priority.Low); return _model; } #endregion public API #region IDisposable Support private bool disposedValue = false; // To detect redundant calls private HttpClient m_Client = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue }; /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) m_Client.Dispose(); m_Client = null; disposedValue = true; } } // This code added to correctly implement the disposable pattern. /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); } #endregion IDisposable Support #region private /// <summary> /// Resolve domain description as an asynchronous operation. /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="address">The address of the discovery service.</param> /// <param name="log">Encapsulates the log operation.</param> /// <returns>Task{TResult}</returns> private async Task<TResult> GetHTTPResponseAsync<TResult>(Uri address, Action<string, TraceEventType, Priority> log) where TResult : class, new() { m_Client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); //_client.DefaultRequestHeaders.Accept.Clear(); //_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("opc/application/json")); int _retryCount = 0; do { try { using (HttpResponseMessage message = await m_Client.GetAsync(address)) { message.EnsureSuccessStatusCode(); using (Task<Stream> descriptionStream = message.Content.ReadAsStreamAsync()) { XmlSerializer serializer = new XmlSerializer(typeof(TResult)); Stream _description = await descriptionStream; TResult _newDescription = (TResult)serializer.Deserialize(_description); return _newDescription; } }; } catch (Exception _ex) { log($"Error for {address} in {nameof(GetHTTPResponseAsync)} retry ={_retryCount}: {_ex.Message} ", TraceEventType.Error, Priority.Medium); if (_retryCount < 3) _retryCount++; else throw; } } while (true); } //UnitTest instrumentation [Conditional("DEBUG")] internal void GetHTTPResponse<T>(Uri address, Action<string, TraceEventType, Priority> debugLog, Action<T> getResult) where T : class, new() { Task<T> _task = GetHTTPResponseAsync<T>(address, debugLog); _task.Wait(); getResult(_task.Result); } #endregion private } } <|start_filename|>SemanticData/SolutionConfiguration/Serialization/UAModelDesignerSolution.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System; using System.IO; using System.Runtime.Serialization; namespace UAOOI.SemanticData.SolutionConfiguration.Serialization { /// <summary> /// Class UAModelDesignerSolution. /// </summary> public partial class UAModelDesignerSolution { /// <summary> /// Creates an empty solution model. /// </summary> /// <returns>UAModelDesignerSolution.</returns> internal static UAModelDesignerSolution CreateEmptyModel(string solutionName) { return new UAModelDesignerSolution() { Name = solutionName, Projects = new UAModelDesignerProject[] { }, ServerDetails = UAModelDesignerSolutionServerDetails.CreateEmptyInstance() }; } [OnDeserialized()] public void OnDeserialized(StreamingContext context) { ServerDetails = ServerDetails ?? UAModelDesignerSolutionServerDetails.CreateEmptyInstance(); } } /// <summary> /// Class UAModelDesignerSolutionServerDetails - encapsulates details about the associated server configuration /// </summary> public partial class UAModelDesignerSolutionServerDetails { internal static UAModelDesignerSolutionServerDetails CreateEmptyInstance() { return new UAModelDesignerSolutionServerDetails() { codebase = string.Empty, configuration = string.Empty }; } } internal enum ResourceEntries { Token_ProjectFileName, DefaultCSVFileName, Project_FileDialogDefaultExt }; public partial class UAModelDesignerProject { internal static UAModelDesignerProject CreateEmpty(string name, Func<ResourceEntries, string> resource) { return new UAModelDesignerProject() { buildOutputDirectoryNameField = resource(ResourceEntries.Token_ProjectFileName), cSVFileNameField = resource(ResourceEntries.DefaultCSVFileName), fileNameField = Path.ChangeExtension(resource(ResourceEntries.Token_ProjectFileName), resource(ResourceEntries.Project_FileDialogDefaultExt)), nameField = name, ProjectIdentifier = Guid.NewGuid().ToString(), }; } } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/ModelFactoryTestingFixture/ObjectTypeFactoryBase.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using UAOOI.SemanticData.InformationModelFactory; namespace UAOOI.SemanticData.UANodeSetValidation.ModelFactoryTestingFixture { /// <summary> /// Class ObjectTypeFactoryBase. /// Implements the <see cref="UAOOI.SemanticData.UANodeSetValidation.InformationModelFactory.TypeFactoryBase" /> /// Implements the <see cref="UAOOI.SemanticData.InformationModelFactory.IObjectTypeFactory" /> /// </summary> /// <seealso cref="UAOOI.SemanticData.UANodeSetValidation.InformationModelFactory.TypeFactoryBase" /> /// <seealso cref="UAOOI.SemanticData.InformationModelFactory.IObjectTypeFactory" /> internal class ObjectTypeFactoryBase : TypeFactoryBase, IObjectTypeFactory { } } <|start_filename|>SemanticData/UAModelDesignExport/Diagnostic/AssemblyTraceSource.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System.Diagnostics; using UAOOI.Common.Infrastructure.Diagnostic; using UAOOI.SemanticData.BuildingErrorsHandling; namespace UAOOI.SemanticData.UAModelDesignExport.Diagnostic { /// <summary> /// Class AssemblyTraceSource. Implements the <see cref="ITraceSource" /> /// </summary> /// <seealso cref="ITraceSource" /> internal class AssemblyTraceSource : ITraceSource { /// <summary> /// Initializes a new instance of the <see cref="AssemblyTraceSource"/> class using the default of the <see cref="ITraceSource"/>. /// </summary> internal AssemblyTraceSource() { traceSource = new TraceSourceBase("UAModelDesignExport"); } /// <summary> /// Initializes a new instance of the <see cref="AssemblyTraceSource"/> class using a provided implementation of the <see cref="ITraceSource"/>. /// </summary> /// <param name="traceEvent">The provided implementation of the <see cref="ITraceSource"/>.</param> internal AssemblyTraceSource(ITraceSource traceEvent) { traceSource = traceEvent; } /// <summary> /// Writes the trace message. /// </summary> /// <param name="traceMessage">The trace message.</param> internal void WriteTraceMessage(TraceMessage traceMessage) { traceSource.TraceData(traceMessage.TraceLevel, 39445735, traceMessage.ToString()); } #region ITraceSource /// <summary> /// Writes trace data to the trace listeners in the <see cref="P:System.Diagnostics.TraceSource.Listeners" /> collection using the specified <paramref name="eventType" />, /// event identifier <paramref name="id" />, and trace <paramref name="data" />. /// </summary> /// <param name="eventType">One of the enumeration values that specifies the event type of the trace data.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="data">The trace data.</param> public void TraceData(TraceEventType eventType, int id, object data) { traceSource.TraceData(eventType, id, data); } #endregion ITraceSource private readonly ITraceSource traceSource; } } <|start_filename|>Common/Infrastructure/Serializers/XmlFile.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System; using System.IO; using System.Linq; using System.Xml; using System.Xml.Serialization; namespace UAOOI.Common.Infrastructure.Serializers { /// <summary> /// Provides static methods for serialization objects into XML documents and writing the XML document to a file. /// </summary> public static class XmlFile { #region public /// <summary> /// Serializes the specified <paramref name="dataObject"/> and writes the XML document to a file. /// </summary> /// <typeparam name="type">The type of the root object to be serialized and saved in the file.</typeparam> /// <param name="dataObject">The object containing working data to be serialized and saved in the file.</param> /// <param name="path">A relative or absolute path for the file containing the serialized object.</param> /// <param name="mode">Specifies how the operating system should open a file <see cref="FileMode"/>.</param> /// <param name="stylesheetName">Name of the stylesheet document.</param> /// <exception cref="System.ArgumentNullException"> /// path /// or /// dataObject /// or /// stylesheetName /// </exception> public static void WriteXmlFile<type>(type dataObject, string path, FileMode mode, string stylesheetName) where type : INamespaces { if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); if (dataObject == null) throw new ArgumentNullException(nameof(dataObject)); XmlSerializer _xmlSerializer = new XmlSerializer(typeof(type)); XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(dataObject.GetNamespaces().ToArray<XmlQualifiedName>()); XmlWriterSettings _setting = new XmlWriterSettings() { Indent = true, IndentChars = " ", NewLineChars = "\r\n" }; using (FileStream _docStream = new FileStream(path, mode, FileAccess.Write)) { XmlWriter _writer = XmlWriter.Create(_docStream, _setting); if (!string.IsNullOrEmpty(stylesheetName)) _writer.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" " + string.Format("href=\"{0}\"", stylesheetName)); _xmlSerializer.Serialize(_writer, dataObject, namespaces); } } /// <summary> /// Serializes the specified <paramref name="dataObject"/> and writes the XML document to a file. /// </summary> /// <typeparam name="type">The type of the object to be serialized and saved in the file.</typeparam> /// <param name="dataObject">The object containing working data to be serialized and saved in the file.</param> /// <param name="path">A relative or absolute path for the file containing the serialized object.</param> /// <param name="mode">Specifies how the operating system should open a file.</param> public static void WriteXmlFile<type>(type dataObject, string path, FileMode mode) where type : IStylesheetNameProvider, INamespaces { WriteXmlFile(dataObject, path, mode, dataObject.StylesheetName); } /// <summary> /// Reads an XML document from the file <paramref name="path"/> and deserializes its content to returned object. /// </summary> /// <typeparam name="type">The type of the object to be deserialized.</typeparam> /// <param name="path">A relative or absolute path for the file containing the serialized object.</param> /// <returns>An object containing working data retrieved from an XML file.</returns> /// <exception cref="ArgumentNullException"> path is null or empty</exception> public static type ReadXmlFile<type>(string path) { if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); using (FileStream _docStream = new FileStream(path, FileMode.Open)) return ReadXmlFile<type>(_docStream); } /// <summary> /// Reads an XML document from the <paramref name="reader"/> and deserializes its content to returned object. /// </summary> /// <typeparam name="type">The type of the object to be deserialized.</typeparam> /// <param name="reader">The source of the stream to be deserialized.</param> /// <returns>An object of type <typeparamref name="type"/> containing working data retrieved from an XML stream..</returns> public static type ReadXmlFile<type>(Stream reader) { type _content = default(type); XmlSerializer _xmlSerializer = new XmlSerializer(typeof(type)); using (XmlReader xmlReader = XmlReader.Create(reader)) _content = (type)_xmlSerializer.Deserialize(xmlReader); return _content; } #endregion public } } <|start_filename|>SemanticData/Tests/AddressSpaceComplianceTestToolUnitTests/Instrumentation/Extensions.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Diagnostics; using System.Reflection; namespace UAOOI.SemanticData.AddressSpacePrototyping.Instrumentation { /// <summary> /// Class Extensions to get access to non public field of the <see cref="DelimitedListTraceListener"/> /// </summary> internal static class Extensions { internal static string GetFileName(this DelimitedListTraceListener _listener) { FieldInfo fi = typeof(TextWriterTraceListener).GetField("fileName", BindingFlags.NonPublic | BindingFlags.Instance); Assert.IsNotNull(fi); return (string)fi.GetValue(_listener); } } } <|start_filename|>SemanticData/UAModelDesignExport/XML/UA Model Design.xsd.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System.Collections.Generic; using System.Xml; using UAOOI.Common.Infrastructure.Serializers; namespace UAOOI.SemanticData.UAModelDesignExport.XML { public partial class ModelDesign : INamespaces { /// <summary> /// Gets the namespaces that is to be used to parametrize XML document. /// </summary> /// <returns>An instance of IEnumerable[XmlQualifiedName] containing the XML namespaces and prefixes that a serializer uses to generate qualified names in an XML-document instance.</returns> public IEnumerable<XmlQualifiedName> GetNamespaces() { List<XmlQualifiedName> ret = new List<XmlQualifiedName> { new XmlQualifiedName("xsd", "http://www.w3.org/2001/XMLSchema"), new XmlQualifiedName("xsi", "http://www.w3.org/2001/XMLSchema-instance"), new XmlQualifiedName("uax", "http://opcfoundation.org/UA/2008/02/Types.xsd") }; foreach (Namespace item in Namespaces) ret.Add(new XmlQualifiedName(item.XmlPrefix, item.Value)); return ret; } } } <|start_filename|>SemanticData/UAModelDesignExport/ModelDesignExport.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System; using System.Diagnostics; using System.IO; using UAOOI.Common.Infrastructure.Diagnostic; using UAOOI.Common.Infrastructure.Serializers; using UAOOI.SemanticData.InformationModelFactory; using UAOOI.SemanticData.UAModelDesignExport.Diagnostic; namespace UAOOI.SemanticData.UAModelDesignExport { /// <summary> /// Class ModelDesignExport - captures functionality supporting export functionality of the OPC UA Information Model represented by an XML file compliant with UA Model Design. /// </summary> public abstract class ModelDesignExportAPI { #region factory /// <summary> /// Gets the model design export. /// </summary> /// <returns>An instance capturing model design export implemented using the <see cref="IModelDesignExport"/> interface.</returns> public static IModelDesignExport GetModelDesignExport() { return new ModelDesignExport(); } internal static IModelDesignExport GetModelDesignExport(ITraceSource traceSource) { return new ModelDesignExport(traceSource); } #endregion factory private class ModelDesignExport : IModelDesignExport { #region IModelDesignExport /// <summary> /// Gets the factory. /// </summary> /// <returns>An instance of the <see cref="IModelFactory"/> to be used to generate the OPC UA Information Model captured as the <see cref="XML.ModelDesign"/>.</returns> public IModelFactory GetFactory() { m_Model = new ModelFactory(m_traceEvent.WriteTraceMessage); return m_Model; } /// <summary> /// Serializes the already generated model using the interface <see cref="IModelFactory"/> and writes the XML document to a file. /// </summary> /// <param name="outputFilePtah">A relative or absolute path for the file containing the serialized object.</param> public void ExportToXMLFile(string outputFilePtah) { ExportToXMLFile(outputFilePtah, string.Empty); } /// <summary> /// Serializes the already generated model using the interface <see cref="IModelFactory"/> and writes the XML document to a file. /// </summary> /// <param name="outputFilePtah">A relative or absolute path for the file containing the serialized object.</param> /// <param name="stylesheetName">Name of the stylesheet document.</param> public void ExportToXMLFile(string outputFilePtah, string stylesheetName) { if (m_Model == null) throw new ArgumentNullException("UAModelDesign", "The model must be generated first."); if (string.IsNullOrEmpty(outputFilePtah)) throw new ArgumentNullException(nameof(outputFilePtah), $"{nameof(outputFilePtah)} must be a valid file path."); XML.ModelDesign _model = m_Model.Export(); XmlFile.WriteXmlFile<XML.ModelDesign>(_model, outputFilePtah, FileMode.Create, stylesheetName); m_traceEvent.TraceData(TraceEventType.Information, 279330276, $"The ModelDesign XML has been saved to file {outputFilePtah} and decorated with the stylesheet {stylesheetName}"); } /// <summary> /// Convert the UA Information Model to graph of objects /// </summary> /// <returns>Returns an instance of the type <see cref="XML.ModelDesign"/>.</returns> public XML.ModelDesign ExportToObject() { m_traceEvent.TraceData(TraceEventType.Information, 52892026, $"The ModelDesign a graph of objects is exporting"); return m_Model.Export(); } #endregion IModelDesignExport #region private private ModelFactory m_Model = null; private readonly AssemblyTraceSource m_traceEvent; internal ModelDesignExport(ITraceSource traceEvent) { m_traceEvent = new AssemblyTraceSource(traceEvent); } internal ModelDesignExport() { m_traceEvent = new AssemblyTraceSource(); } #endregion private } } } <|start_filename|>SemanticData/UANodeSetValidation/DataSerialization/Extensions.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using UAOOI.SemanticData.BuildingErrorsHandling; namespace UAOOI.SemanticData.UANodeSetValidation.DataSerialization { /// <summary> /// Class Extensions - contains helper functions to parse values of built-in data types. /// </summary> internal static class Extensions { internal static QualifiedName ParseBrowseName(this string qualifiedName, NodeId nodeId, Action<TraceMessage> traceEvent) { if ((nodeId == null) || nodeId == NodeId.Null) throw new ArgumentNullException(nameof(NodeId)); QualifiedName qualifiedNameToReturn = null; if (string.IsNullOrEmpty(qualifiedName)) { qualifiedNameToReturn = nodeId.RandomQualifiedName(); traceEvent(TraceMessage.BuildErrorTraceMessage(BuildError.EmptyBrowseName, $"new identifier {qualifiedNameToReturn.ToString()} is generated to proceed.")); } else try { qualifiedNameToReturn = QualifiedName.Parse(qualifiedName); } catch (Exception ex) { qualifiedNameToReturn = nodeId.RandomQualifiedName(); traceEvent(TraceMessage.BuildErrorTraceMessage(BuildError.QualifiedNameInvalidSyntax, $"Error message: {ex.Message} - new identifier {qualifiedNameToReturn.ToString()} is generated to proceed.")); } return qualifiedNameToReturn; } //Enhance/Improve NodeId parser #541 rewrite and add to UT /// <summary> /// Parses the node identifier with the syntax defined in Part 3-8.2 and Part 6-5.3.1.10 /// </summary> /// <param name="nodeId">The node identifier.</param> /// <param name="traceEvent">The trace event.</param> /// <returns>NodeId.</returns> internal static NodeId ParseNodeId(this string nodeId, Action<TraceMessage> traceEvent) { NodeId nodeId2Return = null; try { nodeId2Return = NodeId.Parse(nodeId); } catch (ServiceResultException se) { traceEvent(se.TraceMessage); } if (nodeId2Return == null) { nodeId2Return = new NodeId(System.Guid.NewGuid()); traceEvent(TraceMessage.DiagnosticTraceMessage($"Generated random NodeId = {nodeId2Return.ToString()}")); } return nodeId2Return; } /// <summary> /// Gets the <see cref="NodeId.IdentifierPart" /> as uint number. /// </summary> /// <param name="nodeId">The node identifier.</param> /// <returns>Returns <see cref="NodeId.IdentifierPart" /> as the System.UInt32.</returns> /// <exception cref="System.ArgumentNullException">NodeId must not be null</exception> /// <exception cref="System.ApplicationException">To get the identifier as uint the NodeId must be Numeric</exception> internal static uint? UintIdentifier(this NodeId nodeId) { if (nodeId == null || nodeId.IdType != IdType.Numeric_0) return new Nullable<uint>(); return (uint)nodeId.IdentifierPart; } /// <summary> /// Gets the supports events. /// </summary> /// <param name="eventNotifier">The event notifier. The EventNotifier represents the mandatory EventNotifier attribute of the Object NodeClass and identifies whether /// the object can be used to subscribe to events or to read and write the history of the events.</param> /// <param name="traceEvent">The trace event.</param> /// <returns><c>true</c> if supports events, <c>false</c> otherwise.</returns> internal static bool? GetSupportsEvents(this byte eventNotifier, Action<TraceMessage> traceEvent) { if (eventNotifier > EventNotifiers.SubscribeToEvents + EventNotifiers.HistoryRead + EventNotifiers.HistoryWrite) traceEvent(TraceMessage.BuildErrorTraceMessage(BuildError.WrongEventNotifier, String.Format("EventNotifier value: {0}", eventNotifier))); else if (eventNotifier > EventNotifiers.SubscribeToEvents) traceEvent(TraceMessage.BuildErrorTraceMessage(BuildError.EventNotifierValueNotSupported, String.Format("EventNotifier value: {0}", eventNotifier))); return eventNotifier != 0 ? (eventNotifier & EventNotifiers.SubscribeToEvents) != 0 : new Nullable<bool>(); } internal static uint? GetAccessLevel(this uint accessLevel, Action<TraceMessage> traceEvent) { uint? _ret = new Nullable<byte>(); if (accessLevel <= 0x7F) _ret = accessLevel; else traceEvent(TraceMessage.BuildErrorTraceMessage(BuildError.WrongAccessLevel, String.Format("The AccessLevel value {0:X} is not supported", accessLevel))); return _ret; } /// <summary> /// Gets the value rank. /// </summary> /// <param name="valueRank">The value rank.</param> /// <param name="traceEvent">An <see cref="Action" /> delegate is used to trace event as the <see cref="TraceMessage" />.</param> /// <returns>Returns validated value.</returns> internal static int? GetValueRank(this int valueRank, Action<TraceMessage> traceEvent) { int? _vr = new Nullable<int>(); if (valueRank < -2) traceEvent(TraceMessage.BuildErrorTraceMessage(BuildError.WrongValueRank, String.Format("The value {0} is not supported", valueRank))); else if (valueRank == -3) traceEvent(TraceMessage.BuildErrorTraceMessage(BuildError.WrongValueRank, String.Format("The value {0} is not supported", valueRank))); else if (valueRank != -1) _vr = valueRank; return _vr; } #region private private static QualifiedName RandomQualifiedName(this NodeId nodeId) { return new QualifiedName() { Name = $"EmptyBrowseName_{nodeId.IdentifierPart.ToString()}_{ _RandomNumber.Next(-9999, 0)}", NamespaceIndex = nodeId.NamespaceIndex, NamespaceIndexSpecified = true, }; } private static Random _RandomNumber = new Random(); #endregion private } } <|start_filename|>SemanticData/Tests/AddressSpaceComplianceTestToolUnitTests/CommandLineSyntaxUnitTest.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2019, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using CommandLine; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Linq; using UAOOI.SemanticData.AddressSpacePrototyping.CommandLineSyntax; namespace UAOOI.SemanticData.AddressSpaceTestTool.UnitTests { [TestClass] public class CommandLineSyntaxUnitTest { [TestMethod] public void EmptyLineTest() { string[] emptyLine = new string[] {"" }; Options options = null; List<Error> errors = null; int doCount = 0; emptyLine.Parse<Options>(x => { options = x; doCount++; }, y => errors = y.ToList<Error>()); Assert.IsNull(options); Assert.IsNotNull(errors); Assert.AreEqual<int>(1, errors.Count<Error>()); Assert.AreEqual<string>("CommandLine.MissingRequiredOptionError", errors[0].ToString()); Assert.AreEqual<ErrorType>(ErrorType.MissingRequiredOptionError, errors[0].Tag); Assert.AreEqual<int>(0, doCount); } [TestMethod] public void FilenamesTest() { string[] _emptyLine = new string[] { "AssemblyInfo.cs", "myproject.csproj", "-n", "http://a.b.c" }; Options _return = null; IEnumerable<Error> _errors = null; _emptyLine.Parse<Options>(x => _return = x, y => _errors = y); Assert.IsNotNull(_return); Assert.IsNull(_errors); Assert.IsNotNull(_return.Filenames); Assert.AreEqual<int>(2, _return.Filenames.Count()); string[] _files = _return.Filenames.ToArray<string>(); Assert.AreEqual<string>("AssemblyInfo.cs", _files[0]); Assert.AreEqual<string>("myproject.csproj", _files[1]); } [TestMethod] public void AllLongSwitchesTest() { string[] _emptyLine = new string[] { "App_Data/cachefile.json", "App_Data/cachefile2.json", "--namespace=XSLTName", "--export=ModelDesign.xml", "--stylesheet=XMLstylesheet", "--nologo" }; Options _return = null; IEnumerable<Error> _errors = null; _emptyLine.Parse<Options>(x => _return = x, y => _errors = y); Assert.IsNotNull(_return); Assert.IsNull(_errors); Assert.IsNotNull(_return.Filenames); Assert.AreEqual<int>(2, _return.Filenames.Count()); string[] _files = _return.Filenames.ToArray<string>(); Assert.AreEqual<string>("App_Data/cachefile.json", _files[0]); Assert.AreEqual<string>("App_Data/cachefile2.json", _files[1]); Assert.AreEqual<string>("XSLTName", _return.IMNamespace); Assert.AreEqual<string>("ModelDesign.xml", _return.ModelDesignFileName); Assert.IsTrue(_return.NoLogo); Assert.AreEqual<string>("XMLstylesheet", _return.Stylesheet); } [TestMethod] public void AllShortSwitchesTest() { string[] _emptyLine = new string[] { "App_Data/cachefile.json", "App_Data/cachefile2.json", "-n", "http://a.b.c", "-e", "ModelDesign.xml", "-s", "XMLstylesheet", "--nologo" }; Options _return = null; IEnumerable<Error> _errors = null; _emptyLine.Parse<Options>(x => _return = x, y => _errors = y); Assert.IsNotNull(_return); Assert.IsNull(_errors); Assert.IsNotNull(_return.Filenames); Assert.AreEqual<int>(2, _return.Filenames.Count()); string[] _files = _return.Filenames.ToArray<string>(); Assert.AreEqual<string>("App_Data/cachefile.json", _files[0]); Assert.AreEqual<string>("App_Data/cachefile2.json", _files[1]); Assert.AreEqual<string>("http://a.b.c", _return.IMNamespace); Assert.AreEqual<string>("ModelDesign.xml", _return.ModelDesignFileName); Assert.IsTrue(_return.NoLogo); Assert.AreEqual<string>("XMLstylesheet", _return.Stylesheet); } } } <|start_filename|>SemanticData/UANodeSetValidation/XML/UAVariableType.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System; using UAOOI.SemanticData.BuildingErrorsHandling; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.SemanticData.UANodeSetValidation.XML { public partial class UAVariableType { /// <summary> /// Get the clone from the types derived from this one. /// </summary> /// <returns>An instance of <see cref="T:UAOOI.SemanticData.UANodeSetValidation.XML.UANode" />.</returns> protected override UANode ParentClone() { UAVariableType _ret = new UAVariableType() { Value = this.Value, DataType = this.DataType, ValueRank = this.ValueRank, ArrayDimensions = this.ArrayDimensions }; base.CloneUAType(_ret); return _ret; } /// <summary> /// Recalculates the node identifiers. /// </summary> /// <param name="modelContext">The model context.</param> /// <param name="trace">The trace.</param> internal override void RecalculateNodeIds(IUAModelContext modelContext, Action<TraceMessage> trace) { base.RecalculateNodeIds(modelContext, trace); DataTypeNodeId = modelContext.ImportNodeId(DataType, trace); } internal NodeId DataTypeNodeId { get; private set; } } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/ModelFactoryTestingFixture/DataTypeFactoryBase.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using UAOOI.SemanticData.InformationModelFactory; namespace UAOOI.SemanticData.UANodeSetValidation.ModelFactoryTestingFixture { /// <summary> /// Class DataTypeFactoryBase. /// Implements the <see cref="UAOOI.SemanticData.UANodeSetValidation.InformationModelFactory.TypeFactoryBase" /> /// Implements the <see cref="UAOOI.SemanticData.InformationModelFactory.IDataTypeFactory" /> /// </summary> /// <seealso cref="UAOOI.SemanticData.UANodeSetValidation.InformationModelFactory.TypeFactoryBase" /> /// <seealso cref="UAOOI.SemanticData.InformationModelFactory.IDataTypeFactory" /> internal class DataTypeFactoryBase : TypeFactoryBase, IDataTypeFactory { /// <summary> /// Sets a value indicating whether this instance is option set. This flag indicates that the data type defines the OptionSetValues Property. /// This field is optional.The default value is false. /// </summary> /// <value><c>true</c> if this instance is option set; otherwise, <c>false</c>.</value> public bool IsOptionSet { set; private get; } /// <summary> /// Creates new implementation dependent object implementing the <see cref="T:UAOOI.SemanticData.InformationModelFactory.IDataTypeDefinitionFactory" /> interface. /// The data type model is used to define simple and complex data types. Types are used to describe the structure of the Value attribute of variables and their types. /// Therefore each Variable and VariableType node is pointing with its DataType attribute to a node of the DataType node class. /// </summary> /// <returns>IDataTypeDefinitionFactory.</returns> /// <value>Returns new object of <see cref="T:UAOOI.SemanticData.InformationModelFactory.IDataTypeDefinitionFactory" /> type encapsulating DataType definition factory.</value> public IDataTypeDefinitionFactory NewDefinition() { return new DataTypeDefinitionFactoryBase(); } } } <|start_filename|>SemanticData/UANodeSetValidation/XML/UAModelContext.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System; using System.Collections.Generic; using UAOOI.SemanticData.BuildingErrorsHandling; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.SemanticData.UANodeSetValidation.XML { internal class UAModelContext : IUAModelContext { #region API /// <summary> /// Initializes a new instance of the <see cref="UAModelContext" /> class. /// </summary> /// <param name="modelHeader">The model header of the <see cref="UANodeSet"/> represented as an instance of <see cref="IUANodeSetModelHeader"/>.</param> /// <param name="addressSpaceContext">The address space context represented by an instance of <see cref="IAddressSpaceBuildContext" />.</param> /// <param name="traceEvent">The trace event call back delegate.</param> /// <exception cref="ArgumentNullException">buildErrorsHandlingLog /// or /// addressSpaceContext</exception> internal static UAModelContext ParseUANodeSetModelHeader(IUANodeSetModelHeader modelHeader, INamespaceTable addressSpaceContext, Action<TraceMessage> traceEvent) { UAModelContext context2Return = new UAModelContext(modelHeader, addressSpaceContext, traceEvent); context2Return.Parse(modelHeader, addressSpaceContext); return context2Return; } internal Uri DefaultUri => new Uri(_namespaceUris[0]); #endregion API #region IUAModelContext //public Uri ModelUri { get; private set; } /// <summary> /// Imports the browse name <see cref="QualifiedName" /> and Node identifier as <see cref="NodeId" />. It recalculates the <see cref="QualifiedName.NamespaceIndex" /> and <see cref="NodeId.NamespaceIndex" /> against local namespace index table. /// </summary> /// <param name="browseNameText">The <see cref="QualifiedName" /> serialized as text to be imported.</param> /// <param name="nodeIdText">The <see cref="NodeId" /> serialized as text to be imported.</param> /// <param name="trace">Captures the functionality of trace.</param> /// <returns>A <see cref="ValueTuple{T1, T2}" /> value containing <see cref="QualifiedName" /> and <see cref="NodeId" /> with recalculated NamespaceIndex.</returns> public (QualifiedName browseName, NodeId nodeId) ImportBrowseName(string browseNameText, string nodeIdText, Action<TraceMessage> trace) { nodeIdText = LookupAlias(nodeIdText); NodeId nodeId = nodeIdText.ParseNodeId(trace); QualifiedName browseName = browseNameText.ParseBrowseName(nodeId, trace); nodeId.SetNamespaceIndex(ImportNamespaceIndex(nodeId.NamespaceIndex)); browseName.NamespaceIndex = ImportNamespaceIndex(browseName.NamespaceIndex); browseName.NamespaceIndexSpecified = true; return (browseName, nodeId); } /// <summary> /// Imports the node identifier if <paramref name="nodeId" /> is not empty. /// </summary> /// <param name="nodeId">The node identifier.</param> /// <param name="trace">Captures the functionality of trace.</param> /// <returns>An instance of the <see cref="NodeId" /> or null is the <paramref name="nodeId" /> is null or empty.</returns> public NodeId ImportNodeId(string nodeId, Action<TraceMessage> trace) { if (string.IsNullOrEmpty(nodeId)) return NodeId.Null; nodeId = LookupAlias(nodeId); NodeId _nodeId = nodeId.ParseNodeId(trace); ushort namespaceIndex = ImportNamespaceIndex(_nodeId.NamespaceIndex); return new NodeId(_nodeId.IdentifierPart, namespaceIndex); } public void RegisterUAReferenceType(QualifiedName browseName) { if (UAReferenceTypNames.Contains(browseName)) { string message = $"The {nameof(UAReferenceType)} duplicated BrowseName={browseName}. It is not allowed that two different ReferenceTypes have the same BrowseName"; _logTraceMessage(TraceMessage.BuildErrorTraceMessage(BuildError.DuplicatedReferenceType, message)); } else UAReferenceTypNames.Add(browseName); } #endregion IUAModelContext #region private //var private readonly IUANodeSetModelHeader _modelHeader; private readonly Action<TraceMessage> _logTraceMessage; private readonly Dictionary<string, string> _aliasesDictionary = new Dictionary<string, string>(); private IList<string> _namespaceUris = new List<string>(); private INamespaceTable _addressSpaceContext { get; } private readonly List<QualifiedName> UAReferenceTypNames = new List<QualifiedName>(); private static Random _randomNumber = new Random(); //methods private UAModelContext(IUANodeSetModelHeader modelHeader, INamespaceTable addressSpaceContext, Action<TraceMessage> traceEvent) { _modelHeader = modelHeader ?? throw new ArgumentNullException(nameof(modelHeader)); if (modelHeader.ServerUris != null && modelHeader.ServerUris.Length > 0) traceEvent(TraceMessage.BuildErrorTraceMessage(BuildError.NotSupportedFeature, "ServerUris is omitted during the import")); if (modelHeader.Extensions != null && modelHeader.Extensions.Length > 0) traceEvent(TraceMessage.BuildErrorTraceMessage(BuildError.NotSupportedFeature, "Extensions are omitted during the import")); _logTraceMessage = traceEvent ?? throw new ArgumentNullException(nameof(traceEvent)); _addressSpaceContext = addressSpaceContext ?? throw new ArgumentNullException(nameof(addressSpaceContext)); } private void Parse(IUANodeSetModelHeader modelHeader, INamespaceTable namespaceTable) { _namespaceUris = Parse(modelHeader.NamespaceUris); Parse(modelHeader.Models, namespaceTable); Parse(modelHeader.Aliases); } //TODO Enhance/Improve NodeIdAlias array parser #557 private void Parse(NodeIdAlias[] nodeIdAlias) { if (nodeIdAlias is null) return; foreach (NodeIdAlias alias in nodeIdAlias) _aliasesDictionary.Add(alias.Alias.Trim(), alias.Value); } private List<string> Parse(string[] namespaceUris) { List<string> list2Return = new List<string>(); if (namespaceUris is null || namespaceUris.Length == 0) { namespaceUris = new string[] { RandomUri().ToString() }; _logTraceMessage(TraceMessage.BuildErrorTraceMessage(BuildError.NamespaceUrisCannotBeNull, $"Added a random URI { namespaceUris[0] } to NamespaceUris.")); } for (int i = 0; i < namespaceUris.Length; i++) list2Return.Add(namespaceUris[i]); return list2Return; } private void Parse(ModelTableEntry[] models, INamespaceTable namespaceTable) { if (models == null || models.Length == 0) { models = new ModelTableEntry[] { new ModelTableEntry() { AccessRestrictions = 0, ModelUri = _namespaceUris[0], PublicationDate = DateTime.UtcNow, PublicationDateSpecified = true, RequiredModel = new ModelTableEntry[]{ }, RolePermissions = new RolePermission[] { }, Version = new Version().ToString() } }; _logTraceMessage(TraceMessage.BuildErrorTraceMessage(BuildError.ModelsCannotBeNull, $"Added default model {models[0].ModelUri}")); } foreach (ModelTableEntry item in models) { namespaceTable.RegisterModel(item); if (item.RequiredModel != null) foreach (ModelTableEntry requiredModel in item.RequiredModel) namespaceTable.RegisterDependency(requiredModel); } } private string LookupAlias(string id) { string _newId = string.Empty; return _aliasesDictionary.TryGetValue(id.Trim(), out _newId) ? _newId : id; } private ushort ImportNamespaceIndex(ushort namespaceIndex) { // nothing special required for indexes < 0. if (namespaceIndex == 0) return namespaceIndex; string uriString; if (_namespaceUris.Count > namespaceIndex - 1) uriString = _namespaceUris[namespaceIndex - 1]; else { // return a random value if index is out of range. uriString = RandomUri().ToString(); this._logTraceMessage( TraceMessage.BuildErrorTraceMessage(BuildError.UndefinedNamespaceIndex, $"ImportNamespaceIndex failed - namespace index {namespaceIndex - 1} is out of the NamespaceUris index. New namespace {uriString} is created instead.")); _namespaceUris.Add(uriString); } return _addressSpaceContext.GetURIIndexOrAppend(new Uri(uriString)); } private static Uri RandomUri() { UriBuilder _builder = new UriBuilder() { Path = $@"github.com/mpostol/OPC-UA-OOI/NameUnknown{_randomNumber.Next(0, int.MaxValue)}", Scheme = Uri.UriSchemeHttp, }; return _builder.Uri; } #endregion private } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/ModelFactoryTestingFixture/MethodInstanceFactoryBase.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using System.Collections.Generic; using System.Xml; using UAOOI.SemanticData.InformationModelFactory; using UAOOI.SemanticData.UANodeSetValidation.UAInformationModel; namespace UAOOI.SemanticData.UANodeSetValidation.ModelFactoryTestingFixture { /// <summary> /// Class MethodInstanceFactoryBase - basic implementation of the <see cref="IMethodInstanceFactory"/>. /// </summary> internal class MethodInstanceFactoryBase : InstanceFactoryBase, IMethodInstanceFactory { #region IMethodInstanceFactory /// <summary> /// Sets a value indicating whether the Method node is executable (“False” means not executable, “True” means executable), not taking user access rights into account. /// If the server cannot get the executable information from the underlying system, it should state that it is executable. If a Method is called, the server should transfer /// this request and return the corresponding StatusCode if such a request is rejected. /// </summary> /// <value><c>true</c> if executable; otherwise, <c>false</c>. Default value is <c>true</c></value> public bool? Executable { set { } } /// <summary> /// Sets a value indicating whether the Method is currently executable taking user access rights into account (“False” means not executable, “True” means executable). /// </summary> /// <value><c>true</c> if executable by current user; otherwise, <c>false</c>. Default value is <c>true</c></value> public bool? UserExecutable { set { } } /// <summary> /// Gets or sets the method declaration identifier defined in Part 6 F.9. May be specified for Method Nodes that are a target of a HasComponent reference from a single Object Node. /// It is the NodeId of the UAMethod with the same BrowseName contained in the TypeDefinition associated with the Object Node. /// If the TypeDefinition overrides a Method inherited from a base ObjectType then this attribute shall reference the Method Node in the subtype. /// </summary> /// <value>The method declaration identifier.</value> public string MethodDeclarationId { set { } } /// <summary> /// Adds the input arguments. The InputArgument specify the input argument of the Method. The Method contains an array of the Argument data type. /// An empty array indicates that there are no input arguments for the Method. /// </summary> /// <param name="argument">Encapsulates a method used to convert Argument represented as <see cref="XmlElement" />.</param> public void AddInputArguments(System.Func<XmlElement, Parameter[]> argument) { RemoveArguments(BrowseNames.InputArguments, argument); } /// <summary> /// Adds the output argument. The OutputArgument specifies the output argument of the Method. The Method contains an array of the Argument data type. /// An empty array indicates that there are no output arguments for the Method. /// </summary> /// <param name="argument">Encapsulates a method used to convert Argument represented as <see cref="XmlElement" />.</param> public void AddOutputArguments(System.Func<XmlElement, Parameter[]> argument) { RemoveArguments(BrowseNames.OutputArguments, argument); } /// <summary> /// Adds the argument description. /// </summary> /// <param name="name">The name.</param> /// <param name="locale">The locale.</param> /// <param name="value">The value.</param> public void AddArgumentDescription(string name, string locale, string value) { } #endregion IMethodInstanceFactory private Parameter[] RemoveArguments(string parameterKind, Func<XmlElement, Parameter[]> getParameters) { Parameter[] _parameters = null; List<NodeFactoryBase> _newChildrenCollection = new List<NodeFactoryBase>(); foreach (NodeFactoryBase _item in m_Nodes) { if (_item.SymbolicName.Equals(new XmlQualifiedName(parameterKind, Namespaces.OpcUa))) { PropertyInstanceFactoryBase _arg = (PropertyInstanceFactoryBase)_item; _parameters = getParameters(_arg.DefaultValue); } else _newChildrenCollection.Add(_item); } m_Nodes = _newChildrenCollection; return _parameters; } } } <|start_filename|>SemanticData/UANodeSetValidation/IRolePermission.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ namespace UAOOI.SemanticData.UANodeSetValidation { /// <summary> /// Class RolePermission - default RolePermissions for all Nodes in the model. /// </summary> /// <remarks> /// This type is defined in Part 6 F.5 but the definition is not compliant with the UANodeSet schema. /// This type is also defined in the Part 3 5.2.9 but the definition is not compliant. /// </remarks> public interface IRolePermission { /// <summary> /// Gets or sets the permissions. /// </summary> /// <remarks> /// This is a subtype of the UInt32 DataType with the OptionSetValues Property defined. It is used to define the permissions of a Node. The <c>PermissionType</c> is formally defined in Part3 8.55 Table 38. /// </remarks> /// <value>The permissions.</value> uint Permissions { get; set; } /// <summary> /// Gets or sets the value. /// </summary> /// <remarks> /// Not defined in the spec. /// </remarks> /// <value>The value.</value> string Value { get; set; } } } <|start_filename|>SemanticData/UANodeSetValidation/IUAModelContext.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System; using UAOOI.SemanticData.BuildingErrorsHandling; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.SemanticData.UANodeSetValidation { /// <summary> /// Interface IUAModelContext - represents an OPC UA Information Model /// </summary> internal interface IUAModelContext { /// <summary> /// Registers the <see cref="QualifiedName"/> of ReferenceType Node. /// </summary> /// <param name="browseName">An instance of <see cref="QualifiedName"/> used as a name of the ReferenceType node.</param> void RegisterUAReferenceType(QualifiedName browseName); /// <summary> /// Imports the browse name <see cref="QualifiedName"/> and Node identifier as <see cref="NodeId"/>. It recalculates the <see cref="QualifiedName.NamespaceIndex"/> and <see cref="NodeId.NamespaceIndex"/> against local namespace index table. /// </summary> /// <param name="browseNameText">The <see cref="QualifiedName" /> serialized as text to be imported.</param> /// <param name="nodeIdText">The <see cref="NodeId"/> serialized as text to be imported.</param> /// <param name="trace">Captures the functionality of trace.</param> /// <returns>A <see cref="ValueTuple{T1, T2}"/> instance containing <see cref="QualifiedName" /> and <see cref="NodeId"/> with recalculated NamespaceIndex.</returns> (QualifiedName browseName, NodeId nodeId) ImportBrowseName(string browseNameText, string nodeIdText, Action<TraceMessage> trace); /// <summary> /// Imports the node identifier if <paramref name="nodeId" /> is not empty. /// </summary> /// <param name="nodeId">The <see cref="NodeId"/> serialized as string to be imported.</param> /// <param name="trace">Captures the functionality of trace.</param> /// <returns>An instance of the <see cref="NodeId" /> or random if the <paramref name="nodeId" /> is null or empty.</returns> NodeId ImportNodeId(string nodeId, Action<TraceMessage> trace); } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/XMLModels/ProblemsToReport/eoursel510/DoRecoverModelDesign.cmd<|end_filename|> ..\asp "Opc.Ua.NodeSet2.TriCycleType_V1.1.xml" -e "Opc.Ua.NodeSet2.TriCycleType_V1.1.ModelDesign.xml" -s XMLstylesheet -n "http://tricycleTypeV1" <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/XMLModels/ProblemsToReport/eoursel510/Opc.Ua.NodeSet2.TriCycleType_V1.1.ModelDesign/Prefix2.Classes.cs<|end_filename|> /* ======================================================================== * Copyright (c) 2005-2016 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 * * 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. * * The complete license agreement can be found here: * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Runtime.Serialization; using Prefix0; namespace Prefix2 { #region DataType Identifiers /// <summary> /// A class that declares constants for all DataTypes in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class DataTypes { /// <summary> /// The identifier for the TireEnum DataType. /// </summary> public const uint TireEnum = 1; /// <summary> /// The identifier for the TriCycleDataType DataType. /// </summary> public const uint TriCycleDataType = 3; /// <summary> /// The identifier for the WheelDataType DataType. /// </summary> public const uint WheelDataType = 4; } #endregion #region Object Identifiers /// <summary> /// A class that declares constants for all Objects in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class Objects { /// <summary> /// The identifier for the VehicleType_S_Owner_ Object. /// </summary> public const uint VehicleType_S_Owner_ = 47; /// <summary> /// The identifier for the TrailerType_S_Owner_ Object. /// </summary> public const uint TrailerType_S_Owner_ = 52; /// <summary> /// The identifier for the TriCycleType_S_Owner_ Object. /// </summary> public const uint TriCycleType_S_Owner_ = 57; /// <summary> /// The identifier for the TriCycleDataType_Encoding_DefaultXml Object. /// </summary> public const uint TriCycleDataType_Encoding_DefaultXml = 24; /// <summary> /// The identifier for the WheelDataType_Encoding_DefaultXml Object. /// </summary> public const uint WheelDataType_Encoding_DefaultXml = 25; /// <summary> /// The identifier for the TriCycleDataType_Encoding_DefaultBinary Object. /// </summary> public const uint TriCycleDataType_Encoding_DefaultBinary = 35; /// <summary> /// The identifier for the WheelDataType_Encoding_DefaultBinary Object. /// </summary> public const uint WheelDataType_Encoding_DefaultBinary = 36; } #endregion #region ObjectType Identifiers /// <summary> /// A class that declares constants for all ObjectTypes in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class ObjectTypes { /// <summary> /// The identifier for the HumanType ObjectType. /// </summary> public const uint HumanType = 5; /// <summary> /// The identifier for the VehicleType ObjectType. /// </summary> public const uint VehicleType = 10; /// <summary> /// The identifier for the TrailerType ObjectType. /// </summary> public const uint TrailerType = 9; /// <summary> /// The identifier for the TriCycleType ObjectType. /// </summary> public const uint TriCycleType = 11; } #endregion #region Variable Identifiers /// <summary> /// A class that declares constants for all Variables in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class Variables { /// <summary> /// The identifier for the TireEnum_EnumStrings Variable. /// </summary> public const uint TireEnum_EnumStrings = 2; /// <summary> /// The identifier for the HumanType_Name Variable. /// </summary> public const uint HumanType_Name = 6; /// <summary> /// The identifier for the HumanType_Age Variable. /// </summary> public const uint HumanType_Age = 7; /// <summary> /// The identifier for the HumanType_Gender Variable. /// </summary> public const uint HumanType_Gender = 8; /// <summary> /// The identifier for the VehicleType_buildDate Variable. /// </summary> public const uint VehicleType_buildDate = 46; /// <summary> /// The identifier for the VehicleType_S_Owner__Name Variable. /// </summary> public const uint VehicleType_S_Owner__Name = 48; /// <summary> /// The identifier for the VehicleType_S_Owner__Age Variable. /// </summary> public const uint VehicleType_S_Owner__Age = 49; /// <summary> /// The identifier for the VehicleType_S_Owner__Gender Variable. /// </summary> public const uint VehicleType_S_Owner__Gender = 50; /// <summary> /// The identifier for the TrailerType_S_Owner__Name Variable. /// </summary> public const uint TrailerType_S_Owner__Name = 53; /// <summary> /// The identifier for the TrailerType_S_Owner__Age Variable. /// </summary> public const uint TrailerType_S_Owner__Age = 54; /// <summary> /// The identifier for the TrailerType_S_Owner__Gender Variable. /// </summary> public const uint TrailerType_S_Owner__Gender = 55; /// <summary> /// The identifier for the TrailerType_LoadedTricycle Variable. /// </summary> public const uint TrailerType_LoadedTricycle = 61; /// <summary> /// The identifier for the TriCycleType_S_Owner__Name Variable. /// </summary> public const uint TriCycleType_S_Owner__Name = 58; /// <summary> /// The identifier for the TriCycleType_S_Owner__Age Variable. /// </summary> public const uint TriCycleType_S_Owner__Age = 59; /// <summary> /// The identifier for the TriCycleType_S_Owner__Gender Variable. /// </summary> public const uint TriCycleType_S_Owner__Gender = 60; /// <summary> /// The identifier for the TriCycleType_weight Variable. /// </summary> public const uint TriCycleType_weight = 12; /// <summary> /// The identifier for the TriCycleType_wheels Variable. /// </summary> public const uint TriCycleType_wheels = 13; /// <summary> /// The identifier for the TriCycleType_wheels_tickness Variable. /// </summary> public const uint TriCycleType_wheels_tickness = 14; /// <summary> /// The identifier for the TriCycleType_wheels_diameter Variable. /// </summary> public const uint TriCycleType_wheels_diameter = 15; /// <summary> /// The identifier for the TriCycleType_wheels_pressure Variable. /// </summary> public const uint TriCycleType_wheels_pressure = 16; /// <summary> /// The identifier for the TriCycleType_wheels_tiretype Variable. /// </summary> public const uint TriCycleType_wheels_tiretype = 17; /// <summary> /// The identifier for the TriCycleType_Model Variable. /// </summary> public const uint TriCycleType_Model = 18; /// <summary> /// The identifier for the WheelVariableType_tickness Variable. /// </summary> public const uint WheelVariableType_tickness = 20; /// <summary> /// The identifier for the WheelVariableType_diameter Variable. /// </summary> public const uint WheelVariableType_diameter = 21; /// <summary> /// The identifier for the WheelVariableType_pressure Variable. /// </summary> public const uint WheelVariableType_pressure = 22; /// <summary> /// The identifier for the WheelVariableType_tiretype Variable. /// </summary> public const uint WheelVariableType_tiretype = 23; /// <summary> /// The identifier for the Name2_XmlSchema Variable. /// </summary> public const uint Name2_XmlSchema = 26; /// <summary> /// The identifier for the Name2_XmlSchema_NamespaceUri Variable. /// </summary> public const uint Name2_XmlSchema_NamespaceUri = 28; /// <summary> /// The identifier for the Name2_XmlSchema_TriCycleDataType Variable. /// </summary> public const uint Name2_XmlSchema_TriCycleDataType = 29; /// <summary> /// The identifier for the Name2_XmlSchema_WheelDataType Variable. /// </summary> public const uint Name2_XmlSchema_WheelDataType = 32; /// <summary> /// The identifier for the Name2_BinarySchema Variable. /// </summary> public const uint Name2_BinarySchema = 37; /// <summary> /// The identifier for the Name2_BinarySchema_NamespaceUri Variable. /// </summary> public const uint Name2_BinarySchema_NamespaceUri = 39; /// <summary> /// The identifier for the Name2_BinarySchema_TriCycleDataType Variable. /// </summary> public const uint Name2_BinarySchema_TriCycleDataType = 40; /// <summary> /// The identifier for the Name2_BinarySchema_WheelDataType Variable. /// </summary> public const uint Name2_BinarySchema_WheelDataType = 43; } #endregion #region VariableType Identifiers /// <summary> /// A class that declares constants for all VariableTypes in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class VariableTypes { /// <summary> /// The identifier for the WheelVariableType VariableType. /// </summary> public const uint WheelVariableType = 19; } #endregion #region DataType Node Identifiers /// <summary> /// A class that declares constants for all DataTypes in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class DataTypeIds { /// <summary> /// The identifier for the TireEnum DataType. /// </summary> public static readonly ExpandedNodeId TireEnum = new ExpandedNodeId(Prefix2.DataTypes.TireEnum, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleDataType DataType. /// </summary> public static readonly ExpandedNodeId TriCycleDataType = new ExpandedNodeId(Prefix2.DataTypes.TriCycleDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the WheelDataType DataType. /// </summary> public static readonly ExpandedNodeId WheelDataType = new ExpandedNodeId(Prefix2.DataTypes.WheelDataType, Prefix2.Namespaces.Name2); } #endregion #region Object Node Identifiers /// <summary> /// A class that declares constants for all Objects in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class ObjectIds { /// <summary> /// The identifier for the VehicleType_S_Owner_ Object. /// </summary> public static readonly ExpandedNodeId VehicleType_S_Owner_ = new ExpandedNodeId(Prefix2.Objects.VehicleType_S_Owner_, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TrailerType_S_Owner_ Object. /// </summary> public static readonly ExpandedNodeId TrailerType_S_Owner_ = new ExpandedNodeId(Prefix2.Objects.TrailerType_S_Owner_, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType_S_Owner_ Object. /// </summary> public static readonly ExpandedNodeId TriCycleType_S_Owner_ = new ExpandedNodeId(Prefix2.Objects.TriCycleType_S_Owner_, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleDataType_Encoding_DefaultXml Object. /// </summary> public static readonly ExpandedNodeId TriCycleDataType_Encoding_DefaultXml = new ExpandedNodeId(Prefix2.Objects.TriCycleDataType_Encoding_DefaultXml, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the WheelDataType_Encoding_DefaultXml Object. /// </summary> public static readonly ExpandedNodeId WheelDataType_Encoding_DefaultXml = new ExpandedNodeId(Prefix2.Objects.WheelDataType_Encoding_DefaultXml, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleDataType_Encoding_DefaultBinary Object. /// </summary> public static readonly ExpandedNodeId TriCycleDataType_Encoding_DefaultBinary = new ExpandedNodeId(Prefix2.Objects.TriCycleDataType_Encoding_DefaultBinary, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the WheelDataType_Encoding_DefaultBinary Object. /// </summary> public static readonly ExpandedNodeId WheelDataType_Encoding_DefaultBinary = new ExpandedNodeId(Prefix2.Objects.WheelDataType_Encoding_DefaultBinary, Prefix2.Namespaces.Name2); } #endregion #region ObjectType Node Identifiers /// <summary> /// A class that declares constants for all ObjectTypes in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class ObjectTypeIds { /// <summary> /// The identifier for the HumanType ObjectType. /// </summary> public static readonly ExpandedNodeId HumanType = new ExpandedNodeId(Prefix2.ObjectTypes.HumanType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the VehicleType ObjectType. /// </summary> public static readonly ExpandedNodeId VehicleType = new ExpandedNodeId(Prefix2.ObjectTypes.VehicleType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TrailerType ObjectType. /// </summary> public static readonly ExpandedNodeId TrailerType = new ExpandedNodeId(Prefix2.ObjectTypes.TrailerType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType ObjectType. /// </summary> public static readonly ExpandedNodeId TriCycleType = new ExpandedNodeId(Prefix2.ObjectTypes.TriCycleType, Prefix2.Namespaces.Name2); } #endregion #region Variable Node Identifiers /// <summary> /// A class that declares constants for all Variables in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class VariableIds { /// <summary> /// The identifier for the TireEnum_EnumStrings Variable. /// </summary> public static readonly ExpandedNodeId TireEnum_EnumStrings = new ExpandedNodeId(Prefix2.Variables.TireEnum_EnumStrings, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the HumanType_Name Variable. /// </summary> public static readonly ExpandedNodeId HumanType_Name = new ExpandedNodeId(Prefix2.Variables.HumanType_Name, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the HumanType_Age Variable. /// </summary> public static readonly ExpandedNodeId HumanType_Age = new ExpandedNodeId(Prefix2.Variables.HumanType_Age, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the HumanType_Gender Variable. /// </summary> public static readonly ExpandedNodeId HumanType_Gender = new ExpandedNodeId(Prefix2.Variables.HumanType_Gender, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the VehicleType_buildDate Variable. /// </summary> public static readonly ExpandedNodeId VehicleType_buildDate = new ExpandedNodeId(Prefix2.Variables.VehicleType_buildDate, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the VehicleType_S_Owner__Name Variable. /// </summary> public static readonly ExpandedNodeId VehicleType_S_Owner__Name = new ExpandedNodeId(Prefix2.Variables.VehicleType_S_Owner__Name, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the VehicleType_S_Owner__Age Variable. /// </summary> public static readonly ExpandedNodeId VehicleType_S_Owner__Age = new ExpandedNodeId(Prefix2.Variables.VehicleType_S_Owner__Age, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the VehicleType_S_Owner__Gender Variable. /// </summary> public static readonly ExpandedNodeId VehicleType_S_Owner__Gender = new ExpandedNodeId(Prefix2.Variables.VehicleType_S_Owner__Gender, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TrailerType_S_Owner__Name Variable. /// </summary> public static readonly ExpandedNodeId TrailerType_S_Owner__Name = new ExpandedNodeId(Prefix2.Variables.TrailerType_S_Owner__Name, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TrailerType_S_Owner__Age Variable. /// </summary> public static readonly ExpandedNodeId TrailerType_S_Owner__Age = new ExpandedNodeId(Prefix2.Variables.TrailerType_S_Owner__Age, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TrailerType_S_Owner__Gender Variable. /// </summary> public static readonly ExpandedNodeId TrailerType_S_Owner__Gender = new ExpandedNodeId(Prefix2.Variables.TrailerType_S_Owner__Gender, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TrailerType_LoadedTricycle Variable. /// </summary> public static readonly ExpandedNodeId TrailerType_LoadedTricycle = new ExpandedNodeId(Prefix2.Variables.TrailerType_LoadedTricycle, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType_S_Owner__Name Variable. /// </summary> public static readonly ExpandedNodeId TriCycleType_S_Owner__Name = new ExpandedNodeId(Prefix2.Variables.TriCycleType_S_Owner__Name, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType_S_Owner__Age Variable. /// </summary> public static readonly ExpandedNodeId TriCycleType_S_Owner__Age = new ExpandedNodeId(Prefix2.Variables.TriCycleType_S_Owner__Age, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType_S_Owner__Gender Variable. /// </summary> public static readonly ExpandedNodeId TriCycleType_S_Owner__Gender = new ExpandedNodeId(Prefix2.Variables.TriCycleType_S_Owner__Gender, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType_weight Variable. /// </summary> public static readonly ExpandedNodeId TriCycleType_weight = new ExpandedNodeId(Prefix2.Variables.TriCycleType_weight, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType_wheels Variable. /// </summary> public static readonly ExpandedNodeId TriCycleType_wheels = new ExpandedNodeId(Prefix2.Variables.TriCycleType_wheels, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType_wheels_tickness Variable. /// </summary> public static readonly ExpandedNodeId TriCycleType_wheels_tickness = new ExpandedNodeId(Prefix2.Variables.TriCycleType_wheels_tickness, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType_wheels_diameter Variable. /// </summary> public static readonly ExpandedNodeId TriCycleType_wheels_diameter = new ExpandedNodeId(Prefix2.Variables.TriCycleType_wheels_diameter, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType_wheels_pressure Variable. /// </summary> public static readonly ExpandedNodeId TriCycleType_wheels_pressure = new ExpandedNodeId(Prefix2.Variables.TriCycleType_wheels_pressure, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType_wheels_tiretype Variable. /// </summary> public static readonly ExpandedNodeId TriCycleType_wheels_tiretype = new ExpandedNodeId(Prefix2.Variables.TriCycleType_wheels_tiretype, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the TriCycleType_Model Variable. /// </summary> public static readonly ExpandedNodeId TriCycleType_Model = new ExpandedNodeId(Prefix2.Variables.TriCycleType_Model, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the WheelVariableType_tickness Variable. /// </summary> public static readonly ExpandedNodeId WheelVariableType_tickness = new ExpandedNodeId(Prefix2.Variables.WheelVariableType_tickness, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the WheelVariableType_diameter Variable. /// </summary> public static readonly ExpandedNodeId WheelVariableType_diameter = new ExpandedNodeId(Prefix2.Variables.WheelVariableType_diameter, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the WheelVariableType_pressure Variable. /// </summary> public static readonly ExpandedNodeId WheelVariableType_pressure = new ExpandedNodeId(Prefix2.Variables.WheelVariableType_pressure, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the WheelVariableType_tiretype Variable. /// </summary> public static readonly ExpandedNodeId WheelVariableType_tiretype = new ExpandedNodeId(Prefix2.Variables.WheelVariableType_tiretype, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_NamespaceUri Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_NamespaceUri = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_NamespaceUri, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_TriCycleDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_TriCycleDataType = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_TriCycleDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_WheelDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_WheelDataType = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_WheelDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_NamespaceUri Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_NamespaceUri = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_NamespaceUri, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_TriCycleDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_TriCycleDataType = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_TriCycleDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_WheelDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_WheelDataType = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_WheelDataType, Prefix2.Namespaces.Name2); } #endregion #region VariableType Node Identifiers /// <summary> /// A class that declares constants for all VariableTypes in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class VariableTypeIds { /// <summary> /// The identifier for the WheelVariableType VariableType. /// </summary> public static readonly ExpandedNodeId WheelVariableType = new ExpandedNodeId(Prefix2.VariableTypes.WheelVariableType, Prefix2.Namespaces.Name2); } #endregion #region BrowseName Declarations /// <summary> /// Declares all of the BrowseNames used in the Model Design. /// </summary> public static partial class BrowseNames { /// <summary> /// The BrowseName for the HumanType component. /// </summary> public const string HumanType = "HumanType"; /// <summary> /// The BrowseName for the Name2_BinarySchema component. /// </summary> public const string Name2_BinarySchema = "Prefix2"; /// <summary> /// The BrowseName for the Name2_XmlSchema component. /// </summary> public const string Name2_XmlSchema = "Prefix2"; /// <summary> /// The BrowseName for the TireEnum component. /// </summary> public const string TireEnum = "TireEnum"; /// <summary> /// The BrowseName for the TrailerType component. /// </summary> public const string TrailerType = "TrailerType"; /// <summary> /// The BrowseName for the TriCycleDataType component. /// </summary> public const string TriCycleDataType = "TriCycleDataType"; /// <summary> /// The BrowseName for the TriCycleType component. /// </summary> public const string TriCycleType = "TriCycleType"; /// <summary> /// The BrowseName for the VehicleType component. /// </summary> public const string VehicleType = "VehicleType"; /// <summary> /// The BrowseName for the WheelDataType component. /// </summary> public const string WheelDataType = "WheelDataType"; /// <summary> /// The BrowseName for the WheelVariableType component. /// </summary> public const string WheelVariableType = "WheelVariableType"; } #endregion #region Namespace Declarations /// <summary> /// Defines constants for all namespaces referenced by the model design. /// </summary> public static partial class Namespaces { /// <summary> /// The URI for the Name0Xsd namespace (.NET code namespace is 'Prefix0'). /// </summary> public const string Name0Xsd = "http://opcfoundation.org/UA/"; /// <summary> /// The URI for the Name0Xsd namespace (.NET code namespace is 'Prefix0'). /// </summary> public const string Name0Xsd = "http://opcfoundation.org/UA/"; /// <summary> /// The URI for the Name2Xsd namespace (.NET code namespace is 'Prefix2'). /// </summary> public const string Name2Xsd = "http://tricycletypev1/"; /// <summary> /// The URI for the Name2Xsd namespace (.NET code namespace is 'Prefix2'). /// </summary> public const string Name2Xsd = "http://tricycletypev1/"; } #endregion #region TireEnum Enumeration #if (!OPCUA_EXCLUDE_TireEnum) /// <summary> /// A description for the TireEnum DataType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public enum TireEnum { /// <summary> /// A description for the Mud field. /// </summary> [EnumMember(Value = "Mud_0")] Mud = 0, /// <summary> /// A description for the Ice field. /// </summary> [EnumMember(Value = "Ice_1")] Ice = 1, /// <summary> /// A description for the Sand field. /// </summary> [EnumMember(Value = "Sand_2")] Sand = 2, } #region TireEnumCollection Class /// <summary> /// A collection of TireEnum objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfTireEnum", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "TireEnum")] #if !NET_STANDARD public partial class TireEnumCollection : List<TireEnum>, ICloneable #else public partial class TireEnumCollection : List<TireEnum> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public TireEnumCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public TireEnumCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public TireEnumCollection(IEnumerable<TireEnum> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator TireEnumCollection(TireEnum[] values) { if (values != null) { return new TireEnumCollection(values); } return new TireEnumCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator TireEnum[](TireEnumCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (TireEnumCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { TireEnumCollection clone = new TireEnumCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((TireEnum)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region TriCycleDataType Class #if (!OPCUA_EXCLUDE_TriCycleDataType) /// <summary> /// A description for the TriCycleDataType DataType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public partial class TriCycleDataType : IEncodeable { #region Constructors /// <summary> /// The default constructor. /// </summary> public TriCycleDataType() { Initialize(); } /// <summary> /// Called by the .NET framework during deserialization. /// </summary> [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_weight = (float)0; m_wheel = new WheelDataType(); m_model = null; } #endregion #region Public Properties /// <summary> /// A description for the weight field. /// </summary> [DataMember(Name = "weight", IsRequired = false, Order = 1)] public float weight { get { return m_weight; } set { m_weight = value; } } /// <summary> /// A description for the wheel field. /// </summary> [DataMember(Name = "wheel", IsRequired = false, Order = 2)] public WheelDataType wheel { get { return m_wheel; } set { m_wheel = value; if (value == null) { m_wheel = new WheelDataType(); } } } /// <summary> /// A description for the Model field. /// </summary> [DataMember(Name = "Model", IsRequired = false, Order = 3)] public string Model { get { return m_model; } set { m_model = value; } } #endregion #region IEncodeable Members /// <summary cref="IEncodeable.TypeId" /> public virtual ExpandedNodeId TypeId { get { return DataTypeIds.TriCycleDataType; } } /// <summary cref="IEncodeable.BinaryEncodingId" /> public virtual ExpandedNodeId BinaryEncodingId { get { return ObjectIds.TriCycleDataType_Encoding_DefaultBinary; } } /// <summary cref="IEncodeable.XmlEncodingId" /> public virtual ExpandedNodeId XmlEncodingId { get { return ObjectIds.TriCycleDataType_Encoding_DefaultXml; } } /// <summary cref="IEncodeable.Encode(IEncoder)" /> public virtual void Encode(IEncoder encoder) { encoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); encoder.WriteFloat("weight", weight); encoder.WriteEncodeable("wheel", wheel, typeof(WheelDataType)); encoder.WriteString("Model", Model); encoder.PopNamespace(); } /// <summary cref="IEncodeable.Decode(IDecoder)" /> public virtual void Decode(IDecoder decoder) { decoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); weight = decoder.ReadFloat("weight"); wheel = (WheelDataType)decoder.ReadEncodeable("wheel", typeof(WheelDataType)); Model = decoder.ReadString("Model"); decoder.PopNamespace(); } /// <summary cref="IEncodeable.IsEqual(IEncodeable)" /> public virtual bool IsEqual(IEncodeable encodeable) { if (Object.ReferenceEquals(this, encodeable)) { return true; } TriCycleDataType value = encodeable as TriCycleDataType; if (value == null) { return false; } if (!Utils.IsEqual(m_weight, value.m_weight)) return false; if (!Utils.IsEqual(m_wheel, value.m_wheel)) return false; if (!Utils.IsEqual(m_model, value.m_model)) return false; return true; } #if !NET_STANDARD /// <summary cref="ICloneable.Clone" /> public virtual object Clone() { return (TriCycleDataType)this.MemberwiseClone(); } #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { TriCycleDataType clone = (TriCycleDataType)base.MemberwiseClone(); clone.m_weight = (float)Utils.Clone(this.m_weight); clone.m_wheel = (WheelDataType)Utils.Clone(this.m_wheel); clone.m_model = (string)Utils.Clone(this.m_model); return clone; } #endregion #region Private Fields private float m_weight; private WheelDataType m_wheel; private string m_model; #endregion } #region TriCycleDataTypeCollection Class /// <summary> /// A collection of TriCycleDataType objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfTriCycleDataType", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "TriCycleDataType")] #if !NET_STANDARD public partial class TriCycleDataTypeCollection : List<TriCycleDataType>, ICloneable #else public partial class TriCycleDataTypeCollection : List<TriCycleDataType> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public TriCycleDataTypeCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public TriCycleDataTypeCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public TriCycleDataTypeCollection(IEnumerable<TriCycleDataType> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator TriCycleDataTypeCollection(TriCycleDataType[] values) { if (values != null) { return new TriCycleDataTypeCollection(values); } return new TriCycleDataTypeCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator TriCycleDataType[](TriCycleDataTypeCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (TriCycleDataTypeCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { TriCycleDataTypeCollection clone = new TriCycleDataTypeCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((TriCycleDataType)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region WheelDataType Class #if (!OPCUA_EXCLUDE_WheelDataType) /// <summary> /// Wheel datatype. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public partial class WheelDataType : IEncodeable { #region Constructors /// <summary> /// The default constructor. /// </summary> public WheelDataType() { Initialize(); } /// <summary> /// Called by the .NET framework during deserialization. /// </summary> [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_tickness = (float)0; m_diameter = (float)0; m_pressure = (float)0; m_tireType = TireEnum.Mud; m_raysLen = (int)0; } #endregion #region Public Properties /// <summary> /// A description for the tickness field. /// </summary> [DataMember(Name = "tickness", IsRequired = false, Order = 1)] public float tickness { get { return m_tickness; } set { m_tickness = value; } } /// <summary> /// A description for the diameter field. /// </summary> [DataMember(Name = "diameter", IsRequired = false, Order = 2)] public float diameter { get { return m_diameter; } set { m_diameter = value; } } /// <summary> /// A description for the pressure field. /// </summary> [DataMember(Name = "pressure", IsRequired = false, Order = 3)] public float pressure { get { return m_pressure; } set { m_pressure = value; } } /// <summary> /// A description for the TireType field. /// </summary> [DataMember(Name = "TireType", IsRequired = false, Order = 4)] public TireEnum TireType { get { return m_tireType; } set { m_tireType = value; } } /// <summary> /// A description for the raysLen field. /// </summary> [DataMember(Name = "raysLen", IsRequired = false, Order = 5)] public int raysLen { get { return m_raysLen; } set { m_raysLen = value; } } #endregion #region IEncodeable Members /// <summary cref="IEncodeable.TypeId" /> public virtual ExpandedNodeId TypeId { get { return DataTypeIds.WheelDataType; } } /// <summary cref="IEncodeable.BinaryEncodingId" /> public virtual ExpandedNodeId BinaryEncodingId { get { return ObjectIds.WheelDataType_Encoding_DefaultBinary; } } /// <summary cref="IEncodeable.XmlEncodingId" /> public virtual ExpandedNodeId XmlEncodingId { get { return ObjectIds.WheelDataType_Encoding_DefaultXml; } } /// <summary cref="IEncodeable.Encode(IEncoder)" /> public virtual void Encode(IEncoder encoder) { encoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); encoder.WriteFloat("tickness", tickness); encoder.WriteFloat("diameter", diameter); encoder.WriteFloat("pressure", pressure); encoder.WriteEnumerated("TireType", TireType); encoder.WriteInt32("raysLen", raysLen); encoder.PopNamespace(); } /// <summary cref="IEncodeable.Decode(IDecoder)" /> public virtual void Decode(IDecoder decoder) { decoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); tickness = decoder.ReadFloat("tickness"); diameter = decoder.ReadFloat("diameter"); pressure = decoder.ReadFloat("pressure"); TireType = (TireEnum)decoder.ReadEnumerated("TireType", typeof(TireEnum)); raysLen = decoder.ReadInt32("raysLen"); decoder.PopNamespace(); } /// <summary cref="IEncodeable.IsEqual(IEncodeable)" /> public virtual bool IsEqual(IEncodeable encodeable) { if (Object.ReferenceEquals(this, encodeable)) { return true; } WheelDataType value = encodeable as WheelDataType; if (value == null) { return false; } if (!Utils.IsEqual(m_tickness, value.m_tickness)) return false; if (!Utils.IsEqual(m_diameter, value.m_diameter)) return false; if (!Utils.IsEqual(m_pressure, value.m_pressure)) return false; if (!Utils.IsEqual(m_tireType, value.m_tireType)) return false; if (!Utils.IsEqual(m_raysLen, value.m_raysLen)) return false; return true; } #if !NET_STANDARD /// <summary cref="ICloneable.Clone" /> public virtual object Clone() { return (WheelDataType)this.MemberwiseClone(); } #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { WheelDataType clone = (WheelDataType)base.MemberwiseClone(); clone.m_tickness = (float)Utils.Clone(this.m_tickness); clone.m_diameter = (float)Utils.Clone(this.m_diameter); clone.m_pressure = (float)Utils.Clone(this.m_pressure); clone.m_tireType = (TireEnum)Utils.Clone(this.m_tireType); clone.m_raysLen = (int)Utils.Clone(this.m_raysLen); return clone; } #endregion #region Private Fields private float m_tickness; private float m_diameter; private float m_pressure; private TireEnum m_tireType; private int m_raysLen; #endregion } #region WheelDataTypeCollection Class /// <summary> /// A collection of WheelDataType objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfWheelDataType", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "WheelDataType")] #if !NET_STANDARD public partial class WheelDataTypeCollection : List<WheelDataType>, ICloneable #else public partial class WheelDataTypeCollection : List<WheelDataType> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public WheelDataTypeCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public WheelDataTypeCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public WheelDataTypeCollection(IEnumerable<WheelDataType> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator WheelDataTypeCollection(WheelDataType[] values) { if (values != null) { return new WheelDataTypeCollection(values); } return new WheelDataTypeCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator WheelDataType[](WheelDataTypeCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (WheelDataTypeCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { WheelDataTypeCollection clone = new WheelDataTypeCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((WheelDataType)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region HumanState Class #if (!OPCUA_EXCLUDE_HumanState) /// <summary> /// Stores an instance of the HumanType ObjectType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public partial class HumanState : BaseObjectState { #region Constructors /// <summary> /// Initializes the type with its default attribute values. /// </summary> public HumanState(NodeState parent) : base(parent) { } /// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return Opc.Ua.NodeId.Create(Prefix2.ObjectTypes.HumanType, Prefix2.Namespaces.Name2, namespaceUris); } #if (!OPCUA_EXCLUDE_InitializationStrings) /// <summary> /// Initializes the instance. /// </summary> protected override void Initialize(ISystemContext context) { Initialize(context, InitializationString); InitializeOptionalChildren(context); } protected override void Initialize(ISystemContext context, NodeState source) { InitializeOptionalChildren(context); base.Initialize(context, source); } /// <summary> /// Initializes the any option children defined for the instance. /// </summary> protected override void InitializeOptionalChildren(ISystemContext context) { base.InitializeOptionalChildren(context); } #region Initialization String private const string InitializationString = "AQAAABYAAABodHRwOi8vdHJpY3ljbGV0eXBldjEv/////wRggAABAAAAAQARAAAASHVtYW5UeXBlSW5z" + "dGFuY2UBAQUAAQEFAP////8DAAAAFWCJCgIAAAAAAAQAAABOYW1lAQEGAAAvAD8GAAAAAAz/////AQH/" + "////AAAAABVgiQoCAAAAAAADAAAAQWdlAQEHAAAvAD8HAAAAAAb/////AQH/////AAAAABVgiQoCAAAA" + "AAAGAAAAR2VuZGVyAQEIAAAuAEQIAAAAAAz/////AQH/////AAAAAA=="; #endregion #endif #endregion #region Public Properties /// <summary> /// A description for the Name Variable. /// </summary> public BaseDataVariableState<string> Name { get { return m_name; } set { if (!Object.ReferenceEquals(m_name, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_name = value; } } /// <summary> /// A description for the Age Variable. /// </summary> public BaseDataVariableState<int> Age { get { return m_age; } set { if (!Object.ReferenceEquals(m_age, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_age = value; } } /// <summary> /// A description for the Gender Property. /// </summary> public PropertyState<string> Gender { get { return m_gender; } set { if (!Object.ReferenceEquals(m_gender, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_gender = value; } } #endregion #region Overridden Methods /// <summary> /// Populates a list with the children that belong to the node. /// </summary> /// <param name="context">The context for the system being accessed.</param> /// <param name="children">The list of children to populate.</param> public override void GetChildren( ISystemContext context, IList<BaseInstanceState> children) { if (m_name != null) { children.Add(m_name); } if (m_age != null) { children.Add(m_age); } if (m_gender != null) { children.Add(m_gender); } base.GetChildren(context, children); } /// <summary> /// Finds the child with the specified browse name. /// </summary> protected override BaseInstanceState FindChild( ISystemContext context, QualifiedName browseName, bool createOrReplace, BaseInstanceState replacement) { if (QualifiedName.IsNull(browseName)) { return null; } BaseInstanceState instance = null; switch (browseName.Name) { case Prefix0.BrowseNames.Name: { if (createOrReplace) { if (Name == null) { if (replacement == null) { Name = new BaseDataVariableState<string>(this); } else { Name = (BaseDataVariableState<string>)replacement; } } } instance = Name; break; } case Prefix0.BrowseNames.Age: { if (createOrReplace) { if (Age == null) { if (replacement == null) { Age = new BaseDataVariableState<int>(this); } else { Age = (BaseDataVariableState<int>)replacement; } } } instance = Age; break; } case Prefix0.BrowseNames.Gender: { if (createOrReplace) { if (Gender == null) { if (replacement == null) { Gender = new PropertyState<string>(this); } else { Gender = (PropertyState<string>)replacement; } } } instance = Gender; break; } } if (instance != null) { return instance; } return base.FindChild(context, browseName, createOrReplace, replacement); } #endregion #region Private Fields private BaseDataVariableState<string> m_name; private BaseDataVariableState<int> m_age; private PropertyState<string> m_gender; #endregion } #endif #endregion #region VehicleState Class #if (!OPCUA_EXCLUDE_VehicleState) /// <summary> /// Stores an instance of the VehicleType ObjectType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public partial class VehicleState : BaseObjectState { #region Constructors /// <summary> /// Initializes the type with its default attribute values. /// </summary> public VehicleState(NodeState parent) : base(parent) { } /// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return Opc.Ua.NodeId.Create(Prefix2.ObjectTypes.VehicleType, Prefix2.Namespaces.Name2, namespaceUris); } #if (!OPCUA_EXCLUDE_InitializationStrings) /// <summary> /// Initializes the instance. /// </summary> protected override void Initialize(ISystemContext context) { Initialize(context, InitializationString); InitializeOptionalChildren(context); } protected override void Initialize(ISystemContext context, NodeState source) { InitializeOptionalChildren(context); base.Initialize(context, source); } /// <summary> /// Initializes the any option children defined for the instance. /// </summary> protected override void InitializeOptionalChildren(ISystemContext context) { base.InitializeOptionalChildren(context); } #region Initialization String private const string InitializationString = "<KEY>" + "bnN<KEY>" + "/////wEB/////wAAAABEYMAKAQAAAAgAAABTX093bmVyXwAABgAAAE93bmVyPgEBLwADAAAAAAcAAAA8" + "T3duZXI+AC8BAQUALwAAAP////8DAAAAFWCJCgIAAAAAAAQAAABOYW1lAQEwAAAvAD8wAAAAAAz/////" + "AQH/////AAAAABVgiQoCAAAAAAADAAAAQWdlAQExAAAvAD8xAAAAAAb/////AQH/////AAAAABVgiQoC" + "AAAAAAAGAAAAR2VuZGVyAQEyAAAuAEQyAAAAAAz/////AQH/////AAAAAA=="; #endregion #endif #endregion #region Public Properties /// <summary> /// A description for the buildDate Property. /// </summary> public PropertyState<DateTime> buildDate { get { return m_buildDate; } set { if (!Object.ReferenceEquals(m_buildDate, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_buildDate = value; } } /// <summary> /// A description for the Owner> Object. /// </summary> public HumanState S_Owner_ { get { return m_s_Owner_; } set { if (!Object.ReferenceEquals(m_s_Owner_, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_s_Owner_ = value; } } #endregion #region Overridden Methods /// <summary> /// Populates a list with the children that belong to the node. /// </summary> /// <param name="context">The context for the system being accessed.</param> /// <param name="children">The list of children to populate.</param> public override void GetChildren( ISystemContext context, IList<BaseInstanceState> children) { if (m_buildDate != null) { children.Add(m_buildDate); } if (m_s_Owner_ != null) { children.Add(m_s_Owner_); } base.GetChildren(context, children); } /// <summary> /// Finds the child with the specified browse name. /// </summary> protected override BaseInstanceState FindChild( ISystemContext context, QualifiedName browseName, bool createOrReplace, BaseInstanceState replacement) { if (QualifiedName.IsNull(browseName)) { return null; } BaseInstanceState instance = null; switch (browseName.Name) { case Prefix0.BrowseNames.buildDate: { if (createOrReplace) { if (buildDate == null) { if (replacement == null) { buildDate = new PropertyState<DateTime>(this); } else { buildDate = (PropertyState<DateTime>)replacement; } } } instance = buildDate; break; } case Prefix0.BrowseNames.S_Owner_: { if (createOrReplace) { if (S_Owner_ == null) { if (replacement == null) { S_Owner_ = new HumanState(this); } else { S_Owner_ = (HumanState)replacement; } } } instance = S_Owner_; break; } } if (instance != null) { return instance; } return base.FindChild(context, browseName, createOrReplace, replacement); } #endregion #region Private Fields private PropertyState<DateTime> m_buildDate; private HumanState m_s_Owner_; #endregion } #endif #endregion #region TrailerState Class #if (!OPCUA_EXCLUDE_TrailerState) /// <summary> /// Stores an instance of the TrailerType ObjectType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public partial class TrailerState : VehicleState { #region Constructors /// <summary> /// Initializes the type with its default attribute values. /// </summary> public TrailerState(NodeState parent) : base(parent) { } /// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return Opc.Ua.NodeId.Create(Prefix2.ObjectTypes.TrailerType, Prefix2.Namespaces.Name2, namespaceUris); } #if (!OPCUA_EXCLUDE_InitializationStrings) /// <summary> /// Initializes the instance. /// </summary> protected override void Initialize(ISystemContext context) { Initialize(context, InitializationString); InitializeOptionalChildren(context); } protected override void Initialize(ISystemContext context, NodeState source) { InitializeOptionalChildren(context); base.Initialize(context, source); } /// <summary> /// Initializes the any option children defined for the instance. /// </summary> protected override void InitializeOptionalChildren(ISystemContext context) { base.InitializeOptionalChildren(context); } #region Initialization String private const string InitializationString = "AQ<KEY>" + "bnN<KEY>AAAA<KEY>EBMwAALgBEMwAAAAAN" + "/////wEB/////wAAAABEYMAKAQAAAAgAAABTX093bmVyXwAABgAAAE93bmVyPgEBNAADAAAAAAcAAAA8" + "T3duZXI+AC8BAQUANAAAAP////8DAAAAFWCJCgIAAAAAAAQAAABOYW1lAQE1AAAvAD81AAAAAAz/////" + "AQH/////AAAAABVgiQoCAAAAAAADAAAAQWdlAQE2AAAvAD82AAAAAAb/////AQH/////AAAAABVgiQoC" + "AAAAAAAGAAAAR2VuZGVyAQE3AAAuAEQ3AAAAAAz/////AQH/////AAAAABdgiQoCAAAAAAAOAAAATG9h" + "ZGVkVHJpY3ljbGUBAT0AADEAPz0AAAABAQMAAQAAAAEAAAAAAAAAAQH/////AAAAAA=="; #endregion #endif #endregion #region Public Properties /// <summary> /// A description for the LoadedTricycle Variable. /// </summary> public BaseDataVariableState<TriCycleDataType[]> LoadedTricycle { get { return m_loadedTricycle; } set { if (!Object.ReferenceEquals(m_loadedTricycle, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_loadedTricycle = value; } } #endregion #region Overridden Methods /// <summary> /// Populates a list with the children that belong to the node. /// </summary> /// <param name="context">The context for the system being accessed.</param> /// <param name="children">The list of children to populate.</param> public override void GetChildren( ISystemContext context, IList<BaseInstanceState> children) { if (m_loadedTricycle != null) { children.Add(m_loadedTricycle); } base.GetChildren(context, children); } /// <summary> /// Finds the child with the specified browse name. /// </summary> protected override BaseInstanceState FindChild( ISystemContext context, QualifiedName browseName, bool createOrReplace, BaseInstanceState replacement) { if (QualifiedName.IsNull(browseName)) { return null; } BaseInstanceState instance = null; switch (browseName.Name) { case Prefix0.BrowseNames.LoadedTricycle: { if (createOrReplace) { if (LoadedTricycle == null) { if (replacement == null) { LoadedTricycle = new BaseDataVariableState<TriCycleDataType[]>(this); } else { LoadedTricycle = (BaseDataVariableState<TriCycleDataType[]>)replacement; } } } instance = LoadedTricycle; break; } } if (instance != null) { return instance; } return base.FindChild(context, browseName, createOrReplace, replacement); } #endregion #region Private Fields private BaseDataVariableState<TriCycleDataType[]> m_loadedTricycle; #endregion } #endif #endregion #region TriCycleState Class #if (!OPCUA_EXCLUDE_TriCycleState) /// <summary> /// Stores an instance of the TriCycleType ObjectType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public partial class TriCycleState : VehicleState { #region Constructors /// <summary> /// Initializes the type with its default attribute values. /// </summary> public TriCycleState(NodeState parent) : base(parent) { } /// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return Opc.Ua.NodeId.Create(Prefix2.ObjectTypes.TriCycleType, Prefix2.Namespaces.Name2, namespaceUris); } #if (!OPCUA_EXCLUDE_InitializationStrings) /// <summary> /// Initializes the instance. /// </summary> protected override void Initialize(ISystemContext context) { Initialize(context, InitializationString); InitializeOptionalChildren(context); } protected override void Initialize(ISystemContext context, NodeState source) { InitializeOptionalChildren(context); base.Initialize(context, source); } /// <summary> /// Initializes the any option children defined for the instance. /// </summary> protected override void InitializeOptionalChildren(ISystemContext context) { base.InitializeOptionalChildren(context); } #region Initialization String private const string InitializationString = "AQAAABYAAABodHRwOi8vdHJpY3ljbGV0eXBldjEv/////wRggAABAAAAAQAUAAAAVHJpQ3ljbGVUeXBl" + "SW5zdGFuY2UBAQsAAQELAP////8FAAAAFWCJCgIAAAAAAAkAAABidWlsZERhdGUBATgAAC4ARDgAAAAA" + "Df////8BAf////8AAAAARGDACgEAAAAIAAAAU19Pd25lcl8AAAYAAABPd25lcj4BATkAAwAAAAAHAAAA" + "PE93bmVyPgAvAQEFADkAAAD/////AwAAABVgiQoCAAAAAAAEAAAATmFtZQEBOgAALwA/OgAAAAAM////" + "/wEB/////wAAAAAVYIkKAgAAAAAAAwAAAEFnZQEBOwAALwA/OwAAAAAG/////wEB/////wAAAAAVYIkK" + "AgAAAAAABgAAAEdlbmRlcgEBPAAALgBEPAAAAAAM/////wEB/////wAAAAAVYIkKAgAAAAAABgAAAHdl" + "aWdodAEBDAAALgBEDAAAAAAK/////wEB/////wAAAAAXYIkKAgAAAAAABgAAAHdoZWVscwEBDQAALgEB" + "EwANAAAAAQEEAAEAAAABAAAAAwAAAAEB/////wQAAAAVYIkKAgAAAAAACAAAAHRpY2tuZXNzAQEOAAAv" + "AD8OAAAAAAr/////AQH/////AAAAABVgiQoCAAAAAAAIAAAAZGlhbWV0ZXIBAQ8AAC8APw8AAAAACv//" + "//8BAf////8AAAAAFWCJCgIAAAAAAAgAAABwcmVzc3VyZQEBEAAALwA/EAAAAAAK/////wEB/////wAA" + "AAAVYIkKAgAAAAAACAAAAHRpcmV0eXBlAQERAAAvAD8RAAAAAQEBAP////8BAf////8AAAAAFWCJCgIA" + "AAAAAAUAAABNb2RlbAEBEgAALwA/EgAAAAAM/////wEB/////wAAAAA="; #endregion #endif #endregion #region Public Properties /// <summary> /// A description for the weight Property. /// </summary> public PropertyState<float> weight { get { return m_weight; } set { if (!Object.ReferenceEquals(m_weight, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_weight = value; } } /// <summary> /// A description for the wheels Property. /// </summary> public WheelVariableState wheels { get { return m_wheels; } set { if (!Object.ReferenceEquals(m_wheels, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_wheels = value; } } /// <summary> /// A description for the Model Variable. /// </summary> public BaseDataVariableState<string> Model { get { return m_model; } set { if (!Object.ReferenceEquals(m_model, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_model = value; } } #endregion #region Overridden Methods /// <summary> /// Populates a list with the children that belong to the node. /// </summary> /// <param name="context">The context for the system being accessed.</param> /// <param name="children">The list of children to populate.</param> public override void GetChildren( ISystemContext context, IList<BaseInstanceState> children) { if (m_weight != null) { children.Add(m_weight); } if (m_wheels != null) { children.Add(m_wheels); } if (m_model != null) { children.Add(m_model); } base.GetChildren(context, children); } /// <summary> /// Finds the child with the specified browse name. /// </summary> protected override BaseInstanceState FindChild( ISystemContext context, QualifiedName browseName, bool createOrReplace, BaseInstanceState replacement) { if (QualifiedName.IsNull(browseName)) { return null; } BaseInstanceState instance = null; switch (browseName.Name) { case Prefix0.BrowseNames.weight: { if (createOrReplace) { if (weight == null) { if (replacement == null) { weight = new PropertyState<float>(this); } else { weight = (PropertyState<float>)replacement; } } } instance = weight; break; } case Prefix0.BrowseNames.wheels: { if (createOrReplace) { if (wheels == null) { if (replacement == null) { wheels = new WheelVariableState(this); } else { wheels = (WheelVariableState)replacement; } } } instance = wheels; break; } case Prefix0.BrowseNames.Model: { if (createOrReplace) { if (Model == null) { if (replacement == null) { Model = new BaseDataVariableState<string>(this); } else { Model = (BaseDataVariableState<string>)replacement; } } } instance = Model; break; } } if (instance != null) { return instance; } return base.FindChild(context, browseName, createOrReplace, replacement); } #endregion #region Private Fields private PropertyState<float> m_weight; private WheelVariableState m_wheels; private BaseDataVariableState<string> m_model; #endregion } #endif #endregion #region WheelVariableState Class #if (!OPCUA_EXCLUDE_WheelVariableState) /// <summary> /// Stores an instance of the WheelVariableType VariableType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public partial class WheelVariableState : BaseDataVariableState<WheelDataType> { #region Constructors /// <summary> /// Initializes the type with its default attribute values. /// </summary> public WheelVariableState(NodeState parent) : base(parent) { } /// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return Opc.Ua.NodeId.Create(Prefix2.VariableTypes.WheelVariableType, Prefix2.Namespaces.Name2, namespaceUris); } /// <summary> /// Returns the id of the default data type node for the instance. /// </summary> protected override NodeId GetDefaultDataTypeId(NamespaceTable namespaceUris) { return Opc.Ua.NodeId.Create(Prefix2.DataTypes.WheelDataType, Prefix2.Namespaces.Name2, namespaceUris); } /// <summary> /// Returns the id of the default value rank for the instance. /// </summary> protected override int GetDefaultValueRank() { return ValueRanks.Scalar; } #if (!OPCUA_EXCLUDE_InitializationStrings) /// <summary> /// Initializes the instance. /// </summary> protected override void Initialize(ISystemContext context) { Initialize(context, InitializationString); InitializeOptionalChildren(context); } protected override void Initialize(ISystemContext context, NodeState source) { InitializeOptionalChildren(context); base.Initialize(context, source); } /// <summary> /// Initializes the any option children defined for the instance. /// </summary> protected override void InitializeOptionalChildren(ISystemContext context) { base.InitializeOptionalChildren(context); } #region Initialization String private const string InitializationString = "AQ<KEY>" + "Z<KEY>" + "AAAvAD8UAAAAAAr/////AQH/////AAAA<KEY>AAAAAA<KEY>AAAAA" + "Cv////8BAf////8AAAAAFWCJCgIAAAAAAAgAAABwcmVzc3VyZQEBFgAALwA/FgAAAAAK/////wEB////" + "/wAAAAAVYIkKAgAAAAAACAAAAHRpcmV0eXBlAQEXAAAvAD8XAAAAAQEBAP////8BAf////8AAAAA"; #endregion #endif #endregion #region Public Properties /// <summary> /// A description for the tickness Variable. /// </summary> public BaseDataVariableState<float> tickness { get { return m_tickness; } set { if (!Object.ReferenceEquals(m_tickness, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_tickness = value; } } /// <summary> /// A description for the diameter Variable. /// </summary> public BaseDataVariableState<float> diameter { get { return m_diameter; } set { if (!Object.ReferenceEquals(m_diameter, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_diameter = value; } } /// <summary> /// A description for the pressure Variable. /// </summary> public BaseDataVariableState<float> pressure { get { return m_pressure; } set { if (!Object.ReferenceEquals(m_pressure, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_pressure = value; } } /// <summary> /// A description for the tiretype Variable. /// </summary> public BaseDataVariableState<TireEnum> tiretype { get { return m_tiretype; } set { if (!Object.ReferenceEquals(m_tiretype, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_tiretype = value; } } #endregion #region Overridden Methods /// <summary> /// Populates a list with the children that belong to the node. /// </summary> /// <param name="context">The context for the system being accessed.</param> /// <param name="children">The list of children to populate.</param> public override void GetChildren( ISystemContext context, IList<BaseInstanceState> children) { if (m_tickness != null) { children.Add(m_tickness); } if (m_diameter != null) { children.Add(m_diameter); } if (m_pressure != null) { children.Add(m_pressure); } if (m_tiretype != null) { children.Add(m_tiretype); } base.GetChildren(context, children); } /// <summary> /// Finds the child with the specified browse name. /// </summary> protected override BaseInstanceState FindChild( ISystemContext context, QualifiedName browseName, bool createOrReplace, BaseInstanceState replacement) { if (QualifiedName.IsNull(browseName)) { return null; } BaseInstanceState instance = null; switch (browseName.Name) { case Prefix0.BrowseNames.tickness: { if (createOrReplace) { if (tickness == null) { if (replacement == null) { tickness = new BaseDataVariableState<float>(this); } else { tickness = (BaseDataVariableState<float>)replacement; } } } instance = tickness; break; } case Prefix0.BrowseNames.diameter: { if (createOrReplace) { if (diameter == null) { if (replacement == null) { diameter = new BaseDataVariableState<float>(this); } else { diameter = (BaseDataVariableState<float>)replacement; } } } instance = diameter; break; } case Prefix0.BrowseNames.pressure: { if (createOrReplace) { if (pressure == null) { if (replacement == null) { pressure = new BaseDataVariableState<float>(this); } else { pressure = (BaseDataVariableState<float>)replacement; } } } instance = pressure; break; } case Prefix0.BrowseNames.tiretype: { if (createOrReplace) { if (tiretype == null) { if (replacement == null) { tiretype = new BaseDataVariableState<TireEnum>(this); } else { tiretype = (BaseDataVariableState<TireEnum>)replacement; } } } instance = tiretype; break; } } if (instance != null) { return instance; } return base.FindChild(context, browseName, createOrReplace, replacement); } #endregion #region Private Fields private BaseDataVariableState<float> m_tickness; private BaseDataVariableState<float> m_diameter; private BaseDataVariableState<float> m_pressure; private BaseDataVariableState<TireEnum> m_tiretype; #endregion } #region WheelVariableValue Class /// <summary> /// A typed version of the _BrowseName_ variable. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public class WheelVariableValue : BaseVariableValue { #region Constructors /// <summary> /// Initializes the instance with its defalt attribute values. /// </summary> public WheelVariableValue(WheelVariableState variable, WheelDataType value, object dataLock) : base(dataLock) { m_value = value; if (m_value == null) { m_value = new WheelDataType(); } Initialize(variable); } #endregion #region Public Members /// <summary> /// The variable that the value belongs to. /// </summary> public WheelVariableState Variable { get { return m_variable; } } /// <summary> /// The value of the variable. /// </summary> public WheelDataType Value { get { return m_value; } set { m_value = value; } } #endregion #region Private Methods /// <summary> /// Initializes the object. /// </summary> private void Initialize(WheelVariableState variable) { lock (Lock) { m_variable = variable; variable.Value = m_value; variable.OnReadValue = OnReadValue; variable.OnSimpleWriteValue = OnWriteValue; BaseVariableState instance = null; List<BaseInstanceState> updateList = new List<BaseInstanceState>(); updateList.Add(variable); instance = m_variable.tickness; instance.OnReadValue = OnRead_tickness; instance.OnSimpleWriteValue = OnWrite_tickness; updateList.Add(instance); instance = m_variable.diameter; instance.OnReadValue = OnRead_diameter; instance.OnSimpleWriteValue = OnWrite_diameter; updateList.Add(instance); instance = m_variable.pressure; instance.OnReadValue = OnRead_pressure; instance.OnSimpleWriteValue = OnWrite_pressure; updateList.Add(instance); SetUpdateList(updateList); } } /// <summary> /// Reads the value of the variable. /// </summary> protected ServiceResult OnReadValue( ISystemContext context, NodeState node, NumericRange indexRange, QualifiedName dataEncoding, ref object value, ref StatusCode statusCode, ref DateTime timestamp) { lock (Lock) { DoBeforeReadProcessing(context, node); if (m_value != null) { value = m_value; } return Read(context, node, indexRange, dataEncoding, ref value, ref statusCode, ref timestamp); } } /// <summary> /// Writes the value of the variable. /// </summary> private ServiceResult OnWriteValue(ISystemContext context, NodeState node, ref object value) { lock (Lock) { m_value = (WheelDataType)Write(value); } return ServiceResult.Good; } #region tickness Access Methods /// <summary> /// Reads the value of the variable child. /// </summary> private ServiceResult OnRead_tickness( ISystemContext context, NodeState node, NumericRange indexRange, QualifiedName dataEncoding, ref object value, ref StatusCode statusCode, ref DateTime timestamp) { lock (Lock) { DoBeforeReadProcessing(context, node); if (m_value != null) { value = m_value.tickness; } return Read(context, node, indexRange, dataEncoding, ref value, ref statusCode, ref timestamp); } } /// <summary> /// Writes the value of the variable child. /// </summary> private ServiceResult OnWrite_tickness(ISystemContext context, NodeState node, ref object value) { lock (Lock) { m_value.tickness = (float)Write(value); } return ServiceResult.Good; } #endregion #region diameter Access Methods /// <summary> /// Reads the value of the variable child. /// </summary> private ServiceResult OnRead_diameter( ISystemContext context, NodeState node, NumericRange indexRange, QualifiedName dataEncoding, ref object value, ref StatusCode statusCode, ref DateTime timestamp) { lock (Lock) { DoBeforeReadProcessing(context, node); if (m_value != null) { value = m_value.diameter; } return Read(context, node, indexRange, dataEncoding, ref value, ref statusCode, ref timestamp); } } /// <summary> /// Writes the value of the variable child. /// </summary> private ServiceResult OnWrite_diameter(ISystemContext context, NodeState node, ref object value) { lock (Lock) { m_value.diameter = (float)Write(value); } return ServiceResult.Good; } #endregion #region pressure Access Methods /// <summary> /// Reads the value of the variable child. /// </summary> private ServiceResult OnRead_pressure( ISystemContext context, NodeState node, NumericRange indexRange, QualifiedName dataEncoding, ref object value, ref StatusCode statusCode, ref DateTime timestamp) { lock (Lock) { DoBeforeReadProcessing(context, node); if (m_value != null) { value = m_value.pressure; } return Read(context, node, indexRange, dataEncoding, ref value, ref statusCode, ref timestamp); } } /// <summary> /// Writes the value of the variable child. /// </summary> private ServiceResult OnWrite_pressure(ISystemContext context, NodeState node, ref object value) { lock (Lock) { m_value.pressure = (float)Write(value); } return ServiceResult.Good; } #endregion #endregion #region Private Fields private WheelDataType m_value; private WheelVariableState m_variable; #endregion } #endregion #endif #endregion } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/ModelFactoryTestingFixture/NodeFactoryBase.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System.Collections.Generic; using System.Xml; using UAOOI.SemanticData.InformationModelFactory; using UAOOI.SemanticData.InformationModelFactory.UAConstants; namespace UAOOI.SemanticData.UANodeSetValidation.ModelFactoryTestingFixture { /// <summary> /// Class NodeFactoryBase. /// Implements the <see cref="UAOOI.SemanticData.UANodeSetValidation.InformationModelFactory.NodesContainer" /> /// Implements the <see cref="UAOOI.SemanticData.InformationModelFactory.INodeFactory" /> /// </summary> /// <seealso cref="UAOOI.SemanticData.UANodeSetValidation.InformationModelFactory.NodesContainer" /> /// <seealso cref="UAOOI.SemanticData.InformationModelFactory.INodeFactory" /> internal class NodeFactoryBase : NodesContainer, INodeFactory { /// <summary> /// It holds the value of the BrowseName attribute of modes in the Address Space. /// </summary> /// <value>The BrowseName of the node.</value> public string BrowseName { set; get; } /// <summary> /// Add new reference to the references collection of the node. This collection represents all the references defined by the selected Information Model including /// references to the instance declarations nodes. The References list specifies references that must be created for the node during Address Space instantiation. /// The reference can be forward or inverse. /// </summary> /// <returns>IReferenceFactory.</returns> public IReferenceFactory NewReference() { ReferenceFactoryBase _ret = new ReferenceFactoryBase(); m_References.Add(_ret); return _ret; } /// <summary> /// Sets the a symbolic name for the node that can be used as a class/field name by a design tools to enhance auto-generated code. /// It should only be specified if the BrowseName cannot be used for this purpose. This field is not used directly to instantiate /// Address Space and is intended for use by design tools. Only letters, digits or the underscore (‘_’) are permitted. /// This attribute is not exposed in the Address Space. /// </summary> /// <value>The symbolic name for the node.</value> public XmlQualifiedName SymbolicName { set; internal get; } /// <summary> /// Sets the write mask. The optional WriteMask attribute represents the WriteMask attribute of the Basic NodeClass, which exposes the possibilities of a client /// to write the attributes of the node. The WriteMask attribute does not take any user access rights into account, that is, although an attribute is writable /// this may be restricted to a certain user/user group. /// </summary> /// <value>The write access.</value> /// <remarks>Default Value "0"</remarks> public uint WriteAccess { set { } } /// <summary> /// Sets the access restrictions. /// </summary> /// <value>The access restrictions.</value> /// <remarks>The AccessRestrictions that apply to the Node.</remarks> public AccessRestrictions AccessRestrictions { set { } } /// <summary> /// Sets the release status of the node. /// </summary> /// <value>The release status.</value> /// <remarks>It is not exposed in the address space. /// Added in the Rel 1.04 to the specification.</remarks> public ReleaseStatus ReleaseStatus { set { } } /// <summary> /// Sets the data type purpose. /// </summary> /// <value>The data type purpose.</value> /// <remarks>Not defined in the specification Part 2, 5, 6 and Errata Release 1.04.2 September 25, 2018</remarks> public DataTypePurpose DataTypePurpose { set { } } /// <summary> /// Sets the category. A list of identifiers used to group related UANodes together for use by tools that create/edit UANodeSet files. /// </summary> /// <value>The category.</value> /// <exception cref="System.NotImplementedException"></exception> public string[] Category { set { } } /// <summary> /// Adds new value for the Description. The optional Description element shall explain the meaning of the node in a localized text using the same mechanisms /// for localization as described for the DisplayName. /// </summary> /// <param name="localeField">The locale field.</param> /// <param name="valueField">The value field.</param> public void AddDescription(string localeField, string valueField) { } /// <summary> /// Adds new value for the DisplayName. The DisplayName attribute contains the localized name of the node. /// Clients should use this attribute if they want to display the name of the node to the user. They should not use /// the BrowseName for this purpose. The server may maintain one or more localized representations for each DisplayName. /// Clients negotiate the locale to be returned when they open a session with the server. The section DisplayName defines the structure of the DisplayName. /// The string part of the DisplayName is restricted to 512 characters. /// </summary> /// <param name="localeField">The locale field.</param> /// <param name="valueField">The value field.</param> public void AddDisplayName(string localeField, string valueField) { } protected List<ReferenceFactoryBase> m_References = new List<ReferenceFactoryBase>(); } } <|start_filename|>SemanticData/UANodeSetValidation/IAddressSpaceBuildContext.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using System.Collections.Generic; using System.Xml; using UAOOI.SemanticData.InformationModelFactory; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.SemanticData.UANodeSetValidation { /// <summary> /// Interface IAddressSpaceBuildContext representing the Address Space Context used during build operation /// </summary> internal interface IAddressSpaceBuildContext { /// <summary> /// Exports the browse name if it is not default value, otherwise null. /// </summary> /// <param name="id">The identifier.</param> /// <param name="defaultValue">The default value.</param> /// <returns>XmlQualifiedName.</returns> XmlQualifiedName ExportBrowseName(NodeId id, NodeId defaultValue); /// <summary> /// Exports the argument for a method. /// </summary> /// <param name="argument">The argument - it defines a Method input or output argument specification. It is for example used in the input and output argument Properties for Methods.</param> /// <param name="dataType">Type of the data.</param> Parameter ExportArgument(DataSerialization.Argument argument, XmlQualifiedName dataType); /// <summary> /// Gets the or create node context. /// </summary> /// <param name="nodeId">The node identifier.</param> /// <param name="createUAModelContext">Delegated capturing functionality to create UA model context.</param> /// <returns>Returns an instance of <see cref="IUANodeContext"/>.</returns> IUANodeContext GetOrCreateNodeContext(NodeId nodeId, Func<NodeId, IUANodeContext> createUAModelContext); /// <summary> /// Gets the namespace value as the <see cref="string"/>. /// </summary> /// <param name="namespaceIndex">Index of the namespace.</param> /// <returns>The namespace of the index pointed out by the <paramref name="namespaceIndex"/></returns> string GetNamespace(ushort namespaceIndex); /// <summary> /// Gets my references. /// </summary> /// <param name="node">The source node</param> /// <returns>Returns <see cref="IEnumerable{UAReferenceContex}"/> containing references attached to the <paramref name="node"/>.</returns> IEnumerable<UAReferenceContext> GetMyReferences(IUANodeBase node); /// <summary> /// Gets the references to me. /// </summary> /// <param name="node">The node in concern.</param> /// <returns>All references targeting the <paramref name="node"/> node</returns> IEnumerable<UAReferenceContext> GetReferences2Me(IUANodeBase node); /// <summary> /// Gets the children nodes (<see cref="ReferenceKindEnum.HasProperty"/> or <see cref="ReferenceKindEnum.HasComponent"/>) for the <paramref name="node" />. /// </summary> /// <param name="node">The root node of the requested children.</param> /// <returns>Return an instance of <see cref="IEnumerable{IUANodeBase}"/> capturing all children of the selected node.</returns> IEnumerable<IUANodeBase> GetChildren(IUANodeBase node); /// <summary> /// Exports the argument. /// </summary> /// <param name="argument">The argument.</param> /// <returns>An instance encapsulating <see cref="Parameter"/>.</returns> Parameter ExportArgument(Argument argument); void GetBaseTypes(IUANodeContext rootNode, List<IUANodeContext> inheritanceChain); } } <|start_filename|>DataDiscovery/DiscoveryServices/Models/SemanticsDataIndex.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ namespace UAOOI.DataDiscovery.DiscoveryServices.Models { /// <summary> /// Class SemanticsDataIndex - provides description of a set of data items representing the current state of a selected object uniquely named by the <see cref="SemanticsDataIndex.SymbolicName"/>. /// </summary> /// <remarks> /// Each Semantic data belongs to the only one domain and must have symbolic name unique in context of the domain. /// <see cref="SemanticsDataIndex.Index"/> is used to replace the symbolic name with the purpose of optimization of the data transfer. /// </remarks> public partial class SemanticsDataIndex { } } <|start_filename|>SemanticData/UANodeSetValidation/Extensions.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Xml; using System.Xml.Serialization; using UAOOI.Common.Infrastructure.Serializers; using UAOOI.SemanticData.BuildingErrorsHandling; using UAOOI.SemanticData.InformationModelFactory; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; using UAOOI.SemanticData.UANodeSetValidation.UAInformationModel; namespace UAOOI.SemanticData.UANodeSetValidation { /// <summary> /// Delegate LocalizedTextFactory - encapsulates a method that must be used to create localized text using <paramref name="localeField"/> and <paramref name="valueField"/> /// </summary> /// <param name="localeField">The locale field. This argument is specified as a <see cref="string"/> that is composed of a language component and a country/region /// component as specified by RFC 3066. The country/region component is always preceded by a hyphen. The format of the LocaleId string is shown below: /// <c> /// &lt;language&gt;[-&lt;country/region&gt;], /// where: /// &lt;language&gt; is the two letter ISO 639 code for a language, /// &lt;country/region&gt; is the two letter ISO 3166 code for the country/region. /// </c> /// </param> /// <param name="valueField">The value field.</param> internal delegate void LocalizedTextFactory(string localeField, string valueField); /// <summary> /// Class Extensions - provides helper functions for this namespace /// </summary> internal static class Extensions { //string internal static string SymbolicName(this List<string> path) { return string.Join("_", path.ToArray()); } /// <summary> /// Exports the string and filter out the default value. /// </summary> /// <param name="value">The value.</param> /// <param name="defaultValue">The default value.</param> /// <returns>Returns <paramref name="value"/> if not equal to <paramref name="defaultValue"/>, otherwise it returns <see cref="string.Empty"/>.</returns> internal static string ExportString(this string value, string defaultValue) { if (string.IsNullOrEmpty(value)) return null; return string.Compare(value, defaultValue) == 0 ? null : value; } internal static bool? Export(this bool value, bool defaultValue) { return !value.Equals(defaultValue) ? value : new Nullable<bool>(); } internal static int? Export(this double value, double defaultValue) { return !value.Equals(defaultValue) ? Convert.ToInt32(value) : new Nullable<int>(); } internal static uint Validate(this uint value, uint maxValue, Action<uint> reportError) { if (value.CompareTo(maxValue) >= 0) reportError(value); return value & maxValue - 1; } //TODO IsValidLanguageIndependentIdentifier is not supported by the .NET standard #340 /// <summary> /// Gets a value indicating whether the specified value is a valid language independent identifier. /// </summary> /// <remarks> /// it is implemented using /// https://raw.githubusercontent.com/Microsoft/referencesource/3b1eaf5203992df69de44c783a3eda37d3d4cd10/System/compmod/system/codedom/compiler/CodeGenerator.cs as the starting point. /// </remarks> private static bool IsValidLanguageIndependentIdentifier(this string value) { if (value.Length == 0) return false; // each char must be Lu, Ll, Lt, Lm, Lo, Nd, Mn, Mc, Pc for (int i = 0; i < value.Length; i++) { char ch = value[i]; UnicodeCategory uc = char.GetUnicodeCategory(ch); switch (uc) { case UnicodeCategory.UppercaseLetter: // Lu case UnicodeCategory.LowercaseLetter: // Ll case UnicodeCategory.TitlecaseLetter: // Lt case UnicodeCategory.ModifierLetter: // Lm case UnicodeCategory.LetterNumber: // Lm case UnicodeCategory.OtherLetter: // Lo break; case UnicodeCategory.NonSpacingMark: // Mn case UnicodeCategory.SpacingCombiningMark: // Mc case UnicodeCategory.ConnectorPunctuation: // Pc case UnicodeCategory.DecimalDigitNumber: // Nd // Underscore is a valid starting character, even though it is a ConnectorPunctuation. //if (nextMustBeStartChar && ch != '_') // return false; break; default: return false; } } return true; } internal static string ValidateIdentifier(this string name, Action<TraceMessage> reportError) { if (!name.IsValidLanguageIndependentIdentifier()) reportError(TraceMessage.BuildErrorTraceMessage(BuildError.WrongSymbolicName, string.Format("SymbolicName: '{0}'.", name))); return name; } internal static string NodeIdentifier(this XML.UANode node) { if (string.IsNullOrEmpty(node.BrowseName)) return node.SymbolicName; return node.BrowseName; } internal static string ConvertToString(this XML.LocalizedText[] localizedText) { if (localizedText == null || localizedText.Length == 0) return "Empty LocalizedText"; return string.Format("{0}:{1}", localizedText[0].Locale, localizedText[0].Value); } /// <summary> /// Converts the ArrayDimensions represented as the array of <seealso cref="uint"/> to string. /// </summary> /// <remarks> /// The maximum length of an array. /// This value is a comma separated list of unsigned integer values.The list has a number of elements equal to the ValueRank. /// The value is 0 if the maximum is not known for a dimension. /// This field is not specified if the ValueRank less or equal 0. /// This field is not specified for subtypes of Enumeration or for DataTypes with the OptionSetValues Property. /// </remarks> /// <param name="arrayDimensions">The array dimensions represented as the string.</param> /// <returns>System.String.</returns> internal static string ArrayDimensionsToString(this uint[] arrayDimensions) { return string.Join(", ", arrayDimensions); } internal static void GetParameters(this XML.DataTypeDefinition dataTypeDefinition, IDataTypeDefinitionFactory dataTypeDefinitionFactory, IAddressSpaceBuildContext nodeContext, Action<TraceMessage> traceEvent) { if (dataTypeDefinition is null) return; //xsd comment < !--BaseType is obsolete and no longer used.Left in for backwards compatibility. --> //definition.BaseType = modelContext.ExportBrowseName(dataTypeDefinition.BaseType, DataTypes.BaseDataType); dataTypeDefinitionFactory.IsOptionSet = dataTypeDefinition.IsOptionSet; dataTypeDefinitionFactory.IsUnion = dataTypeDefinition.IsUnion; dataTypeDefinitionFactory.Name = null; //TODO UADataType.Definition.Name wrong value #341 modelContext.ExportBrowseName( dataTypeDefinition.Name, DataTypes.BaseDataType); dataTypeDefinitionFactory.SymbolicName = dataTypeDefinition.SymbolicName; if (dataTypeDefinition.Field == null || dataTypeDefinition.Field.Length == 0) return; foreach (XML.DataTypeField _item in dataTypeDefinition.Field) { IDataTypeFieldFactory _nP = dataTypeDefinitionFactory.NewField(); _nP.Name = _item.Name; _nP.SymbolicName = _item.SymbolicName; _item.DisplayName.ExportLocalizedTextArray(_nP.AddDisplayName); _nP.DataType = nodeContext.ExportBrowseName(_item.DataTypeNodeId, DataTypes.BaseDataType); _nP.ValueRank = _item.ValueRank.GetValueRank(traceEvent); _nP.ArrayDimensions = _item.ArrayDimensions; _nP.MaxStringLength = _item.MaxStringLength; _item.Description.ExportLocalizedTextArray(_nP.AddDescription); _nP.Value = _item.Value; _nP.IsOptional = _item.IsOptional; } } internal static void ExportLocalizedTextArray(this XML.LocalizedText[] text, LocalizedTextFactory createLocalizedText) { if (text == null || text.Length == 0) return; foreach (XML.LocalizedText item in text) createLocalizedText(item.Locale, item.Value); } internal static XML.LocalizedText[] Truncate(this XML.LocalizedText[] localizedText, int maxLength, Action<TraceMessage> reportError) { if (localizedText == null || localizedText.Length == 0) return null; List<XML.LocalizedText> _ret = new List<XML.LocalizedText>(); foreach (XML.LocalizedText _item in localizedText) { if (_item.Value.Length > maxLength) { reportError(TraceMessage.BuildErrorTraceMessage(BuildError.WrongDisplayNameLength, string.Format ("The localized text starting with '{0}:{1}' of length {2} is too long.", _item.Locale, _item.Value.Substring(0, 20), _item.Value.Length))); XML.LocalizedText _localizedText = new XML.LocalizedText() { Locale = _item.Locale, Value = _item.Value.Substring(0, maxLength) }; } } return localizedText; } internal static List<DataSerialization.Argument> GetParameters(this XmlElement xmlElement) { //TODO UANodeSetValidation.Extensions.GetObject - object reference not set #624 ListOfExtensionObject _wrapper = xmlElement.GetObject<ListOfExtensionObject>(); Debug.Assert(_wrapper != null); if (_wrapper.ExtensionObject.AsEnumerable<ExtensionObject>().Where<ExtensionObject>(x => !((string)x.TypeId.Identifier).Equals("i=297")).Any()) throw new ArgumentOutOfRangeException("ExtensionObject.TypeId.Identifier"); List<DataSerialization.Argument> _ret = new List<DataSerialization.Argument>(); foreach (ExtensionObject item in _wrapper.ExtensionObject) _ret.Add(item.Body.GetObject<DataSerialization.Argument>()); return _ret; } internal static ReleaseStatus ConvertToReleaseStatus(this XML.ReleaseStatus releaseStatus) { ReleaseStatus _status = ReleaseStatus.Released; switch (releaseStatus) { case XML.ReleaseStatus.Released: _status = ReleaseStatus.Released; break; case XML.ReleaseStatus.Draft: _status = ReleaseStatus.Draft; break; case XML.ReleaseStatus.Deprecated: _status = ReleaseStatus.Deprecated; break; } return _status; } internal static DataTypePurpose ConvertToDataTypePurpose(this XML.DataTypePurpose releaseStatus) { DataTypePurpose _status = DataTypePurpose.Normal; switch (releaseStatus) { case XML.DataTypePurpose.Normal: _status = DataTypePurpose.Normal; break; case XML.DataTypePurpose.CodeGenerator: _status = DataTypePurpose.CodeGenerator; break; case XML.DataTypePurpose.ServicesOnly: _status = DataTypePurpose.ServicesOnly; break; } return _status; } internal static bool LocalizedTextArraysEqual(this XML.LocalizedText[] first, XML.LocalizedText[] second) { if (Object.ReferenceEquals(first, null)) return Object.ReferenceEquals(second, null); if (Object.ReferenceEquals(second, null)) return false; if (first.Length != second.Length) return false; try { Dictionary<string, XML.LocalizedText> _dictionaryForFirst = first.ToDictionary(x => ConvertToString(x)); foreach (XML.LocalizedText _text in second) if (!_dictionaryForFirst.ContainsKey(ConvertToString(_text))) return false; } catch (Exception) { return false; } return true; } internal static bool RolePermissionsEquals(this XML.RolePermission[] first, XML.RolePermission[] second) { if (Object.ReferenceEquals(first, null)) return Object.ReferenceEquals(second, null); if (first.Length != second.Length) return false; Dictionary<uint, XML.RolePermission> _dictionaryForFirst = first.ToDictionary<XML.RolePermission, uint>(x => x.Permissions); foreach (XML.RolePermission _permission in second) { if (!_dictionaryForFirst.ContainsKey(_permission.Permissions)) return false; if (_dictionaryForFirst[_permission.Permissions].Value != _permission.Value) return false; } return true; } internal static bool ReferencesEquals(this XML.Reference[] first, XML.Reference[] second) { return true; } internal static bool AreEqual(this string first, string second) { if (String.IsNullOrEmpty(first)) return String.IsNullOrEmpty(second); return String.Compare(first, second) == 0; } #region private private static string ConvertToString(XML.LocalizedText x) { return $"{ x.Locale}:{x.Value}"; } /// <summary> /// Deserialize <see cref="XmlElement" /> object using <see cref="XmlSerializer" /> /// </summary> /// <typeparam name="type">The type of the type.</typeparam> /// <param name="xmlElement">The object to be deserialized.</param> /// <returns>Deserialized object</returns> private static type GetObject<type>(this XmlElement xmlElement) { using (MemoryStream _memoryBuffer = new MemoryStream(1000)) { XmlWriterSettings _settings = new XmlWriterSettings() { ConformanceLevel = ConformanceLevel.Fragment }; using (XmlWriter wrt = XmlWriter.Create(_memoryBuffer, _settings)) //TODO UANodeSetValidation.Extensions.GetObject - object reference not set #624 xmlElement.WriteTo(wrt); _memoryBuffer.Flush(); _memoryBuffer.Position = 0; return XmlFile.ReadXmlFile<type>(_memoryBuffer); } } #endregion private } } <|start_filename|>Networking/Simulator.Boiler/AddressSpace/BaseInstanceState.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using System.Collections.Generic; using UAOOI.SemanticData.UANodeSetValidation; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.Networking.Simulator.Boiler.AddressSpace { /// <summary> /// Used to receive notifications when a non-value attribute is read or written. /// </summary> public delegate void NodeStateChangedHandler(ISystemContext context, NodeState node, NodeStateChangeMasks changes); /// <summary> /// Class BaseInstanceState. /// </summary> /// <seealso cref="UAOOI.Networking.Simulator.Boiler.AddressSpace.NodeState" /> public class BaseInstanceState : NodeState { /// <summary> /// Initializes the instance with its default attribute values. /// </summary> protected BaseInstanceState(NodeState parent, NodeClass nodeClass, QualifiedName browseName) : base(nodeClass, browseName) { if (parent == null) return; Parent = (BaseInstanceState)parent; Parent.AddChild(this); } [Obsolete()] public BaseInstanceState(NodeState parent) : base(parent) { } /// <summary> /// The parent node. /// </summary> public BaseInstanceState Parent { get; internal set; } /// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> /// <param name="namespaceUris">The namespace uris.</param> /// <returns></returns> protected virtual NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return null; } /// <summary> /// Finds the child with the specified browse path. /// </summary> /// <param name="context">The context to use.</param> /// <param name="browsePath">The browse path.</param> /// <param name="index">The current position in the browse path.</param> /// <returns>The target if found. Null otherwise.</returns> public virtual BaseInstanceState FindChild(ISystemContext context, IList<QualifiedName> browsePath, int index) { if (index < 0 || index >= int.MaxValue) throw new ArgumentOutOfRangeException("index"); BaseInstanceState instance = FindChild(context, browsePath[index], false, null); if (instance != null) { if (browsePath.Count == index + 1) return instance; return instance.FindChild(context, browsePath, index + 1); } return null; } /// <summary> /// Finds the child with the specified browse name. /// </summary> /// <param name="context">The context for the system being accessed.</param> /// <param name="browseName">The browse name of the children to add.</param> /// <param name="createOrReplace">if set to <c>true</c> and the child could exist then the child is created.</param> /// <param name="replacement">The replacement to use if createOrReplace is true.</param> /// <returns>The child.</returns> protected virtual BaseInstanceState FindChild(ISystemContext context, QualifiedName browseName, bool createOrReplace, BaseInstanceState replacement) { if (QualifiedName.IsNull(browseName)) return null; for (int ii = 0; ii < m_children.Count; ii++) { BaseInstanceState child = m_children[ii]; if (browseName == child.BrowseName) { if (createOrReplace && replacement != null) m_children[ii] = child = replacement; return child; } } if (createOrReplace) { if (replacement != null) AddChild(replacement); } return null; } /// <summary> /// Populates a list with the children that belong to the node. /// </summary> /// <param name="context">The context for the system being accessed.</param> /// <param name="children">The list of children to populate.</param> /// <exception cref="System.NotImplementedException">This method is added to avoid compiler errors only</exception> [Obsolete("This method is added to avoid compiler errors only and will cause NotImplementedException")] public virtual void GetChildren(ISystemContext context, IList<BaseInstanceState> children) { throw new NotImplementedException("This method is added to avoid compiler errors only"); } /// <summary> /// Populates a list with the children that belong to the node. /// </summary> /// <param name="children">The list of children to populate.</param> public void GetChildren(IList<BaseInstanceState> children) { for (int ii = 0; ii < m_children.Count; ii++) children.Add(m_children[ii]); } /// <summary> /// Clears the change masks. /// </summary> /// <param name="context">The context that describes how access the system containing the data..</param> /// <param name="includeChildren">if set to <c>true</c> clear masks recursively for all children..</param> public void ClearChangeMasks(ISystemContext context, bool includeChildren) { if (includeChildren) { List<BaseInstanceState> children = new List<BaseInstanceState>(); GetChildren(children); for (int ii = 0; ii < children.Count; ii++) children[ii].ClearChangeMasks(context, true); } if (ChangeMasks == NodeStateChangeMasks.None) return; OnStateChanged?.Invoke(context, this, ChangeMasks); ChangeMasks = NodeStateChangeMasks.None; } /// <summary> /// Called when ClearChangeMasks is called and the ChangeMask is not None. /// </summary> public event NodeStateChangedHandler OnStateChanged; /// <summary> /// Adds a child to the node. /// </summary> internal void AddChild(BaseInstanceState child) { m_children.Add(child); ChangeMasks |= NodeStateChangeMasks.Children; } internal void RegisterVariable(IReadOnlyList<BaseInstanceState> hasComponentPath, Action<BaseInstanceState, string[]> register) { List<BaseInstanceState> _hasComponentPathAndMe = new List<BaseInstanceState>(hasComponentPath) { this }; CallRegister(_hasComponentPathAndMe, register); List<BaseInstanceState> _myComponents = new List<BaseInstanceState>(); GetChildren(_myComponents); for (int ii = 0; ii < _myComponents.Count; ii++) { if (_myComponents[ii] == this) throw new ArgumentOutOfRangeException("Redundant browse path"); _myComponents[ii].RegisterVariable(_hasComponentPathAndMe, register); } } protected virtual void CallRegister(List<BaseInstanceState> hasComponentPathAndMe, Action<BaseInstanceState, string[]> register) { } private List<BaseInstanceState> m_children = new List<BaseInstanceState>(); } } <|start_filename|>Common/Infrastructure/Diagnostic/IEventSourceProvider.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System.Diagnostics.Tracing; namespace UAOOI.Common.Infrastructure.Diagnostic { /// <summary> /// Interface IEventSourceProvider - if implemented returns an instance of <see cref="EventSource"/> to be registered by the logging infrastructure. /// </summary> public interface IEventSourceProvider { /// <summary> /// Gets the part event source. /// </summary> /// <returns>Returns an instance of <see cref="EventSource"/>.</returns> EventSource GetPartEventSource(); } } <|start_filename|>SemanticData/UANodeSetValidation/XML/UANodeSetChanges.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using UAOOI.SemanticData.BuildingErrorsHandling; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.SemanticData.UANodeSetValidation.XML { /// <summary> /// Class UANodeSetChanges. /// </summary> public partial class UANodeSetChanges { internal void RecalculateNodeIds(IUAModelContext modelContext, Action<TraceMessage> trace) { Func<string, NodeId> importNodeId = x => modelContext.ImportNodeId(x, trace); if (this.Aliases != null) foreach (NodeIdAlias _alias in this.Aliases) _alias.RecalculateNodeIds(importNodeId); if (this.NodesToAdd != null) foreach (UANode _node in this.NodesToAdd) _node.RecalculateNodeIds(modelContext, trace); if (this.NodesToDelete != null) foreach (NodeToDelete _node in this.NodesToDelete) _node.RecalculateNodeIds(importNodeId); if (this.ReferencesToAdd != null) foreach (ReferenceChange _reference in this.ReferencesToAdd) _reference.RecalculateNodeIds(importNodeId); if (this.ReferencesToDelete != null) foreach (ReferenceChange _reference in this.ReferencesToDelete) _reference.RecalculateNodeIds(importNodeId); } } } <|start_filename|>SemanticData/UANodeSetValidation/XML/UANodeSet.Utils.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System; using System.IO; using System.Reflection; using UAOOI.Common.Infrastructure.Serializers; using UAOOI.SemanticData.BuildingErrorsHandling; namespace UAOOI.SemanticData.UANodeSetValidation.XML { public partial class UANodeSet : IUANodeSetModelHeader { #region API internal Uri ParseUAModelContext(INamespaceTable addressSpaceContext, Action<TraceMessage> traceEvent) { UAModelContext model = UAModelContext.ParseUANodeSetModelHeader(this, addressSpaceContext, traceEvent); this.RecalculateNodeIds(model, traceEvent); return model.DefaultUri; } #endregion API #region static helpers internal static UANodeSet ReadUADefinedTypes() { Assembly assembly = Assembly.GetExecutingAssembly(); UANodeSet uaDefinedTypes = null; using (Stream stream = assembly.GetManifestResourceStream(m_UADefinedTypesName)) uaDefinedTypes = XmlFile.ReadXmlFile<UANodeSet>(stream); if (uaDefinedTypes.Models is null || uaDefinedTypes.Models.Length == 0) throw new ArgumentNullException(nameof(UANodeSet.Models)); if (uaDefinedTypes.NamespaceUris is null) uaDefinedTypes.NamespaceUris = new string[] { uaDefinedTypes.Models[0].ModelUri }; return uaDefinedTypes; } internal static UANodeSet ReadModelFile(FileInfo path) { using (Stream stream = path.OpenRead()) return XmlFile.ReadXmlFile<UANodeSet>(stream); } #endregion static helpers #region private private const string m_UADefinedTypesName = @"UAOOI.SemanticData.UANodeSetValidation.XML.Opc.Ua.NodeSet2.xml"; //OPC UA standard NodeSet model resource folder. private void RecalculateNodeIds(IUAModelContext modelContext, Action<TraceMessage> trace) { if (this.Aliases != null) foreach (NodeIdAlias alias in this.Aliases) alias.RecalculateNodeIds(x => modelContext.ImportNodeId(x, trace)); if (this.Items != null) foreach (UANode item in Items) item.RecalculateNodeIds(modelContext, trace); } #endregion private } } <|start_filename|>SemanticData/UAModelDesignExport/XML/Resource.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System; using System.Globalization; using System.IO; using System.Reflection; using UAOOI.Common.Infrastructure.Serializers; namespace UAOOI.SemanticData.UAModelDesignExport.XML { /// <summary> /// Resources management helper class /// </summary> public static class UAResources { /// <summary> /// Loads the OPC UA defined types. /// </summary> /// <returns>An instance of <see cref="ModelDesign"/> representing UA defined types</returns> public static ModelDesign LoadUADefinedTypes() { try { Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream(UADefinedTypesName)) return XmlFile.ReadXmlFile<ModelDesign>(stream); } catch (Exception e) { throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "Could not load resource '{0}' because the exception {1} reports the error {2}.", UADefinedTypesName, e.GetType().Name, e.Message), e); } } private static string UADefinedTypesName => $"{typeof(UAResources).Namespace}.UA Defined Types.xml"; } } <|start_filename|>SemanticData/UANodeSetValidation/XML/DataTypeDefinition.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.SemanticData.UANodeSetValidation.XML { public partial class DataTypeDefinition { internal void RecalculateNodeIds(Func<string, NodeId> importNodeId) { //BaseType - is obsolete and no longer used. Left in for backwards compatibility. // this.Name - name should be QualifiedName but it is not. if (Field is null) return; foreach (DataTypeField _field in Field) _field.RecalculateNodeIds(importNodeId); } } } <|start_filename|>SemanticData/UANodeSetValidation/Diagnostic/AssemblyTraceSource.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System.Diagnostics; using UAOOI.Common.Infrastructure.Diagnostic; using UAOOI.SemanticData.BuildingErrorsHandling; namespace UAOOI.SemanticData.UANodeSetValidation.Diagnostic { /// <summary> /// Class AssemblyTraceSource. Implements the <see cref="ITraceSource" /> /// </summary> /// <seealso cref="ITraceSource" /> internal class AssemblyTraceSource : IBuildErrorsHandling { #region constructors /// <summary> /// Initializes a new instance of the <see cref="AssemblyTraceSource"/> class using the default of the <see cref="ITraceSource"/>. /// </summary> internal AssemblyTraceSource() { traceSource = new TraceSourceBase("UANodeSetValidation"); } /// <summary> /// Initializes a new instance of the <see cref="AssemblyTraceSource"/> class using a provided implementation of the <see cref="ITraceSource"/>. /// </summary> /// <param name="traceEvent">The provided implementation of the <see cref="ITraceSource"/>.</param> internal AssemblyTraceSource(ITraceSource traceEvent) { traceSource = traceEvent; } #endregion constructors #region IBuildErrorsHandling /// <summary> /// Writes the trace message. /// </summary> /// <param name="traceMessage">The trace message.</param> public void WriteTraceMessage(TraceMessage traceMessage) { traceSource.TraceData(traceMessage.TraceLevel, 43988162, traceMessage.ToString()); if (traceMessage.BuildError.Focus != Focus.Diagnostic) Errors++; } public int Errors { get; private set; } = 0; #endregion IBuildErrorsHandling #region ITraceSource /// <summary> /// Writes trace data to the trace listeners in the <see cref="P:System.Diagnostics.TraceSource.Listeners" /> collection using the specified <paramref name="eventType" />, /// event identifier <paramref name="id" />, and trace <paramref name="data" />. /// </summary> /// <param name="eventType">One of the enumeration values that specifies the event type of the trace data.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="data">The trace data.</param> public void TraceData(TraceEventType eventType, int id, object data) { traceSource.TraceData(eventType, id, data); } #endregion ITraceSource #region private private readonly ITraceSource traceSource; #endregion private } } <|start_filename|>SemanticData/UANodeSetValidation/XML/IUANodeSetModelHeader.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System.Xml; namespace UAOOI.SemanticData.UANodeSetValidation.XML { /// <summary> /// Interface IUANodeSetModelHeader - represents a structure of the <see cref="UANodeSet"/> document header. /// </summary> internal interface IUANodeSetModelHeader { /// <summary> /// Gets the list of NamespaceUris used in the <see cref="UANodeSet"/>. /// </summary> /// <value>An array of <see cref="string"/> representing URI.</value> string[] NamespaceUris { get; } /// <summary> /// Gets the list of ServerUris used in the <see cref="UANodeSet"/>. /// </summary> /// <value>An array of <see cref="string"/> representing URI.</value> string[] ServerUris { get; } /// <summary> /// Gets the list of <see cref="ModelTableEntry"/> that are defined in the <see cref="UANodeSet"/> along with any dependencies these models have. /// </summary> /// <value>An array of <see cref="ModelTableEntry"/> representing a model.</value> ModelTableEntry[] Models { get; } /// <summary> /// Gets the list of <see cref="NodeIdAlias"/>used in the <see cref="UANodeSet"/> . /// </summary> /// <value>An array of <see cref="NodeIdAlias"/> representing alias description.</value> NodeIdAlias[] Aliases { get; } /// <summary> /// Gets the array of <see cref="XmlElement"/> containing any vendor defined extensions to the <see cref="UANodeSet"/>. /// </summary> /// <value>An array of <see cref="XmlElement"/> representing extension.</value> XmlElement[] Extensions { get; } } } <|start_filename|>SemanticData/SolutionConfiguration/Serialization/UAModelDesignerSolution.GoCS.cmd<|end_filename|> :: convert the scheme DomainDescriptor.xsd to cs code xsd.exe UAModelDesignerSolution.xsd /N:UAOOI.SemanticData.SolutionConfiguration.Serialization /c <|start_filename|>SemanticData/UANodeSetValidation/XML/UAVariable.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using UAOOI.SemanticData.BuildingErrorsHandling; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.SemanticData.UANodeSetValidation.XML { public partial class UAVariable { /// <summary> /// Indicates whether the inherited parent object is also equal to another object. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// <c>true</c> if the current object is equal to the <paramref name="other">other</paramref>; otherwise,, <c>false</c> otherwise.</returns> protected override bool ParentEquals(UANode other) { UAVariable _other = other as UAVariable; if (_other == null) return false; return base.ParentEquals(_other) && //TODO compare Value, Translation this.DataTypeNodeId == _other.DataTypeNodeId && this.ValueRank == _other.ValueRank && this.ArrayDimensions == _other.ArrayDimensions && this.AccessLevel == _other.AccessLevel && this.UserAccessLevel == _other.UserAccessLevel && this.MinimumSamplingInterval == _other.MinimumSamplingInterval && this.Historizing == _other.Historizing; } internal override void RemoveInheritedValues(UANode baseNode) { base.RemoveInheritedValues(baseNode); UAVariable _other = baseNode as UAVariable; if (baseNode is null) throw new System.ArgumentNullException($"{nameof(baseNode)}", $"The parameter of the {nameof(RemoveInheritedValues)} must not be null"); if (this.DataType == _other.DataType) this.DataType = null; if (this.ArrayDimensions == _other.ArrayDimensions) this.ArrayDimensions = string.Empty; } internal override void RecalculateNodeIds(IUAModelContext modelContext, Action<TraceMessage> trace) { DataTypeNodeId = modelContext.ImportNodeId(DataType, trace); base.RecalculateNodeIds(modelContext, trace); } internal NodeId DataTypeNodeId { get; private set; } /// <summary> /// Get the clone from the types derived from this one. /// </summary> /// <returns>An instance of <see cref="UANode" />.</returns> protected override UANode ParentClone() { UAVariable _ret = new UAVariable() { Value = this.Value, Translation = this.Translation, DataType = this.DataType, DataTypeNodeId = new NodeId(this.DataTypeNodeId), ValueRank = this.ValueRank, ArrayDimensions = this.ArrayDimensions, AccessLevel = this.AccessLevel, UserAccessLevel = this.UserAccessLevel, MinimumSamplingInterval = this.MinimumSamplingInterval, Historizing = this.Historizing, }; return _ret; } } } <|start_filename|>SemanticData/UANodeSetValidation/Diagnostic/IBuildErrorsHandling.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using UAOOI.Common.Infrastructure.Diagnostic; using UAOOI.SemanticData.BuildingErrorsHandling; namespace UAOOI.SemanticData.UANodeSetValidation.Diagnostic { internal interface IBuildErrorsHandling : ITraceSource { /// <summary> /// Traces the event using <see cref="TraceMessage"/>. /// </summary> /// <param name="traceMessage">The message to be send to trace.</param> void WriteTraceMessage(TraceMessage traceMessage); /// <summary> /// Gets the number of traced errors. /// </summary> /// <value>The errors.</value> int Errors { get; } } } <|start_filename|>DataDiscovery/Tests/DiscoveryServices.UnitTest/DomainDescriptorUnitTest.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Xml.Serialization; using UAOOI.DataDiscovery.DiscoveryServices.Models; using UAOOI.DataDiscovery.DiscoveryServices.UnitTest.TestData; namespace UAOOI.DataDiscovery.DiscoveryServices.UnitTest { [TestClass] public class DomainDescriptorUnitTest { [TestMethod] public void GetRootDomainDescriptorTest() { DomainDescriptor rootDomainDescriptor = DomainDescriptorFactory.GetRootDomainDescriptor(); Uri _resolution = rootDomainDescriptor.ResolveUri(m_ModelUri); string expectedFirsRoundUrl = "https://raw.githubusercontent.com/mpostol/OPC-UA-OOI/master/DataDiscovery/Tests/DiscoveryServices.UnitTest/TestData/root.zone/commsvr.com/DomainDescriptor.xml"; Assert.AreEqual<string>(expectedFirsRoundUrl, _resolution.ToString()); string _fn = "RootDomainDescriptor.xml"; FileInfo file = new FileInfo($@"TestData\{_fn}"); using (Stream outputStream = file.Create()) { XmlSerializer _serializer = new XmlSerializer(typeof(DomainDescriptor)); _serializer.Serialize(outputStream, rootDomainDescriptor); } file.Refresh(); Assert.IsTrue(file.Exists); Assert.IsTrue(file.Length > 0); DomainDescriptor domainDescriptor; using (Stream descriptionStream = file.OpenRead()) { XmlSerializer serializer = new XmlSerializer(typeof(DomainDescriptor)); domainDescriptor = (DomainDescriptor)serializer.Deserialize(descriptionStream); Assert.IsNotNull(domainDescriptor); } Assert.IsTrue(domainDescriptor.Description.Contains("Starting point")); Assert.AreEqual<RecordType>(RecordType.DomainDescriptor, domainDescriptor.NextStepRecordType); Assert.AreEqual<string>(@"https://raw.githubusercontent.com/mpostol/OPC-UA-OOI/master/DataDiscovery/Tests/DiscoveryServices.UnitTest/TestData/root.zone/#authority#/DomainDescriptor.xml", domainDescriptor.UrlPattern); _resolution = domainDescriptor.ResolveUri(m_ModelUri); Assert.AreEqual<string>(expectedFirsRoundUrl, _resolution.ToString()); } [TestMethod] [DeploymentItem(@"TestData\", @"TestData\")] public void RootZoneDomainDescriptorTest() { DomainDescriptor _referenceDomainDescriptor = DomainDescriptorFactory.GetRootDomainDescriptor(); AreEqualsDomainDescriptors(_referenceDomainDescriptor, @"root.zone\DomainDescriptor.xml"); _referenceDomainDescriptor = DomainDescriptorFactory.Iteration1DomainDescriptor(); AreEqualsDomainDescriptors(_referenceDomainDescriptor, @"root.zone\commsvr.com\DomainDescriptor.xml"); _referenceDomainDescriptor = DomainDescriptorFactory.Iteration2DomainDescriptor(); AreEqualsDomainDescriptors(_referenceDomainDescriptor, @"root.zone\commsvr.com\UA\Examples\BoilersSet\DomainDescriptor.xml"); } [TestMethod] [DeploymentItem(@"TestData\", @"TestData\")] public void DomainDescriptorAutogeneratedFileTest() { FileInfo _fi = new FileInfo(@"TestData\DomainDescriptor.xml"); Assert.IsTrue(_fi.Exists); DomainDescriptor newDescription = null; using (Stream _descriptionStream = _fi.OpenRead()) { XmlSerializer _serializer = new XmlSerializer(typeof(DomainDescriptor)); newDescription = (DomainDescriptor)_serializer.Deserialize(_descriptionStream); } Assert.IsNotNull(newDescription); Assert.IsFalse(string.IsNullOrEmpty(newDescription.Description)); Assert.IsFalse(string.IsNullOrEmpty(newDescription.UrlPattern)); } //instrumentation private readonly Uri m_ModelUri = new Uri(@"http://commsvr.com/UA/Examples/BoilersSet"); private static void AreEqualsDomainDescriptors(DomainDescriptor _rootDomainDescriptor, string fileName) { FileInfo file = new FileInfo($@"TestData\{fileName}"); Assert.IsTrue(file.Exists); DomainDescriptor domainDescriptor; using (Stream _descriptionStream = file.OpenRead()) { XmlSerializer _serializer = new XmlSerializer(typeof(DomainDescriptor)); domainDescriptor = (DomainDescriptor)_serializer.Deserialize(_descriptionStream); } Assert.IsNotNull(domainDescriptor); Assert.AreEqual<string>(_rootDomainDescriptor.Description, domainDescriptor.Description); Assert.AreEqual<RecordType>(_rootDomainDescriptor.NextStepRecordType, domainDescriptor.NextStepRecordType); Assert.AreEqual<String>(_rootDomainDescriptor.UrlPattern, domainDescriptor.UrlPattern); } } } <|start_filename|>SemanticData/UAModelDesignExport/NodeFactoryBase.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2019, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using System.Collections.Generic; using System.Linq; using System.Xml; using UAOOI.SemanticData.InformationModelFactory; using UAOOI.SemanticData.InformationModelFactory.UAConstants; using TraceMessage = UAOOI.SemanticData.BuildingErrorsHandling.TraceMessage; namespace UAOOI.SemanticData.UAModelDesignExport { internal abstract class NodeFactoryBase : NodesContainer, INodeFactory { /// <summary> /// Initializes a new instance of the <see cref="NodeFactoryBase"/> class. /// </summary> /// <param name="traceEvent">Encapsulates an action used to trace events and model errors.</param> public NodeFactoryBase(Action<TraceMessage> traceEvent) : base(traceEvent) { } #region INodeFactory /// <summary> /// It holds the value of the BrowseName attribute of modes in the Address Space. /// </summary> /// <value>The BrowseName of the node.</value> public string BrowseName { set; private get; } /// <summary> /// Add new reference to the references collection of the node. This collection represents all the references defined by the selected Information Model including /// references to the instance declarations nodes. The References list specifies references that must be created for the node during Address Space instantiation. /// The reference can be forward or inverse. /// </summary> /// <returns>IReferenceFactory.</returns> public IReferenceFactory NewReference() { ReferenceFactoryBase _ret = new ReferenceFactoryBase(); m_References.Add(_ret); return _ret; } /// <summary> /// Sets the a symbolic name for the node that can be used as a class/field name by a design tools to enhance auto-generated code. /// It should only be specified if the BrowseName cannot be used for this purpose. This field is not used directly to instantiate /// Address Space and is intended for use by design tools. Only letters, digits or the underscore (‘_’) are permitted. /// This attribute is not exposed in the Address Space. /// </summary> /// <value>The symbolic name for the node.</value> public XmlQualifiedName SymbolicName { set; internal get; } /// <summary> /// Sets the write mask. The optional WriteMask attribute represents the WriteMask attribute of the Basic NodeClass, which exposes the possibilities of a client /// to write the attributes of the node. The WriteMask attribute does not take any user access rights into account, that is, although an attribute is writable /// this may be restricted to a certain user/user group. /// </summary> /// <value>The write access.</value> /// <remarks>Default Value "0"</remarks> public uint WriteAccess { set; private get; } /// <summary> /// Sets the access restrictions. /// </summary> /// <value>The access restrictions.</value> /// <remarks>The AccessRestrictions that apply to the Node.</remarks> public AccessRestrictions AccessRestrictions { set; private get; } /// <summary> /// Sets the release status of the node. /// </summary> /// <value>The release status.</value> /// <remarks>It is not exposed in the address space. /// Added in the Rel 1.04 to the specification.</remarks> public ReleaseStatus ReleaseStatus { set; private get; } /// <summary> /// Sets the data type purpose. /// </summary> /// <value>The data type purpose.</value> /// <exception cref="NotImplementedException"></exception> /// <remarks>Not defined in the specification Part 2, 5, 6 and Errata Release 1.04.2 September 25, 2018</remarks> public DataTypePurpose DataTypePurpose { set; private get; } = DataTypePurpose.Normal; /// <summary> /// Sets the category. A list of identifiers used to group related UANodes together for use by tools that create/edit UANodeSet files. /// </summary> /// <remarks> /// In the UA Model Design it is a comment separated list of categories assigned to the node (e.g. Part4/Services or Part5/StateMachines). /// </remarks> /// <value>The category.</value> public string[] Category { set; private get; } = null; /// <summary> /// Adds new value for the Description. The optional Description element shall explain the meaning of the node in a localized text using the same mechanisms /// for localization as described for the DisplayName. /// </summary> /// <param name="localeField">The locale field.</param> /// <param name="valueField">The value field.</param> public void AddDescription(string localeField, string valueField) { Extensions.AddLocalizedText(localeField, valueField, ref m_Description, TraceEvent); } /// <summary> /// Adds new value for the DisplayName. The DisplayName attribute contains the localized name of the node. /// Clients should use this attribute if they want to display the name of the node to the user. They should not use /// the BrowseName for this purpose. The server may maintain one or more localized representations for each DisplayName. /// Clients negotiate the locale to be returned when they open a session with the server. The section DisplayName defines the structure of the DisplayName. /// The string part of the DisplayName is restricted to 512 characters. /// </summary> /// <param name="localeField">The locale field.</param> /// <param name="valueField">The value field.</param> public void AddDisplayName(string localeField, string valueField) { Extensions.AddLocalizedText(localeField, valueField, ref m_DisplayName, TraceEvent); } #endregion #region internal API /// <summary> /// Exports an instance of <see cref="XML.NodeDesign"/>. /// </summary> /// <param name="path">The path.</param> /// <param name="createInstanceType">Type of the create instance.</param> /// <returns>NodeDesign.</returns> internal abstract XML.NodeDesign Export(List<string> path, Action<XML.InstanceDesign, List<string>> createInstanceType); #endregion #region private protected void UpdateNode(XML.NodeDesign nodeDesign, List<string> path, Action<XML.InstanceDesign, List<string>> createInstanceType) { string _defaultDisplay = string.IsNullOrEmpty(BrowseName) ? SymbolicName.Name : BrowseName; nodeDesign.BrowseName = BrowseName == SymbolicName.Name ? null : BrowseName; List<XML.NodeDesign> _Members = new List<XML.NodeDesign>(); path.Add(SymbolicName.Name); base.ExportNodes(_Members, path, createInstanceType); XML.InstanceDesign[] _items = _Members.Cast<XML.InstanceDesign>().ToArray<XML.InstanceDesign>(); nodeDesign.Category = Category == null ? null : string.Join(", ", Category); nodeDesign.Children = _items == null || _items.Length == 0 ? null : new XML.ListOfChildren() { Items = _items }; nodeDesign.Description = m_Description; nodeDesign.DisplayName = m_DisplayName == null || m_DisplayName.Value == _defaultDisplay ? null : m_DisplayName; nodeDesign.IsDeclaration = false; nodeDesign.NotInAddressSpace = false; nodeDesign.NumericId = 0; nodeDesign.NumericIdSpecified = false; nodeDesign.PartNo = 0; nodeDesign.Purpose = DataTypePurpose.ConvertToDataTypePurpose(); nodeDesign.References = m_References.Count == 0 ? null : m_References.Select<ReferenceFactoryBase, XML.Reference>(x => x.Export()).ToArray<XML.Reference>(); nodeDesign.ReleaseStatus = ReleaseStatus.ConvertToReleaseStatus(); nodeDesign.StringId = null; nodeDesign.SymbolicId = null; nodeDesign.SymbolicName = SymbolicName; nodeDesign.WriteAccess = WriteAccess; // AccessRestrictions _access = AccessRestrictions; model design doesn't support AccessRestrictions } private XML.LocalizedText m_Description = null; private XML.LocalizedText m_DisplayName = null; private List<ReferenceFactoryBase> m_References = new List<ReferenceFactoryBase>(); #endregion } } <|start_filename|>SemanticData/AddressSpaceComplianceTestTool/CommandLineSyntax/Options.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using CommandLine; using CommandLine.Text; using System.Collections.Generic; namespace UAOOI.SemanticData.AddressSpacePrototyping.CommandLineSyntax { /// <summary> /// Class Options - defines command line switches used to control behavior of the application. /// </summary> internal class Options { [Value(0, Required = true, HelpText = "Specifies the input file to convert. At least one file containing Address Space definition compliant with UANodeSet schema must be specified. Many files may be entered at once.", MetaValue = "filePath")] public IEnumerable<string> Filenames { get; set; } [Option('e', "export", HelpText = "Specifies the output file path containing the ModelDesign XML document.", MetaValue = "filePath")] public string ModelDesignFileName { get; set; } [Option('s', "stylesheet", HelpText = "Name of the stylesheet document (XSLT - eXtensible Stylesheet Language Transformations). With XSLT you can transform an XML document into any text document.", MetaValue = "stylesheetName")] public string Stylesheet { get; set; } [Option('n', "namespace", Required = true, HelpText = "Specifies the namespace for the generated types. If not specified last imported model is used for export.", MetaValue = "ns")] public string IMNamespace { get; set; } [Option("nologo", HelpText = "If present suppresses the banner.")] public bool NoLogo { get; set; } [Usage(ApplicationAlias = "asp")] public static IEnumerable<Example> Examples => new List<Example>() { new Example("Validate UANodeSet", new Options() { Filenames = new List<string>(){ @"XMLModels\DataTypeTest.NodeSet2.xml", @"XMLModels\ReferenceTest.NodeSet2.xml", @"XMLModels\ObjectTypeTest.NodeSet2.xml", @"XMLModels\VariableTypeTest.NodeSet2.xml" } }), new Example("Recover ModelDesign", new Options(){ Filenames = new List<string>(){ @"XMLModels\DataTypeTest.NodeSet2.xml" }, ModelDesignFileName = @"XMLModels\DataTypeTest.ModelDesign.xml", IMNamespace = "http://cas.eu/UA/CommServer/UnitTests/DataTypeTest"}) }; }; } <|start_filename|>Networking/DataRepository/AzureGateway/PartDataManagementSetup.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2020, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using CommonServiceLocator; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using UAOOI.Configuration.Networking.Serialization; using UAOOI.Networking.Core; using UAOOI.Networking.DataRepository.AzureGateway.AzureInterconnection; using UAOOI.Networking.DataRepository.AzureGateway.Diagnostic; using UAOOI.Networking.ReferenceApplication.Core; using UAOOI.Networking.SemanticData; namespace UAOOI.Networking.DataRepository.AzureGateway { /// <summary> /// Class AzureGatewayDataManagementSetup - represents a data producer in the Reference Application. It is responsible to compose all parts making up a producer /// This class cannot be inherited. /// Implements the <see cref="DataManagementSetup" /> /// </summary> /// <seealso cref="DataManagementSetup" /> [Export(typeof(PartDataManagementSetup))] [PartCreationPolicy(CreationPolicy.Shared)] public sealed class PartDataManagementSetup : DataManagementSetup { #region Composition /// <summary> /// Initializes a new instance of the <see cref="PartDataManagementSetup"/> class. /// </summary> public PartDataManagementSetup() { _Logger.EnteringMethodPart(nameof(PartDataManagementSetup)); //Compose external parts IServiceLocator _serviceLocator = ServiceLocator.Current; //string _configurationFileName = _serviceLocator.GetInstance<string>(CompositionSettings.ConfigurationFileNameContract); m_ViewModel = _serviceLocator.GetInstance<ProducerViewModel>(); EncodingFactory = _serviceLocator.GetInstance<IEncodingFactory>(); _Logger.Composed(nameof(EncodingFactory), EncodingFactory.GetType().FullName); MessageHandlerFactory = _serviceLocator.GetInstance<IMessageHandlerFactory>(); _Logger.Composed(nameof(MessageHandlerFactory), MessageHandlerFactory.GetType().FullName); //compose internal parts ConfigurationFactory = new PartConfigurationFactory(ConfigurationFilePath); PartBindingFactory pbf = new PartBindingFactory(); _DTOProvider = pbf; BindingFactory = pbf; } internal static string ConfigurationFilePath { get; set; } = @"ConfigurationDataConsumer.BoilersSet.xml"; #endregion Composition #region IProducerDataManagementSetup /// <summary> /// Setups this instance. /// </summary> public void Setup() { _Logger.EnteringMethodPart(nameof(PartDataManagementSetup)); try { m_ViewModel.ChangeProducerCommand(() => { m_ViewModel.ProducerErrorMessage = "Restarted"; }); _Logger.EnteringMethodPart(nameof(DataManagementSetup), nameof(Start)); Start(); StartAzureCommunication(ConfigurationFactory.GetConfiguration()); _Logger.PartInitializationCompleted(); } catch (Exception ex) { m_ViewModel.ProducerErrorMessage = "ERROR"; _Logger.LogException(nameof(PartDataManagementSetup), ex); throw; } } #endregion IProducerDataManagementSetup #region IDisposable /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { _Logger.EnteringMethodPart(nameof(PartDataManagementSetup), nameof(Dispose)); m_onDispose(disposing); base.Dispose(disposing); if (!disposing || m_disposed) return; m_disposed = true; _tokenSource.Cancel(); try { Task.WhenAll(_tasks.ToArray()).Wait(); } catch (OperationCanceledException oce) { _Logger.LogException(nameof(PartDataManagementSetup), oce); } finally { _Logger.DisposingObject(nameof(CancellationTokenSource), nameof(Dispose)); _tokenSource.Dispose(); } } #endregion IDisposable #region private /// <summary> /// Gets or sets the view model to be used for diagnostic purpose.. /// </summary> /// <value>The view model.</value> private ProducerViewModel m_ViewModel; private readonly ConcurrentBag<Task> _tasks = new ConcurrentBag<Task>(); private readonly AzureGatewaySemanticEventSource _Logger = AzureGatewaySemanticEventSource.Log(); private CancellationTokenSource _tokenSource = new CancellationTokenSource(); /// <summary> /// Gets a value indicating whether this <see cref="PartDataManagementSetup"/> is disposed. /// </summary> /// <value><c>true</c> if disposed; otherwise, <c>false</c>.</value> private bool m_disposed = false; private readonly IDTOProvider _DTOProvider = null; private Action<bool> m_onDispose = disposing => { }; private void StartAzureCommunication(ConfigurationData configuration) { _Logger.EnteringMethodPart(nameof(PartDataManagementSetup)); CancellationToken token = _tokenSource.Token; List<CommunicationContext> azureComunicationContextList = new List<CommunicationContext>(); TaskFactory taskFactory = Task.Factory; foreach (DataSetConfiguration dataset in configuration.DataSets) { try { AzureDeviceParameters parameters = AzureDeviceParameters.ParseRepositoryGroup(dataset.RepositoryGroup); if (parameters == null) continue; CommunicationContext communicationContext = new CommunicationContext(_DTOProvider, dataset.RepositoryGroup, parameters); azureComunicationContextList.Add(communicationContext); Task newCommunicatinTask = taskFactory.StartNew(() => communicationContext.Run(token), token); _tasks.Add(newCommunicatinTask); } catch (AggregateException ax) { _Logger.LogException(nameof(PartDataManagementSetup), ax); continue; } catch (Exception) { throw; } } m_ViewModel.ProducerErrorMessage = "Running"; } #endregion private #region Unit tests instrumentation [Conditional("DEBUG")] internal void DisposeCheck(Action<bool> onDispose) { _Logger.EnteringMethodPart(nameof(PartDataManagementSetup)); m_onDispose = onDispose; } #endregion Unit tests instrumentation } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/UAReferenceContextTestClass.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; using System.Xml; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; using UAOOI.SemanticData.UANodeSetValidation.UAInformationModel; namespace UAOOI.SemanticData.UANodeSetValidation { [TestClass] public class UAReferenceContextTestClass { [TestMethod] public void NullArgumentConstructorTest() { Mock<IAddressSpaceBuildContext> asMock = new Mock<IAddressSpaceBuildContext>(); Mock<IUANodeContext> nodeMock = new Mock<IUANodeContext>(); Assert.ThrowsException<ArgumentNullException>(() => new UAReferenceContext(null, asMock.Object, nodeMock.Object)); Assert.ThrowsException<ArgumentNullException>(() => new UAReferenceContext(new XML.Reference(), null, nodeMock.Object)); Assert.ThrowsException<ArgumentNullException>(() => new UAReferenceContext(new XML.Reference(), asMock.Object, null)); } [TestMethod] public void ConstructorTest() { XML.Reference reference = new XML.Reference() { IsForward = true, ReferenceType = ReferenceTypeIds.HasOrderedComponent.ToString(), Value = "ns=1;i=11" }; reference.RecalculateNodeIds(x => NodeId.Parse(x)); Mock<IUANodeContext> typeMock = new Mock<IUANodeContext>(); typeMock.Setup(x => x.NodeIdContext).Returns(new NodeId("i=10")); Mock<IUANodeContext> targetMock = new Mock<IUANodeContext>(); targetMock.Setup(x => x.NodeIdContext).Returns(new NodeId("ns=1;i=12")); Mock<IAddressSpaceBuildContext> asMock = new Mock<IAddressSpaceBuildContext>(); asMock.Setup(x => x.GetOrCreateNodeContext(It.IsAny<NodeId>(), It.IsAny<Func<NodeId, IUANodeContext>>())).Returns(typeMock.Object); asMock.Setup(x => x.GetOrCreateNodeContext(It.Is<NodeId>(z => z == reference.ValueNodeId), It.IsAny<Func<NodeId, IUANodeContext>>())).Returns(targetMock.Object); Mock<IUANodeContext> sourceMock = new Mock<IUANodeContext>(); sourceMock.Setup(x => x.NodeIdContext).Returns(NodeId.Parse("ns=1;i=1")); UAReferenceContext instance2Test = new UAReferenceContext(reference, asMock.Object, sourceMock.Object); Assert.IsTrue(instance2Test.IsForward); Assert.AreEqual<string>("ns=1;i=1:i=10:ns=1;i=12", instance2Test.Key); Assert.AreSame(typeMock.Object, instance2Test.TypeNode); Assert.AreSame(sourceMock.Object, instance2Test.ParentNode); Assert.AreSame(sourceMock.Object, instance2Test.SourceNode); Assert.AreSame(targetMock.Object, instance2Test.TargetNode); asMock.Verify(z => z.GetOrCreateNodeContext(It.IsAny<NodeId>(), It.IsAny<Func<NodeId, IUANodeContext>>()), Times.Exactly(2)); reference.IsForward = false; instance2Test = new UAReferenceContext(reference, asMock.Object, sourceMock.Object); Assert.IsFalse(instance2Test.IsForward); Assert.AreEqual<string>("ns=1;i=12:i=10:ns=1;i=1", instance2Test.Key); Assert.AreSame(typeMock.Object, instance2Test.TypeNode); Assert.AreSame(sourceMock.Object, instance2Test.ParentNode); Assert.AreSame(sourceMock.Object, instance2Test.TargetNode); Assert.AreSame(targetMock.Object, instance2Test.SourceNode); } [TestMethod] public void GetReferenceTypeNameTest() { XML.Reference reference = new XML.Reference() { IsForward = true, ReferenceType = ReferenceTypeIds.HasOrderedComponent.ToString(), Value = "ns=1;i=11" }; reference.RecalculateNodeIds(x => NodeId.Parse(x)); Mock<IUANodeContext> typeMock = new Mock<IUANodeContext>(); typeMock.Setup(x => x.NodeIdContext).Returns(new NodeId("i=10")); Mock<IUANodeContext> targetMock = new Mock<IUANodeContext>(); targetMock.Setup(x => x.NodeIdContext).Returns(new NodeId("ns=1;i=12")); Mock<IAddressSpaceBuildContext> asMock = new Mock<IAddressSpaceBuildContext>(); asMock.Setup(x => x.GetOrCreateNodeContext(It.IsAny<NodeId>(), It.IsAny<Func<NodeId, IUANodeContext>>())).Returns(typeMock.Object); asMock.Setup(x => x.GetOrCreateNodeContext(It.Is<NodeId>(z => z == reference.ValueNodeId), It.IsAny<Func<NodeId, IUANodeContext>>())).Returns(targetMock.Object); Mock<IUANodeContext> sourceMock = new Mock<IUANodeContext>(); sourceMock.Setup(x => x.NodeIdContext).Returns(NodeId.Parse("ns=1;i=1")); UAReferenceContext instance2Test = new UAReferenceContext(reference, asMock.Object, sourceMock.Object); asMock.Setup(x => x.ExportBrowseName(It.Is<NodeId>(z => z == new NodeId("i=10")), It.IsAny<NodeId>())).Returns(new XmlQualifiedName("2P8ZkTA2Ccahvs", "943IbIVI6ivpBj")); XmlQualifiedName typeName = instance2Test.GetReferenceTypeName(); asMock.Verify(x => x.ExportBrowseName(It.Is<NodeId>(z => z == new NodeId("i=10")), It.IsAny<NodeId>()), Times.Once); Assert.IsNotNull(typeName); Assert.AreEqual<string>("943IbIVI6ivpBj", typeName.Namespace); Assert.AreEqual<string>("2P8ZkTA2Ccahvs", typeName.Name); } [TestMethod] public void BrowsePathNameIsForwardTest() { XML.Reference reference = new XML.Reference() { IsForward = true, ReferenceType = ReferenceTypeIds.HasOrderedComponent.ToString(), Value = "ns=1;i=11" }; reference.RecalculateNodeIds(x => NodeId.Parse(x)); Mock<IUANodeContext> typeMock = new Mock<IUANodeContext>(); typeMock.Setup(x => x.NodeIdContext).Returns(new NodeId("i=10")); Mock<IUANodeContext> targetMock = new Mock<IUANodeContext>(); targetMock.Setup(x => x.NodeIdContext).Returns(new NodeId("ns=1;i=12")); Mock<IAddressSpaceBuildContext> asMock = new Mock<IAddressSpaceBuildContext>(); asMock.Setup(x => x.GetOrCreateNodeContext(It.IsAny<NodeId>(), It.IsAny<Func<NodeId, IUANodeContext>>())).Returns(typeMock.Object); asMock.Setup(x => x.GetOrCreateNodeContext(It.Is<NodeId>(z => z == reference.ValueNodeId), It.IsAny<Func<NodeId, IUANodeContext>>())).Returns(targetMock.Object); Mock<IUANodeContext> sourceMock = new Mock<IUANodeContext>(); sourceMock.Setup(x => x.NodeIdContext).Returns(NodeId.Parse("ns=1;i=1")); UAReferenceContext instance2Test = new UAReferenceContext(reference, asMock.Object, sourceMock.Object); targetMock.Setup(z => z.BuildSymbolicId(It.Is<List<string>>(x => CreatePathFixture(x)))); XmlQualifiedName typeName = instance2Test.BrowsePath(); targetMock.Verify(z => z.BuildSymbolicId(It.IsAny<List<string>>()), Times.Once); sourceMock.Verify(z => z.BuildSymbolicId(It.IsAny<List<string>>()), Times.Never); typeMock.Verify(z => z.BuildSymbolicId(It.IsAny<List<string>>()), Times.Never); Assert.IsNotNull(typeName); Assert.AreEqual<string>("", typeName.Namespace); Assert.AreEqual<string>("2P8ZkTA2Ccahvs_bLAsL6DSp1Ow5d", typeName.Name); } [TestMethod] public void BrowsePathNameTest() { XML.Reference reference = new XML.Reference() { IsForward = false, ReferenceType = ReferenceTypeIds.HasOrderedComponent.ToString(), Value = "ns=1;i=11" }; reference.RecalculateNodeIds(x => NodeId.Parse(x)); Mock<IUANodeContext> typeMock = new Mock<IUANodeContext>(); typeMock.Setup(x => x.NodeIdContext).Returns(new NodeId("i=10")); Mock<IUANodeContext> targetMock = new Mock<IUANodeContext>(); targetMock.Setup(x => x.NodeIdContext).Returns(new NodeId("ns=1;i=12")); Mock<IAddressSpaceBuildContext> asMock = new Mock<IAddressSpaceBuildContext>(); asMock.Setup(x => x.GetOrCreateNodeContext(It.IsAny<NodeId>(), It.IsAny<Func<NodeId, IUANodeContext>>())).Returns(typeMock.Object); asMock.Setup(x => x.GetOrCreateNodeContext(It.Is<NodeId>(z => z == reference.ValueNodeId), It.IsAny<Func<NodeId, IUANodeContext>>())).Returns(targetMock.Object); Mock<IUANodeContext> sourceMock = new Mock<IUANodeContext>(); sourceMock.Setup(x => x.NodeIdContext).Returns(NodeId.Parse("ns=1;i=1")); UAReferenceContext instance2Test = new UAReferenceContext(reference, asMock.Object, sourceMock.Object); Assert.IsFalse(instance2Test.IsForward); targetMock.Setup(z => z.BuildSymbolicId(It.Is<List<string>>(x => CreatePathFixture(x)))); XmlQualifiedName typeName = instance2Test.BrowsePath(); targetMock.Verify(z => z.BuildSymbolicId(It.IsAny<List<string>>()), Times.Once); sourceMock.Verify(z => z.BuildSymbolicId(It.IsAny<List<string>>()), Times.Never); typeMock.Verify(z => z.BuildSymbolicId(It.IsAny<List<string>>()), Times.Never); Assert.IsNotNull(typeName); Assert.AreEqual<string>("", typeName.Namespace); Assert.AreEqual<string>("2P8ZkTA2Ccahvs_bLAsL6DSp1Ow5d", typeName.Name); } [TestMethod] public void BuildSymbolicIdTest() { XML.Reference reference = new XML.Reference() { IsForward = false, ReferenceType = ReferenceTypeIds.HasOrderedComponent.ToString(), Value = "ns=1;i=11" }; reference.RecalculateNodeIds(x => NodeId.Parse(x)); Mock<IUANodeContext> typeMock = new Mock<IUANodeContext>(); Mock<IUANodeContext> targetMock = new Mock<IUANodeContext>(); targetMock.Setup(x => x.NodeIdContext).Returns(new NodeId("ns=1;i=12")); Mock<IAddressSpaceBuildContext> asMock = new Mock<IAddressSpaceBuildContext>(); asMock.Setup(x => x.GetOrCreateNodeContext(It.IsAny<NodeId>(), It.IsAny<Func<NodeId, IUANodeContext>>())).Returns(typeMock.Object); asMock.Setup(x => x.GetOrCreateNodeContext(It.Is<NodeId>(z => z == reference.ValueNodeId), It.IsAny<Func<NodeId, IUANodeContext>>())).Returns(targetMock.Object); Mock<IUANodeContext> sourceMock = new Mock<IUANodeContext>(); sourceMock.Setup(x => x.NodeIdContext).Returns(NodeId.Parse("ns=1;i=1")); UAReferenceContext instance2Test = new UAReferenceContext(reference, asMock.Object, sourceMock.Object); Assert.IsFalse(instance2Test.IsForward); targetMock.Setup(z => z.BuildSymbolicId(It.Is<List<string>>(x => CreatePathFixture(x)))); List<string> path = new List<string>(); instance2Test.BuildSymbolicId(path); targetMock.Verify(z => z.BuildSymbolicId(It.IsAny<List<string>>()), Times.Once); sourceMock.Verify(z => z.BuildSymbolicId(It.IsAny<List<string>>()), Times.Never); typeMock.Verify(z => z.BuildSymbolicId(It.IsAny<List<string>>()), Times.Never); Assert.AreEqual<int>(2, path.Count); } [TestMethod] public void ChildConnector() { XML.Reference reference = new XML.Reference() { IsForward = false, ReferenceType = ReferenceTypeIds.HasOrderedComponent.ToString(), Value = "ns=1;i=11" }; reference.RecalculateNodeIds(x => NodeId.Parse(x)); Mock<IUANodeContext> typeMock = new Mock<IUANodeContext>(); typeMock.Setup(x => x.NodeIdContext).Returns(ReferenceTypeIds.HasOrderedComponent); Mock<IUANodeContext> sourceMock = new Mock<IUANodeContext>(); Mock<IAddressSpaceBuildContext> asMock = new Mock<IAddressSpaceBuildContext>(); asMock.Setup(x => x.GetBaseTypes(It.IsAny<IUANodeContext>(), It.Is<List<IUANodeContext>>(z => ListContainingAggregatesTypesFixture(z)))); asMock.Setup(x => x.GetOrCreateNodeContext(It.Is<NodeId>(v => v == reference.ReferenceTypeNodeid), It.IsAny<Func<NodeId, IUANodeContext>>())).Returns(typeMock.Object); UAReferenceContext instance2Test = new UAReferenceContext(reference, asMock.Object, sourceMock.Object); Assert.IsTrue(instance2Test.ChildConnector); //asMock.Verify(x => x.GetBaseTypes(It.IsAny<IUANodeContext>(), It.Is<List<IUANodeContext>>(z => ListContainingAggregatesTypesFixture(z))), Times.Once); } private bool ListContainingAggregatesTypesFixture(List<IUANodeContext> references) { Assert.AreEqual<int>(0, references.Count); Mock<IUANodeContext> node1 = new Mock<IUANodeContext>(); references.Add(node1.Object); references.Add(node1.Object); references.Add(node1.Object); Mock<IUANodeContext> node2 = new Mock<IUANodeContext>(); node2.Setup(x => x.NodeIdContext).Returns(ReferenceTypeIds.HasComponent); references.Add(node2.Object); Mock<IUANodeContext> node3 = new Mock<IUANodeContext>(); references.Add(node3.Object); references.Add(node3.Object); references.Add(node3.Object); references.Add(node1.Object); references.Add(node1.Object); return true; } private bool CreatePathFixture(List<string> z) { z.Add("2P8ZkTA2Ccahvs"); z.Add("bLAsL6DSp1Ow5d"); return true; } } } <|start_filename|>SemanticData/SolutionConfiguration/Serialization/UAModelDesignerSolution.GoXSD.cmd<|end_filename|> xsd.exe ..\bin\Debug\UAOOI.SemanticData.SolutionConfiguration.dll /t:UAOOI.SemanticData.SolutionConfiguration.Serialization.UAModelDesignerSolution <|start_filename|>Common/Infrastructure/Serializers/INamespaces.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System.Collections.Generic; using System.Xml; namespace UAOOI.Common.Infrastructure.Serializers { /// <summary> /// Interface INamespaces - define functionality necessary to manage namespaces for the XML serialization /// </summary> public interface INamespaces { /// <summary> /// Gets the namespaces that is to be used to parametrize XML document. /// </summary> /// <returns>An instance of IEnumerable[XmlQualifiedName] containing the XML namespaces and prefixes that a serializer uses to generate qualified names in an XML-document instance.</returns> IEnumerable<XmlQualifiedName> GetNamespaces(); } } <|start_filename|>SemanticData/UANodeSetValidation/XML/DataTypeField.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.SemanticData.UANodeSetValidation.XML { /// <summary> /// Class DataTypeField /// </summary> public partial class DataTypeField { internal void RecalculateNodeIds(Func<string, NodeId> importNodeId) { DataTypeNodeId = importNodeId(DataType); } internal NodeId DataTypeNodeId { get; private set; } } } <|start_filename|>Networking/ReferenceApplication.Core/IDataRepositoryStartup.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2020, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; namespace UAOOI.Networking.ReferenceApplication.Core { /// <summary> /// Interface IDataRepositoryStartup - a contract to be used by IoC container to get DataRepository parts. /// Implements the <see cref="System.IDisposable" /> /// </summary> /// <seealso cref="System.IDisposable" /> public interface IDataRepositoryStartup : IDisposable { void Setup(); } } <|start_filename|>Common/Infrastructure/Serializers/IStylesheetNameProvider.cs<|end_filename|> //____________________________________________________________________________ // // Copyright (C) 2021, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/TP //____________________________________________________________________________ namespace UAOOI.Common.Infrastructure.Serializers { /// <summary> /// Represents XML file style sheet name provider /// </summary> public interface IStylesheetNameProvider { /// <summary> /// The style sheet name /// </summary> string StylesheetName { get; } } } <|start_filename|>SemanticData/Tests/AddressSpaceComplianceTestToolUnitTests/ProgramUnitTest.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using UAOOI.Common.Infrastructure.Diagnostic; using UAOOI.SemanticData.AddressSpacePrototyping.CommandLineSyntax; using UAOOI.SemanticData.InformationModelFactory; using UAOOI.SemanticData.UANodeSetValidation; using UAOOI.SemanticData.UANodeSetValidation.XML; namespace UAOOI.SemanticData.AddressSpacePrototyping { [TestClass] [DeploymentItem(@"XMLModels\", @"XMLModels\")] public class ProgramUnitTest { [TestMethod] public void DeploymentItemTestMethod() { FileInfo _testDataFileInfo = new FileInfo(@"XMLModels\DataTypeTest.NodeSet2.xml"); Assert.IsTrue(_testDataFileInfo.Exists); } [TestMethod] public void ConstructorTest() { Program programInstance = new Program(); ITraceSource currentLogger = null; programInstance.GetTraceSource(x => currentLogger = x); Assert.IsNotNull(currentLogger); } [TestMethod] public async Task EmptyArgsTest() { Program programInstance = new Program(); Mock<ITraceSource> mockLogerr = new Mock<ITraceSource>(); mockLogerr.Setup(x => x.TraceData(It.IsAny<TraceEventType>(), It.IsAny<int>(), It.IsAny<string>())); programInstance.DebugITraceSource = mockLogerr.Object; await programInstance.Run(new string[] { }); mockLogerr.Verify(x => x.TraceData(It.IsAny<TraceEventType>(), It.IsAny<int>(), It.IsAny<string>()), Times.Exactly(2)); } [TestMethod] public async Task RunTheApplicationTestMethod() { Program program = new Program(); await program.Run(new string[] { @"XMLModels\DataTypeTest.NodeSet2.xml" }); } [TestMethod] public void OptionsTestMethod() { Mock<IAddressSpaceContext> asMock = new Mock<IAddressSpaceContext>(); asMock.Setup(x => x.ImportUANodeSet(It.IsAny<FileInfo>())); asMock.Setup(x => x.ImportUANodeSet(It.IsAny<UANodeSet>())); asMock.SetupSet(x => x.InformationModelFactory = It.IsAny<IModelFactory>()); Program program = new Program(); Options options = new Options() { Filenames = null, IMNamespace = "bleble", ModelDesignFileName = string.Empty, NoLogo = true, Stylesheet = string.Empty }; Assert.ThrowsException<ArgumentOutOfRangeException>(() => program.Do(options, asMock.Object)); options = new Options() { Filenames = new List<string>() { "" }, IMNamespace = "bleble", ModelDesignFileName = string.Empty, NoLogo = true, Stylesheet = string.Empty }; Assert.ThrowsException<UriFormatException>(() => program.Do(options, asMock.Object)); options = new Options() { Filenames = new List<string>() { "bleble" }, IMNamespace = "http://cas.eu/UA/CommServer/UnitTests/DataTypeTest", ModelDesignFileName = string.Empty, NoLogo = true, Stylesheet = string.Empty }; Assert.ThrowsException<FileNotFoundException>(() => program.Do(options, asMock.Object)); options = new Options() { Filenames = new List<string>() { @"XMLModels\DataTypeTest.NodeSet2.xml" }, IMNamespace = String.Empty, ModelDesignFileName = string.Empty, NoLogo = true, Stylesheet = string.Empty }; Assert.ThrowsException<ArgumentOutOfRangeException>(() => program.Do(options, asMock.Object)); asMock.VerifySet(x => x.InformationModelFactory = It.IsAny<IModelFactory>(), Times.Never); asMock.Verify(x => x.ImportUANodeSet(It.IsAny<FileInfo>()), Times.Never); asMock.Verify(x => x.ImportUANodeSet(It.IsAny<UANodeSet>()), Times.Never); options = new Options() { Filenames = new List<string>() { @"XMLModels\DataTypeTest.NodeSet2.xml" }, IMNamespace = "http://cas.eu/UA/CommServer/UnitTests/DataTypeTest", ModelDesignFileName = string.Empty, NoLogo = true, Stylesheet = string.Empty }; program.Do(options, asMock.Object); asMock.VerifySet(x => x.InformationModelFactory = It.IsAny<IModelFactory>(), Times.Never); asMock.Verify(x => x.ImportUANodeSet(It.IsAny<FileInfo>()), Times.Once); asMock.Verify(x => x.ImportUANodeSet(It.IsAny<UANodeSet>()), Times.Never); } } } <|start_filename|>SemanticData/SolutionConfiguration/Serialization/UAModelDesignerSolution.design.cs<|end_filename|> //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by xsd, Version=4.6.1055.0. // namespace UAOOI.SemanticData.SolutionConfiguration.Serialization { using System.Xml.Serialization; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] public partial class UAModelDesignerSolution { private string nameField; private UAModelDesignerProject[] projectsField; private UAModelDesignerSolutionServerDetails serverDetailsField; /// <remarks/> public string Name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayItemAttribute("UAModelDesignerProject", IsNullable=false)] public UAModelDesignerProject[] Projects { get { return this.projectsField; } set { this.projectsField = value; } } /// <remarks/> public UAModelDesignerSolutionServerDetails ServerDetails { get { return this.serverDetailsField; } set { this.serverDetailsField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName = "UAModelDesignerProject", AnonymousType=false)] public partial class UAModelDesignerProject { private string nameField; private string cSVFileNameField; private string buildOutputDirectoryNameField; private string fileNameField; private string projectIdentifierField; /// <remarks/> public string Name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> public string CSVFileName { get { return this.cSVFileNameField; } set { this.cSVFileNameField = value; } } /// <remarks/> public string BuildOutputDirectoryName { get { return this.buildOutputDirectoryNameField; } set { this.buildOutputDirectoryNameField = value; } } /// <remarks/> public string FileName { get { return this.fileNameField; } set { this.fileNameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string ProjectIdentifier { get { return this.projectIdentifierField; } set { this.projectIdentifierField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] public partial class UAModelDesignerSolutionServerDetails { private string codebaseField; private string configurationField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string codebase { get { return this.codebaseField; } set { this.codebaseField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string configuration { get { return this.configurationField; } set { this.configurationField = value; } } } } <|start_filename|>SemanticData/UANodeSetValidation/XML/NodeToDelete.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; namespace UAOOI.SemanticData.UANodeSetValidation.XML { public partial class NodeToDelete { internal void RecalculateNodeIds(Func<string, NodeId> importNodeId) { throw new NotImplementedException(); } } } <|start_filename|>SemanticData/UAModelDesignExport/IModelDesignExport.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using UAOOI.SemanticData.InformationModelFactory; using UAOOI.SemanticData.UAModelDesignExport.XML; namespace UAOOI.SemanticData.UAModelDesignExport { /// <summary> /// Interface IModelDesignExport - abstract API of the UAModelDesignExport. /// </summary> public interface IModelDesignExport { /// <summary> /// Gets the factory. /// </summary> /// <returns>An instance of the <see cref="IModelFactory"/> to be used to generate the OPC UA Information Model captured as the <see cref="ModelDesign"/>.</returns> IModelFactory GetFactory(); /// <summary> /// Serializes the already generated model using the interface <see cref="IModelFactory"/> and writes the XML document to a file. /// </summary> /// <param name="outputFilePtah">A relative or absolute path for the file containing the serialized object.</param> /// <param name="stylesheetName">Name of the stylesheet document.</param> void ExportToXMLFile(string outputFilePtah, string stylesheetName); /// <summary> /// Serializes the already generated model using the interface <see cref="IModelFactory"/> and writes the XML document to a file. /// </summary> /// <param name="outputFilePtah">A relative or absolute path for the file containing the serialized object.</param> void ExportToXMLFile(string outputFilePtah); /// <summary> /// Convert the UA Information Model to graph of objects /// </summary> /// <returns>Returns an instance of the type <see cref="ModelDesign"/>.</returns> ModelDesign ExportToObject(); } } <|start_filename|>SemanticData/UAModelDesignExport.UnitTest/ExtensionsUnitTest.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2019, <NAME>DZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Xml; using UAOOI.SemanticData.UAModelDesignExport.XML; namespace UAOOI.SemanticData.UAModelDesignExport { [TestClass] public class ExtensionsUnitTest { [TestMethod] public void AddLocalizedTextTestMethod() { LocalizedText _description = null; int _counter = 0; Extensions.AddLocalizedText("localeField1", "valueField1", ref _description, x => _counter++); Assert.AreEqual<int>(0, _counter); Assert.IsNotNull(_description); Assert.AreEqual<string>("localeField1", _description.Key); Assert.AreEqual<string>("valueField1", _description.Value); LocalizedText _descriptionCopy = _description; Extensions.AddLocalizedText("localeField1", "valueField1", ref _description, x => _counter++); Assert.AreEqual<int>(1, _counter); Assert.IsNotNull(_description); Assert.AreSame(_descriptionCopy, _description); } [TestMethod] public void KeyTest() { Reference value1 = new Reference() { IsInverse = false, IsOneWay = true, ReferenceType = new XmlQualifiedName("Type Name"), TargetId = new XmlQualifiedName("TargetId") }; Reference value2 = new Reference() { IsInverse = true, IsOneWay = true, ReferenceType = new XmlQualifiedName("Type Name"), TargetId = new XmlQualifiedName("TargetId") }; Assert.AreNotEqual<string>(value1.Key(), value2.Key()); } } } <|start_filename|>Common/Infrastructure/Diagnostic/TraceSourceBase.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System; using System.Diagnostics; namespace UAOOI.Common.Infrastructure.Diagnostic { /// <summary> /// Class TraceSourceBase - default implementation of the <see cref="ITraceSource"/> /// </summary> public class TraceSourceBase : ITraceSource { /// <summary> /// Initializes a new instance of the <see cref="TraceSourceBase"/> class provider of a named <see cref="ITraceSource"/>. /// </summary> /// <param name="TraceSourceName">Name of the <see cref="TraceSource"/>.</param> public TraceSourceBase(string TraceSourceName) { m_TraceEventInternal = new Lazy<TraceSource>(() => new TraceSource(TraceSourceName)); } /// <summary> /// Initializes a new instance of the <see cref="TraceSourceBase"/> class provider of a default <see cref="ITraceSource"/>. /// </summary> public TraceSourceBase() : this("UAOOI.Common") { } /// <summary> /// Writes trace data to the trace listeners in the <see cref="TraceSource.Listeners" /> collection using the specified <paramref name="eventType" />, /// event identifier <paramref name="id" />, and trace <paramref name="data" />. /// </summary> /// <param name="eventType">One of the enumeration values <see cref="TraceEventType"/> that specifies the event type of the trace data.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="data">The trace data.</param> public virtual void TraceData(TraceEventType eventType, int id, object data) { m_TraceEventInternal.Value.TraceData(eventType, id, data); } /// <summary> /// Gets the trace source instance. /// </summary> /// <value>The trace source instance of type <see cref="TraceSource"/>.</value> public TraceSource TraceSource => m_TraceEventInternal.Value; private Lazy<TraceSource> m_TraceEventInternal = null; } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/ServiceResultExceptionUnitTest.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Diagnostics; using UAOOI.SemanticData.BuildingErrorsHandling; namespace UAOOI.SemanticData.UANodeSetValidation.DataSerialization { [TestClass] public class ServiceResultExceptionUnitTest { [TestMethod] public void ServiceResultExceptionCreateTestMethod() { ServiceResultException _ex = new ServiceResultException(); Assert.IsNotNull(_ex); Assert.IsNull(_ex.InnerException); Assert.IsNull(_ex.TraceMessage); Assert.IsFalse(String.IsNullOrEmpty(_ex.Message), _ex.Message); Assert.IsTrue(_ex.Message.Contains("UAOOI.SemanticData.UANodeSetValidation.DataSerialization")); } [TestMethod] public void ServiceResultExceptionCreateWithMessageTestMethod() { TraceMessage traceMessage = TraceMessage.BuildErrorTraceMessage(BuildError.NodeIdInvalidSyntax, "BuildError_BadNodeIdInvalid"); ServiceResultException _ex = new ServiceResultException(traceMessage, "test message"); Assert.IsNotNull(_ex); Assert.IsNotNull(_ex.TraceMessage); Assert.IsNull(_ex.InnerException); Assert.AreEqual<string>("test message", _ex.Message); Assert.IsNotNull(_ex.TraceMessage); Assert.AreEqual<Focus>(BuildError.NodeIdInvalidSyntax.Focus, _ex.TraceMessage.BuildError.Focus); Assert.AreEqual<TraceEventType>(TraceEventType.Warning, _ex.TraceMessage.TraceLevel); } } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/DataSerialization/ExtensionsUnitTest.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Diagnostics; using UAOOI.SemanticData.BuildingErrorsHandling; using UAOOI.SemanticData.UANodeSetValidation.Helpers; namespace UAOOI.SemanticData.UANodeSetValidation.DataSerialization { [TestClass] public class ExtensionsUnitTest { [TestMethod] public void ParseBrowseNameNodeIdNullTest() { Assert.ThrowsException<ArgumentNullException>(() => "".ParseBrowseName(null, x => Assert.Fail())); Assert.ThrowsException<ArgumentNullException>(() => "".ParseBrowseName(NodeId.Null, x => Assert.Fail())); } [TestMethod] public void ParseBrowseNameBrowseNameEmptyTest() { List<TraceMessage> traceLog = new List<TraceMessage>(); QualifiedName name = "".ParseBrowseName(new NodeId("i=105"), x => traceLog.Add(x)); Assert.IsNotNull(name); Assert.IsFalse(String.IsNullOrEmpty(name.Name)); Assert.IsTrue(name.Name.StartsWith("EmptyBrowseName_")); Assert.IsTrue(name.NamespaceIndexSpecified); Assert.AreEqual<int>(1, traceLog.Count); Debug.WriteLine(traceLog[0].ToString()); Assert.AreEqual<Focus>(Focus.NodeClass, traceLog[0].BuildError.Focus); Assert.AreEqual<String>(BuildError.EmptyBrowseName.Identifier, traceLog[0].BuildError.Identifier); } [TestMethod] public void ParseBrowseNameBrowseNameSyntaxErrorTest() { List<TraceMessage> traceLog = new List<TraceMessage>(); QualifiedName name = "@^#^#^".ParseBrowseName(new NodeId("i=105"), x => traceLog.Add(x)); Assert.IsNotNull(name); Assert.IsFalse(String.IsNullOrEmpty(name.Name)); Assert.IsTrue(name.Name.StartsWith("EmptyBrowseName_")); Assert.IsTrue(name.NamespaceIndexSpecified); Assert.AreEqual<int>(1, traceLog.Count); Debug.WriteLine(traceLog[0].ToString()); Assert.AreEqual<Focus>(Focus.DataEncoding, traceLog[0].BuildError.Focus); Assert.AreEqual<String>(BuildError.QualifiedNameInvalidSyntax.Identifier, traceLog[0].BuildError.Identifier); } [TestMethod] public void ParseBrowseNameMyNamespaceIndex0TestMethod() { List<TraceMessage> traceLog = new List<TraceMessage>(); QualifiedName name = "Id".ParseBrowseName(new NodeId("ns=1;i=28"), x => traceLog.Add(x)); Assert.IsNotNull(name); Assert.IsFalse(String.IsNullOrEmpty(name.Name)); Assert.AreEqual<string>("Id", name.Name); Assert.IsTrue(name.NamespaceIndexSpecified); Assert.AreEqual<ushort>(0, name.NamespaceIndex); Assert.AreEqual<int>(0, traceLog.Count); } [TestMethod] public void ParseBrowseNameTest() { List<TraceMessage> traceLog = new List<TraceMessage>(); QualifiedName name = " 123:Id".ParseBrowseName(new NodeId("ns=1;i=28"), x => traceLog.Add(x)); Assert.IsNotNull(name); Assert.IsFalse(String.IsNullOrEmpty(name.Name)); Assert.AreEqual<string>("Id", name.Name); Assert.IsTrue(name.NamespaceIndexSpecified); Assert.AreEqual<ushort>(123, name.NamespaceIndex); Assert.AreEqual<int>(0, traceLog.Count); } [TestMethod] public void ParseNodeIdValidTest() { //Numeric NodeId _ni = "i=13".ParseNodeId(x => Assert.Fail()); Assert.IsNotNull(_ni); _ni = "i=0".ParseNodeId(x => Assert.Fail()); Assert.IsNotNull(_ni); //STRING _ni = "ns=10;s=Hello:World".ParseNodeId(x => Assert.Fail()); Assert.IsNotNull(_ni); //GUID _ni = "g=09087e75-8e5e-499b-954f-f2a9603db28a".ParseNodeId(x => Assert.Fail()); Assert.IsNotNull(_ni); //OPAQUE _ni = "ns=1;b=M/RbKBsRVkePCePcx24oRA==".ParseNodeId(x => Assert.Fail()); Assert.IsNotNull(_ni); //?? Default string - should be not valid ? _ni = "M/RbKBsRVkePCePcx24oRA==".ParseNodeId(x => Assert.Fail()); Assert.IsNotNull(_ni); } [TestMethod] public void NodeIdNonValidNumericTest1() { TraceDiagnosticFixture inMemoryTrace = new Helpers.TraceDiagnosticFixture(); NodeId _ni = "ns=10;i=-1".ParseNodeId(inMemoryTrace.TraceDiagnostic); //this example is in the specification as valid Assert.AreEqual<int>(1, inMemoryTrace.DiagnosticCounter); Assert.AreEqual<int>(1, inMemoryTrace.TraceList.Count); Assert.AreEqual<string>(BuildError.NodeIdInvalidSyntax.Identifier, inMemoryTrace.TraceList[0].BuildError.Identifier); } [TestMethod] public void NodeIdNonValidNumericTest2() { TraceDiagnosticFixture inMemoryTrace = new Helpers.TraceDiagnosticFixture(); NodeId _ni = "ns=-10;i=01".ParseNodeId(inMemoryTrace.TraceDiagnostic); //this example is in the specification as valid Assert.AreEqual<int>(1, inMemoryTrace.DiagnosticCounter); Assert.AreEqual<int>(1, inMemoryTrace.TraceList.Count); Assert.AreEqual<string>(BuildError.NodeIdInvalidSyntax.Identifier, inMemoryTrace.TraceList[0].BuildError.Identifier); } } } <|start_filename|>SemanticData/Tests/AddressSpaceComplianceTestToolUnitTests/TraceSourceBaseUnitTest.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using UAOOI.SemanticData.AddressSpacePrototyping.Instrumentation; namespace UAOOI.SemanticData.AddressSpacePrototyping { [TestClass] public class TraceSourceBaseUnitTest { [TestMethod] public void AssemblyTraceEventTestMethod() { TraceSource tracer = new TraceSource("AddressSpacePrototyping"); Assert.AreEqual<string>("AddressSpacePrototyping", tracer.Name, $"Actual tracer name: {tracer.Name}"); //Assert.AreEqual(1, Trace.Listeners.Count); Dictionary<string, TraceListener> _listeners = tracer.Listeners.Cast<TraceListener>().ToDictionary<TraceListener, string>(x => x.Name); Assert.IsNotNull(_listeners); Assert.IsTrue(_listeners.ContainsKey("LogFile")); TraceListener _listener = _listeners["LogFile"]; Assert.IsNotNull(_listener); Assert.IsInstanceOfType(_listener, typeof(DelimitedListTraceListener)); DelimitedListTraceListener _advancedListener = _listener as DelimitedListTraceListener; Assert.IsNotNull(_advancedListener.Filter); Assert.IsInstanceOfType(_advancedListener.Filter, typeof(EventTypeFilter)); EventTypeFilter _eventTypeFilter = _advancedListener.Filter as EventTypeFilter; Assert.AreEqual(SourceLevels.All, _eventTypeFilter.EventType); string _testPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Assert.AreEqual<string>(Path.Combine(_testPath, @"asp.log"), _advancedListener.GetFileName()); } [TestMethod] public void LogFileExistsTest() { TraceSource tracer = new TraceSource("AddressSpacePrototyping"); TraceListener _listener = tracer.Listeners.Cast<TraceListener>().Where<TraceListener>(x => x.Name == "LogFile").First<TraceListener>(); DelimitedListTraceListener _advancedListener = _listener as DelimitedListTraceListener; Assert.IsNotNull(_advancedListener); Assert.IsFalse(string.IsNullOrEmpty(_advancedListener.GetFileName())); FileInfo _logFileInfo = new FileInfo(_advancedListener.GetFileName()); long _startLength = _logFileInfo.Exists ? _logFileInfo.Length : 0; tracer.TraceEvent(TraceEventType.Information, 0, "LogFileExistsTest is executed"); Assert.IsFalse(string.IsNullOrEmpty(_advancedListener.GetFileName())); _logFileInfo.Refresh(); Assert.IsTrue(_logFileInfo.Exists); Assert.IsTrue(_logFileInfo.Length > _startLength); } } } <|start_filename|>SemanticData/UANodeSetValidation/DataSerialization/QualifiedName.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using UAOOI.SemanticData.BuildingErrorsHandling; namespace UAOOI.SemanticData.UANodeSetValidation.DataSerialization { /// <summary> /// A name qualified with a namespace. /// </summary> /// <remarks> /// <para> /// The QualifiedName is defined in <b>Part 3 - Address Space Model, Section 7.3</b>, titled /// <b>Qualified Name</b>. /// <br/></para> /// <para> /// The QualifiedName is a simple wrapper class that is used to generate a fully-qualified name /// for any type that has a name. /// <br/></para> /// <para> /// A <i>Fully Qualified</i> name is one that consists of a name, and an index of which namespace /// (within a namespace table) this name belongs to. /// For example<br/> /// <b>Namespace Index</b> = 1<br/> /// <b>Name</b> = MyName<br/> /// becomes:<br/> /// <i>1:MyName</i> /// <br/></para> /// </remarks> public partial class QualifiedName : IFormattable, ICloneable, IComparable { #region Constructors /// <summary> /// Initializes the object with default values. /// </summary> /// <remarks> /// Initializes the object with default values. /// </remarks> internal QualifiedName() { NamespaceIndex = 0; Name = null; } /// <summary> /// Creates a deep copy of the value. /// </summary> /// <remarks> /// Creates a deep copy of the value. /// </remarks> /// <param name="value">The qualified name to copy</param> /// <exception cref="ArgumentNullException">Thrown if the provided value is null</exception> public QualifiedName(QualifiedName value) { if (value == null) throw new ArgumentNullException("value"); Name = value.Name; NamespaceIndex = value.NamespaceIndex; NamespaceIndexSpecified = value.NamespaceIndexSpecified; } /// <summary> /// Initializes the object with a name. /// </summary> /// <remarks> /// Initializes the object with a name. /// </remarks> /// <param name="name">The name-portion to store as part of the fully qualified name</param> public QualifiedName(string name) { NamespaceIndex = 0; Name = name; NamespaceIndexSpecified = false; } /// <summary> /// Initializes the object with a name and a namespace index. /// </summary> /// <remarks> /// Initializes the object with a name and a namespace index. /// </remarks> /// <param name="name">The name-portion of the fully qualified name</param> /// <param name="namespaceIndex">The index of the namespace within the namespace-table</param> public QualifiedName(string name, ushort namespaceIndex) { NamespaceIndex = namespaceIndex; Name = name; NamespaceIndexSpecified = namespaceIndex != 0; } #endregion Constructors #region Public Properties /// <summary cref="QualifiedName.NamespaceIndex" /> internal ushort XmlEncodedNamespaceIndex { get => NamespaceIndex; set => NamespaceIndex = value; } #endregion Public Properties #region IComparable Members /// <summary> /// Compares two QualifiedNames. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns> /// Less than zero if the instance is less than the object. /// Zero if the instance is equal to the object. /// Greater than zero if the instance is greater than the object. /// </returns> public int CompareTo(object obj) { if (Object.ReferenceEquals(obj, null)) return -1; if (Object.ReferenceEquals(this, obj)) return 0; QualifiedName _qualifiedName = obj as QualifiedName; if (_qualifiedName == null) return typeof(QualifiedName).GUID.CompareTo(obj.GetType().GUID); if (_qualifiedName.NamespaceIndex != NamespaceIndex) return NamespaceIndex.CompareTo(_qualifiedName.NamespaceIndex); if (Name != null) return String.CompareOrdinal(Name, _qualifiedName.Name); return -1; } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="value1">The value1.</param> /// <param name="value2">The value2.</param> /// <returns>The result of the operator.</returns> public static bool operator >(QualifiedName value1, QualifiedName value2) { if (!Object.ReferenceEquals(value1, null)) return value1.CompareTo(value2) > 0; return false; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="value1">The value1.</param> /// <param name="value2">The value2.</param> /// <returns>The result of the operator.</returns> public static bool operator <(QualifiedName value1, QualifiedName value2) { if (!Object.ReferenceEquals(value1, null)) return value1.CompareTo(value2) < 0; return true; } #endregion IComparable Members #region Overridden Methods /// <summary> /// Returns a suitable hash value for the instance. /// </summary> public override int GetHashCode() { if (Name != null) return Name.GetHashCode(); return 0; } /// <summary> /// Returns true if the objects are equal. /// </summary> /// <remarks> /// Returns true if the objects are equal. /// </remarks> /// <param name="obj">The object to compare to this/me</param> public override bool Equals(object obj) { if (Object.ReferenceEquals(obj, null)) return false; if (Object.ReferenceEquals(this, obj)) return true; QualifiedName _qualifiedName = obj as QualifiedName; if (_qualifiedName == null) return false; if (_qualifiedName.NamespaceIndex != NamespaceIndex) return false; return _qualifiedName.Name == Name; } /// <summary> /// Returns true if the objects are equal. /// </summary> /// <remarks> /// Returns true if the objects are equal. /// </remarks> /// <param name="value1">The first value to compare</param> /// <param name="value2">The second value to compare</param> public static bool operator ==(QualifiedName value1, QualifiedName value2) { if (Object.ReferenceEquals(value1, null)) return Object.ReferenceEquals(value2, null); return value1.Equals(value2); } /// <summary> /// Returns true if the objects are not equal. /// </summary> /// <remarks> /// Returns true if the objects are equal. /// </remarks> /// <param name="value1">The first value to compare</param> /// <param name="value2">The second value to compare</param> public static bool operator !=(QualifiedName value1, QualifiedName value2) { if (Object.ReferenceEquals(value1, null)) return !Object.ReferenceEquals(value2, null); return !value1.Equals(value2); } /// <summary> /// Returns the string representation of the object. /// </summary> /// <remarks> /// Returns the string representation of the object. /// </remarks> public override string ToString() { return ToString(null, null); } #endregion Overridden Methods #region IFormattable Members /// <summary> /// Returns the string representation of the object. /// </summary> /// <remarks> /// Returns the string representation of the object. /// </remarks> /// <param name="format">(Unused) Always pass null</param> /// <param name="formatProvider">(Unused) Always pass null</param> /// <exception cref="FormatException">Thrown if non-null parameters are passed</exception> public string ToString(string format, IFormatProvider formatProvider) { if (format == null) { int capacity = (Name != null) ? Name.Length : 0; StringBuilder builder = new StringBuilder(capacity + 10); if (this.NamespaceIndex == 0) { // prepend the namespace index if the name contains a colon. if (Name != null) { int index = Name.IndexOf(':'); if (index != -1) builder.Append("0:"); } } else { builder.Append(NamespaceIndex); builder.Append(':'); } if (Name != null) builder.Append(Name); return builder.ToString(); } throw new FormatException(String.Format("Invalid format string: '{0}'.", format)); } #endregion IFormattable Members #region ICloneable Members /// <summary> /// Makes a deep copy of the object. /// </summary> /// <remarks> /// Makes a deep copy of the object. /// </remarks> public object Clone() { // this object cannot be altered after it is created so no new allocation is necessary. return this; } #endregion ICloneable Members #region Static Methods /// <summary> /// Converts an expanded node id to a node id using a namespace table. /// </summary> internal static QualifiedName Create(string name, string namespaceUri, INamespaceTable namespaceTable) { // check for null. if (String.IsNullOrEmpty(name)) return QualifiedName.Null; // return a name using the default namespace. if (String.IsNullOrEmpty(namespaceUri)) return new QualifiedName(name); // find the namespace index. int namespaceIndex = -1; if (namespaceTable != null) namespaceIndex = namespaceTable.GetURIIndex(new Uri(namespaceUri)); // oops - not found. if (namespaceIndex < 0) throw new ServiceResultException (TraceMessage.BuildErrorTraceMessage(BuildError.QualifiedNameInvalidSyntax, String.Format("NamespaceUri ({0}) is not in the NamespaceTable.", namespaceUri)), "Cannot create the QualifiedName because NamespaceUri is not in the NamespaceTable."); // return the name. return new QualifiedName(name, (ushort)namespaceIndex); } /// <summary> /// Returns true if the QualifiedName is valid. /// </summary> /// <param name="value">The name to be validated.</param> /// <param name="namespaceUris">The table namespaces known to the server.</param> /// <returns>True if the name is value.</returns> internal static bool IsValid(QualifiedName value, INamespaceTable namespaceUris) { if (value == null || String.IsNullOrEmpty(value.Name)) return false; if (namespaceUris != null && namespaceUris.GetModelTableEntry(value.NamespaceIndex) == null) return false; return true; } /// <summary> /// Parses a string containing a <see cref="QualifiedName"/> with the syntax <code>n:qname</code> /// </summary> /// <param name="text">The QualifiedName value as a string.</param> internal static QualifiedName Parse(string text) { ushort defaultNamespaceIndex = 0; string pattern = @"\b((\d{1,}):)?(.+)"; RegexOptions options = RegexOptions.Singleline; MatchCollection parseResult = Regex.Matches(text, pattern, options); if (parseResult.Count == 0) throw new ArgumentOutOfRangeException(nameof(text), $"The entry text {text} cannot be resolved to create a valid instance of the {nameof(QualifiedName)}."); else if (parseResult.Count > 1) throw new ArgumentOutOfRangeException(nameof(text), $"Ambiguous entry - {text} contains {parseResult.Count} parts that match the {nameof(QualifiedName)} syntax."); if (!parseResult[0].Groups[3].Success) throw new ArgumentOutOfRangeException(nameof(text), $"The entry text {text} doesn't contain a required {nameof(QualifiedName.Name)} field."); if (ushort.TryParse(parseResult[0].Groups[2].Value, out ushort index)) defaultNamespaceIndex = index; return new QualifiedName() { Name = parseResult[0].Groups[3].Value, namespaceIndexFieldSpecified = true, NamespaceIndex = defaultNamespaceIndex }; } /// <summary> /// Returns true if the value is null. /// </summary> /// <param name="value">The qualified name to check</param> public static bool IsNull(QualifiedName value) { if (value != null) { if (value.NamespaceIndex != 0 || !String.IsNullOrEmpty(value.Name)) { return false; } } return true; } /// <summary> /// Converts a string to a qualified name. /// </summary> /// <remarks> /// Converts a string to a qualified name. /// </remarks> /// <param name="value">The string to turn into a fully qualified name</param> public static QualifiedName ToQualifiedName(string value) { return new QualifiedName(value); } /// <summary> /// Converts a string to a qualified name. /// </summary> /// <remarks> /// Converts a string to a qualified name. /// </remarks> /// <param name="value">The string to turn into a fully qualified name</param> public static implicit operator QualifiedName(string value) { return new QualifiedName(value); } /// <summary> /// Returns an instance of a null QualifiedName. /// </summary> public static QualifiedName Null => s_Null; private static readonly QualifiedName s_Null = new QualifiedName(); #endregion Static Methods } /// <summary> /// A collection of QualifiedName objects. /// </summary> /// <remarks> /// A strongly-typed collection of QualifiedName objects. /// </remarks> public partial class QualifiedNameCollection : List<QualifiedName>, ICloneable { /// <summary> /// Initializes an empty collection. /// </summary> /// <remarks> /// Initializes an empty collection. /// </remarks> public QualifiedNameCollection() { } /// <summary> /// Initializes the collection from another collection. /// </summary> /// <remarks> /// Initializes the collection from another collection. /// </remarks> /// <param name="collection">The enumerated collection of qualified names to add to this new collection</param> public QualifiedNameCollection(IEnumerable<QualifiedName> collection) : base(collection) { } /// <summary> /// Initializes the collection with the specified capacity. /// </summary> /// <remarks> /// Initializes the collection with the specified capacity. /// </remarks> /// <param name="capacity">Max capacity of this collection</param> public QualifiedNameCollection(int capacity) : base(capacity) { } /// <summary> /// Converts an array to a collection. /// </summary> /// <remarks> /// Converts an array to a collection. /// </remarks> /// <param name="values">The array to turn into a collection</param> public static QualifiedNameCollection ToQualifiedNameCollection(QualifiedName[] values) { if (values != null) return new QualifiedNameCollection(values); return new QualifiedNameCollection(); } /// <summary> /// Converts an array to a collection. /// </summary> /// <remarks> /// Converts an array to a collection. /// </remarks> /// <param name="values">The array to turn into a collection</param> public static implicit operator QualifiedNameCollection(QualifiedName[] values) { return ToQualifiedNameCollection(values); } #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> /// <remarks> /// Creates a deep copy of the collection. /// </remarks> public object Clone() { QualifiedNameCollection _clonedCollection = new QualifiedNameCollection(this.Count); foreach (QualifiedName _item in this) _clonedCollection.Add((QualifiedName)_item.Clone()); return _clonedCollection; } #endregion ICloneable Methods }//QualifiedNameCollection }//namespace <|start_filename|>DataDiscovery/Tests/DiscoveryServices.UnitTest/DomainModelUnitTest.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; using UAOOI.DataDiscovery.DiscoveryServices.Models; using UAOOI.DataDiscovery.DiscoveryServices.UnitTest.TestData; namespace UAOOI.DataDiscovery.DiscoveryServices.UnitTest { [TestClass] public class DomainModelUnitTest { [TestMethod] [DeploymentItem(@"TestData\", @"TestData\")] public void DeserializeAutoGeneratedXmlTest() { FileInfo file = new FileInfo(@"TestData\DomainModel.xml"); Assert.IsTrue(file.Exists); DomainModel newDescription = null; using (Stream _descriptionStream = file.OpenRead()) { XmlSerializer _serializer = new XmlSerializer(typeof(DomainModel)); newDescription = (DomainModel)_serializer.Deserialize(_descriptionStream); } Assert.IsNotNull(newDescription); Assert.IsFalse(string.IsNullOrEmpty(newDescription.AliasName)); Assert.IsFalse(string.IsNullOrEmpty(newDescription.Description)); Assert.IsFalse(string.IsNullOrEmpty(newDescription.DomainModelGuidString)); Assert.IsFalse(string.IsNullOrEmpty(newDescription.DomainModelUriString)); Assert.IsFalse(string.IsNullOrEmpty(newDescription.UniversalAddressSpaceLocator)); Assert.IsFalse(string.IsNullOrEmpty(newDescription.UniversalAuthorizationServerLocator)); Assert.IsTrue(string.IsNullOrEmpty(newDescription.UniversalDiscoveryServiceLocator)); } [TestMethod] public void TypeDictionariesTestMethod() { DomainModel domainModel = ReferenceDomainModel.GerReferenceDomainModel(); Assert.IsNotNull(domainModel.TypeDictionaries); Dictionary<string, TypeDictionaryWitKey> _dictionary = (from x in domainModel.TypeDictionaries from y in x.StructuredType select new TypeDictionaryWitKey { Key = $"{x.TargetNamespace}:{y.Name}", Dictionary = y }).ToDictionary<TypeDictionaryWitKey, string>(z => z.Key); Assert.AreEqual<int>(2, _dictionary.Count); } [TestMethod] public void SerializeTestMethod() { string fileName = "ReferenceDomainModel.xml"; DomainModel _dm = ReferenceDomainModel.GerReferenceDomainModel(); FileInfo file = new FileInfo($@"TestData\{fileName}"); using (Stream _outputStream = file.Create()) { XmlSerializer _serializer = new XmlSerializer(typeof(DomainModel)); _serializer.Serialize(_outputStream, _dm); } Assert.IsTrue(file.Exists); Assert.IsTrue(file.Length > 0); using (Stream _descriptionStream = file.OpenRead()) { XmlSerializer _serializer = new XmlSerializer(typeof(DomainModel)); DomainModel newDescription = (DomainModel)_serializer.Deserialize(_descriptionStream); Assert.IsNotNull(newDescription); } } [TestMethod] public void TestDataFolderContentTestMethod() { FileInfo _fi = new FileInfo(@"TestData\root.zone\commsvr.com\UA\Examples\BoilersSet\DomainModel.xml"); Assert.IsTrue(_fi.Exists); _fi = new FileInfo(@"TestData\root.zone\commsvr.com\UA\Examples\BoilersSet\DomainDescriptor.xml"); Assert.IsTrue(_fi.Exists); _fi = new FileInfo(@"TestData\root.zone\commsvr.com\UA\Examples\BoilersSet\Commsvr.UA.Examples.BoilersSet.NodeSet2.xml"); Assert.IsTrue(_fi.Exists); } private class TypeDictionaryWitKey { public string Key; public StructuredType Dictionary; } } } <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/XML/UANodeSetUnitTest.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; using System.IO; using UAOOI.SemanticData.BuildingErrorsHandling; using UAOOI.SemanticData.UANodeSetValidation.DataSerialization; using UAOOI.SemanticData.UANodeSetValidation.UAInformationModel; namespace UAOOI.SemanticData.UANodeSetValidation.XML { [TestClass] [DeploymentItem(@"XMLModels\", @"XMLModels\")] public class UANodeSetUnitTest { #region tests [TestMethod] public void OpcUaNodeSet2TestMethod() { FileInfo _testDataFileInfo = new FileInfo(@"XMLModels\CorrectModels\ReferenceTest\ReferenceTest.NodeSet2.xml"); Assert.IsTrue(_testDataFileInfo.Exists); UANodeSet instance = UANodeSet.ReadModelFile(_testDataFileInfo); Assert.IsNotNull(instance); Assert.IsNotNull(instance.NamespaceUris); Assert.IsNotNull(instance.Models); Mock<INamespaceTable> asbcMock = new Mock<INamespaceTable>(); asbcMock.Setup(x => x.GetURIIndexOrAppend(new Uri(@"http://cas.eu/UA/CommServer/UnitTests/ReferenceTest"))).Returns(1); List<TraceMessage> trace = new List<TraceMessage>(); Uri model = instance.ParseUAModelContext(asbcMock.Object, x => trace.Add(x)); Assert.IsNotNull(model); Assert.AreEqual<string>("http://cas.eu/UA/CommServer/UnitTests/ReferenceTest", model.ToString()); Assert.AreEqual<int>(0, trace.Count); asbcMock.Verify(x => x.GetURIIndexOrAppend(It.IsAny<Uri>()), Times.Exactly(2)); } [TestMethod] public void ReadUADefinedTypesTest() { UANodeSet instance = UANodeSet.ReadUADefinedTypes(); Assert.IsNotNull(instance); Assert.IsNotNull(instance.NamespaceUris); Assert.IsNotNull(instance.Models); Mock<INamespaceTable> asbcMock = new Mock<INamespaceTable>(); asbcMock.Setup(x => x.GetURIIndexOrAppend(It.IsAny<Uri>())); List<TraceMessage> trace = new List<TraceMessage>(); Uri model = instance.ParseUAModelContext(asbcMock.Object, x => trace.Add(x)); Assert.IsNotNull(model); Assert.AreEqual<string>("http://opcfoundation.org/UA/", model.ToString()); Assert.AreEqual<int>(0, trace.Count); asbcMock.Verify(x => x.GetURIIndexOrAppend(It.IsAny<Uri>()), Times.Never); } [TestMethod] public void NodeClassEnumTest() { UANode _toTest = new UADataType(); Assert.AreEqual<NodeClassEnum>(NodeClassEnum.UADataType, _toTest.NodeClassEnum); _toTest = new UAObject(); Assert.AreEqual<NodeClassEnum>(NodeClassEnum.UAObject, _toTest.NodeClassEnum); _toTest = new UAObjectType(); Assert.AreEqual<NodeClassEnum>(NodeClassEnum.UAObjectType, _toTest.NodeClassEnum); _toTest = new UAReferenceType(); Assert.AreEqual<NodeClassEnum>(NodeClassEnum.UAReferenceType, _toTest.NodeClassEnum); _toTest = new UAVariable(); Assert.AreEqual<NodeClassEnum>(NodeClassEnum.UAVariable, _toTest.NodeClassEnum); _toTest = new UAVariableType(); Assert.AreEqual<NodeClassEnum>(NodeClassEnum.UAVariableType, _toTest.NodeClassEnum); _toTest = new UAView(); Assert.AreEqual<NodeClassEnum>(NodeClassEnum.UAView, _toTest.NodeClassEnum); _toTest = new UAMethod(); Assert.AreEqual<NodeClassEnum>(NodeClassEnum.UAMethod, _toTest.NodeClassEnum); } [TestMethod] public void RemoveInheritedKeepDifferentValuesTest() { UAObjectType _derived = GetDerivedFromComplexObjectType(); UAObjectType _base = GetComplexObjectType(); _derived.RemoveInheritedValues(_base); Assert.AreEqual<int>(1, _derived.DisplayName.Length); Assert.AreEqual<string>("DerivedFromComplexObjectType", _derived.DisplayName[0].Value); } [TestMethod] public void RemoveInheritedRemoveSameValuesTest() { UAObjectType _derived = GetDerivedFromComplexObjectType(); UAObjectType _base = GetDerivedFromComplexObjectType(); _derived.RemoveInheritedValues(_base); Assert.IsNull(_derived.DisplayName); } [TestMethod] [ExpectedException(typeof(NotImplementedException))] public void EqualsTypesTest() { UANode _derived = GetDerivedFromComplexObjectType(); UANode _base = GetDerivedFromComplexObjectType(); Assert.IsTrue(_derived.Equals(_base)); } [TestMethod] public void EqualsInstancesTest() { UAObject _derived = GetInstanceOfDerivedFromComplexObjectType(); UAObject _base = GetInstanceOfDerivedFromComplexObjectType(); _derived.RecalculateNodeIds(new ModelContextMock(), x => Assert.Fail()); _base.RecalculateNodeIds(new ModelContextMock(), x => Assert.Fail()); Assert.IsTrue(_derived.Equals(_base)); } [TestMethod] public void EqualsUAVariableTest() { UAVariable firsNode = new UAVariable() { NodeId = "ns=1;i=47", BrowseName = "EURange", ParentNodeId = "ns=1;i=43", DataType = "i=884", DisplayName = new XML.LocalizedText[] { new XML.LocalizedText() { Value = "EURange" } } }; UAVariable secondNode = new UAVariable() { NodeId = "i=17568", BrowseName = "EURange", ParentNodeId = "i=15318", DataType = "i=884", DisplayName = new XML.LocalizedText[] { new XML.LocalizedText() { Value = "EURange" } } }; firsNode.RecalculateNodeIds(new ModelContextMock(), x => Assert.Fail()); secondNode.RecalculateNodeIds(new ModelContextMock(), x => Assert.Fail()); Assert.IsTrue(firsNode.Equals(secondNode)); } [TestMethod] public void NotEqualsInstancesTest() { UAObject firsNode = GetInstanceOfDerivedFromComplexObjectType(); UAObject secondNode = GetInstanceOfDerivedFromComplexObjectType2(); firsNode.RecalculateNodeIds(new ModelContextMock(), x => Assert.Fail()); secondNode.RecalculateNodeIds(new ModelContextMock(), x => Assert.Fail()); Assert.IsFalse(firsNode.Equals(secondNode)); } [TestMethod] public void RecalculateNodeIdsUADataTypeTest() { UADataType _enumeration = new UADataType() { NodeId = "ns=1;i=11", BrowseName = "1:EnumerationDataType", DisplayName = new LocalizedText[] { new LocalizedText() { Value = "EnumerationDataType" } }, References = new Reference[] { new Reference() {ReferenceType = ReferenceTypeIds.HasProperty.ToString(), Value="ns=1;i=12", IsForward = true }, new Reference() {ReferenceType = ReferenceTypeIds.HasSubtype.ToString(), Value="ns=1;i=9", IsForward = false } }, Definition = new DataTypeDefinition() { Name = "EnumerationDataType", Field = new DataTypeField[] { new DataTypeField() { Name = "Field3", Value = 1 } , new DataTypeField() { Name = "Field4", DataType = "ns=1;i=24" } } } }; _enumeration.RecalculateNodeIds(new ModelContextMock(), x => Assert.Fail()); Assert.AreEqual<string>("1:EnumerationDataType", _enumeration.BrowseName); Assert.AreEqual<string>("ns=1;i=11", _enumeration.NodeId); Assert.IsNotNull(_enumeration.BrowseNameQualifiedName); Assert.IsNotNull(_enumeration.NodeIdNodeId); Assert.AreEqual<int>(1, _enumeration.NodeIdNodeId.NamespaceIndex); Assert.IsTrue(_enumeration.BrowseNameQualifiedName.NamespaceIndexSpecified); Assert.AreEqual<int>(1, _enumeration.References[0].ValueNodeId.NamespaceIndex); Assert.AreEqual<int>(0, _enumeration.References[0].ReferenceTypeNodeid.NamespaceIndex); Assert.AreEqual<int>(1, _enumeration.References[1].ValueNodeId.NamespaceIndex); Assert.AreEqual<int>(0, _enumeration.References[1].ReferenceTypeNodeid.NamespaceIndex); Assert.AreEqual<string>("i=24", _enumeration.Definition.Field[0].DataTypeNodeId.ToString()); Assert.AreEqual<string>("ns=1;i=24", _enumeration.Definition.Field[1].DataTypeNodeId.ToString()); } #endregion tests #region test instrumentation private class ModelContextMock : IUAModelContext { public Uri ModelUri => throw new NotImplementedException(); public (QualifiedName browseName, NodeId nodeId) ImportBrowseName(string browseNameText, string nodeIdText, Action<TraceMessage> trace) { return (QualifiedName.Parse(browseNameText), NodeId.Parse(nodeIdText)); } public NodeId ImportNodeId(string nodeId, Action<TraceMessage> trace) { return NodeId.Parse(nodeId); } public void RegisterUAReferenceType(QualifiedName browseName) { throw new NotImplementedException(); } } private static UAObject GetInstanceOfDerivedFromComplexObjectType() { return new UAObject() { BrowseName = "1:InstanceOfDerivedFromComplexObjectType", NodeId = "ns=1;i=30", DisplayName = new XML.LocalizedText[] { new XML.LocalizedText() { Value = "InstanceOfDerivedFromComplexObjectType" } }, References = new XML.Reference[] { new XML.Reference(){ IsForward = true, ReferenceType = "HasProperty", Value = "ns=1;i=32" } } }; } private static UAObject GetInstanceOfDerivedFromComplexObjectType2() { return new UAObject() { BrowseName = "1:InstanceOfDerivedFromComplexObjectType", NodeId = "ns=1;i=30", DisplayName = new XML.LocalizedText[] { new XML.LocalizedText() { Value = "NewDisplayName" } }, References = new XML.Reference[] { new XML.Reference(){ IsForward = true, ReferenceType = "HasProperty", Value = "ns=1;i=32" } } }; } private static UAObjectType GetDerivedFromComplexObjectType() { return new UAObjectType() { NodeId = "ns=1;i=16", BrowseName = "1:DerivedFromComplexObjectType", DisplayName = new XML.LocalizedText[] { new XML.LocalizedText() { Value = "DerivedFromComplexObjectType" } }, References = new XML.Reference[] { new XML.Reference(){ IsForward = true, ReferenceType = "HasSubtype", Value = "ns=1;i=25" } } }; } private static UAObjectType GetComplexObjectType() { return new UAObjectType() { NodeId = "ns=1;i=1", BrowseName = "1:ComplexObjectType", DisplayName = new XML.LocalizedText[] { new XML.LocalizedText() { Value = "ComplexObjectType" } }, }; } #endregion test instrumentation } } <|start_filename|>DataDiscovery/DiscoveryServices/Properties/AssemblyInfo.cs<|end_filename|> //__________________________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions //__________________________________________________________________________________________________ using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTrademark("Object Oriented Internet")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo( "UAOOI.DataDiscovery.DiscoveryServices.UnitTest, PublicKey=" + "00240000048000009400000006020000002400005253413100040000010001005b97a0972ff6b13a" + "8a9ff9c09503aea0e5e2fe29cb2275a0c0942182f4c3431814b6bc9a556d9fe0d7e7823439c1ba28" + "521f6318e4c936c4461604ef668e9686c2021571b093e1bfba071b373bc56a07a3afdc120c5313d3" + "9a935cda64b759f857ebb3db483641444a5347e1564f8ba6d4fad2f968d3caf9991a4fa6aa019ebe" )] <|start_filename|>SemanticData/Tests/USNodeSetValidationUnitTestProject/ModelFactoryTestingFixture/DataTypeDefinitionFactoryBase.cs<|end_filename|> //___________________________________________________________________________________ // // Copyright (C) 2021, <NAME>. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System.Xml; using UAOOI.SemanticData.InformationModelFactory; namespace UAOOI.SemanticData.UANodeSetValidation.ModelFactoryTestingFixture { /// <summary> /// Class DataTypeDefinitionFactoryBase. /// Implements the <see cref="UAOOI.SemanticData.InformationModelFactory.IDataTypeDefinitionFactory" /> /// </summary> /// <seealso cref="UAOOI.SemanticData.InformationModelFactory.IDataTypeDefinitionFactory" /> internal class DataTypeDefinitionFactoryBase : IDataTypeDefinitionFactory { /// <summary> /// Creates new field and provides an object of <see cref="T:UAOOI.SemanticData.InformationModelFactory.IDataTypeFieldFactory" /> type encapsulating information about the field data type. /// </summary> /// <returns>Returns <see cref="T:UAOOI.SemanticData.InformationModelFactory.IDataTypeFieldFactory" /> .</returns> public IDataTypeFieldFactory NewField() { return new DataTypeFieldFactoryBase(); } /// <summary> /// Sets the name of the DataType. /// </summary> /// <value>The name represented as <see cref="T:System.Xml.XmlQualifiedName" />.</value> public XmlQualifiedName Name { set { } } /// <summary> /// A symbolic name for the data type. It should only be specified if the Name cannot be used for this purpose. /// Only letters, digits or the underscore (‘_’) are permitted. /// </summary> /// <value>The symbolic name of ti entity.</value> public string SymbolicName { set { } } /// <summary> /// Sets a value indicating whether this instance is option set. This flag indicates that the data type defines the OptionSetValues Property. /// This field is optional.The default value is false. /// </summary> /// <value><c>true</c> if this instance is option set; otherwise, <c>false</c>.</value> public bool IsOptionSet { set { } } /// <summary> /// Sets a value indicating whether this instance is union. /// Only one of the Fields defined for the data type is encoded into a value. /// This field is optional.The default value is false. If this value is true, the first field is the switch value. /// </summary> /// <value><c>true</c> if this instance is union; otherwise, <c>false</c>.</value> public bool IsUnion { set { } } } }
MichalSzczekocki/OPC-UA-OOI
<|start_filename|>src/windows/sitewaertsdocumentviewer/js/pdfviewer.js<|end_filename|> (function (window) { "use strict"; var debug = { enabled: true }; var PDFJS; var _closeRequested = false; var _closeables = []; function _addCloseable(handler) { _closeables.push(handler); } var _suspended = false; function _onSuspending() { _suspended = true; } function _onResuming() { _suspended = false; } function createCommonErrorHandler(context) { return function (eventInfo) { window.console.error(context, eventInfo); if (!_suspended) { var dialog; if (eventInfo.detail) { var detail = eventInfo.detail; dialog = new Windows.UI.Popups.MessageDialog( detail.stack, detail.message); } else { dialog = new Windows.UI.Popups.MessageDialog( context, eventInfo); } dialog.showAsync().done(); } // By returning true, we signal that the exception was handled, // preventing the application from being terminated return true; } } WinJS.Application.onerror = createCommonErrorHandler('WinJS.Application.onerror'); WinJS.Promise.onerror = createCommonErrorHandler('WinJS.Promise.onerror'); window.onerror = function (msg, url, line, col, error) { window.console.error(msg, {url: url, line: line, col: col, error: error}); // TODO: suspend event not fired in windows apps. why? // if (!_suspended) // { // try // { // var extra = !col ? '' : '\ncolumn: ' + col; // extra += !error ? '' : '\nerror: ' + error; // // var dialog = new Windows.UI.Popups.MessageDialog( // msg, "\nurl: " + url + "\nline: " + line + extra); // dialog.showAsync().done(); // } // catch (e) // { // // ignore // window.console.error("cannot show dialog", e); // } // } // //return true; }; // var webUIApp = (Windows // && Windows.UI) ? Windows.UI.WebUI.WebUIApplication : null; // if (webUIApp) // { // webUIApp.addEventListener("suspending", _onSuspending); // webUIApp.addEventListener("resuming", _onResuming); // } // function _eventLogger(element) { var events = [ 'MSPointerDown', 'MSPointerUp', 'MSPointerCancel', 'MSPointerMove', 'MSPointerOver', 'MSPointerOut', 'MSPointerEnter', 'MSPointerLeave', 'MSGotPointerCapture', 'MSLostPointerCapture', 'pointerdown', 'pointerup', 'pointercancel', 'pointermove', 'pointerover', 'pointerout', 'pointerenter', 'pointerleave', 'gotpointercapture', 'lostpointercapture', 'touchstart', 'touchmove', 'touchend', 'touchenter', 'touchleave', 'touchcancel', 'mouseover', 'mousemove', 'mouseout', 'mouseenter', 'mouseleave', 'mousedown', 'mouseup', 'focus', 'blur', 'click', 'webkitmouseforcewillbegin', 'webkitmouseforcedown', 'webkitmouseforceup', 'webkitmouseforcechanged' ]; function report(e) { console.log("event logger [" + e.type + "]", e, element); } for (var i = 0; i < events.length; i++) element.addEventListener(events[i], report, false); } $.fn.scrollLeftTo = function (target, options, callback) { if (typeof options === 'function' && arguments.length === 2) { callback = options; options = target; } var settings = $.extend({ scrollTarget: target, offsetLeft: 50, duration: 500, easing: 'swing' }, options); return this.each(function () { var scrollPane = $(this); var scrollX = -1; if (typeof settings.scrollTarget === "number") { scrollX = settings.scrollTarget; } else { if (settings.scrollTarget) { var scrollTarget = $(settings.scrollTarget); if (scrollTarget[0] && scrollTarget.offset()) scrollX = scrollTarget.offset().left + scrollPane.scrollLeft() - (scrollPane.width() / 2) + (scrollTarget.outerWidth() / 2); } } if (scrollX >= 0) { scrollPane.animate({scrollLeft: scrollX}, parseInt(settings.duration), settings.easing, function () { if (typeof callback === 'function') { callback.call(this); } }); } else { if (typeof callback === 'function') { callback.call(this); } } }); }; /** * * @type {angular.IModule} */ var module = angular.module('viewer', ['winjs'], null); module.run(function ($rootScope) { $rootScope.$on("app.suspending", _onSuspending); $rootScope.$on("app.resuming", _onResuming); }); module.factory('log', function ($window) { return $window.console; }); module.config([ '$compileProvider', function ($compileProvider) { // ms-appx|ms-appx-web ?? //$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); $compileProvider.imgSrcSanitizationWhitelist( /^\s*(blob|file|local|data):/); } ]); module.directive('backgroundImage', function () { return function (scope, element, attrs) { scope.$watch(attrs.backgroundImage, function (newValue) { if (newValue && newValue.length > 0) element.css('background-image', 'url("' + newValue + '")'); else element.css('background-image', ''); }); }; }); module.directive('interactionObserver', function ($timeout) { return function (scope, element, attrs) { var pointer = {}; var mouse = {}; var touch = {}; var pen = {}; var timeout = 3000; scope.interaction = { pointer: pointer, mouse: mouse, touch: touch, pen: pen }; function Observer(model, onActive) { var _endIt; function _detected() { if (_endIt) { $timeout.cancel(_endIt); _endIt = null; } _endIt = $timeout(function () { _endIt = null; _deactivate(); }, timeout); if (!model.detected || !model.active) { model.detected = true; model.active = true; scope.$evalAsync(function () { if (onActive) onActive(); }); } } function _deactivate() { if (_endIt) { $timeout.cancel(_endIt); _endIt = null; } if (model.active) { model.active = false; scope.$evalAsync(function () { }); } } this.onActivity = function () { _detected(); }; this.deactivate = function () { _deactivate(); }; } var _pointer = new Observer(pointer, function () { }); var _mouse = new Observer(mouse, function () { _touch.deactivate(); _pen.deactivate(); }); var _touch = new Observer(touch, function () { _mouse.deactivate(); _pen.deactivate(); }); var _pen = new Observer(pen, function () { _touch.deactivate(); _mouse.deactivate(); }); var _handlers = { 'mouse': { onActivity: _mouse.onActivity.bind(_mouse) }, 'touch': { onActivity: _touch.onActivity.bind(_touch) }, 'pen': { onActivity: _pen.onActivity.bind(_pen) } }; function _onPointerActivity(e) { _pointer.onActivity(e); var device = e.pointerType; var h = _handlers[device]; if (h) h.onActivity(e); } element.on( "pointerenter pointerleave pointermove pointerout pointerover pointerup pointerdown", _onPointerActivity) }; }); module.factory('views', function () { var _views = { loading: { id: 'loading', template: 'loading.html' }, pageflow: { id: 'pageflow', template: 'pageflow.html' }, outline: { id: 'outline', template: 'outline.html' }, tiles: { id: 'tiles', template: 'tiles.html' } }; function _getView(id) { var v = _views[id]; if (!v) throw new Error("unknown view '" + id + "'"); return v; } return { getView: _getView }; }); module.controller('PdfViewerCtrl', function ($scope, pdfViewer, views) { var ctrl = this; function _setView(id) { if (!ctrl.view || ctrl.view.id !== id) ctrl.view = views.getView(id); } ctrl.setView = _setView; ctrl.gotoPage = function (pageIndex, viewId) { if (pageIndex == null) return; ctrl.setFocusedPageIndex(pageIndex); if (viewId) ctrl.setView(viewId); }; ctrl.close = pdfViewer.close.bind(pdfViewer); ctrl.setFocusedPageIndex = pdfViewer.setFocusedPageIndex.bind(pdfViewer); ctrl.error = { message: null, dialog: { winControl: null, show: function () { if (ctrl.error.dialog.winControl) { // var _hideOnce = function(){ // ctrl.error.dialog.winControl.removeEventListener("afterhide", _hideOnce); // // }; // ctrl.error.dialog.winControl.addEventListener("afterhide", _hideOnce); ctrl.error.dialog.winControl.show(); } }, hide: function () { if (ctrl.error.dialog.winControl) { ctrl.error.dialog.winControl.hide(); } } } }; function _setViewerError() { var error = pdfViewer.doc.error; if (error) _setError(error); } function _setError(error) { ctrl.error.message = error.message || error; ctrl.error.details = error; ctrl.error.dialog.show(); } _setView('loading'); function _update() { ctrl.doc = pdfViewer.doc; } function _showPDF() { // TODO ctrl.doc = pdfViewer.doc; _setView('pageflow'); } $scope.$on("$destroy", pdfViewer.onPDFLoading(_update)); $scope.$on("$destroy", pdfViewer.onPDFLoaded(_showPDF)); $scope.$on("$destroy", pdfViewer.onPDFError(_setViewerError)); }); module.factory('ViewCtrlBase', function ($q, $window, pdfViewer) { function ViewCtrlBase($scope) { var ctrl = this; function _recalculateItemPosition() { if (ctrl.viewWinControl) ctrl.viewWinControl.recalculateItemPosition(); } ctrl.recalculateItemPosition = _recalculateItemPosition; ctrl.viewWinControl = null; function _getWinCtrl() { if (ctrl.viewWinControl && ctrl.viewWinControl._element) return $q.when(ctrl.viewWinControl); else return $q(function (resolve, reject) { var remove = $scope.$watch(function () { return ctrl.viewWinControl; }, function (viewWinControl) { if (viewWinControl && viewWinControl._element) { remove(); resolve(viewWinControl); } }); }); } ctrl.getWinCtrl = _getWinCtrl; function resize() { if (ctrl.resize) ctrl.resize(); } function close() { if (ctrl.close) ctrl.close(); } $window.addEventListener("resize", resize, false); $scope.$on('$destroy', function () { $window.removeEventListener("resize", resize); }); $scope.$on('$destroy', close); } return ViewCtrlBase; }); module.factory('ViewCtrlPagesBase', function ($q, $timeout, $interval, $window, pdfViewer, ViewCtrlBase) { /** * * @param {angular.IScope} $scope * @param opts * @constructor */ function ViewCtrlPagesBase($scope, opts) { var ctrl = this; ViewCtrlBase.call(ctrl, $scope); var localScope = $scope.$new(); localScope.ctrl = ctrl; ctrl.options = angular.extend( { containerMargin: 5, isIgnoringHighContrast: false, highRes: false, verticalCutOff: 50, horizontalCutOff: 0 }, opts); var _tmp = null; function getTemp() { if (ctrl.options.inMemory || _tmp) return $q.when(_tmp); return pdfViewer.getTemp().then(function (tmp) { _tmp = tmp; return $q.when(_tmp); }) } function _buildViewInfo() { var viewWidth = window.innerWidth; var viewHeight = window.innerHeight; var margin = ctrl.options.containerMargin; var rows = Math.max(1, ctrl.options.rows); var rawViewHeight = viewHeight - ctrl.options.verticalCutOff; if (rows > 1) rawViewHeight = rawViewHeight - (2 * margin) // top and bottom - ((rows - 1) * (2 * margin)); // margins between rows var containerHeight = Math.floor(rawViewHeight / rows); var rawViewWidth = viewWidth - ctrl.options.horizontalCutOff; rawViewWidth = rawViewWidth - (2 * margin); // left and right var containerWidth = Math.floor(rawViewWidth); var imageHeight = Math.max(window.screen.width, window.screen.height) / rows; var zoomFactor = 1; var resolutionFactor = 1; if (ctrl.options.highRes) { // zoomFactor = 1.3; // the use of dip should automatically apply the devicePixelRatio factor (but it actually doesn't) resolutionFactor = window.devicePixelRatio; } // init listeners etc. _getScrollContainer(); return { viewWidth: rawViewWidth, viewHeight: rawViewHeight, containerWidth: containerWidth, containerHeight: containerHeight, imageHeight: imageHeight, zoomFactor: zoomFactor * resolutionFactor }; } function _getViewInfo() { if (ctrl._viewInfo) return ctrl._viewInfo; return ctrl._viewInfo = _buildViewInfo(); } function _updateViewInfo() { var newViewInfo = _buildViewInfo(); if (!ctrl._viewInfo || !angular.equals(ctrl._viewInfo, newViewInfo)) { ctrl._viewInfo = newViewInfo; } ctrl.groupInfo = { enableCellSpanning: true, cellWidth: ctrl._viewInfo.containerWidth, cellHeight: ctrl._viewInfo.containerHeight }; return ctrl._viewInfo; } ctrl.getGroupInfo = function () { return ctrl.groupInfo; }; ctrl.getItemInfo = function (index) { if (!ctrl.pages || !ctrl.pages.list) return null; var p = ctrl.pages.list[index]; if (!p) return null; return p.itemInfo; }; function _isViewInfoChanged() { if (!ctrl._viewInfo) return true; var nvi = _buildViewInfo(); var ovi = ctrl._viewInfo; return !angular.equals(nvi, ovi); } function _reset() { delete ctrl.doc; if (ctrl.pages) ctrl.pages.close(); delete ctrl.pages; } function Page(options, pdf) { var page = this; angular.extend(this, options || {}); this.imageSrc = null; this.width = 0; this.height = 0; this.itemInfo = {width: 0, height: 0}; var _imageSrc_revoker; this.setImageSrc = function (url, revoker) { if (page.imageSrc !== url) { _clearImageSrc(); page.imageSrc = url; _imageSrc_revoker = revoker; } }; this.close = function () { _cancelGenerator(); _clearImageSrc(); }; function _clearImageSrc() { if (page.imageSrc && _imageSrc_revoker) _imageSrc_revoker(page.imageSrc); page.imageSrc = null; } var _pdfOptions = null; var _pdfOptionsChecksum = null; var _viewInfo = null; var _dirty = false; var _generator = null; var _pdfPage = pdf.getPage(page.pageIndex); var _dimRelation = _pdfPage.size.width / _pdfPage.size.height; _pdfOptions = new Windows.Data.Pdf.PdfPageRenderOptions(); _pdfOptions.isIgnoringHighContrast = page.isIgnoringHighContrast; function _isViewUpToDate(newViewInfo) { return angular.equals(_viewInfo, newViewInfo || _getViewInfo()); } function _calcDimensions() { var viewInfo = _viewInfo; var containerWidth = viewInfo.containerWidth; var pageHeight = viewInfo.containerHeight; var pageWidth = Math.floor( pageHeight * _dimRelation); if (pageWidth > containerWidth) { pageWidth = containerWidth; pageHeight = Math.floor( pageWidth / _dimRelation); } // used for item info page.width = pageWidth; page.height = pageHeight; //var imageHeight = pageHeight; var imageHeight = viewInfo.imageHeight; // destination height is in dp aka dip // https://msdn.microsoft.com/de-de/library/windows/apps/windows.data.pdf.pdfpagerenderoptions.destinationheight.aspx //http://stackoverflow.com/questions/2025282/difference-between-px-dp-dip-and-sp-in-android _pdfOptions.destinationHeight = Math.floor( imageHeight * viewInfo.zoomFactor); _pdfOptions.destinationWidth = null; // keep page ratio var pdfOptionsChecksum = _getChecksum(_pdfOptions); if (_pdfOptionsChecksum !== pdfOptionsChecksum && page.imageSrc) _dirty = true; _pdfOptionsChecksum = pdfOptionsChecksum; } function _getChecksum(object) { if (object == null) return ""; return JSON.stringify(object); // HACK } function _updateView() { _viewInfo = _getViewInfo(); _calcDimensions(); } function _updateViewIfNecessary() { if (_pdfOptionsChecksum && _isViewUpToDate()) return false; _updateView(); return true; } function _cancelInvalidGenerator() { if (!_generator) return; if (_generator.pdfOptionsChecksum === _pdfOptionsChecksum) return; _cancelGenerator(); } function _cancelGenerator() { if (!_generator) return; _generator.cancel(); _generator = null; } function _load() { _cancelInvalidGenerator(); if (_generator) return; var generator = _generator = { pdfOptions: _pdfOptions, pdfOptionsChecksum: _pdfOptionsChecksum, promise: null, canceled: false, cancel: function () { if (generator.canceled) return; generator.canceled = true; if (generator.promise) generator.promise.cancel(); }, applyResult: function (pi) { try { if (generator.canceled || _generator !== generator || _closeRequested) return; _dirty = false; _generator = null; var srcObject = pi.imageSrc; $scope.$evalAsync(function () { if (generator.canceled || _closeRequested) return; page.setImageSrc( URL.createObjectURL( srcObject, {oneTimeOnly: false}), URL.revokeObjectURL ); // page.setImageSrc( // URL.createObjectURL( // srcObject, // {oneTimeOnly: false}), // function () // { // // url will be revoked when iframe is closed // } // ); // page.setImageSrc( // URL.createObjectURL( // srcObject, // {oneTimeOnly: true}), // function () // { // } // ); }); } catch (e) { window.console.error(e); } }, applyError: function (error) { if (generator.canceled || _generator !== generator || _closeRequested) return; window.console.error(error); //_dirty = false; _generator = null; // keep old src } }; var _unregisterOnSuspending; function _onSuspending() { // webUIApp.removeEventListener("suspending", // _onSuspending); if (_unregisterOnSuspending) { _unregisterOnSuspending(); _unregisterOnSuspending = null; } generator.cancel(); } // force async exec $scope.$applyAsync(function () { if (_closeRequested) generator.cancel(); if (generator.canceled || _closeRequested) return; // if (webUIApp) // webUIApp.addEventListener("suspending", // _onSuspending); _unregisterOnSuspending = $scope.$on("app.suspending", _onSuspending); _unregisterOnSuspending = $scope.$on("closing", _onSuspending); generator.promise = pdfLibrary.loadPage( page.pageIndex, pdf, _generator.pdfOptions, _tmp == null, _tmp); generator.promise.done( generator.applyResult.bind(generator), generator.applyError.bind(generator)); }); } this.prepareDimensions = function () { return _updateViewIfNecessary(); }; // called when view dimensions may have changed this.triggerRefresh = function () { if (_isViewUpToDate()) return; _updateView(); if (!page.imageSrc && !_generator) return; // not yet loaded/loading --> no refresh necessary $scope.$applyAsync(_load); }; // called when image src is definitely needed (item is rendered) this.triggerLoad = function (async) { if (!_isViewUpToDate()) _updateView(); if (page.imageSrc && !_dirty) return; if (async) $scope.$applyAsync(_load); else _load(); }; } function createPagesDataSource(pages) { // implements IListDataAdapter (get only) var DataAdapter = WinJS.Class.define(function () { }, { getCount: function () { return WinJS.Promise.wrap(pages.length); }, // Called by the virtualized data source to fetch items // It will request a specific item and optionally ask for a number of items on either side of the requested item. // The implementation should return the specific item and, in addition, can choose to return a range of items on either // side of the requested index. The number of extra items returned by the implementation can be more or less than the number requested. itemsFromIndex: function (requestIndex, countBefore, countAfter) { if (requestIndex >= pages.length) return WinJS.Promise.wrapError( new WinJS.ErrorFromName( WinJS.UI.FetchError.doesNotExist)); // countBefore = Math.min(ctrl.options.pagesToLoad, // countBefore); // countAfter = Math.min(ctrl.options.pagesToLoad, // countAfter); var results = []; var fetchIndex = Math.max( requestIndex - countBefore, 0); var lastFetchIndex = Math.min( requestIndex + countAfter, pages.length - 1); pages[requestIndex].triggerLoad(); // trigger image generator on requested page first for (var i = fetchIndex; i <= lastFetchIndex; i++) { /** * @type Page */ var page = pages[i]; //page.triggerLoad(); // trigger image generator on requested pages results.push( {key: i.toString(), data: page}); } pdfViewer.setFocusedPageIndex(requestIndex); // implements IFetchResult return WinJS.Promise.wrap({ absoluteIndex: requestIndex, items: results, // The array of items. offset: requestIndex - fetchIndex, // The index of the requested item in the items array. totalCount: pages.length, // The total number of records. This is equal to total number of pages in a PDF file , atStart: fetchIndex === 0, atEnd: fetchIndex === pages.length - 1 }); } }); var DataSource = WinJS.Class.derive( WinJS.UI.VirtualizedDataSource, function () { this._baseDataSourceConstructor( new DataAdapter(), { // cacheSize: (ctrl.options.pagesToLoad * 2) + 1 cacheSize: ctrl.options.pagesToLoad } ); }, {} ); return new DataSource(); } function _showPDF() { _reset(); var doc = ctrl.doc = pdfViewer.doc; var pdf = pdfViewer.doc.file.pdf; var pageCount = doc.pageCount = pdf.pageCount; _updateViewInfo(); /** * * @type {Array} */ var pages = []; for (var count = 0; count < pageCount; count++) { var page = new Page({pageIndex: count}, pdf); pages.push(page); page.prepareDimensions(); } _updateDimensions(); function _refreshPages() { for (var i = 0; i < pages.length; i++) { var page = pages[i]; page.triggerRefresh(); // will recalc dimension at once and trigger async image calc if needed } _updateDimensions(); } function _close() { if (pages) { for (var i = 0; i < pages.length; i++) { var page = pages[i]; page.close(); } } pages = null; doc = null; pdf = null; } function _updateDimensions() { var rows = ctrl.options.rows; var cellWidth; if (rows === 1) { cellWidth = ctrl.options.containerMargin; } else { cellWidth = 0; } var cellHeight = ctrl.groupInfo.cellHeight; if (rows !== 1) { for (var i = 0; i < pages.length; i++) { cellWidth = Math.max( cellWidth, pages[i].width); } } // this is the raster with (minimal width of a cell) ctrl.groupInfo.cellWidth = cellWidth; for (var j = 0; j < pages.length; j++) { /** * * @type {Page} */ var page = pages[j]; if (rows === 1) { // calc needed number of cells spanned page.itemInfo.width = (Math.floor(page.width / cellWidth)) * cellWidth; // if (page.width % cellWidth !== 0) // page.itemInfo.width = page.itemInfo.width // + cellWidth; } else { page.itemInfo.width = cellWidth; } page.itemInfo.height = cellHeight; } ctrl.recalculateItemPosition(); } _gotoPageIndex(pdfViewer.getFocusedPageIndex()); $scope.$applyAsync(function () { ctrl.pages = { list: pages, dataSource: createPagesDataSource(pages), refresh: _refreshPages, close: _close }; ctrl.recalculateItemPosition(); }); } function _gotoPageIndex(idx) { function awaitCorrectLoadingState(winControl) { function isStateOK() { return winControl.loadingState === "viewPortLoaded"; } if (isStateOK()) return $q.when(winControl); else return $q(function (resolve, reject) { winControl.addEventListener( "loadingstatechanged", checkState); function checkState() { if (isStateOK()) { winControl.removeEventListener( "loadingstatechanged", checkState); resolve(winControl); } } }); } function ensureVisible(winControl) { winControl.ensureVisible(idx); } ctrl.getWinCtrl() .then(awaitCorrectLoadingState) .then(ensureVisible); } function _refreshView() { if (!_isViewInfoChanged()) return null; _updateViewInfo(); if (ctrl.pages) ctrl.pages.refresh(); _updateNav(); } ctrl.close = function () { if (ctrl.pages) ctrl.pages.close(); delete ctrl.pages; }; ctrl.resize = function () { var i = ctrl.viewWinControl.indexOfFirstVisible; $scope.$evalAsync( function () { _refreshView(); ctrl.viewWinControl.indexOfFirstVisible = i; $scope.$applyAsync(function () { ctrl.viewWinControl.indexOfFirstVisible = i; }); } ); }; var _nav = ctrl.nav = { scrollLeft: null, scrollRight: null }; function _scrollLeft() { if (_nav.nextLeftIndex != null) ctrl.focusPage(_nav.nextLeftIndex); else if (_nav.nextLeftPixel != null) ctrl.scrollToPixel(_nav.nextLeftPixel); } function _scrollRight() { if (_nav.nextRightIndex != null) ctrl.focusPage(_nav.nextRightIndex); else if (_nav.nextRightPixel != null) ctrl.scrollToPixel(_nav.nextRightPixel); } function _noNav() { _noLeftNav(); _noRightNav(); } function _noLeftNav() { delete _nav.nextLeftIndex; delete _nav.nextLeftPixel; delete _nav.scrollLeft; } function _noRightNav() { delete _nav.nextRightIndex; delete _nav.nextRightPixel; delete _nav.scrollRight; } var _scrollAnimationRunning = false; function _updateNav() { if (_scrollAnimationRunning) return; if (!ctrl.viewWinControl || !ctrl.pages || !ctrl.pages.list) return _noNav(); var _vwc = ctrl.viewWinControl; var sc = _getScrollContainer(); //var sp = _vwc.scrollPosition; var sp = sc.scrollLeft; var width = _vwc.element.clientWidth; if (!ctrl.zoom.zoomed) { var fvIdx = _vwc.indexOfFirstVisible; var lvIdx = _vwc.indexOfLastVisible; var length = ctrl.pages.list.length; var fvE = _vwc.elementFromIndex(fvIdx); if (!fvE || !fvE.offsetParent) return _noNav(); var fvEOffset = fvE.offsetParent.offsetLeft; var nextLeftIndex = fvEOffset < sp ? fvIdx // scroll the first item to be fully visible : fvIdx - 1; // scroll to the next left item var lvE = _vwc.elementFromIndex(lvIdx); if (!lvE || !lvE.offsetParent) return _noNav(); var lvEOffset = lvE.offsetParent.offsetLeft; var nextRightIndex = (lvEOffset + lvE.offsetWidth) > (sp + width) ? lvIdx // scroll the last item to be fully visible : lvIdx + 1; // scroll to the next right item if (nextLeftIndex >= 0) { _nav.nextLeftIndex = nextLeftIndex; delete _nav.nextLeftPixel; _nav.scrollLeft = _scrollLeft; } else { _noLeftNav(); } if (nextRightIndex < length) { _nav.nextRightIndex = nextRightIndex; delete _nav.nextRightPixel; _nav.scrollRight = _scrollRight; } else { _noRightNav(); } } else { var totalWidth = sc.scrollWidth; var maxScrollLeft = _fixedScrollPos(totalWidth, totalWidth, width * -1, ctrl.zoom.factor); if (sp > 0) { delete _nav.nextLeftIndex; _nav.nextLeftPixel = Math.max(0, _fixedScrollPos(totalWidth, sp, width * -1, ctrl.zoom.factor)); _nav.scrollLeft = _scrollLeft; } else { _noLeftNav(); } if (sp < maxScrollLeft) { delete _nav.nextRightIndex; // browser will auto fix values which exceed the limit _nav.nextRightPixel = _fixedScrollPos(totalWidth, sp, width, ctrl.zoom.factor); _nav.scrollRight = _scrollRight; } else { _noRightNav(); } } } localScope.$watch('ctrl.viewWinControl.indexOfFirstVisible', _updateNav); localScope.$watch('ctrl.viewWinControl.indexOfLastVisible', _updateNav); localScope.$watch('ctrl.viewWinControl.scrollPosition', _updateNav); localScope.$watch('ctrl.pages.list.length', _updateNav); var _fixedScrollPos = function (scrollWidth, start, delta, zoomFactor) { if (zoomFactor != null && zoomFactor * 100 !== 100) { // hack: edge calculates wrong scrollLeft, width etc. when zoomed return Math.floor(((start * zoomFactor) + delta) / zoomFactor); } return start + delta; }; function _addMouseDragScroll(scrollable) { if (!scrollable || scrollable._mouseDragScroll) return; scrollable._mouseDragScroll = true; //_eventLogger(scrollable); scrollable.ondragstart = function () { return false; }; function _isMouseEvent(event) { return event && event.pointerType === 'mouse'; } function _onScrollStart(event) { if (!_isMouseEvent(event)) return; // event.preventDefault(); // event.stopPropagation(); // event.stopImmediatePropagation(); var target = event.target; var zoom = _zoomForElement(scrollable); var sw = scrollable.scrollWidth; var sh = scrollable.scrollHeight; var _mouseStartX = event.pageX; var _scrollStartX = scrollable.scrollLeft; var _mouseStartY = event.pageY; var _scrollStartY = scrollable.scrollTop; var _moved = false; var _capturedPointerId = null; function _onScroll(event) { if (!_isMouseEvent(event)) return; // event.preventDefault(); // event.stopPropagation(); // event.stopImmediatePropagation(); if (!_moved) { // this is a scroll situation: // capture the event to tell others that // they must cancel their pending tasks (e.g. click) _moved = true; _capturedPointerId = event.pointerId; target.setPointerCapture(event.pointerId); } var sl = _fixedScrollPos( sw, _scrollStartX, _mouseStartX - event.pageX, zoom); var st = _fixedScrollPos( sh, _scrollStartY, _mouseStartY - event.pageY, zoom); scrollable.scrollLeft = sl; scrollable.scrollTop = st; } function _onScrollEnd(event) { // event.preventDefault(); // event.stopPropagation(); // event.stopImmediatePropagation(); target.removeEventListener('pointermove', _onScroll); target.removeEventListener('pointerup', _onScrollEnd); //scrollable.removeEventListener('pointerout', _onScrollEnd); target.removeEventListener('lostpointercapture', _onScrollEnd); target.removeEventListener('pointercancel', _onScrollEnd); if (_moved && _capturedPointerId === event.pointerId) { event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation(); target.releasePointerCapture(event.pointerId); _onScroll(event); } scrollable.addEventListener('pointerdown', _onScrollStart); } scrollable.removeEventListener('pointerdown', _onScrollStart); target.addEventListener('pointermove', _onScroll); target.addEventListener('pointerup', _onScrollEnd); //scrollable.addEventListener('pointerout', _onScrollEnd, false); target.addEventListener('lostpointercapture', _onScrollEnd); target.addEventListener('pointercancel', _onScrollEnd); } scrollable.addEventListener('pointerdown', _onScrollStart); } function _getScrollContainer() { if (!ctrl.viewWinControl) return null; var e = ctrl.viewWinControl.element.querySelector('.win-viewport.win-horizontal'); if (e && !e._zoomListener) { e._zoomListener = true; e.addEventListener("MSContentZoom", _$updateZoom); } _addMouseDragScroll(e); return e; } function _get$ScrollContainer() { var e = _getScrollContainer(); if (!e) return null; return $(e); } function _getPageElement(idx) { if (!ctrl.viewWinControl || !ctrl.pages || !ctrl.pages.list) return null; if (idx == null) return null; if (idx < 0) return null; var length = ctrl.pages.list.length; if (idx > length - 1) return null; var _vwc = ctrl.viewWinControl; return _vwc.elementFromIndex(idx); } function _getPageScrollPos(idx) { var e = _getPageElement(idx); if (!e) return null; return e.offsetParent.offsetLeft; } function _isFullyVisible(idx) { var e = _getPageElement(idx); if (!e) return false; var _vwc = ctrl.viewWinControl; var sc = _getScrollContainer(); //var sp = _vwc.scrollPosition; var sp = sc.scrollLeft; var width = _vwc.element.clientWidth; var offset = e.offsetParent.offsetLeft; if (offset < sp) return false; return (offset + e.offsetWidth) <= (sp + width); } ctrl.ensurePageFocused = function (pageIndex) { if (_isFullyVisible(pageIndex)) return false; ctrl.focusPage(pageIndex); return true; }; ctrl.focusPage = function (pageIndex) { if (pageIndex == null) return; if (!ctrl.viewWinControl) return; var pixel = _getPageScrollPos(pageIndex); if (pixel == null) return; var sc = _getScrollContainer(); var sp = sc.scrollLeft; if (sp < pixel) { var _vwc = ctrl.viewWinControl; var width = _vwc.element.clientWidth; // scroll right --> adjust on right side pixel = pixel - width + _getPageElement(pageIndex).offsetWidth } pdfViewer.setFocusedPageIndex(pageIndex); ctrl.scrollToPixel(pixel); // ctrl.viewWinControl.ensureVisible(pageIndex); //ctrl.viewWinControl.recalculateItemPosition(); }; ctrl.scrollToPixel = function (pixel) { if (pixel == null) return; if (!ctrl.viewWinControl) return; //ctrl.viewWinControl.scrollPosition = pixel; _scrollAnimationRunning = true; _get$ScrollContainer().scrollLeftTo(pixel, function () { // done _scrollAnimationRunning = false; $scope.$evalAsync(function () { _updateNav(); }); }); }; var _zoomLevels = [1, 1.5, 2, 3]; function _findNextZoomLevelUp(current) { for (var i = 0; i < _zoomLevels.length; i++) { var zl = _zoomLevels[i]; if (zl > current) return zl; } return null; } function _findNextZoomLevelDown(current) { for (var i = _zoomLevels.length - 1; i >= 0; i--) { var zl = _zoomLevels[i]; if (zl < current) return zl; } return null; } function _zoom(factor) { return _zoomForElement(_getScrollContainer(), factor); } function _zoomForElement(element, factor) { var result = null; if (element) { result = element.msContentZoomFactor.toFixed(2); if (factor != null) element.msContentZoomFactor = factor; } if (isNaN(result) || result == null || result === "") return 1; return result; } ctrl.zoom = { factor: 1, zoomed: false, forward: function () { var current = _zoom(); var next = _findNextZoomLevelUp(current); if (next == null) next = _zoomLevels[0]; _zoom(next); }, zoomIn: function () { var current = _zoom(); var next = _findNextZoomLevelUp(current); if (next != null) _zoom(next); }, zoomOut: function () { var current = _zoom(); var next = _findNextZoomLevelDown(current); if (next != null) _zoom(next); } }; function _$updateZoom() { var newZoom = _zoom(); if (ctrl.zoom.factor !== newZoom) { ctrl.zoom.factor = newZoom; ctrl.zoom.zoomed = ctrl.zoom.factor * 100 !== 100; $scope.$evalAsync(function () { _updateNav(); }); } } // function _updateZoom() // { // ctrl.zoom.factor = _zoom(); // ctrl.zoom.zoomed = ctrl.zoom.factor * 100 !== 100; // _updateNav(); // } // // localScope.$watch('ctrl.viewWinControl.element.style.zoom', // _updateZoom); // // function _waitForPDF() { return getTemp().then( pdfViewer.waitForPDF.bind(pdfViewer)); } // start _waitForPDF().then(_showPDF); } return ViewCtrlPagesBase; }); module.controller('PageflowViewCtrl', function (ViewCtrlPagesBase, $scope) { var ctrl = this; ViewCtrlPagesBase.call(ctrl, $scope, { rows: 1, inMemory: false, pagesToLoad: 2, highRes: true, verticalCutOff: 50, horizontalCutOff: 0 }); }); module.controller('TilesViewCtrl', function (ViewCtrlPagesBase, $scope) { var ctrl = this; ViewCtrlPagesBase.call(ctrl, $scope, { rows: 4, inMemory: false, pagesToLoad: 2, highRes: false, verticalCutOff: 50, horizontalCutOff: 0 }); }); module.controller('OutlineViewCtrl', function (ViewCtrlBase, $scope, pdfViewer) { var ctrl = this; ViewCtrlBase.call(ctrl, $scope); function _showOutline() { ctrl.outline = pdfViewer.doc.outline; } pdfViewer.waitForPDF().then(_showOutline); }); module.factory('pdfViewer', /** * * @param {angular.IScope} $rootScope * @param {angular.IQService} $q * @param log * @return {{}} */ function ($rootScope, $q, log) { PDFJS = window['pdfjs-dist/build/pdf']; var EVENTS = { LOADING_PDF: 'pdf.loading', SHOW_PDF: 'pdf.loaded', ERROR: 'pdf.error' }; function _cleanupUri(uri) { if (!uri || uri.length <= 0) return null; // remove double slashes uri = uri.replace(/([^\/:])\/\/([^\/])/g, '$1/$2'); // ms-appx-web --> ms-appx uri = uri.replace(/^ms-appx-web:\/\//, 'ms-appx://'); return uri; } var pdfUri; var pdfOptions; var closeHandler; var service = {}; function _showPdf(args) { pdfUri = args.pdfUri; pdfOptions = args.pdfOptions; closeHandler = args.closeHandler; service.doc = { title: pdfOptions.title, file: {} }; if (!pdfUri) { $rootScope.$broadcast(EVENTS.ERROR, {message: "no file specified"}); return; } pdfUri = _cleanupUri(pdfUri); service.doc.file.uri = pdfUri; $rootScope.$broadcast(EVENTS.LOADING_PDF); function _onError(error) { if (_closeRequested) return; window.console.error(pdfUri, error); service.doc.error = error; $rootScope.$broadcast(EVENTS.ERROR); } loadFile(pdfUri) .then(function (file) { if (_closeRequested) return; return $q.all([loadPDF(file), loadPDFOutline(pdfUri)]); }) .done(function () { if (_closeRequested) return; $rootScope.$broadcast(EVENTS.SHOW_PDF); }, _onError); function loadFile(fileUri) { var uri = new Windows.Foundation.Uri(fileUri); return Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri) .then( function (file) { if (_closeRequested) return; // Updating details of file currently loaded service.doc.file.loaded = file; $rootScope.$broadcast(EVENTS.LOADING_PDF); return file; } ); } function loadPDF(file) { // Loading PDf file from the assets // TODO: Password protected file? user should provide a password to open the file return pdfLibrary.loadPDF(file).then( function (pdfDocument) { if (_closeRequested) return; if (!pdfDocument) throw new Error( {message: "pdf file cannot be loaded"}); // Updating details of file currently loaded service.doc.file.pdf = pdfDocument; $rootScope.$broadcast(EVENTS.LOADING_PDF); return getCleanTemp().then(function () { return pdfDocument }); }); } function loadPDFOutline(fileUri) { // TODO: Password protected file? user should provide a password to open the file PDFJS.GlobalWorkerOptions.disableWorker = true; PDFJS.GlobalWorkerOptions.workerSrc = 'js/worker.js'; return $q(function (resolve, reject) { function onError(error) { if (_closeRequested) return; log.warn("cannot load outline for pdf", fileUri, error); service.doc.outline = null; resolve(); } function onSuccess(pdf, outline) { if (_closeRequested) return; /* raw outline is structured like this: *[ * { * title: string, * bold: boolean, * italic: boolean, * color: rgb Uint8Array, * dest: dest obj, * url: string, * items: array of more items like this * }, * ... * ] * */ function convertItems(items) { if (!items || items.length <= 0) return; items.forEach(function (item) { getPageIndex(item).then( function (pageIndex) { if (pageIndex != null) item.pageIndex = pageIndex; else delete item.pageIndex; }, function (error) { log.error( "cannot determine page index for outline item", item, error); delete item.pageIndex; } ); convertItems(item.items); }); } function getPageIndex(item) { return $q(function (resolve, reject) { var dest = item.dest; var destProm; if (typeof dest === 'string') destProm = pdf.getDestination(dest); else destProm = Promise.resolve(dest); destProm.then(function (destination) { if (!(destination instanceof Array)) { reject(destination); return; // invalid destination } var destRef = destination[0]; pdf.getPageIndex(destRef).then( function (pageIndex) { resolve(pageIndex); }, reject); }, reject); }); } if (outline && outline.length > 0) { outline = angular.copy(outline); convertItems(outline); service.doc.outline = outline; } else { outline = null; delete service.doc.outline; } //$rootScope.$broadcast(EVENTS.LOADING_PDF); resolve(); } var pdfLoadingTask = PDFJS.getDocument(fileUri); _addCloseable(function(){ return pdfLoadingTask.destroy(); }); pdfLoadingTask.promise.then( /** * * @param {PDFDocumentProxy} pdf */ function (pdf) { if (!_closeRequested) { _addCloseable(function () { return WinJS.Promise.join([pdf.cleanup(), pdf.destroy()]); }) } var _outlineReady = new WinJS.Promise(function (resolve, reject) { if (_closeRequested) return; _addCloseable(function () { return _outlineReady; }) console.log("outline pending") pdf.getOutline().then(function (outline) { console.log("outline ready") resolve(); onSuccess(pdf, outline); }, function (error) { console.log("outline ready", error) resolve(); onError(error) } ); }) }, onError); }); } } function _prepareClose(callback) { _closeRequested = true; $rootScope.$broadcast("closing"); WinJS.Promise.join(_closeables.map(function (closeable) { try { if (closeable) return WinJS.Promise.wrap(closeable()).done(function () { }, function (e) { console.error("pdfviewer.js: cannot close a closeable", e, closeable); }); return WinJS.Promise.wrap(); } catch (e) { console.error("pdfviewer.js: cannot close a closeable", e, closeable); } })).done(function () { WinJS.Application.stop(); setTimeout(callback, 60 * 1000); // wait for pdfjs worker cleanup }, function (e) { console.error("pdfviewer.js: cannot close all closeables", e); WinJS.Application.stop(); setTimeout(callback, 60 * 1000); }); } _setHandler({ showPDF: function (args) { _showPdf(args); }, prepareClose: function (callback) { _prepareClose(callback); }, appSuspend: function () { $rootScope.$broadcast("app.suspend"); }, appResume: function () { $rootScope.$broadcast("app.resume"); } }); function getCleanTemp() { // clear/create temp folder return WinJS.Application.temp.folder.createFolderAsync( "pdfViewer", Windows.Storage.CreationCollisionOption.replaceExisting ); } service.getCleanTemp = getCleanTemp; function getTemp() { // clear/create temp folder return WinJS.Application.temp.folder.createFolderAsync( "pdfViewer", Windows.Storage.CreationCollisionOption.openIfExists ); } service.getTemp = getTemp; service.close = function () { closeHandler(); }; service.onPDFLoading = function (handler) { function _handler() { $rootScope.$applyAsync(handler); } if (pdfUri) _handler(); return $rootScope.$on(EVENTS.LOADING_PDF, _handler); }; service.onPDFLoaded = function (handler) { function _handler() { $rootScope.$applyAsync(handler); } if (service.isPDFLoaded()) _handler(); return $rootScope.$on(EVENTS.SHOW_PDF, _handler); }; service.isPDFLoaded = function () { return service.doc && service.doc.file && service.doc.file.pdf; }; service.waitForPDF = function () { if (service.isPDFLoaded()) return $q.when(); return $q(function (resolve, reject) { var removeLoaded = service.onPDFLoaded(function notify() { cleanup(); resolve(); }); var removeError = service.onPDFError(function notify() { cleanup(); reject(); }); function cleanup() { // if(removeLoaded) removeLoaded(); // if(removeError) removeError(); } }); }; service.onPDFError = function (handler) { function _handler() { $rootScope.$applyAsync(handler); } return $rootScope.$on(EVENTS.ERROR, _handler); }; var _focusedPageIndex = 0; service.setFocusedPageIndex = function (idx) { _focusedPageIndex = idx; }; service.getFocusedPageIndex = function () { return _focusedPageIndex; }; return service; }); // ========================================================================= var _args = null; var _handler = []; function _setHandler(handler) { _handler.push(handler); if (_args) handler.showPDF(_args); } /** * public api to start the viewer * * @param pdfUri * @param pdfOptions * @param closeHandler */ window.showPDF = function (pdfUri, pdfOptions, closeHandler) { _args = { pdfUri: pdfUri, pdfOptions: pdfOptions, closeHandler: closeHandler }; _handler.forEach(function (handler) { handler.showPDF(_args); }); }; window.prepareClose = function (callback) { _handler.forEach(function (handler) { handler.prepareClose(callback); }); } window.appSuspend = function () { _handler.forEach(function (handler) { handler.appSuspend(_args); }); }; window.appResume = function () { _handler.forEach(function (handler) { handler.appResume(_args); }); }; })(this); <|start_filename|>update_dependencies.bat<|end_filename|> call bower update call npm update xcopy bower_components\jquery src\common\js\jquery /S /E /Y /i xcopy bower_components\winjs src\common\js\winjs /S /E /Y /i xcopy bower_components\angular src\common\js\angular /S /E /Y /i xcopy bower_components\angular-winjs src\common\js\angular-winjs /S /E /Y /i xcopy bower_components\angular-gestures src\common\js\angular-gestures /S /E /Y /i xcopy node_modules\pdfjs-dist src\common\js\pdfjs-dist /S /E /Y /i <|start_filename|>src/windows/sitewaertsdocumentviewerProxy_native.js<|end_filename|> var parser = document.createElement("a"); var PDF = "application/pdf"; // this dir must be located in www var viewerLocation = "sitewaertsdocumentviewer"; parser.href = "/www/" + viewerLocation + "/viewer.html"; var viewerIFrameSrc = parser.href; // avoid loading of apps index.html when source is set to "" parser.href = "/www/" + viewerLocation + "/empty.html"; var emptyIFrameSrc = parser.href; // avoid loading of apps index.html when source is set to "" parser.href = "/www/" + viewerLocation + "/intermediate.html"; var intermediateIFrameSrc = parser.href; // avoid app crash var viewerCloseDelay = 1; var Args = { URL: "url", CONTENT_TYPE: "contentType", OPTIONS: "options" }; var viewerIdBase = "sitewaertsdocumentviewer_windows"; /** * @typedef {Object} Container * @property {number} index * @property {function(options:any, close:function())} showPDF, * @property {function(callback:function()):void} prepare, * @property {function():void} close, * @property {function():void} cleanup, * @property {function():void} appSuspend, * @property {function():void} appResume, * @property {function(errorHandler:function()):void} setErrorHandler, * @property {function(closeHandler:function()):void} setCloseHandler, * @property {function(closeOnPause:boolean):void} setCloseOnPause */ /** * @callback ContainerCallback * @param {Container} container */ /** * * @type {Record<string, Container>} */ var containers = {}; /** * @type {string | null} */ var containers_current_Id = null; /** * @type {number} */ var containers_counter = -1; /** * @return {Container | null} */ function _getCurrentContainer() { if (!containers.containers_current_Id) return null; return containers[containers_current_Id]; } /** * @param {string} url * @param {ContainerCallback} callback * @void */ function _createContainer(url, callback) { return _createContainerIFrameReusable(url, callback); } /** * BROKEN as WebView cannot natively show pdfs * @param {string} url * @param {ContainerCallback} callback * @void */ function _createContainerMSWebView(url, callback) { var viewerIndex = ++containers_counter; var viewerId = viewerIdBase + "_" + viewerIndex; var webviewId = viewerId + "_webview"; var closeId = viewerId + "_close"; /** * @type {HTMLElement} */ var viewer = document.getElementById(viewerId) || document.createElement("div"); // noinspection JSValidateTypes /** * * @type {HTMLIFrameElement} */ var webview = document.getElementById(webviewId) || document.createElement("x-ms-webview"); /** * @type {HTMLElement} */ var close = document.getElementById(closeId) || document.createElement("div"); viewer.id = viewerId; viewer.className = "sitewaertsdocumentviewer windows"; close.id = closeId; close.className = "close"; webview.id = webviewId; webview.src = emptyIFrameSrc; viewer.appendChild(webview); viewer.appendChild(close); document.body.appendChild(viewer); close.onclick = _doClose; webview.onerror = _onError; var _info = "[" + viewerIndex + "][" + url + "]"; var _closeHandler; /** * @param {function():void} closeHandler * @private */ function _setCloseHandler(closeHandler) { _closeHandler = closeHandler; } var _closeOnPause; /** * @param {boolean} closeOnPause * @private */ function _setCloseOnPause(closeOnPause) { _closeOnPause = closeOnPause === true; } var _errorHandler; /** * @param {function(error:any):void} errorHandler * @private */ function _setErrorHandler(errorHandler) { _errorHandler = errorHandler; } function _onError(arguments) { try { console.error(_info + ': error in iframe', arguments); if (_errorHandler) _errorHandler.apply(null, arguments); } catch (e) { console.error(_info + ': error in iframe error handling', e); } return true; // avoid app crash } /** * @void * @private */ function _cleanup() { _closeHandler = null; _closeOnPause = null; const v = viewer; viewer = null; if (v) { console.info(_info + ': cleanup: hiding dom elements'); v.style.display = 'none'; // setTimeout(function () // { console.info(_info + ': cleanup: loading empty content'); webview.src = emptyIFrameSrc; webview.onload = function () { _destroy(v); } // }, viewerCloseDelay); } delete containers[viewerId]; } /** * @param {HTMLElement} viewer * @void * @private */ function _destroy(viewer) { if (viewer) { console.info(_info + ': destroy: removing dom elements'); viewer.remove(); viewer = null; } } /** * @void * @private */ function _doClose() { var ch = _closeHandler; _cleanup(); if (ch) ch(); // closed } /** * @param {function():void} callback * @void * @private */ function _prepare(callback) { // iframe.src = viewerIFrameSrc; // iframe.onload = function () // { // // avoid reloading on close // iframe.onload = null; callback(); // } } /** * @param {any} options * @param {function()} close * @void * @private */ function _showPDF(options, close) { webview.src = url; // /** // * // * @type {Window} // */ // var w = iframe['window'] || iframe.contentWindow; // w.showPDF(url, options, close); viewer.style.display = 'block'; } /** * @void * @private */ function _appSuspend() { // var w = iframe.window || iframe.contentWindow; // if (w && w.appSuspend) // w.appSuspend(); // if (_closeOnPause) // _doClose(); } /** * @void * @private */ function _appResume() { // var w = iframe.window || iframe.contentWindow; // if (w && w.appResume) // w.appResume(); } /** * * @type {Container} */ var container = { showPDF: _showPDF, prepare: _prepare, close: _doClose, cleanup: _cleanup, appSuspend: _appSuspend, appResume: _appResume, setErrorHandler: _setErrorHandler, setCloseHandler: _setCloseHandler, setCloseOnPause: _setCloseOnPause }; containers[viewerId] = container; containers_current_Id = viewerId; callback(container); } var _globalIntermediate; /** * @typedef {Object} GlobalIntermediate * @property {HTMLElement} viewer * @property {HTMLElement} close * @property {function():HTMLIFrameElement} getContentIFrame */ /** * @callback GlobalIntermediateCallback * @param {GlobalIntermediate} globalIntermediate */ /** * @param {GlobalIntermediateCallback} callback * @void */ function _getGlobalIntermediate(callback) { if (_globalIntermediate) return callback(_globalIntermediate); var viewerId = viewerIdBase + "_intermediate"; var iframeId = viewerId + "_iframe"; var closeId = viewerId + "_close"; /** * @type {HTMLElement} */ var viewer = document.getElementById(viewerId) || document.createElement("div"); // noinspection JSValidateTypes /** * * @type {HTMLIFrameElement} */ var iframe = document.getElementById(iframeId) || document.createElement("iframe"); /** * @type {HTMLElement} */ var close = document.getElementById(closeId) || document.createElement("div"); viewer.id = viewerId; viewer.className = "sitewaertsdocumentviewer windows"; close.id = closeId; close.className = "close"; iframe.id = iframeId; viewer.appendChild(iframe); viewer.appendChild(close); document.body.appendChild(viewer); close.onclick = function () { console.warn("close click not yet implemented in global intermediate"); }; iframe.onerror = function (error) { console.error("error in global intermediate", error); return true; }; viewer.style.display = 'none'; _globalIntermediate = { viewer: viewer, close: close, getContentIFrame: function () { return (iframe.window || iframe.contentWindow).document.getElementById('intermediate') } }; iframe.onload = function () { iframe.onload = null; callback(_globalIntermediate); } iframe.src = intermediateIFrameSrc; } /** * @param {string} url * @param {ContainerCallback} callback * @void */ function _createContainerIntermediateIFrame(url, callback) { _getGlobalIntermediate(function (_intermediate) { var viewerIndex = ++containers_counter; var viewerId = viewerIdBase + "_" + viewerIndex; var viewer = _intermediate.viewer; var close = _intermediate.close; var iframe = _intermediate.getContentIFrame(); close.onclick = _doClose; var _info = "[" + viewerIndex + "][" + url + "]"; var _closeHandler; /** * @param {function():void} closeHandler * @private */ function _setCloseHandler(closeHandler) { _closeHandler = closeHandler; } var _closeOnPause; /** * @param {boolean} closeOnPause * @private */ function _setCloseOnPause(closeOnPause) { _closeOnPause = closeOnPause === true; } var _errorHandler; /** * @param {function(error:any):void} errorHandler * @private */ function _setErrorHandler(errorHandler) { _errorHandler = errorHandler; } /** * @void * @private */ function _cleanup() { _closeHandler = null; _closeOnPause = null; const v = viewer; viewer = null; if (v) { v.style.display = 'none'; iframe.src = emptyIFrameSrc; } delete containers[viewerId]; } /** * @void * @private */ function _doClose() { var ch = _closeHandler; _cleanup(); if (ch) ch(); // closed } /** * @param {function():void} callback * @void * @private */ function _prepare(callback) { iframe.src = viewerIFrameSrc; iframe.onload = function () { // avoid reloading on close iframe.onload = null; callback(); } } /** * @param {any} options * @param {function()} close * @void * @private */ function _showPDF(options, close) { /** * * @type {Window} */ var w = iframe['window'] || iframe.contentWindow; w.showPDF(url, options, close); viewer.style.display = 'block'; } /** * @void * @private */ function _appSuspend() { var w = iframe.window || iframe.contentWindow; if (w && w.appSuspend) w.appSuspend(); if (_closeOnPause) _doClose(); } /** * @void * @private */ function _appResume() { var w = iframe.window || iframe.contentWindow; if (w && w.appResume) w.appResume(); } /** * * @type {Container} */ var container = { showPDF: _showPDF, prepare: _prepare, close: _doClose, cleanup: _cleanup, appSuspend: _appSuspend, appResume: _appResume, setErrorHandler: _setErrorHandler, setCloseHandler: _setCloseHandler, setCloseOnPause: _setCloseOnPause }; containers[viewerId] = container; containers_current_Id = viewerId; callback(container); }); } /** * @param {string} url * @param {ContainerCallback} callback * @void */ function _createContainerIFrame(url, callback) { var viewerIndex = ++containers_counter; var viewerId = viewerIdBase + "_" + viewerIndex; var iframeId = viewerId + "_iframe"; var closeId = viewerId + "_close"; /** * @type {HTMLElement} */ var viewer = document.getElementById(viewerId) || document.createElement("div"); // noinspection JSValidateTypes /** * * @type {HTMLIFrameElement} */ var iframe = document.getElementById(iframeId) || document.createElement("iframe"); /** * @type {HTMLElement} */ var close = document.getElementById(closeId) || document.createElement("div"); viewer.id = viewerId; viewer.className = "sitewaertsdocumentviewer windows"; close.id = closeId; close.className = "close"; iframe.id = iframeId; iframe.src = emptyIFrameSrc; viewer.appendChild(iframe); viewer.appendChild(close); document.body.appendChild(viewer); close.onclick = _doClose; //iframe.onerror = _onError; var _info = "[" + viewerIndex + "][" + url + "]"; var _closeHandler; /** * @param {function():void} closeHandler * @private */ function _setCloseHandler(closeHandler) { _closeHandler = closeHandler; } var _closeOnPause; /** * @param {boolean} closeOnPause * @private */ function _setCloseOnPause(closeOnPause) { _closeOnPause = closeOnPause === true; } var _errorHandler; /** * @param {function(error:any):void} errorHandler * @private */ function _setErrorHandler(errorHandler) { _errorHandler = errorHandler; } function _onError(arguments) { try { console.error(_info + ': error in iframe', arguments); if (_errorHandler) _errorHandler.apply(null, arguments); } catch (e) { console.error(_info + ': error in iframe error handling', e); } return true; // avoid app crash } /** * @void * @private */ function _cleanup() { _closeHandler = null; _closeOnPause = null; const v = viewer; viewer = null; if (v) { console.info(_info + ': cleanup: hiding dom elements'); v.style.display = 'none'; var w = iframe['window'] || iframe.contentWindow; if (w && w.prepareClose) w.prepareClose(doClose); else doClose(); function doClose() { setTimeout(function () { console.info(_info + ': cleanup: loading empty content'); iframe.src = emptyIFrameSrc; iframe.onload = function () { _destroy(v); } }, viewerCloseDelay); } } delete containers[viewerId]; } /** * @param {HTMLElement} viewer * @void * @private */ function _destroy(viewer) { if (viewer) { console.info(_info + ': destroy: removing dom elements'); viewer.remove(); viewer = null; } } /** * @void * @private */ function _doClose() { var ch = _closeHandler; _cleanup(); if (ch) ch(); // closed } /** * @param {function():void} callback * @void * @private */ function _prepare(callback) { iframe.src = viewerIFrameSrc; iframe.onload = function () { // avoid reloading on close iframe.onload = null; callback(); } } /** * @param {any} options * @param {function()} close * @void * @private */ function _showPDF(options, close) { /** * * @type {Window} */ var w = iframe['window'] || iframe.contentWindow; w.showPDF(url, options, close); viewer.style.display = 'block'; } /** * @void * @private */ function _appSuspend() { var w = iframe.window || iframe.contentWindow; if (w && w.appSuspend) w.appSuspend(); if (_closeOnPause) _doClose(); } /** * @void * @private */ function _appResume() { var w = iframe.window || iframe.contentWindow; if (w && w.appResume) w.appResume(); } /** * * @type {Container} */ var container = { showPDF: _showPDF, prepare: _prepare, close: _doClose, cleanup: _cleanup, appSuspend: _appSuspend, appResume: _appResume, setErrorHandler: _setErrorHandler, setCloseHandler: _setCloseHandler, setCloseOnPause: _setCloseOnPause }; containers[viewerId] = container; containers_current_Id = viewerId; callback(container); } /** * @param {string} url * @param {ContainerCallback} callback * @void */ function _createContainerIFrameReusable(url, callback) { var viewerIndex = ++containers_counter; var viewerId = viewerIdBase + "_" + url; var existing = containers[viewerId]; if (existing) return callback(existing); var iframeId = viewerId + "_iframe"; var closeId = viewerId + "_close"; /** * @type {HTMLElement} */ var viewer = document.getElementById(viewerId) || document.createElement("div"); // noinspection JSValidateTypes /** * * @type {HTMLIFrameElement} */ var iframe = document.getElementById(iframeId) || document.createElement("iframe"); /** * @type {HTMLElement} */ var close = document.getElementById(closeId) || document.createElement("div"); viewer.id = viewerIndex + "_" + viewerId; // prepend idx for better readability only viewer.className = "sitewaertsdocumentviewer windows"; close.id = closeId; close.className = "close"; iframe.id = iframeId; iframe.src = emptyIFrameSrc; viewer.appendChild(iframe); viewer.appendChild(close); document.body.appendChild(viewer); close.onclick = _doClose; //iframe.onerror = _onError; var _info = "[" + viewerIndex + "][" + url + "]"; var _closeHandler; /** * @param {function():void} closeHandler * @private */ function _setCloseHandler(closeHandler) { _closeHandler = closeHandler; } var _closeOnPause; /** * @param {boolean} closeOnPause * @private */ function _setCloseOnPause(closeOnPause) { _closeOnPause = closeOnPause === true; } var _errorHandler; /** * @param {function(error:any):void} errorHandler * @private */ function _setErrorHandler(errorHandler) { _errorHandler = errorHandler; } function _onError(arguments) { try { console.error(_info + ': error in iframe', arguments); if (_errorHandler) _errorHandler.apply(null, arguments); } catch (e) { console.error(_info + ': error in iframe error handling', e); } return true; // avoid app crash } var _closeTimeout; /** * @void * @private */ function _cleanup() { _closeHandler = null; _closeOnPause = null; if (viewer) { console.info(_info + ': cleanup: hiding dom elements'); viewer.style.display = 'none'; if (_closeTimeout) clearTimeout(_closeTimeout); _closeTimeout = setTimeout(function () { var w = iframe['window'] || iframe.contentWindow; if (w && w.prepareClose) w.prepareClose(doClose); else doClose(); function doClose() { delete containers[viewerId]; if(viewer) { console.info(_info + ': cleanup: removing from dom'); viewer.remove(); viewer = null; } } }, 2 * 60 * 1000); } } /** * @void * @private */ function _doClose() { var ch = _closeHandler; _cleanup(); _close = null; if (ch) ch(); // closed } var _initialized = false; /** * @param {function():void} callback * @void * @private */ function _prepare(callback) { if (_closeTimeout) clearTimeout(_closeTimeout); if (_initialized) return callback(); iframe.src = viewerIFrameSrc; iframe.onload = function () { // avoid reloading on close iframe.onload = null; callback(); } } function closer(){ if(_close) return _close(); } var _close; /** * @param {any} options * @param {function()} close * @void * @private */ function _showPDF(options, close) { if(!_initialized) { _initialized = true; /** * * @type {Window} */ var w = iframe['window'] || iframe.contentWindow; w.showPDF(url, options, closer); } _close = close; viewer.style.display = 'block'; } /** * @void * @private */ function _appSuspend() { var w = iframe.window || iframe.contentWindow; if (w && w.appSuspend) w.appSuspend(); if (_closeOnPause) _doClose(); } /** * @void * @private */ function _appResume() { var w = iframe.window || iframe.contentWindow; if (w && w.appResume) w.appResume(); } /** * * @type {Container} */ var container = { showPDF: _showPDF, prepare: _prepare, close: _doClose, cleanup: _cleanup, appSuspend: _appSuspend, appResume: _appResume, setErrorHandler: _setErrorHandler, setCloseHandler: _setCloseHandler, setCloseOnPause: _setCloseOnPause }; containers[viewerId] = container; containers_current_Id = viewerId; callback(container); } //launching file in external app: // see https://msdn.microsoft.com/en-us/library/windows/apps/hh452687.aspx cordova.commandProxy.add("SitewaertsDocumentViewer", { getSupportInfo: function (successCallback, errorCallback) { successCallback({supported: [PDF]}); }, canViewDocument: function (successCallback, errorCallback, params) { function _no(message) { return { status: 0, message: message, params: params }; } if (!params || params.length !== 1) { successCallback(_no("missing or invalid params")); return; } params = params[0]; var url = params[Args.URL]; if (!url || typeof url !== "string") { successCallback(_no("missing or invalid param " + Args.URL)); return; } // TODO: check availability of url var contentType = params[Args.CONTENT_TYPE]; if (contentType !== PDF) { successCallback(_no("missing or invalid param " + Args.CONTENT_TYPE)); return; } successCallback({status: 1}); // YES }, viewDocument: function (successCallback, errorCallback, params) { try { if (!params || params.length !== 1) { errorCallback({status: 0, message: "missing arguments"}); return; } params = params[0]; var url = params[Args.URL]; if (!url || typeof url !== "string") { errorCallback({status: 0, message: "missing argument url"}); return; } var contentType = params[Args.CONTENT_TYPE]; if (contentType !== PDF) { errorCallback({ status: 0, message: "illegal content type " + contentType }); return; } var options = params[Args.OPTIONS]; _createContainer(url, function (c) { try { c.setErrorHandler(function () { if (c) c.cleanup(); c = null; errorCallback({status: 0, message: "error in container", args: arguments}); }); c.setCloseHandler(function () { successCallback({status: 0}); // 0 = closed }); c.setCloseOnPause(options && options.autoClose && options.autoClose.onPause); function doCloseAsync() { if (c) setTimeout(function () { if (c) c.close(); c = null; }, 100); } c.prepare(function () { try { c.showPDF(options, doCloseAsync); successCallback({status: 1}); // 1 = shown } catch (e) { console.error("cannot init container", e); if (c) c.cleanup(); c = null; errorCallback({status: 0, message: "cannot init container", error: e}); } }) } catch (e) { console.error("cannot init container", e); if (c) c.cleanup(); c = null; errorCallback({status: 0, message: "cannot init container", error: e}); } }); } catch (e) { console.error("cannot create container", e); errorCallback({status: 0, message: "cannot create container", error: e}); } }, appPaused: function (successCallback, errorCallback) { // ignore // no need to handle external events as we have internal listeners for pause and resume successCallback(); }, appResumed: function (successCallback, errorCallback) { // ignore // no need to handle external events as we have internal listeners for pause and resume successCallback(); }, close: function (successCallback, errorCallback) { var c = _getCurrentContainer(); try { if (c) c.close(); successCallback({status: 0}); // 1 = closed } catch (e) { c.cleanup(); errorCallback({status: 0, message: "cannot close frame", error: e}); } }, install: function (successCallback, errorCallback) { errorCallback("operation not supported"); } }); // listeners MUST be registered after deviceready event // attention: windows app may be never suspended in debug mode! // TODO: why are these events no fired in windows app even in release mode? document.addEventListener("deviceready", function () { document.addEventListener("pause", function () { var c = _getCurrentContainer(); try { if (c) c.appSuspend(); } catch (e) { window.console.error(e); } }, false); document.addEventListener("resume", function () { var c = _getCurrentContainer(); try { if (c) c.appResume(); } catch (e) { window.console.error(e); } }, false); }, false); <|start_filename|>npm_publish.bat<|end_filename|> rem see https://cordova.apache.org/docs/en/latest/guide/hybrid/plugins/#publishing-plugins npm publish %~dp0 <|start_filename|>bower.json<|end_filename|> { "name": "cordova-plugin-document-viewer", "version": "1.0.0", "dependencies": { "jquery" : "latest", "winjs": "latest", "angular-winjs": "latest", "angular": "<1.5" }, "private": true } <|start_filename|>package.json<|end_filename|> { "name": "cordova-plugin-document-viewer", "version": "1.0.2", "description": "PDF Document viewer cordova plugin for iOS, Android and Windows 8.1 + 10", "license": "MIT", "author": "<NAME>", "bugs": { "url": "https://github.com/sitewaerts/cordova-plugin-document-viewer/issues" }, "scripts": { "updateDependencies": "update_dependencies.bat && npm run build", "build": "bash build.sh", "prepare": "npm run build" }, "cordova": { "id": "cordova-plugin-document-viewer", "platforms": [ "android", "ios", "windows" ] }, "repository": { "type": "git", "url": "git+https://github.com/sitewaerts/cordova-plugin-document-viewer.git" }, "homepage": "https://github.com/sitewaerts/cordova-plugin-document-viewer#readme", "keywords": [ "ecosystem:cordova", "cordova", "cordova-android", "cordova-ios", "cordova-windows", "pdf" ], "engines": { "cordovaDependencies": { "1.0.2": { "cordova": ">=10.0.0", "cordova-windows": ">=4.4.0", "cordova-android": ">=9.0.0" } } }, "devDependencies": { "@types/angular": "^1.8.1", "@types/angularjs": "^1.5.14-alpha", "@types/pdfjs-dist": "^2.1.7", "@types/winjs": "^4.4.0" }, "dependencies": { "pdfjs-dist": "^2.9.359" } }
snuffy/cordova-plugin-document-viewer
<|start_filename|>src/test/java/org/springframework/data/envers/Config.java<|end_filename|> /* * Copyright 2012-2021 the original author or authors. * * 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 * * https://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 org.springframework.data.envers; import java.sql.SQLException; import java.util.Collections; import java.util.Map; import javax.sql.DataSource; import org.hibernate.envers.strategy.ValidityAuditStrategy; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.envers.repository.config.EnableEnversRepositories; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; /** * Spring JavaConfig configuration for general infrastructure. * * @author <NAME> */ @Configuration @EnableEnversRepositories public class Config { @Bean public DataSource dataSource() throws SQLException { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build(); } @Bean public PlatformTransactionManager transactionManager() throws SQLException { return new JpaTransactionManager(); } @Bean public AbstractEntityManagerFactoryBean entityManagerFactory() throws SQLException { HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); jpaVendorAdapter.setDatabase(Database.H2); jpaVendorAdapter.setGenerateDdl(true); LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean(); bean.setJpaVendorAdapter(jpaVendorAdapter); bean.setPackagesToScan(Config.class.getPackage().getName()); bean.setDataSource(dataSource()); bean.setJpaPropertyMap(jpaProperties()); return bean; } private Map<String, String> jpaProperties() { return Collections.singletonMap("org.hibernate.envers.audit_strategy", ValidityAuditStrategy.class.getName()); } } <|start_filename|>src/test/java/org/springframework/data/envers/repository/support/RepositoryIntegrationTests.java<|end_filename|> /* * Copyright 2012-2021 the original author or authors. * * 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 * * https://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 org.springframework.data.envers.repository.support; import static org.assertj.core.api.Assertions.*; import static org.springframework.data.history.RevisionMetadata.RevisionType.*; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.envers.Config; import org.springframework.data.envers.sample.Country; import org.springframework.data.envers.sample.CountryRepository; import org.springframework.data.envers.sample.License; import org.springframework.data.envers.sample.LicenseRepository; import org.springframework.data.history.Revision; import org.springframework.data.history.RevisionSort; import org.springframework.data.history.Revisions; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; /** * Integration tests for repositories. * * @author <NAME> * @author <NAME> */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = Config.class) class RepositoryIntegrationTests { @Autowired LicenseRepository licenseRepository; @Autowired CountryRepository countryRepository; @BeforeEach void setUp() { licenseRepository.deleteAll(); countryRepository.deleteAll(); } @AfterEach void tearDown() { licenseRepository.deleteAll(); countryRepository.deleteAll(); } @Test void testLifeCycle() { License license = new License(); license.name = "Schnitzel"; licenseRepository.save(license); Country de = new Country(); de.code = "de"; de.name = "Deutschland"; countryRepository.save(de); Country se = new Country(); se.code = "se"; se.name = "Schweden"; countryRepository.save(se); license.laender = new HashSet<>(); license.laender.addAll(Arrays.asList(de, se)); licenseRepository.save(license); de.name = "Daenemark"; countryRepository.save(de); Optional<Revision<Integer, License>> revision = licenseRepository.findLastChangeRevision(license.id); assertThat(revision).hasValueSatisfying(it -> { Page<Revision<Integer, License>> page = licenseRepository.findRevisions(license.id, PageRequest.of(0, 10)); Revisions<Integer, License> revisions = Revisions.of(page.getContent()); assertThat(revisions.getLatestRevision()).isEqualTo(it); }); } @Test // #1 void returnsEmptyLastRevisionForUnrevisionedEntity() { assertThat(countryRepository.findLastChangeRevision(100L)).isEmpty(); } @Test // #47 void returnsEmptyRevisionsForUnrevisionedEntity() { assertThat(countryRepository.findRevisions(100L)).isEmpty(); } @Test // #47 void returnsEmptyRevisionForUnrevisionedEntity() { assertThat(countryRepository.findRevision(100L, 23)).isEmpty(); } @Test // #31 void returnsParticularRevisionForAnEntity() { Country de = new Country(); de.code = "de"; de.name = "Deutschland"; countryRepository.save(de); de.name = "Germany"; countryRepository.save(de); Revisions<Integer, Country> revisions = countryRepository.findRevisions(de.id); assertThat(revisions).hasSize(2); Iterator<Revision<Integer, Country>> iterator = revisions.iterator(); Revision<Integer, Country> first = iterator.next(); Revision<Integer, Country> second = iterator.next(); assertThat(countryRepository.findRevision(de.id, first.getRequiredRevisionNumber())) .hasValueSatisfying(it -> assertThat(it.getEntity().name).isEqualTo("Deutschland")); assertThat(countryRepository.findRevision(de.id, second.getRequiredRevisionNumber())) .hasValueSatisfying(it -> assertThat(it.getEntity().name).isEqualTo("Germany")); } @Test // #55 void considersRevisionNumberSortOrder() { Country de = new Country(); de.code = "de"; de.name = "Deutschland"; countryRepository.save(de); de.name = "Germany"; countryRepository.save(de); Page<Revision<Integer, Country>> page = countryRepository.findRevisions(de.id, PageRequest.of(0, 10, RevisionSort.desc())); assertThat(page).hasSize(2); assertThat(page.getContent().get(0).getRequiredRevisionNumber()) .isGreaterThan(page.getContent().get(1).getRequiredRevisionNumber()); } @Test // #21 void findsDeletedRevisions() { Country de = new Country(); de.code = "de"; de.name = "Deutschland"; countryRepository.save(de); countryRepository.delete(de); Revisions<Integer, Country> revisions = countryRepository.findRevisions(de.id); assertThat(revisions).hasSize(2); assertThat(revisions.getLatestRevision().getEntity()) // .isNotNull() // .extracting(c -> c.name, c -> c.code) // .containsExactly(null, null); } @Test // #47 void includesCorrectRevisionType() { Country de = new Country(); de.code = "de"; de.name = "Deutschland"; countryRepository.save(de); de.name = "Bundes Republik Deutschland"; countryRepository.save(de); countryRepository.delete(de); Revisions<Integer, Country> revisions = countryRepository.findRevisions(de.id); assertThat(revisions) // .extracting(r -> r.getMetadata().getRevisionType()) // .containsExactly( // INSERT, // UPDATE, // DELETE // ); } @Test // #146 void shortCircuitingWhenOffsetIsToLarge() { Country de = new Country(); de.code = "de"; de.name = "Deutschland"; countryRepository.save(de); countryRepository.delete(de); check(de.id, 0, 1, 2); check(de.id, 1, 1, 2); check(de.id, 2, 0, 2); } @Test // #47 void paginationWithEmptyResult() { check(23L, 0, 0, 0); } void check(Long id, int page, int expectedSize, int expectedTotalSize) { Page<Revision<Integer, Country>> revisions = countryRepository.findRevisions(id, PageRequest.of(page, 1)); assertThat(revisions).hasSize(expectedSize); assertThat(revisions.getTotalElements()).isEqualTo(expectedTotalSize); } }
neil-ca-moore/spring-data-envers
<|start_filename|>test/spec_tolerations_test.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" v12 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "log" postgresv1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/test/resourceConfigs" "reactive-tech.io/kubegres/test/util" "reactive-tech.io/kubegres/test/util/testcases" "time" ) var _ = Describe("Setting Kubegres spec 'scheduler.tolerations'", func() { var test = SpecTolerationsTest{} BeforeEach(func() { //Skip("Temporarily skipping test") namespace := resourceConfigs.DefaultNamespace test.resourceRetriever = util.CreateTestResourceRetriever(k8sClientTest, namespace) test.resourceCreator = util.CreateTestResourceCreator(k8sClientTest, test.resourceRetriever, namespace) test.dbQueryTestCases = testcases.InitDbQueryTestCases(test.resourceCreator, resourceConfigs.KubegresResourceName) }) AfterEach(func() { if !test.keepCreatedResourcesForNextTest { test.resourceCreator.DeleteAllTestResources() } else { test.keepCreatedResourcesForNextTest = false } }) Context("GIVEN new Kubegres is created without spec 'scheduler.tolerations' and with spec 'replica' set to 3", func() { It("THEN 1 primary and 2 replica should be created with 'scheduler.tolerations' set to nil", func() { log.Print("START OF: Test 'GIVEN new Kubegres is created without spec 'scheduler.tolerations' and with spec 'replica' set to 3'") test.givenNewKubegresSpecIsWithoutTolerations(3) test.whenKubegresIsCreated() test.thenStatefulSetStatesShouldBeWithoutTolerations(1, 2) test.thenDeployedKubegresSpecShouldWithoutTolerations() test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() log.Print("END OF: Test 'GIVEN new Kubegres is created without spec 'scheduler.tolerations' and with spec 'replica' set to 3'") }) }) Context("GIVEN new Kubegres is created with spec 'scheduler.tolerations' set to a value and spec 'replica' set to 3 and later 'scheduler.tolerations' is updated to a new value", func() { It("GIVEN new Kubegres is created with spec 'scheduler.tolerations' set to a value and spec 'replica' set to 3 THEN 1 primary and 2 replica should be created with spec 'scheduler.tolerations' set the value", func() { log.Print("START OF: Test 'GIVEN new Kubegres is created with spec 'scheduler.tolerations' set to a value and spec 'replica' set to 3") toleration := test.givenToleration1() test.givenNewKubegresSpecIsSetTo(toleration, 3) test.whenKubegresIsCreated() test.thenStatefulSetStatesShouldBe(toleration, 1, 2) test.thenDeployedKubegresSpecShouldBeSetTo(toleration) test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() test.keepCreatedResourcesForNextTest = true log.Print("END OF: Test 'GIVEN new Kubegres is created with spec 'scheduler.tolerations' set to a value and spec 'replica' set to 3'") }) It("GIVEN existing Kubegres is updated with spec 'scheduler.tolerations' set to a new value THEN 1 primary and 2 replica should be re-deployed with spec 'scheduler.tolerations' set the new value", func() { log.Print("START OF: Test 'GIVEN existing Kubegres is updated with spec 'scheduler.tolerations' set to a new value") newToleration := test.givenToleration2() test.givenExistingKubegresSpecIsSetTo(newToleration) test.whenKubernetesIsUpdated() test.thenStatefulSetStatesShouldBe(newToleration, 1, 2) test.thenDeployedKubegresSpecShouldBeSetTo(newToleration) test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() log.Print("END OF: Test 'GIVEN existing Kubegres is updated with spec 'scheduler.tolerations' set to a new value") }) }) }) type SpecTolerationsTest struct { keepCreatedResourcesForNextTest bool kubegresResource *postgresv1.Kubegres dbQueryTestCases testcases.DbQueryTestCases resourceCreator util.TestResourceCreator resourceRetriever util.TestResourceRetriever } func (r *SpecTolerationsTest) givenToleration1() v12.Toleration { return v12.Toleration{ Key: "group", Operator: v12.TolerationOpEqual, Value: "critical", } } func (r *SpecTolerationsTest) givenToleration2() v12.Toleration { return v12.Toleration{ Key: "group", Operator: v12.TolerationOpEqual, Value: "nonCritical", } } func (r *SpecTolerationsTest) givenNewKubegresSpecIsWithoutTolerations(specNbreReplicas int32) { r.kubegresResource = resourceConfigs.LoadKubegresYaml() r.kubegresResource.Spec.Scheduler.Tolerations = nil r.kubegresResource.Spec.Replicas = &specNbreReplicas } func (r *SpecTolerationsTest) givenNewKubegresSpecIsSetTo(toleration v12.Toleration, specNbreReplicas int32) { r.kubegresResource = resourceConfigs.LoadKubegresYaml() r.kubegresResource.Spec.Scheduler.Tolerations = []v12.Toleration{toleration} r.kubegresResource.Spec.Replicas = &specNbreReplicas } func (r *SpecTolerationsTest) givenExistingKubegresSpecIsSetTo(toleration v12.Toleration) { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } r.kubegresResource.Spec.Scheduler.Tolerations = []v12.Toleration{toleration} } func (r *SpecTolerationsTest) whenKubegresIsCreated() { r.resourceCreator.CreateKubegres(r.kubegresResource) } func (r *SpecTolerationsTest) whenKubernetesIsUpdated() { r.resourceCreator.UpdateResource(r.kubegresResource, "Kubegres") } func (r *SpecTolerationsTest) thenStatefulSetStatesShouldBeWithoutTolerations(nbrePrimary, nbreReplicas int) bool { return Eventually(func() bool { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil && !apierrors.IsNotFound(err) { log.Println("ERROR while retrieving Kubegres kubegresResources") return false } for _, resource := range kubegresResources.Resources { tolerations := resource.StatefulSet.Spec.Template.Spec.Tolerations if len(tolerations) > 0 { log.Println("StatefulSet '" + resource.StatefulSet.Name + "' doesn't have the expected spec 'scheduler.toleration' which should be nil. " + "Current value: '" + tolerations[0].String() + "'. Waiting...") return false } } if kubegresResources.AreAllReady && kubegresResources.NbreDeployedPrimary == nbrePrimary && kubegresResources.NbreDeployedReplicas == nbreReplicas { time.Sleep(resourceConfigs.TestRetryInterval) log.Println("Deployed and Ready StatefulSets check successful") return true } return false }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecTolerationsTest) thenStatefulSetStatesShouldBe(expectedToleration v12.Toleration, nbrePrimary, nbreReplicas int) bool { return Eventually(func() bool { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil && !apierrors.IsNotFound(err) { log.Println("ERROR while retrieving Kubegres kubegresResources") return false } for _, resource := range kubegresResources.Resources { tolerations := resource.StatefulSet.Spec.Template.Spec.Tolerations if len(tolerations) != 1 { log.Println("StatefulSet '" + resource.StatefulSet.Name + "' doesn't have the expected spec 'scheduler.toleration' which is nil when it should have a value. " + "Current value: '" + tolerations[0].String() + "'. Waiting...") return false } else if tolerations[0] != expectedToleration { log.Println("StatefulSet '" + resource.StatefulSet.Name + "' doesn't have the expected spec scheduler.toleration: " + expectedToleration.String() + " " + "Current value: '" + tolerations[0].String() + "'. Waiting...") return false } } if kubegresResources.AreAllReady && kubegresResources.NbreDeployedPrimary == nbrePrimary && kubegresResources.NbreDeployedReplicas == nbreReplicas { time.Sleep(resourceConfigs.TestRetryInterval) log.Println("Deployed and Ready StatefulSets check successful") return true } return false }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecTolerationsTest) thenDeployedKubegresSpecShouldWithoutTolerations() { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } Expect(len(r.kubegresResource.Spec.Scheduler.Tolerations)).Should(Equal(0)) } func (r *SpecTolerationsTest) thenDeployedKubegresSpecShouldBeSetTo(expectedToleration v12.Toleration) { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } Expect(len(r.kubegresResource.Spec.Scheduler.Tolerations)).Should(Equal(1)) Expect(r.kubegresResource.Spec.Scheduler.Tolerations[0]).Should(Equal(expectedToleration)) } <|start_filename|>controllers/spec/enforcer/statefulset_spec/PortSpecEnforcer.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 statefulset_spec import ( apps "k8s.io/api/apps/v1" core "k8s.io/api/core/v1" "reactive-tech.io/kubegres/controllers/ctx" "reactive-tech.io/kubegres/controllers/states" "strconv" ) type PortSpecEnforcer struct { kubegresContext ctx.KubegresContext resourcesStates states.ResourcesStates } func CreatePortSpecEnforcer(kubegresContext ctx.KubegresContext, resourcesStates states.ResourcesStates) PortSpecEnforcer { return PortSpecEnforcer{kubegresContext: kubegresContext, resourcesStates: resourcesStates} } func (r *PortSpecEnforcer) GetSpecName() string { return "Port" } func (r *PortSpecEnforcer) CheckForSpecDifference(statefulSet *apps.StatefulSet) StatefulSetSpecDifference { current := int(statefulSet.Spec.Template.Spec.Containers[0].Ports[0].ContainerPort) expected := int(r.kubegresContext.Kubegres.Spec.Port) if current != expected { return StatefulSetSpecDifference{ SpecName: r.GetSpecName(), Current: strconv.Itoa(current), Expected: strconv.Itoa(expected), } } return StatefulSetSpecDifference{} } func (r *PortSpecEnforcer) EnforceSpec(statefulSet *apps.StatefulSet) (wasSpecUpdated bool, err error) { statefulSet.Spec.Template.Spec.Containers[0].Ports[0].ContainerPort = r.kubegresContext.Kubegres.Spec.Port return true, nil } func (r *PortSpecEnforcer) OnSpecEnforcedSuccessfully(statefulSet *apps.StatefulSet) error { if r.isPrimaryStatefulSet(statefulSet) && r.isPrimaryServicePortNotUpToDate() { return r.deletePrimaryService() } else if !r.isPrimaryStatefulSet(statefulSet) && r.isReplicaServicePortNotUpToDate() { return r.deleteReplicaService() } return nil } func (r *PortSpecEnforcer) isPrimaryStatefulSet(statefulSet *apps.StatefulSet) bool { return statefulSet.Name == r.resourcesStates.StatefulSets.Primary.StatefulSet.Name } func (r *PortSpecEnforcer) isPrimaryServicePortNotUpToDate() bool { if !r.resourcesStates.Services.Primary.IsDeployed { return false } servicePort := r.resourcesStates.Services.Primary.Service.Spec.Ports[0].Port postgresPort := r.kubegresContext.Kubegres.Spec.Port return postgresPort != servicePort } func (r *PortSpecEnforcer) isReplicaServicePortNotUpToDate() bool { if !r.resourcesStates.Services.Replica.IsDeployed { return false } servicePort := r.resourcesStates.Services.Replica.Service.Spec.Ports[0].Port postgresPort := r.kubegresContext.Kubegres.Spec.Port return postgresPort != servicePort } func (r *PortSpecEnforcer) deletePrimaryService() error { return r.deleteService(r.resourcesStates.Services.Primary.Service) } func (r *PortSpecEnforcer) deleteReplicaService() error { return r.deleteService(r.resourcesStates.Services.Replica.Service) } func (r *PortSpecEnforcer) deleteService(serviceToDelete core.Service) error { r.kubegresContext.Log.Info("Deleting Service because Spec port changed.", "Service name", serviceToDelete.Name) err := r.kubegresContext.Client.Delete(r.kubegresContext.Ctx, &serviceToDelete) if err != nil { r.kubegresContext.Log.ErrorEvent("ServiceDeletionErr", err, "Unable to delete a service to apply the new Spec port change.", "Service name", serviceToDelete.Name) r.kubegresContext.Log.Error(err, "Unable to delete Service", "name", serviceToDelete.Name) return err } r.kubegresContext.Log.InfoEvent("ServiceDeletion", "Deleted a service to apply the new Spec port change.", "Service name", serviceToDelete.Name) return nil } <|start_filename|>controllers/spec/template/ResourceTemplateLoader.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 template import ( apps "k8s.io/api/apps/v1" "k8s.io/api/batch/v1beta1" core "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes/scheme" log2 "reactive-tech.io/kubegres/controllers/ctx/log" "reactive-tech.io/kubegres/controllers/spec/template/yaml" ) type ResourceTemplateLoader struct { log log2.LogWrapper } func (r *ResourceTemplateLoader) LoadBaseConfigMap() (configMap core.ConfigMap, err error) { obj, err := r.decodeYaml(yaml.BaseConfigMapTemplate) if err != nil { r.log.Error(err, "Unable to load Kubegres CustomConfig. Given error:") return core.ConfigMap{}, err } return *obj.(*core.ConfigMap), nil } func (r *ResourceTemplateLoader) LoadPrimaryService() (serviceTemplate core.Service, err error) { serviceTemplate, err = r.loadService(yaml.PrimaryServiceTemplate) return serviceTemplate, err } func (r *ResourceTemplateLoader) LoadReplicaService() (serviceTemplate core.Service, err error) { return r.loadService(yaml.ReplicaServiceTemplate) } func (r *ResourceTemplateLoader) LoadPrimaryStatefulSet() (statefulSetTemplate apps.StatefulSet, err error) { return r.loadStatefulSet(yaml.PrimaryStatefulSetTemplate) } func (r *ResourceTemplateLoader) LoadReplicaStatefulSet() (statefulSetTemplate apps.StatefulSet, err error) { return r.loadStatefulSet(yaml.ReplicaStatefulSetTemplate) } func (r *ResourceTemplateLoader) LoadBackUpCronJob() (cronJob v1beta1.CronJob, err error) { obj, err := r.decodeYaml(yaml.BackUpCronJobTemplate) if err != nil { r.log.Error(err, "Unable to load Kubegres BackUp CronJob. Given error:") return v1beta1.CronJob{}, err } return *obj.(*v1beta1.CronJob), nil } func (r *ResourceTemplateLoader) loadService(yamlContents string) (serviceTemplate core.Service, err error) { obj, err := r.decodeYaml(yamlContents) if err != nil { r.log.Error(err, "Unable to decode Kubegres Service. Given error: ") return core.Service{}, err } return *obj.(*core.Service), nil } func (r *ResourceTemplateLoader) loadStatefulSet(yamlContents string) (statefulSetTemplate apps.StatefulSet, err error) { obj, err := r.decodeYaml(yamlContents) if err != nil { r.log.Error(err, "Unable to decode Kubegres StatefulSet. Given error: ") return apps.StatefulSet{}, err } return *obj.(*apps.StatefulSet), nil } func (r *ResourceTemplateLoader) decodeYaml(yamlContents string) (runtime.Object, error) { decode := scheme.Codecs.UniversalDeserializer().Decode obj, _, err := decode([]byte(yamlContents), nil, nil) if err != nil { r.log.Error(err, "Error in decode: ", "obj", obj) } return obj, err } <|start_filename|>controllers/spec/enforcer/resources_count_spec/ResourcesCountSpecEnforcer.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 resources_count_spec type ResourceCountSpecEnforcer interface { EnforceSpec() error } type ResourcesCountSpecEnforcer struct { registry []ResourceCountSpecEnforcer } func (r *ResourcesCountSpecEnforcer) AddSpecEnforcer(specEnforcer ResourceCountSpecEnforcer) { r.registry = append(r.registry, specEnforcer) } func (r *ResourcesCountSpecEnforcer) EnforceSpec() error { for _, specEnforcer := range r.registry { if err := specEnforcer.EnforceSpec(); err != nil { return err } } return nil } <|start_filename|>controllers/spec/enforcer/statefulset_spec/AllStatefulSetsSpecEnforcer.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 statefulset_spec import ( "errors" apps "k8s.io/api/apps/v1" postgresV1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/controllers/ctx" "reactive-tech.io/kubegres/controllers/operation" "reactive-tech.io/kubegres/controllers/spec/enforcer/comparator" "reactive-tech.io/kubegres/controllers/states" "reactive-tech.io/kubegres/controllers/states/statefulset" ) // Note about Kubernetes: "Forbidden: updates to Statefulset spec for fields other than 'replicas', 'template', //and 'updateStrategy' are forbidden" type AllStatefulSetsSpecEnforcer struct { kubegresContext ctx.KubegresContext resourcesStates states.ResourcesStates blockingOperation *operation.BlockingOperation specsEnforcers StatefulSetsSpecsEnforcer } func CreateAllStatefulSetsSpecEnforcer(kubegresContext ctx.KubegresContext, resourcesStates states.ResourcesStates, blockingOperation *operation.BlockingOperation, specsEnforcers StatefulSetsSpecsEnforcer) AllStatefulSetsSpecEnforcer { return AllStatefulSetsSpecEnforcer{ kubegresContext: kubegresContext, resourcesStates: resourcesStates, blockingOperation: blockingOperation, specsEnforcers: specsEnforcers, } } func (r *AllStatefulSetsSpecEnforcer) CreateOperationConfigForStatefulSetSpecUpdating() operation.BlockingOperationConfig { return operation.BlockingOperationConfig{ OperationId: operation.OperationIdStatefulSetSpecEnforcing, StepId: operation.OperationStepIdStatefulSetSpecUpdating, TimeOutInSeconds: 300, CompletionChecker: r.isStatefulSetSpecUpdated, AfterCompletionMoveToTransitionStep: true, } } func (r *AllStatefulSetsSpecEnforcer) CreateOperationConfigForStatefulSetSpecPodUpdating() operation.BlockingOperationConfig { return operation.BlockingOperationConfig{ OperationId: operation.OperationIdStatefulSetSpecEnforcing, StepId: operation.OperationStepIdStatefulSetPodSpecUpdating, TimeOutInSeconds: 300, CompletionChecker: r.isStatefulSetPodSpecUpdated, AfterCompletionMoveToTransitionStep: true, } } func (r *AllStatefulSetsSpecEnforcer) CreateOperationConfigForStatefulSetWaitingOnStuckPod() operation.BlockingOperationConfig { return operation.BlockingOperationConfig{ OperationId: operation.OperationIdStatefulSetSpecEnforcing, StepId: operation.OperationStepIdStatefulSetWaitingOnStuckPod, TimeOutInSeconds: 300, CompletionChecker: r.isStatefulSetPodNotStuck, AfterCompletionMoveToTransitionStep: true, } } func (r *AllStatefulSetsSpecEnforcer) EnforceSpec() error { if !r.isPrimaryDbReady() { return nil } if r.blockingOperation.IsActiveOperationIdDifferentOf(operation.OperationIdStatefulSetSpecEnforcing) { return nil } for _, statefulSetWrapper := range r.getAllReverseSortedByInstanceIndex() { statefulSet := statefulSetWrapper.StatefulSet statefulSetInstanceIndex := statefulSetWrapper.InstanceIndex specDifferences := r.specsEnforcers.CheckForSpecDifferences(&statefulSet) if r.hasLastSpecUpdateAttemptTimedOut(statefulSetInstanceIndex) { if r.areNewSpecChangesSameAsFailingSpecChanges(specDifferences) { r.logSpecEnforcementTimedOut() return nil } else { r.blockingOperation.RemoveActiveOperation() r.logKubegresFeaturesAreReEnabled() } } if specDifferences.IsThereDifference() { return r.enforceSpec(statefulSet, statefulSetInstanceIndex, specDifferences) } else if r.isStatefulSetSpecUpdating(statefulSetInstanceIndex) { isPodReadyAndSpecUpdated, err := r.verifySpecEnforcementIsAppliedToPod(statefulSetWrapper, specDifferences) if err != nil || !isPodReadyAndSpecUpdated { return err } } } return nil } func (r *AllStatefulSetsSpecEnforcer) isPrimaryDbReady() bool { return r.resourcesStates.StatefulSets.Primary.IsReady } func (r *AllStatefulSetsSpecEnforcer) getAllReverseSortedByInstanceIndex() []statefulset.StatefulSetWrapper { replicas := r.resourcesStates.StatefulSets.Replicas.All.GetAllReverseSortedByInstanceIndex() return append(replicas, r.resourcesStates.StatefulSets.Primary) } func (r *AllStatefulSetsSpecEnforcer) hasLastSpecUpdateAttemptTimedOut(statefulSetInstanceIndex int32) bool { if !r.blockingOperation.HasActiveOperationIdTimedOut(operation.OperationIdStatefulSetSpecEnforcing) { return false } activeOperation := r.blockingOperation.GetActiveOperation() return activeOperation.StatefulSetOperation.InstanceIndex == statefulSetInstanceIndex } func (r *AllStatefulSetsSpecEnforcer) areNewSpecChangesSameAsFailingSpecChanges(newSpecDiff StatefulSetSpecDifferences) bool { activeOperation := r.blockingOperation.GetActiveOperation() return activeOperation.StatefulSetSpecUpdateOperation.SpecDifferences == newSpecDiff.GetSpecDifferencesAsString() } func (r *AllStatefulSetsSpecEnforcer) logKubegresFeaturesAreReEnabled() { r.kubegresContext.Log.InfoEvent("KubegresReEnabled", "The new Spec changes "+ "are different to those which failed during the last spec enforcement."+ "We can safely re-enable all features of Kubegres and we will try to enforce Spec changes again.") } func (r *AllStatefulSetsSpecEnforcer) logSpecEnforcementTimedOut() { activeOperation := r.blockingOperation.GetActiveOperation() specDifferences := activeOperation.StatefulSetSpecUpdateOperation.SpecDifferences StatefulSetName := activeOperation.StatefulSetOperation.Name err := errors.New("Spec enforcement timed-out") r.kubegresContext.Log.ErrorEvent("StatefulSetSpecEnforcementTimedOutErr", err, "Last Spec enforcement attempt has timed-out for a StatefulSet. "+ "You must apply different spec changes to your Kubegres resource since the previous spec changes did not work. "+ "Until you apply it, most of the features of Kubegres are disabled for safety reason. ", "StatefulSet's name", StatefulSetName, "One or many of the following specs failed: ", specDifferences) } func (r *AllStatefulSetsSpecEnforcer) enforceSpec(statefulSet apps.StatefulSet, instanceIndex int32, specDifferences StatefulSetSpecDifferences) error { err := r.activateOperationStepStatefulSetSpecUpdating(instanceIndex, specDifferences) if err != nil { r.kubegresContext.Log.ErrorEvent("StatefulSetSpecEnforcementOperationActivationErr", err, "Error while activating blocking operation for the enforcement of StatefulSet spec.", "StatefulSet name", statefulSet.Name) return err } err = r.specsEnforcers.EnforceSpec(&statefulSet) if err != nil { r.kubegresContext.Log.ErrorEvent("StatefulSetSpecEnforcementErr", err, "Unable to enforce the Spec of a StatefulSet.", "StatefulSet name", statefulSet.Name) r.blockingOperation.RemoveActiveOperation() return err } r.kubegresContext.Log.InfoEvent("StatefulSetOperation", "Enforced the Spec of a StatefulSet.", "StatefulSet name", statefulSet.Name) return nil } func (r *AllStatefulSetsSpecEnforcer) verifySpecEnforcementIsAppliedToPod(statefulSetWrapper statefulset.StatefulSetWrapper, specDifferences StatefulSetSpecDifferences) (isPodReadyAndSpecUpdated bool, err error) { podWrapper := statefulSetWrapper.Pod podSpecComparator := comparator.PodSpecComparator{Pod: podWrapper.Pod, PostgresSpec: r.kubegresContext.Kubegres.Spec} isPodSpecUpToDate := podSpecComparator.IsSpecUpToDate() if podWrapper.IsStuck { return false, r.handleWhenStuckPod(podWrapper, specDifferences) } else if !isPodSpecUpToDate || !podWrapper.IsReady { return false, r.handleWhenPodSpecNotUpToDateOrNotReady(podWrapper, isPodSpecUpToDate, specDifferences) } // SUCCESS: Pod spec was successfully updated r.kubegresContext.Log.InfoEvent("PodSpecEnforcement", "Enforced the Spec of a StatefulSet's Pod.", "Pod name", podWrapper.Pod.Name) r.blockingOperation.RemoveActiveOperation() return true, r.specsEnforcers.OnSpecUpdatedSuccessfully(&statefulSetWrapper.StatefulSet) } func (r *AllStatefulSetsSpecEnforcer) handleWhenStuckPod(podWrapper statefulset.PodWrapper, specDifferences StatefulSetSpecDifferences) (err error) { err = r.activateOperationStepWaitingUntilPodIsNotStuck(podWrapper.InstanceIndex, specDifferences) if err != nil { r.kubegresContext.Log.ErrorEvent("PodSpecEnforcementOperationActivationErr", err, "Error while activating a blocking operation for the enforcement of a Pod's spec. "+ "We wanted to wait for a Pod which is stuck.", "Pod name", podWrapper.Pod.Name) return err } r.kubegresContext.Log.Info("Pod is stuck. Deleting the stuck Pod to create an healthy one.", "Pod name", podWrapper.Pod.Name) err = r.kubegresContext.Client.Delete(r.kubegresContext.Ctx, &podWrapper.Pod) if err != nil { r.kubegresContext.Log.ErrorEvent("PodSpecEnforcementErr", err, "Unable to delete a stuck Pod in order to create an healthy one.", "Pod name", podWrapper.Pod.Name) r.blockingOperation.RemoveActiveOperation() return err } return nil } func (r *AllStatefulSetsSpecEnforcer) handleWhenPodSpecNotUpToDateOrNotReady(podWrapper statefulset.PodWrapper, isPodSpecUpToDate bool, specDifferences StatefulSetSpecDifferences) (err error) { if !isPodSpecUpToDate { r.kubegresContext.Log.Info("Pod has an OLD Spec. Waiting until it is up-to-date.", "Pod name", podWrapper.Pod.Name) } else if !podWrapper.IsReady { r.kubegresContext.Log.Info("Pod is not ready yet. Waiting until it is ready.", "Pod name", podWrapper.Pod.Name) } err = r.activateOperationStepStatefulSetPodSpecUpdating(podWrapper.InstanceIndex, specDifferences) if err != nil { r.kubegresContext.Log.ErrorEvent("PodSpecEnforcementOperationActivationErr", err, "Error while activating a blocking operation for the enforcement of a Pod's spec.", "Pod name", podWrapper.Pod.Name) return err } return nil } func (r *AllStatefulSetsSpecEnforcer) isStatefulSetSpecUpdating(statefulSetInstanceIndex int32) bool { if !r.blockingOperation.IsActiveOperationInTransition(operation.OperationIdStatefulSetSpecEnforcing) { return false } previouslyActiveOperation := r.blockingOperation.GetPreviouslyActiveOperation() return previouslyActiveOperation.StatefulSetOperation.InstanceIndex == statefulSetInstanceIndex } func (r *AllStatefulSetsSpecEnforcer) isStatefulSetSpecUpdated(operation postgresV1.KubegresBlockingOperation) bool { if r.blockingOperation.GetNbreSecondsSinceOperationHasStarted() < 10 { return false } statefulSetInstanceIndex := r.getUpdatingInstanceIndex(operation) statefulSetWrapper, err := r.resourcesStates.StatefulSets.All.GetByInstanceIndex(statefulSetInstanceIndex) if err != nil { r.kubegresContext.Log.InfoEvent("A StatefulSet's instanceIndex does not exist. As a result we will "+ "return false inside a blocking operation completion checker 'isStatefulSetSpecUpdated()'", "instanceIndex", statefulSetInstanceIndex) return false } specDifferences := r.specsEnforcers.CheckForSpecDifferences(&statefulSetWrapper.StatefulSet) return !specDifferences.IsThereDifference() } func (r *AllStatefulSetsSpecEnforcer) isStatefulSetPodSpecUpdated(operation postgresV1.KubegresBlockingOperation) bool { statefulSetInstanceIndex := r.getUpdatingInstanceIndex(operation) statefulSetWrapper, err := r.resourcesStates.StatefulSets.All.GetByInstanceIndex(statefulSetInstanceIndex) if err != nil { r.kubegresContext.Log.InfoEvent("A StatefulSet's instanceIndex does not exist. As a result we will "+ "return false inside a blocking operation completion checker 'isStatefulSetPodSpecUpdated()'", "instanceIndex", statefulSetInstanceIndex) return false } podWrapper := statefulSetWrapper.Pod if !podWrapper.IsReady { return false } podSpecComparator := comparator.PodSpecComparator{Pod: podWrapper.Pod, PostgresSpec: r.kubegresContext.Kubegres.Spec} return podSpecComparator.IsSpecUpToDate() } func (r *AllStatefulSetsSpecEnforcer) isStatefulSetPodNotStuck(operation postgresV1.KubegresBlockingOperation) bool { statefulSetInstanceIndex := r.getUpdatingInstanceIndex(operation) statefulSetWrapper, err := r.resourcesStates.StatefulSets.All.GetByInstanceIndex(statefulSetInstanceIndex) if err != nil { r.kubegresContext.Log.InfoEvent("A StatefulSet's instanceIndex does not exist. As a result we will "+ "return false inside a blocking operation completion checker 'isStatefulSetPodNotStuck()'", "instanceIndex", statefulSetInstanceIndex) return false } podWrapper := statefulSetWrapper.Pod return !podWrapper.IsStuck } func (r *AllStatefulSetsSpecEnforcer) activateOperationStepStatefulSetSpecUpdating(statefulSetInstanceIndex int32, specDifferences StatefulSetSpecDifferences) error { return r.blockingOperation.ActivateOperationOnStatefulSetSpecUpdate(operation.OperationIdStatefulSetSpecEnforcing, operation.OperationStepIdStatefulSetSpecUpdating, statefulSetInstanceIndex, specDifferences.GetSpecDifferencesAsString()) } func (r *AllStatefulSetsSpecEnforcer) activateOperationStepStatefulSetPodSpecUpdating(statefulSetInstanceIndex int32, specDifferences StatefulSetSpecDifferences) error { return r.blockingOperation.ActivateOperationOnStatefulSetSpecUpdate(operation.OperationIdStatefulSetSpecEnforcing, operation.OperationStepIdStatefulSetPodSpecUpdating, statefulSetInstanceIndex, specDifferences.GetSpecDifferencesAsString()) } func (r *AllStatefulSetsSpecEnforcer) activateOperationStepWaitingUntilPodIsNotStuck(statefulSetInstanceIndex int32, specDifferences StatefulSetSpecDifferences) error { return r.blockingOperation.ActivateOperationOnStatefulSetSpecUpdate(operation.OperationIdStatefulSetSpecEnforcing, operation.OperationStepIdStatefulSetWaitingOnStuckPod, statefulSetInstanceIndex, specDifferences.GetSpecDifferencesAsString()) } func (r *AllStatefulSetsSpecEnforcer) getUpdatingInstanceIndex(operation postgresV1.KubegresBlockingOperation) int32 { return operation.StatefulSetOperation.InstanceIndex } <|start_filename|>controllers/states/statefulset/StatefulSetWrapper.go<|end_filename|> package statefulset import ( "errors" "k8s.io/api/apps/v1" "sort" "strconv" ) type StatefulSetWrapper struct { IsDeployed bool IsReady bool InstanceIndex int32 StatefulSet v1.StatefulSet Pod PodWrapper } type StatefulSetWrappers struct { statefulSetsSortedByInstanceIndex []StatefulSetWrapper statefulSetsReverseSortedByInstanceIndex []StatefulSetWrapper } func (r *StatefulSetWrappers) Add(statefulSetWrapper StatefulSetWrapper) { r.statefulSetsSortedByInstanceIndex = append(r.statefulSetsSortedByInstanceIndex, statefulSetWrapper) sort.Sort(SortByInstanceIndex(r.statefulSetsSortedByInstanceIndex)) r.statefulSetsReverseSortedByInstanceIndex = append(r.statefulSetsReverseSortedByInstanceIndex, statefulSetWrapper) sort.Sort(ReverseSortByInstanceIndex(r.statefulSetsReverseSortedByInstanceIndex)) } func (r *StatefulSetWrappers) GetAllSortedByInstanceIndex() []StatefulSetWrapper { return r.copy(r.statefulSetsSortedByInstanceIndex) } func (r *StatefulSetWrappers) GetAllReverseSortedByInstanceIndex() []StatefulSetWrapper { return r.copy(r.statefulSetsReverseSortedByInstanceIndex) } func (r *StatefulSetWrappers) GetByInstanceIndex(instanceIndex int32) (StatefulSetWrapper, error) { for _, statefulSet := range r.statefulSetsSortedByInstanceIndex { if instanceIndex == statefulSet.InstanceIndex { return statefulSet, nil } } return StatefulSetWrapper{}, errors.New("Given StatefulSet's instanceIndex '" + strconv.Itoa(int(instanceIndex)) + "' does not exist.") } func (r *StatefulSetWrappers) GetByName(statefulSetName string) (StatefulSetWrapper, error) { for _, statefulSet := range r.statefulSetsSortedByInstanceIndex { if statefulSetName == statefulSet.StatefulSet.Name { return statefulSet, nil } } return StatefulSetWrapper{}, errors.New("Given StatefulSet's name '" + statefulSetName + "' does not exist.") } func (r *StatefulSetWrappers) copy(toCopy []StatefulSetWrapper) []StatefulSetWrapper { var copyAll []StatefulSetWrapper copy(toCopy, copyAll) return toCopy } /* func (r *StatefulSetWrappers) GetByArrayIndex(arrayIndex int32) (StatefulSetWrapper, error) { arrayLength := len(r.statefulSets) if arrayIndex < 0 || int(arrayIndex) >= arrayLength { return StatefulSetWrapper{}, errors.New("Given StatefulSet's arrayIndex '" + strconv.Itoa(int(arrayIndex)) + "' does not exist.") } return r.statefulSets[arrayIndex], nil } */ <|start_filename|>controllers/kubegres_controller.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 controllers import ( "context" "github.com/go-logr/logr" apps "k8s.io/api/apps/v1" core "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/tools/record" kubegresv1 "reactive-tech.io/kubegres/api/v1" ctx2 "reactive-tech.io/kubegres/controllers/ctx" "reactive-tech.io/kubegres/controllers/ctx/resources" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "time" ) // KubegresReconciler reconciles a Kubegres object type KubegresReconciler struct { client.Client Logger logr.Logger Scheme *runtime.Scheme Recorder record.EventRecorder } //+kubebuilder:rbac:groups=kubegres.reactive-tech.io,resources=kubegres,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=kubegres.reactive-tech.io,resources=kubegres/status,verbs=get;update;patch //+kubebuilder:rbac:groups=kubegres.reactive-tech.io,resources=kubegres/finalizers,verbs=update // +kubebuilder:rbac:groups="",resources=events,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups="",resources=pods,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups="",resources=persistentvolumeclaims,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups="apps",resources=statefulsets,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups="batch",resources=cronjobs,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups="storage.k8s.io",resources=storageclasses,verbs=get;list;watch // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. // For more details, check Reconcile and its Result here: // - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile func (r *KubegresReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { //_ = r.Logger.WithValues("kubegres", req.NamespacedName) r.Logger.Info("=======================================================") r.Logger.Info("=======================================================") kubegres, err := r.getDeployedKubegresResource(ctx, req) if err != nil { r.Logger.Info("Kubegres resource does not exist") return ctrl.Result{}, nil } resourcesContext, err := resources.CreateResourcesContext(kubegres, ctx, r.Logger, r.Client, r.Recorder) if err != nil { return ctrl.Result{}, err } nbreSecondsLeftBeforeTimeOut := resourcesContext.BlockingOperation.LoadActiveOperation() resourcesContext.BlockingOperationLogger.Log() resourcesContext.ResourcesStatesLogger.Log() if nbreSecondsLeftBeforeTimeOut > 0 { resultWithRequeue := ctrl.Result{ Requeue: true, RequeueAfter: time.Duration(nbreSecondsLeftBeforeTimeOut) * time.Second, } return r.returnn(resultWithRequeue, nil, resourcesContext) } specCheckResult, err := resourcesContext.SpecChecker.CheckSpec() if err != nil { return r.returnn(ctrl.Result{}, err, resourcesContext) } else if specCheckResult.HasSpecFatalError { return r.returnn(ctrl.Result{}, nil, resourcesContext) } return r.returnn(ctrl.Result{}, r.enforceSpec(resourcesContext), resourcesContext) } func (r *KubegresReconciler) returnn(result ctrl.Result, err error, resourcesContext *resources.ResourcesContext) (ctrl.Result, error) { errStatusUpt := resourcesContext.KubegresContext.Status.UpdateStatusIfChanged() if errStatusUpt != nil && err == nil { return result, errStatusUpt } return result, err } func (r *KubegresReconciler) getDeployedKubegresResource(ctx context.Context, req ctrl.Request) (*kubegresv1.Kubegres, error) { // We sleep 1 second to let sufficient time to Kubernetes to update its system // so that when we will call the Get method below, we will receive the latest Kubegres resource time.Sleep(1 * time.Second) kubegres := &kubegresv1.Kubegres{} err := r.Client.Get(ctx, req.NamespacedName, kubegres) if err == nil { return kubegres, nil } r.Logger.Info("Kubegres resource does not exist") return &kubegresv1.Kubegres{}, err } func (r *KubegresReconciler) enforceSpec(resourcesContext *resources.ResourcesContext) error { err := r.enforceResourcesCountSpec(resourcesContext) if err != nil { return err } return r.enforceAllStatefulSetsSpec(resourcesContext) } func (r *KubegresReconciler) enforceResourcesCountSpec(resourcesContext *resources.ResourcesContext) error { return resourcesContext.ResourcesCountSpecEnforcer.EnforceSpec() } func (r *KubegresReconciler) enforceAllStatefulSetsSpec(resourcesContext *resources.ResourcesContext) error { return resourcesContext.AllStatefulSetsSpecEnforcer.EnforceSpec() } func (r *KubegresReconciler) SetupWithManager(mgr ctrl.Manager) error { ctx := context.Background() err := ctx2.CreateOwnerKeyIndexation(mgr, ctx) if err != nil { return err } return ctrl.NewControllerManagedBy(mgr). For(&kubegresv1.Kubegres{}). Owns(&apps.StatefulSet{}). Owns(&core.Service{}). Complete(r) } <|start_filename|>controllers/states/DbStorageClassStates.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 states import ( storage "k8s.io/api/storage/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "reactive-tech.io/kubegres/controllers/ctx" "sigs.k8s.io/controller-runtime/pkg/client" ) type DbStorageClassStates struct { IsDeployed bool StorageClassName string kubegresContext ctx.KubegresContext } func loadDbStorageClass(kubegresContext ctx.KubegresContext) (DbStorageClassStates, error) { dbStorageClassStates := DbStorageClassStates{kubegresContext: kubegresContext} err := dbStorageClassStates.loadStates() return dbStorageClassStates, err } func (r *DbStorageClassStates) loadStates() error { dbStorageClass, err := r.GetStorageClass() if err != nil { return err } if dbStorageClass.Name != "" { r.IsDeployed = true r.StorageClassName = dbStorageClass.Name } return nil } func (r *DbStorageClassStates) GetStorageClass() (*storage.StorageClass, error) { namespace := "" resourceName := r.getSpecStorageClassName() resourceKey := client.ObjectKey{Namespace: namespace, Name: resourceName} storageClass := &storage.StorageClass{} err := r.kubegresContext.Client.Get(r.kubegresContext.Ctx, resourceKey, storageClass) if err != nil { if apierrors.IsNotFound(err) { err = nil } else { r.kubegresContext.Log.ErrorEvent("DatabaseStorageClassLoadingErr", err, "Unable to load any deployed Database StorageClass.", "StorageClass name", resourceName) } } return storageClass, err } func (r *DbStorageClassStates) getSpecStorageClassName() string { return *r.kubegresContext.Kubegres.Spec.Database.StorageClassName } <|start_filename|>test/util/TestResourceModifier.go<|end_filename|> package util import ( v12 "k8s.io/api/core/v1" postgresv1 "reactive-tech.io/kubegres/api/v1" ) type TestResourceModifier struct { } func (r *TestResourceModifier) AppendAnnotation(annotationKey, annotationValue string, kubegresResource *postgresv1.Kubegres) { if kubegresResource.Annotations == nil { kubegresResource.Annotations = make(map[string]string) } kubegresResource.Annotations[annotationKey] = annotationValue } func (r *TestResourceModifier) AppendEnvVar(envVarName, envVarVal string, kubegresResource *postgresv1.Kubegres) { envVar := v12.EnvVar{ Name: envVarName, Value: envVarVal, } kubegresResource.Spec.Env = append(kubegresResource.Spec.Env, envVar) } func (r *TestResourceModifier) AppendEnvVarFromSecretKey(envVarName, envVarSecretKeyValueName string, kubegresResource *postgresv1.Kubegres) { envVar := v12.EnvVar{ Name: envVarName, ValueFrom: &v12.EnvVarSource{ SecretKeyRef: &v12.SecretKeySelector{ Key: envVarSecretKeyValueName, LocalObjectReference: v12.LocalObjectReference{ Name: "my-kubegres-secret", }, }, }, } kubegresResource.Spec.Env = append(kubegresResource.Spec.Env, envVar) } <|start_filename|>controllers/states/ResourcesStates.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 states import ( "reactive-tech.io/kubegres/controllers/ctx" "reactive-tech.io/kubegres/controllers/states/statefulset" ) type ResourcesStates struct { DbStorageClass DbStorageClassStates StatefulSets statefulset.StatefulSetsStates Services ServicesStates Config ConfigStates BackUp BackUpStates kubegresContext ctx.KubegresContext } func LoadResourcesStates(kubegresContext ctx.KubegresContext) (ResourcesStates, error) { resourcesStates := ResourcesStates{kubegresContext: kubegresContext} err := resourcesStates.loadStates() return resourcesStates, err } func (r *ResourcesStates) loadStates() (err error) { err = r.loadDbStorageClassStates() if err != nil { return err } err = r.loadConfigStates() if err != nil { return err } err = r.loadStatefulSetsStates() if err != nil { return err } err = r.loadServicesStates() if err != nil { return err } err = r.loadBackUpStates() if err != nil { return err } return nil } func (r *ResourcesStates) loadDbStorageClassStates() (err error) { r.DbStorageClass, err = loadDbStorageClass(r.kubegresContext) return err } func (r *ResourcesStates) loadConfigStates() (err error) { r.Config, err = loadConfigStates(r.kubegresContext) return err } func (r *ResourcesStates) loadStatefulSetsStates() (err error) { r.StatefulSets, err = statefulset.LoadStatefulSetsStates(r.kubegresContext) return err } func (r *ResourcesStates) loadServicesStates() (err error) { r.Services, err = loadServicesStates(r.kubegresContext) return err } func (r *ResourcesStates) loadBackUpStates() (err error) { r.BackUp, err = loadBackUpStates(r.kubegresContext) return err } <|start_filename|>controllers/spec/enforcer/statefulset_spec/StatefulSetSpecDifferences.go<|end_filename|> package statefulset_spec type StatefulSetSpecDifference struct { SpecName string Current string Expected string } func (r *StatefulSetSpecDifference) IsThereDifference() bool { return r.SpecName != "" } type StatefulSetSpecDifferences struct { Differences []StatefulSetSpecDifference } func (r *StatefulSetSpecDifferences) IsThereDifference() bool { return len(r.Differences) > 0 } func (r *StatefulSetSpecDifferences) GetSpecDifferencesAsString() string { if !r.IsThereDifference() { return "" } specDifferencesStr := "" separator := "" for _, specDiff := range r.Differences { specDifferencesStr += separator + specDiff.SpecName + ": " + specDiff.Expected separator = ", " } return specDifferencesStr } <|start_filename|>controllers/spec/enforcer/statefulset_spec/CustomConfigSpecEnforcer.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 statefulset_spec import ( apps "k8s.io/api/apps/v1" "reactive-tech.io/kubegres/controllers/spec/template" ) type CustomConfigSpecEnforcer struct { customConfigSpecHelper template.CustomConfigSpecHelper } func CreateCustomConfigSpecEnforcer(customConfigSpecHelper template.CustomConfigSpecHelper) CustomConfigSpecEnforcer { return CustomConfigSpecEnforcer{customConfigSpecHelper: customConfigSpecHelper} } func (r *CustomConfigSpecEnforcer) GetSpecName() string { return "CustomConfig" } func (r *CustomConfigSpecEnforcer) CheckForSpecDifference(statefulSet *apps.StatefulSet) StatefulSetSpecDifference { statefulSetCopy := *statefulSet hasStatefulSetChanged, changesDetails := r.customConfigSpecHelper.ConfigureStatefulSet(&statefulSetCopy) if hasStatefulSetChanged { return StatefulSetSpecDifference{ SpecName: r.GetSpecName(), Current: " ", Expected: changesDetails, } } return StatefulSetSpecDifference{} } func (r *CustomConfigSpecEnforcer) EnforceSpec(statefulSet *apps.StatefulSet) (wasSpecUpdated bool, err error) { wasSpecUpdated, _ = r.customConfigSpecHelper.ConfigureStatefulSet(statefulSet) return wasSpecUpdated, nil } func (r *CustomConfigSpecEnforcer) OnSpecEnforcedSuccessfully(statefulSet *apps.StatefulSet) error { return nil } <|start_filename|>controllers/operation/BlockingOperationError.go<|end_filename|> package operation const ( errorTypeThereIsAlreadyAnActiveOperation = "There is already an active operation which is running. We cannot have more than 1 active operation running." errorTypeOperationIdHasNoAssociatedConfig = "The given operationId has not an associated config. Please associate it by calling the method BlockingOperation.AddConfig()." ) type BlockingOperationError struct { ThereIsAlreadyAnActiveOperation bool OperationIdHasNoAssociatedConfig bool errorType string } func CreateBlockingOperationError(errorType, operationId string) *BlockingOperationError { return &BlockingOperationError{ errorType: "OperationId: '" + operationId + "' - " + errorType, ThereIsAlreadyAnActiveOperation: errorType == errorTypeThereIsAlreadyAnActiveOperation, OperationIdHasNoAssociatedConfig: errorType == errorTypeOperationIdHasNoAssociatedConfig, } } func (r *BlockingOperationError) Error() string { return "Cannot active a blocking operation. Reason: " + r.errorType } <|start_filename|>test/util/kindcluster/KindTestClusterUtil.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 kindcluster import ( "bytes" "log" "os" "os/exec" "path/filepath" "strings" ) const clusterName = "kubegres" type KindTestClusterUtil struct { kindExecPath string } func (r *KindTestClusterUtil) StartCluster() { log.Println("STARTING KIND CLUSTER '" + clusterName + "'") // start kind cluster var err error r.kindExecPath, err = exec.LookPath("kind") if err != nil { log.Fatal("We cannot find the executable 'kind'. " + "Make sure 'kind' is installed and the executable 'kind' " + "is in the classpath before running the tests.") } if r.isClusterRunning() { log.Println("Cluster is already running. No need to restart it.") r.installOperator() return } clusterConfigFilePath := r.getClusterConfigFilePath() log.Println("Running 'kind create cluster --name " + clusterName + " --config " + clusterConfigFilePath + "'") var out bytes.Buffer cmdStartCluster := &exec.Cmd{ Path: r.kindExecPath, Args: []string{r.kindExecPath, "create", "cluster", "--name", clusterName, "--config", clusterConfigFilePath}, Stdout: &out, Stderr: os.Stdout, } err = cmdStartCluster.Run() if err != nil { log.Fatal("Unable to execute the command 'kind create cluster --name "+clusterName+" --config "+clusterConfigFilePath+"'", err) } else { log.Println("CLUSTER STARTED") r.installOperator() } } func (r *KindTestClusterUtil) DeleteCluster() bool { log.Println("DELETING KIND CLUSTER '" + clusterName + "'") log.Println("Running 'kind delete cluster --name " + clusterName + "'") var out bytes.Buffer cmdDeleteCluster := &exec.Cmd{ Path: r.kindExecPath, Args: []string{r.kindExecPath, "delete", "cluster", "--name", clusterName}, Stdout: &out, Stderr: os.Stdout, } err := cmdDeleteCluster.Run() if err != nil { log.Fatal("Unable to execute the command 'kind delete cluster --name "+clusterName+"'", err) return false } return true } func (r *KindTestClusterUtil) isClusterRunning() bool { var out bytes.Buffer cmdGetClusters := &exec.Cmd{ Path: r.kindExecPath, Args: []string{r.kindExecPath, "get", "clusters"}, Stdout: &out, Stderr: os.Stdout, } err := cmdGetClusters.Run() if err != nil { log.Fatal("Unable to execute the command 'kind get clusters'", err) } outputLines := strings.Split(out.String(), "\n") for _, cluster := range outputLines { if cluster == clusterName { return true } log.Println("cluster: '" + cluster + "'") } return false } func (r *KindTestClusterUtil) installOperator() bool { log.Println("Installing Kubegres operator in Cluster") makeFilePath := r.getMakeFilePath() makeFileFolder := r.getMakeFileFolder(makeFilePath) log.Println("Running 'make install -f " + makeFilePath + " -C " + makeFileFolder + "'") // -C /home/alex/source/kubegres makeExecPath, err := exec.LookPath("make") if err != nil { log.Fatal("We cannot find the executable 'make'. " + "Make sure 'make' is installed and the executable 'make' " + "is in the classpath before running the tests.") } var out bytes.Buffer cmdMakeInstallClusters := &exec.Cmd{ Path: makeExecPath, Args: []string{makeExecPath, "install", "-f", makeFilePath, "-C", makeFileFolder}, Stdout: &out, Stderr: os.Stdout, } err = cmdMakeInstallClusters.Run() if err != nil { log.Fatal("Unable to execute the command 'make install -f "+makeFilePath+" -C "+makeFileFolder+"'", err) return false } return true } func (r *KindTestClusterUtil) getClusterConfigFilePath() string { fileAbsolutePath, err := filepath.Abs("util/kindcluster/kind-cluster-config.yaml") if err != nil { log.Fatal("Error while trying to get the absolute-path of 'kind-cluster-config.yaml': ", err) } return fileAbsolutePath } func (r *KindTestClusterUtil) getMakeFilePath() string { fileAbsolutePath, err := filepath.Abs("../Makefile") if err != nil { log.Fatal("Error while trying to get the absolute-path of 'MakeFile': ", err) } return fileAbsolutePath } func (r *KindTestClusterUtil) getMakeFileFolder(makeFilePath string) string { return filepath.Dir(makeFilePath) } <|start_filename|>test/spec_envVariables_test.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" v12 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "log" postgresv1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/controllers/ctx" "reactive-tech.io/kubegres/test/resourceConfigs" "reactive-tech.io/kubegres/test/util" "reactive-tech.io/kubegres/test/util/testcases" ) var _ = Describe("Setting Kubegres spec 'env.*'", func() { var test = SpecEnVariablesTest{} BeforeEach(func() { //Skip("Temporarily skipping test") namespace := resourceConfigs.DefaultNamespace test.resourceRetriever = util.CreateTestResourceRetriever(k8sClientTest, namespace) test.resourceCreator = util.CreateTestResourceCreator(k8sClientTest, test.resourceRetriever, namespace) test.dbQueryTestCases = testcases.InitDbQueryTestCases(test.resourceCreator, resourceConfigs.KubegresResourceName) }) AfterEach(func() { test.resourceCreator.DeleteAllTestResources() }) Context("GIVEN new Kubegres is created without environment variable of postgres super-user password", func() { It("THEN an error event should be logged saying the super-user password is missing", func() { log.Print("START OF: Test 'GIVEN new Kubegres is created without environment variable of postgres super-user password'") test.givenNewKubegresWithoutEnvVarOfPostgresSuperUserPassword() test.whenKubegresIsCreated() test.thenErrorEventShouldBeLogged("spec.env.POSTGRES_PASSWORD") log.Print("END OF: Test 'GIVEN new Kubegres is created without environment variable of postgres super-user password'") }) }) Context("GIVEN new Kubegres is created without environment variable of postgres replication-user password", func() { It("THEN an error event should be logged saying the replication-user password is missing", func() { log.Print("START OF: Test 'GIVEN new Kubegres is created without environment variable of postgres replication-user password'") test.givenNewKubegresWithoutEnvVarOfPostgresReplicationUserPassword() test.whenKubegresIsCreated() test.thenErrorEventShouldBeLogged("spec.env.POSTGRES_REPLICATION_PASSWORD") log.Print("END OF: Test 'GIVEN new Kubegres is created without environment variable of postgres replication-user password'") }) }) Context("GIVEN new Kubegres is created with all environment variables AND spec 'replica' set to 3", func() { It("THEN 1 primary and 2 replica should be created with all environment variables", func() { log.Print("START OF: Test 'GIVEN new Kubegres is created with all environment variables'") test.givenNewKubegresWithAllEnvVarsSet(3) test.whenKubegresIsCreated() test.thenPodsShouldContainAllEnvVariables(1, 2) test.thenDeployedKubegresSpecShouldHaveAllEnvVars() test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() log.Print("END OF: Test 'GIVEN new Kubegres is created with all environment variables'") }) }) Context("GIVEN new Kubegres is created with all environment variables and a custom one AND spec 'replica' set to 3", func() { It("THEN 1 primary and 2 replica should be created with all environment variables including the custom one too", func() { log.Print("START OF: Test 'GIVEN new Kubegres is created with all environment variables and a custom one'") test.givenNewKubegresWithAllEnvVarsSetAndACustomOne(3) test.whenKubegresIsCreated() test.thenPodsShouldContainAllEnvVariables(1, 2) test.thenDeployedKubegresSpecShouldHaveAllEnvVars() test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() log.Print("END OF: Test 'GIVEN new Kubegres is created with all environment variables and a custom one'") }) }) }) type SpecEnVariablesTest struct { kubegresResource *postgresv1.Kubegres dbQueryTestCases testcases.DbQueryTestCases resourceCreator util.TestResourceCreator resourceRetriever util.TestResourceRetriever resourceModifier util.TestResourceModifier customEnvVariableName string customEnvVariableKey string } func (r *SpecEnVariablesTest) givenNewKubegresWithoutEnvVarOfPostgresSuperUserPassword() { r.kubegresResource = resourceConfigs.LoadKubegresYaml() r.kubegresResource.Spec.Env = []v12.EnvVar{} r.resourceModifier.AppendEnvVarFromSecretKey(ctx.EnvVarNameOfPostgresReplicationUserPsw, "replicationUserPassword", r.kubegresResource) } func (r *SpecEnVariablesTest) givenNewKubegresWithoutEnvVarOfPostgresReplicationUserPassword() { r.kubegresResource = resourceConfigs.LoadKubegresYaml() r.kubegresResource.Spec.Env = []v12.EnvVar{} r.resourceModifier.AppendEnvVarFromSecretKey(ctx.EnvVarNameOfPostgresSuperUserPsw, "superUserPassword", r.kubegresResource) } func (r *SpecEnVariablesTest) givenNewKubegresWithAllEnvVarsSet(specNbreReplicas int32) { r.kubegresResource = resourceConfigs.LoadKubegresYaml() r.kubegresResource.Spec.Replicas = &specNbreReplicas r.kubegresResource.Spec.Env = []v12.EnvVar{} r.resourceModifier.AppendEnvVarFromSecretKey(ctx.EnvVarNameOfPostgresReplicationUserPsw, "replicationUserPassword", r.kubegresResource) r.resourceModifier.AppendEnvVarFromSecretKey(ctx.EnvVarNameOfPostgresSuperUserPsw, "superUserPassword", r.kubegresResource) } func (r *SpecEnVariablesTest) givenNewKubegresWithAllEnvVarsSetAndACustomOne(specNbreReplicas int32) { r.givenNewKubegresWithAllEnvVarsSet(specNbreReplicas) r.customEnvVariableName = "POSTGRES_CUSTOM_ENV_VAR" r.customEnvVariableKey = "myAppUserPassword" r.resourceModifier.AppendEnvVarFromSecretKey(r.customEnvVariableName, r.customEnvVariableKey, r.kubegresResource) } func (r *SpecEnVariablesTest) whenKubegresIsCreated() { r.resourceCreator.CreateKubegres(r.kubegresResource) } func (r *SpecEnVariablesTest) thenPodsShouldContainAllEnvVariables(nbrePrimary, nbreReplicas int) bool { return Eventually(func() bool { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil && !apierrors.IsNotFound(err) { log.Println("ERROR while retrieving Kubegres kubegresResources") return false } for _, resource := range kubegresResources.Resources { envVars := resource.Pod.Spec.Containers[0].Env if !r.doesEnvVarExist(ctx.EnvVarNameOfPostgresSuperUserPsw, envVars) { log.Println("Pod '" + resource.Pod.Name + "' doesn't have the expected env variable: '" + ctx.EnvVarNameOfPostgresSuperUserPsw + "'. Waiting...") return false } if !r.doesEnvVarExist(ctx.EnvVarNameOfPostgresReplicationUserPsw, envVars) { log.Println("Pod '" + resource.Pod.Name + "' doesn't have the expected env variable: '" + ctx.EnvVarNameOfPostgresReplicationUserPsw + "'. Waiting...") return false } if r.customEnvVariableName != "" { if !r.doesEnvVarExist(r.customEnvVariableName, envVars) { log.Println("Pod '" + resource.Pod.Name + "' doesn't have the expected env variable: '" + r.customEnvVariableName + "'. Waiting...") return false } } } return kubegresResources.AreAllReady && kubegresResources.NbreDeployedPrimary == nbrePrimary && kubegresResources.NbreDeployedReplicas == nbreReplicas }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecEnVariablesTest) thenDeployedKubegresSpecShouldHaveAllEnvVars() { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } Expect(r.doesEnvVarExist(ctx.EnvVarNameOfPostgresSuperUserPsw, r.kubegresResource.Spec.Env)).Should(Equal(true)) Expect(r.doesEnvVarExist(ctx.EnvVarNameOfPostgresReplicationUserPsw, r.kubegresResource.Spec.Env)).Should(Equal(true)) } func (r *SpecEnVariablesTest) doesEnvVarExist(envVarName string, envVars []v12.EnvVar) bool { for _, env := range envVars { if env.Name == envVarName { return true } } return false } func (r *SpecEnVariablesTest) thenErrorEventShouldBeLogged(specName string) { expectedErrorEvent := util.EventRecord{ Eventtype: v12.EventTypeWarning, Reason: "SpecCheckErr", Message: "In the Resources Spec the value of '" + specName + "' is undefined. Please set a value otherwise this operator cannot work correctly.", } Eventually(func() bool { _, err := r.resourceRetriever.GetKubegres() if err != nil { return false } return eventRecorderTest.CheckEventExist(expectedErrorEvent) }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } <|start_filename|>controllers/ctx/CreateOwnerKeyIndexation.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 ctx import ( "context" apps "k8s.io/api/apps/v1" core "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" postgresV1 "reactive-tech.io/kubegres/api/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" ) func CreateOwnerKeyIndexation(mgr ctrl.Manager, ctx context.Context) error { if err := mgr.GetFieldIndexer().IndexField(ctx, &apps.StatefulSet{}, DeploymentOwnerKey, func(rawObj client.Object) []string { // grab the StatefultSet object, extract the owner... depl := rawObj.(*apps.StatefulSet) owner := metav1.GetControllerOf(depl) if owner == nil { return nil } // ...make sure it's a Kubegres... if owner.APIVersion != postgresV1.GroupVersion.String() || owner.Kind != KindKubegres { return nil } // ...and if so, return it return []string{owner.Name} }); err != nil { return err } if err := mgr.GetFieldIndexer().IndexField(ctx, &core.Service{}, DeploymentOwnerKey, func(rawObj client.Object) []string { // grab the Service object, extract the owner... depl := rawObj.(*core.Service) owner := metav1.GetControllerOf(depl) if owner == nil { return nil } // ...make sure it's a Kubegres... if owner.APIVersion != postgresV1.GroupVersion.String() || owner.Kind != KindKubegres { return nil } // ...and if so, return it return []string{owner.Name} }); err != nil { return err } if err := mgr.GetFieldIndexer().IndexField(ctx, &core.ConfigMap{}, DeploymentOwnerKey, func(rawObj client.Object) []string { // grab the CustomConfig object, extract the owner... depl := rawObj.(*core.ConfigMap) owner := metav1.GetControllerOf(depl) if owner == nil { return nil } // ...make sure it's a Kubegres... if owner.APIVersion != postgresV1.GroupVersion.String() || owner.Kind != KindKubegres { return nil } // ...and if so, return it return []string{owner.Name} }); err != nil { return err } if err := mgr.GetFieldIndexer().IndexField(ctx, &core.Pod{}, DeploymentOwnerKey, func(rawObj client.Object) []string { // grab the Pod object, extract the owner... depl := rawObj.(*core.Pod) owner := metav1.GetControllerOf(depl) if owner == nil { return nil } // ...make sure it's a Kubegres... if owner.APIVersion != postgresV1.GroupVersion.String() || owner.Kind != KindKubegres { return nil } // ...and if so, return it return []string{owner.Name} }); err != nil { return err } return nil } <|start_filename|>controllers/operation/BlockingOperation.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 operation import ( v1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/controllers/ctx" "time" ) type BlockingOperation struct { kubegresContext ctx.KubegresContext configs map[string]BlockingOperationConfig activeOperation v1.KubegresBlockingOperation previouslyActiveOperation v1.KubegresBlockingOperation } func CreateBlockingOperation(kubegresContext ctx.KubegresContext) *BlockingOperation { return &BlockingOperation{ kubegresContext: kubegresContext, configs: make(map[string]BlockingOperationConfig), activeOperation: v1.KubegresBlockingOperation{}, } } func (r *BlockingOperation) AddConfig(config BlockingOperationConfig) { configId := r.generateConfigId(config.OperationId, config.StepId) r.configs[configId] = config } func (r *BlockingOperation) LoadActiveOperation() int64 { r.activeOperation = r.kubegresContext.Status.GetBlockingOperation() r.previouslyActiveOperation = r.kubegresContext.Status.GetPreviousBlockingOperation() r.removeOperationIfNotActive() nbreSecondsLeftBeforeTimeOut := r.GetNbreSecondsLeftBeforeTimeOut() if nbreSecondsLeftBeforeTimeOut > 20 { return 20 } return nbreSecondsLeftBeforeTimeOut } func (r *BlockingOperation) IsActiveOperationIdDifferentOf(operationId string) bool { return r.isThereActiveOperation() && r.activeOperation.OperationId != operationId } func (r *BlockingOperation) IsActiveOperationInTransition(operationId string) bool { return r.activeOperation.OperationId == operationId && r.activeOperation.StepId == TransitionOperationStepId } func (r *BlockingOperation) HasActiveOperationIdTimedOut(operationId string) bool { return r.activeOperation.OperationId == operationId && r.activeOperation.HasTimedOut } func (r *BlockingOperation) GetActiveOperation() v1.KubegresBlockingOperation { return r.activeOperation } func (r *BlockingOperation) GetPreviouslyActiveOperation() v1.KubegresBlockingOperation { return r.previouslyActiveOperation } func (r *BlockingOperation) ActivateOperation(operationId string, stepId string) error { return r.activateOperation(r.createOperationObj(operationId, stepId)) } func (r *BlockingOperation) ActivateOperationOnStatefulSet(operationId string, stepId string, statefulSetInstanceIndex int32) error { blockingOperation := r.createOperationObj(operationId, stepId) blockingOperation.StatefulSetOperation = r.createStatefulSetOperationObj(statefulSetInstanceIndex) return r.activateOperation(blockingOperation) } func (r *BlockingOperation) ActivateOperationOnStatefulSetSpecUpdate(operationId string, stepId string, statefulSetInstanceIndex int32, specDifferences string) error { blockingOperation := r.createOperationObj(operationId, stepId) blockingOperation.StatefulSetOperation = r.createStatefulSetOperationObj(statefulSetInstanceIndex) blockingOperation.StatefulSetSpecUpdateOperation = r.createStatefulSetSpecUpdateOperationObj(specDifferences) return r.activateOperation(blockingOperation) } func (r *BlockingOperation) RemoveActiveOperation() { r.removeActiveOperation(false) } func (r *BlockingOperation) isThereActiveOperation() bool { return r.activeOperation.OperationId != "" } func (r *BlockingOperation) GetNbreSecondsSinceOperationHasStarted() int64 { configTimeOutInSeconds := r.getConfig(r.activeOperation).TimeOutInSeconds nbreSecondsLeftBeforeTimeOut := r.GetNbreSecondsLeftBeforeTimeOut() return configTimeOutInSeconds - nbreSecondsLeftBeforeTimeOut } func (r *BlockingOperation) GetNbreSecondsLeftBeforeTimeOut() int64 { if r.activeOperation.TimeOutEpocInSeconds == 0 { return 0 } nbreSecondsLeftBeforeTimeOut := r.activeOperation.TimeOutEpocInSeconds - r.getNbreSecondsSinceEpoc() if nbreSecondsLeftBeforeTimeOut < 0 { return 0 } return nbreSecondsLeftBeforeTimeOut } func (r *BlockingOperation) GetNbreSecondsSinceTimedOut() int64 { return r.getNbreSecondsSinceEpoc() - r.activeOperation.TimeOutEpocInSeconds } func (r *BlockingOperation) activateOperation(operation v1.KubegresBlockingOperation) error { if r.isThereActiveOperation() && r.activeOperation.OperationId != operation.OperationId { return CreateBlockingOperationError(errorTypeThereIsAlreadyAnActiveOperation, operation.OperationId) } else if !r.doesOperationHaveAssociatedConfig(operation) { return CreateBlockingOperationError(errorTypeOperationIdHasNoAssociatedConfig, operation.OperationId) } config := r.getConfig(operation) operation.TimeOutEpocInSeconds = r.calculateTimeOutInEpochSeconds(config.TimeOutInSeconds) r.activeOperation = operation r.kubegresContext.Status.SetBlockingOperation(operation) return nil } func (r *BlockingOperation) createOperationObj(operationId string, stepId string) v1.KubegresBlockingOperation { return v1.KubegresBlockingOperation{OperationId: operationId, StepId: stepId} } func (r *BlockingOperation) createStatefulSetOperationObj(statefulSetInstanceIndex int32) v1.KubegresStatefulSetOperation { return v1.KubegresStatefulSetOperation{ InstanceIndex: statefulSetInstanceIndex, Name: r.kubegresContext.GetStatefulSetResourceName(statefulSetInstanceIndex), } } func (r *BlockingOperation) createStatefulSetSpecUpdateOperationObj(specDifferences string) v1.KubegresStatefulSetSpecUpdateOperation { return v1.KubegresStatefulSetSpecUpdateOperation{SpecDifferences: specDifferences} } func (r *BlockingOperation) removeActiveOperation(hasOperationTimedOut bool) { if !r.isOperationInTransition() { r.previouslyActiveOperation = r.activeOperation r.previouslyActiveOperation.HasTimedOut = hasOperationTimedOut r.kubegresContext.Status.SetPreviousBlockingOperation(r.previouslyActiveOperation) } r.activeOperation = v1.KubegresBlockingOperation{} r.kubegresContext.Status.SetBlockingOperation(r.activeOperation) } func (r *BlockingOperation) setActiveOperationInTransition(hasOperationTimedOut bool) { r.previouslyActiveOperation = r.activeOperation r.previouslyActiveOperation.HasTimedOut = hasOperationTimedOut r.kubegresContext.Status.SetPreviousBlockingOperation(r.previouslyActiveOperation) r.activeOperation.StepId = TransitionOperationStepId r.activeOperation.HasTimedOut = false r.activeOperation.TimeOutEpocInSeconds = 0 r.kubegresContext.Status.SetBlockingOperation(r.activeOperation) } func (r *BlockingOperation) removeOperationIfNotActive() { if !r.isThereActiveOperation() || r.isOperationInTransition() { return } hasOperationTimedOut := r.hasOperationTimedOut() if hasOperationTimedOut { r.activeOperation.HasTimedOut = true if !r.hasCompletionChecker() { if r.shouldOperationBeInTransition() { r.setActiveOperationInTransition(hasOperationTimedOut) } else { r.removeActiveOperation(hasOperationTimedOut) } } else { r.kubegresContext.Log.InfoEvent("BlockingOperationTimedOut", "Blocking-Operation timed-out.", "OperationId", r.activeOperation.OperationId, "StepId", r.activeOperation.StepId) } } else if r.isOperationCompletionConditionReached() { r.kubegresContext.Log.InfoEvent("BlockingOperationCompleted", "Blocking-Operation is successfully completed.", "OperationId", r.activeOperation.OperationId, "StepId", r.activeOperation.StepId) if r.shouldOperationBeInTransition() { r.setActiveOperationInTransition(hasOperationTimedOut) } else { r.removeActiveOperation(hasOperationTimedOut) } } } func (r *BlockingOperation) isOperationInTransition() bool { return r.activeOperation.StepId == TransitionOperationStepId } func (r *BlockingOperation) hasCompletionChecker() bool { operationConfig := r.getConfig(r.activeOperation) return operationConfig.CompletionChecker != nil } func (r *BlockingOperation) shouldOperationBeInTransition() bool { operationConfig := r.getConfig(r.activeOperation) return operationConfig.AfterCompletionMoveToTransitionStep } func (r *BlockingOperation) hasOperationTimedOut() bool { return r.activeOperation.TimeOutEpocInSeconds-r.getNbreSecondsSinceEpoc() <= 0 } func (r *BlockingOperation) isOperationCompletionConditionReached() bool { operationConfig := r.getConfig(r.activeOperation) if operationConfig.CompletionChecker != nil { return operationConfig.CompletionChecker(r.activeOperation) } return false } func (r *BlockingOperation) calculateTimeOutInEpochSeconds(timeOutInSeconds int64) int64 { return r.getNbreSecondsSinceEpoc() + timeOutInSeconds } func (r *BlockingOperation) getNbreSecondsSinceEpoc() int64 { return time.Now().Unix() } func (r *BlockingOperation) getConfig(operation v1.KubegresBlockingOperation) BlockingOperationConfig { configId := r.generateConfigId(operation.OperationId, operation.StepId) return r.configs[configId] } func (r *BlockingOperation) generateConfigId(operationId, stepId string) string { return operationId + "_" + stepId } func (r *BlockingOperation) doesOperationHaveAssociatedConfig(operation v1.KubegresBlockingOperation) bool { config := r.getConfig(operation) return config.OperationId == operation.OperationId } <|start_filename|>controllers/spec/enforcer/resources_count_spec/BaseConfigMapCountSpecEnforcer.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 resources_count_spec import ( "errors" core "k8s.io/api/core/v1" v1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/controllers/ctx" "reactive-tech.io/kubegres/controllers/operation" "reactive-tech.io/kubegres/controllers/spec/template" "reactive-tech.io/kubegres/controllers/states" "strconv" ) type BaseConfigMapCountSpecEnforcer struct { kubegresContext ctx.KubegresContext resourcesStates states.ResourcesStates resourcesCreator template.ResourcesCreatorFromTemplate blockingOperation *operation.BlockingOperation } func CreateBaseConfigMapCountSpecEnforcer(kubegresContext ctx.KubegresContext, resourcesStates states.ResourcesStates, resourcesCreator template.ResourcesCreatorFromTemplate, blockingOperation *operation.BlockingOperation) BaseConfigMapCountSpecEnforcer { return BaseConfigMapCountSpecEnforcer{ kubegresContext: kubegresContext, resourcesStates: resourcesStates, resourcesCreator: resourcesCreator, blockingOperation: blockingOperation, } } func (r *BaseConfigMapCountSpecEnforcer) CreateOperationConfig() operation.BlockingOperationConfig { return operation.BlockingOperationConfig{ OperationId: operation.OperationIdBaseConfigCountSpecEnforcement, StepId: operation.OperationStepIdBaseConfigDeploying, TimeOutInSeconds: 10, CompletionChecker: func(operation v1.KubegresBlockingOperation) bool { return r.isBaseConfigDeployed() }, } } func (r *BaseConfigMapCountSpecEnforcer) EnforceSpec() error { if r.blockingOperation.IsActiveOperationIdDifferentOf(operation.OperationIdBaseConfigCountSpecEnforcement) { return nil } if r.hasLastAttemptTimedOut() { if r.isBaseConfigDeployed() { r.blockingOperation.RemoveActiveOperation() r.logKubegresFeaturesAreReEnabled() } else { r.logTimedOut() return nil } } if r.isBaseConfigDeployed() { return nil } baseConfigMap, err := r.resourcesCreator.CreateBaseConfigMap() if err != nil { r.kubegresContext.Log.ErrorEvent("BaseConfigMapTemplateErr", err, "Unable to create a Base ConfigMap object from template.", "Based ConfigMap name", ctx.BaseConfigMapName) return err } return r.deployBaseConfigMap(baseConfigMap) } func (r *BaseConfigMapCountSpecEnforcer) isBaseConfigDeployed() bool { return r.resourcesStates.Config.IsBaseConfigDeployed } func (r *BaseConfigMapCountSpecEnforcer) hasLastAttemptTimedOut() bool { return r.blockingOperation.HasActiveOperationIdTimedOut(operation.OperationIdBaseConfigCountSpecEnforcement) } func (r *BaseConfigMapCountSpecEnforcer) logKubegresFeaturesAreReEnabled() { r.kubegresContext.Log.InfoEvent("KubegresReEnabled", "Base ConfigMap is available again. "+ "We can safely re-enable all features of Kubegres.") } func (r *BaseConfigMapCountSpecEnforcer) logTimedOut() { operationTimeOutStr := strconv.FormatInt(r.CreateOperationConfig().TimeOutInSeconds, 10) err := errors.New("Base ConfigMap deployment timed-out") r.kubegresContext.Log.ErrorEvent("BaseConfigMapDeploymentTimedOutErr", err, "Last Base ConfigMap deployment attempt has timed-out after "+operationTimeOutStr+" seconds. "+ "The new Base ConfigMap is still NOT ready. It must be fixed manually. "+ "Until Base ConfigMap is ready, most of the features of Kubegres are disabled for safety reason. ", "Based ConfigMap to fix", ctx.BaseConfigMapName) } func (r *BaseConfigMapCountSpecEnforcer) deployBaseConfigMap(configMap core.ConfigMap) error { r.kubegresContext.Log.Info("Deploying Base ConfigMap", "name", configMap.Name) if err := r.activateBlockingOperationForDeployment(); err != nil { r.kubegresContext.Log.ErrorEvent("BaseConfigMapDeploymentOperationActivationErr", err, "Error while activating blocking operation for the deployment of a Base ConfigMap.", "ConfigMap name", configMap.Name) return err } if err := r.kubegresContext.Client.Create(r.kubegresContext.Ctx, &configMap); err != nil { r.kubegresContext.Log.ErrorEvent("BaseConfigMapDeploymentErr", err, "Unable to deploy Base ConfigMap.", "ConfigMap name", configMap.Name) r.blockingOperation.RemoveActiveOperation() return err } r.kubegresContext.Log.InfoEvent("BaseConfigMapDeployment", "Deployed Base ConfigMap.", "ConfigMap name", configMap.Name) return nil } func (r *BaseConfigMapCountSpecEnforcer) activateBlockingOperationForDeployment() error { return r.blockingOperation.ActivateOperation(operation.OperationIdBaseConfigCountSpecEnforcement, operation.OperationStepIdBaseConfigDeploying) } <|start_filename|>controllers/operation/log/BlockingOperationLogger.go<|end_filename|> package log import ( v1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/controllers/ctx" "reactive-tech.io/kubegres/controllers/operation" ) type BlockingOperationLogger struct { kubegresContext ctx.KubegresContext blockingOperation *operation.BlockingOperation } func CreateBlockingOperationLogger(kubegresContext ctx.KubegresContext, blockingOperation *operation.BlockingOperation) BlockingOperationLogger { return BlockingOperationLogger{kubegresContext: kubegresContext, blockingOperation: blockingOperation} } func (r *BlockingOperationLogger) Log() { r.logActiveOperation() r.logPreviouslyActiveOperation() } func (r *BlockingOperationLogger) logActiveOperation() { activeOperation := r.blockingOperation.GetActiveOperation() activeOperationId := activeOperation.OperationId nbreSecondsLeftBeforeTimeOut := r.blockingOperation.GetNbreSecondsLeftBeforeTimeOut() keyAndValuesToLog := r.logOperation(activeOperation) keyAndValuesToLog = append(keyAndValuesToLog, "NbreSecondsLeftBeforeTimeOut", nbreSecondsLeftBeforeTimeOut) if activeOperationId == "" { r.kubegresContext.Log.Info("Active Blocking-Operation: None") } else { r.kubegresContext.Log.Info("Active Blocking-Operation ", keyAndValuesToLog...) } } func (r *BlockingOperationLogger) logPreviouslyActiveOperation() { previousActiveOperation := r.blockingOperation.GetPreviouslyActiveOperation() operationId := previousActiveOperation.OperationId keyAndValuesToLog := r.logOperation(previousActiveOperation) if operationId == "" { r.kubegresContext.Log.Info("Previous Blocking-Operation: None") } else { r.kubegresContext.Log.Info("Previous Blocking-Operation ", keyAndValuesToLog...) } } func (r *BlockingOperationLogger) logOperation(operation v1.KubegresBlockingOperation) []interface{} { operationId := operation.OperationId stepId := operation.StepId hasTimedOut := operation.HasTimedOut statefulSetInstanceIndex := operation.StatefulSetOperation.InstanceIndex statefulSetSpecDifferences := operation.StatefulSetSpecUpdateOperation.SpecDifferences var keysAndValues []interface{} keysAndValues = append(keysAndValues, "OperationId", operationId) keysAndValues = append(keysAndValues, "StepId", stepId) keysAndValues = append(keysAndValues, "HasTimedOut", hasTimedOut) if statefulSetInstanceIndex != 0 { keysAndValues = append(keysAndValues, "StatefulSetInstanceIndex", statefulSetInstanceIndex) } if statefulSetSpecDifferences != "" { keysAndValues = append(keysAndValues, "StatefulSetSpecDifferences", statefulSetSpecDifferences) } return keysAndValues } <|start_filename|>controllers/spec/defaultspec/DefaultStorageClass.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 defaultspec import ( "errors" storage "k8s.io/api/storage/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "reactive-tech.io/kubegres/controllers/ctx" ) type DefaultStorageClass struct { kubegresContext ctx.KubegresContext } func CreateDefaultStorageClass(kubegresContext ctx.KubegresContext) DefaultStorageClass { return DefaultStorageClass{kubegresContext} } func (r *DefaultStorageClass) GetDefaultStorageClassName() (string, error) { list := &storage.StorageClassList{} err := r.kubegresContext.Client.List(r.kubegresContext.Ctx, list) if err != nil { if apierrors.IsNotFound(err) { err = nil } else { r.kubegresContext.Log.ErrorEvent("DefaultStorageClassNameErr", err, "Unable to retrieve the name of the default storage class in the Kubernetes cluster.", "Namespace", r.kubegresContext.Kubegres.Namespace) } } for _, storageClass := range list.Items { if storageClass.Annotations["storageclass.kubernetes.io/is-default-class"] == "true" { return storageClass.Name, nil } } err = errors.New("Unable to retrieve the name of the default storage class in the Kubernetes cluster. Namespace: " + r.kubegresContext.Kubegres.Namespace) r.kubegresContext.Log.ErrorEvent("DefaultStorageClassNameErr", err, "Unable to retrieve the name of the default storage class in the Kubernetes cluster.", "Namespace", r.kubegresContext.Kubegres.Namespace) return "", err } <|start_filename|>test/util/DbConnectionTestUtil.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 util import ( "database/sql" "fmt" _ "github.com/lib/pq" "k8s.io/apimachinery/pkg/runtime" "log" "reactive-tech.io/kubegres/test/resourceConfigs" "strconv" ) type DbConnectionDbUtil struct { Port int LogLabel string IsPrimaryDb bool NbreInsertedUsers int LastInsertedUserId string db *sql.DB kubegresName string serviceToQueryDb runtime.Object resourceCreator TestResourceCreator } type AccountUser struct { UserId, Username string } func InitDbConnectionDbUtil(resourceCreator TestResourceCreator, kubegresName string, nodePort int, isPrimaryDb bool) DbConnectionDbUtil { serviceToQueryDb, err := resourceCreator.CreateServiceToSqlQueryDb(kubegresName, nodePort, isPrimaryDb) if err != nil { log.Fatal("Unable to create a Service on port '"+strconv.Itoa(nodePort)+"' to query DB.", err) } logLabel := "Primary " + kubegresName if !isPrimaryDb { logLabel = "Replica " + kubegresName } return DbConnectionDbUtil{ Port: nodePort, LogLabel: logLabel, IsPrimaryDb: isPrimaryDb, kubegresName: kubegresName, serviceToQueryDb: serviceToQueryDb, resourceCreator: resourceCreator, } } func (r *DbConnectionDbUtil) Close() { r.logInfo("Closing DB connection '" + r.LogLabel + "'") err := r.db.Close() if err != nil { r.logError("Error while closing DB connection: ", err) } else { r.logInfo("Closed") } } func (r *DbConnectionDbUtil) InsertUser() bool { if !r.connect() { return false } newUserId, _ := strconv.Atoi(r.LastInsertedUserId) newUserId++ newUserIdStr := strconv.Itoa(newUserId) accountUser := AccountUser{ UserId: newUserIdStr, Username: "username" + newUserIdStr, } sqlQuery := "INSERT INTO " + resourceConfigs.TableName + " VALUES (" + accountUser.UserId + ", '" + accountUser.Username + "');" _, err := r.db.Exec(sqlQuery) if err != nil { r.logError("Error of query: "+sqlQuery+" ", err) return false } r.logInfo("Success of: " + sqlQuery) r.NbreInsertedUsers++ r.LastInsertedUserId = newUserIdStr return true } func (r *DbConnectionDbUtil) connect() bool { psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+ "password=%s dbname=%s sslmode=disable", resourceConfigs.DbHost, r.Port, resourceConfigs.DbUser, resourceConfigs.DbPassword, resourceConfigs.DbName) if r.ping(psqlInfo) { return true } var err error r.db, err = sql.Open("postgres", psqlInfo) if err != nil { r.logError("Unable to connect to: "+psqlInfo, err) _ = r.db.Close() return false } if !r.ping(psqlInfo) { return false } if r.IsPrimaryDb && !r.createTableIfDoesItNotExist() { return false } r.logInfo("Successfully connected to PostgreSql with port: '" + strconv.Itoa(r.Port) + "'") users := r.GetUsers() r.NbreInsertedUsers = len(users) if r.NbreInsertedUsers > 0 { lastUserIndex := r.NbreInsertedUsers - 1 r.LastInsertedUserId = users[lastUserIndex].UserId } else { r.LastInsertedUserId = "0" } return true } func (r *DbConnectionDbUtil) ping(psqlInfo string) bool { if r.db == nil { return false } err := r.db.Ping() if err != nil { r.logError("Ping failed to: "+psqlInfo, err) _ = r.db.Close() return false } r.logError("Ping succeeded to: "+psqlInfo, err) return true } func (r *DbConnectionDbUtil) DeleteUser(userIdToDelete string) bool { if !r.connect() { return false } sqlQuery := "DELETE FROM " + resourceConfigs.TableName + " WHERE user_id=" + userIdToDelete _, err := r.db.Exec(sqlQuery) if err != nil { r.logError("Error of query: "+sqlQuery+" ", err) return false } r.logInfo("Success of: " + sqlQuery) r.NbreInsertedUsers-- return true } func (r *DbConnectionDbUtil) GetUsers() []AccountUser { var accountUsers []AccountUser if !r.connect() { return accountUsers } sqlQuery := "SELECT user_id, username FROM " + resourceConfigs.TableName rows, err := r.db.Query(sqlQuery) if err != nil { r.logError("Error of query: "+sqlQuery+" ", err) return accountUsers } r.logInfo("Success of: " + sqlQuery) defer rows.Close() for rows.Next() { accountUser := AccountUser{} err := rows.Scan(&accountUser.UserId, &accountUser.Username) if err != nil { r.logError("Error while retrieving a user's row: ", err) return accountUsers } accountUsers = append(accountUsers, accountUser) r.logInfo("account.userId: '" + accountUser.UserId + "', account.username: '" + accountUser.Username + "'") } err = rows.Err() if err != nil { r.logError("Row error: ", err) } return accountUsers } func (r *DbConnectionDbUtil) createTableIfDoesItNotExist() bool { sqlQuery := "SELECT to_regclass('" + resourceConfigs.TableName + "');" rows, err := r.db.Query(sqlQuery) if err != nil { r.logError("Error of query: "+sqlQuery+" ", err) return false } var tableFound sql.NullString for rows.Next() { err = rows.Scan(&tableFound) if err != nil { r.logError("Error of query: "+sqlQuery+" ", err) return false } } if !tableFound.Valid { sqlQuery = "CREATE TABLE " + resourceConfigs.TableName + "(user_id serial PRIMARY KEY, username VARCHAR (50) NOT NULL);" _, err = r.db.Exec(sqlQuery) if err != nil { r.logError("Error of query: "+sqlQuery+" ", err) return false } r.logInfo("Table " + resourceConfigs.TableName + " created") } return true } func (r *DbConnectionDbUtil) logInfo(msg string) { log.Println(r.LogLabel + " - " + msg) } func (r *DbConnectionDbUtil) logError(msg string, err error) { log.Println(r.LogLabel+" - "+msg+" ", err) } <|start_filename|>controllers/spec/enforcer/resources_count_spec/StatefulSetCountSpecEnforcer.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 resources_count_spec import ( "reactive-tech.io/kubegres/controllers/spec/enforcer/resources_count_spec/statefulset" ) type StatefulSetCountSpecEnforcer struct { primaryDbCountSpecEnforcer statefulset.PrimaryDbCountSpecEnforcer replicaDbCountSpecEnforcer statefulset.ReplicaDbCountSpecEnforcer } func CreateStatefulSetCountSpecEnforcer(primaryDbCountSpecEnforcer statefulset.PrimaryDbCountSpecEnforcer, replicaDbCountSpecEnforcer statefulset.ReplicaDbCountSpecEnforcer) StatefulSetCountSpecEnforcer { return StatefulSetCountSpecEnforcer{ primaryDbCountSpecEnforcer: primaryDbCountSpecEnforcer, replicaDbCountSpecEnforcer: replicaDbCountSpecEnforcer, } } func (r *StatefulSetCountSpecEnforcer) EnforceSpec() error { if err := r.enforcePrimaryDbInstance(); err != nil { return err } return r.enforceReplicaDbInstances() } func (r *StatefulSetCountSpecEnforcer) enforcePrimaryDbInstance() error { return r.primaryDbCountSpecEnforcer.Enforce() } func (r *StatefulSetCountSpecEnforcer) enforceReplicaDbInstances() error { return r.replicaDbCountSpecEnforcer.Enforce() } <|start_filename|>scripts/WriteYamlTemplatesInGoFile.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 script is executed every time this project is compiled. See main.go where there is a comment triggering this script: "//go:generate go run scripts/WriteYamlTemplatesInGoFile.go" It copies each YAML file inside the package "controllers/template/yaml" and set them as constants in the file "controllers/template/yaml/Templates.go". This mechanism allows developers to work with YAML files when defining templates for resources managed by this operator. It is more convenient to work directly with YAML files than GO API classes when developing. */ package main import ( "fmt" "io" "io/ioutil" "os" "strings" ) const ( yamlTemplateDir = "controllers/spec/template/yaml" destinationGoFile = yamlTemplateDir + "/Templates.go" ) func main() { fs, _ := ioutil.ReadDir(yamlTemplateDir) out, _ := os.Create(destinationGoFile) out.Write([]byte("package yaml " + "\n\n // This file is auto generated by the script in 'WriteYamlTemplatesInGoFile.go'. " + "\n // Any manual modification to this file will be lost during next compilation. " + "\n\nconst (\n")) fmt.Println("Setting constants in the file: '" + destinationGoFile + "', by copying the YAML contents of the following files:") for _, f := range fs { if strings.HasSuffix(f.Name(), ".yaml") { templateYamlFilePath := yamlTemplateDir + "/" + f.Name() fmt.Println("- '" + templateYamlFilePath + "'") out.Write([]byte(strings.TrimSuffix(f.Name(), ".yaml") + " = `")) f, _ := os.Open(templateYamlFilePath) io.Copy(out, f) out.Write([]byte("`\n")) } } out.Write([]byte(")\n")) } <|start_filename|>test/util/testcases/DbQueryTestCases.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 testcases import ( . "github.com/onsi/gomega" "log" "reactive-tech.io/kubegres/test/resourceConfigs" "reactive-tech.io/kubegres/test/util" ) type DbQueryTestCases struct { connectionPrimaryDb util.DbConnectionDbUtil connectionReplicaDb util.DbConnectionDbUtil } func InitDbQueryTestCases(resourceCreator util.TestResourceCreator, kubegresName string) DbQueryTestCases { return InitDbQueryTestCasesWithNodePorts(resourceCreator, kubegresName, resourceConfigs.ServiceToSqlQueryPrimaryDbNodePort, resourceConfigs.ServiceToSqlQueryReplicaDbNodePort) } func InitDbQueryTestCasesWithNodePorts(resourceCreator util.TestResourceCreator, kubegresName string, primaryServiceNodePort, replicaServiceNodePort int) DbQueryTestCases { return DbQueryTestCases{ connectionPrimaryDb: util.InitDbConnectionDbUtil(resourceCreator, kubegresName, primaryServiceNodePort, true), connectionReplicaDb: util.InitDbConnectionDbUtil(resourceCreator, kubegresName, replicaServiceNodePort, false), } } func (r *DbQueryTestCases) ThenWeCanSqlQueryPrimaryDb() { Eventually(func() bool { isInserted := r.connectionPrimaryDb.InsertUser() if !isInserted { return false } users := r.connectionPrimaryDb.GetUsers() r.connectionPrimaryDb.Close() if r.connectionPrimaryDb.LastInsertedUserId != "" { if !r.isLastInsertedUserInDb(users) { log.Println("Does not contain the last inserted userId: '" + r.connectionPrimaryDb.LastInsertedUserId + "'") return false } } return len(users) == r.connectionPrimaryDb.NbreInsertedUsers }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *DbQueryTestCases) ThenWeCanSqlQueryReplicaDb() { Eventually(func() bool { users := r.connectionReplicaDb.GetUsers() r.connectionReplicaDb.Close() return len(users) == r.connectionPrimaryDb.NbreInsertedUsers }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *DbQueryTestCases) isLastInsertedUserInDb(users []util.AccountUser) bool { for _, user := range users { if user.UserId == r.connectionPrimaryDb.LastInsertedUserId { return true } } return false } <|start_filename|>test/custom_namespace_test.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" v12 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "log" postgresv1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/test/resourceConfigs" "reactive-tech.io/kubegres/test/util" "reactive-tech.io/kubegres/test/util/testcases" "time" ) const customNamespace = "toto" var _ = Describe("Creating Kubegres with a custom namespace", func() { var test = CustomNamespaceTest{} BeforeEach(func() { //Skip("Temporarily skipping test") namespace := customNamespace test.resourceRetriever = util.CreateTestResourceRetriever(k8sClientTest, namespace) test.resourceCreator = util.CreateTestResourceCreator(k8sClientTest, test.resourceRetriever, namespace) test.dbQueryTestCases = testcases.InitDbQueryTestCasesWithNodePorts(test.resourceCreator, resourceConfigs.KubegresResourceName, resourceConfigs.ServiceToSqlQueryPrimaryDbNodePort+4, resourceConfigs.ServiceToSqlQueryReplicaDbNodePort+4) }) AfterEach(func() { if !test.keepCreatedResourcesForNextTest { test.resourceCreator.DeleteAllTestResources() } else { test.keepCreatedResourcesForNextTest = false } }) Context("GIVEN new Kubegres is created in a custom namespace with spec 'replica' set to 3 and then it is updated to different values", func() { It("GIVEN new Kubegres is created in a custom namespace with spec 'replica' set to 3 THEN 1 primary and 2 replica should be created", func() { log.Print("START OF: Test 'GIVEN new Kubegres is created in a custom namespace with spec 'replica' set to 3'") test.givenNewKubegresSpecIsSetTo(customNamespace, 3) test.whenKubegresIsCreated() test.thenPodsStatesShouldBe(1, 2) test.thenDeployedKubegresSpecShouldBeSetTo(3) test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() test.keepCreatedResourcesForNextTest = true log.Print("END OF: Test 'GIVEN new Kubegres is created in a custom namespace with spec 'replica' set to 3'") }) It("GIVEN existing Kubegres is updated with spec 'replica' set from 3 to 4 THEN 1 more replica should be created", func() { log.Print("START OF: Test 'GIVEN existing Kubegres is updated with spec 'replica' set from 3 to 4'") test.givenExistingKubegresSpecIsSetTo(4) test.whenKubernetesIsUpdated() test.thenPodsStatesShouldBe(1, 3) test.thenDeployedKubegresSpecShouldBeSetTo(4) test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() test.keepCreatedResourcesForNextTest = true log.Print("END OF: Test 'GIVEN existing Kubegres is updated with spec 'replica' set from 3 to 4'") }) It("GIVEN existing Kubegres is updated with spec 'replica' set from 4 to 3 THEN 1 replica should be deleted", func() { log.Print("START OF: Test 'GIVEN existing Kubegres is updated with spec 'replica' set from 4 to 3'") test.givenExistingKubegresSpecIsSetTo(3) test.whenKubernetesIsUpdated() test.thenPodsStatesShouldBe(1, 2) test.thenDeployedKubegresSpecShouldBeSetTo(3) test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() test.keepCreatedResourcesForNextTest = true log.Print("END OF: Test 'GIVEN existing Kubegres is updated with spec 'replica' set from 4 to 3'") }) It("GIVEN existing Kubegres is updated with spec 'replica' set from 3 to 1 THEN 2 replica should be deleted", func() { log.Print("START OF: Test 'GIVEN existing Kubegres is updated with spec 'replica' set from 3 to 1'") test.givenExistingKubegresSpecIsSetTo(1) test.whenKubernetesIsUpdated() test.thenPodsStatesShouldBe(1, 0) test.thenDeployedKubegresSpecShouldBeSetTo(1) test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() log.Print("END OF: Test 'GIVEN existing Kubegres is updated with spec 'replica' set from 3 to 1'") }) }) }) type CustomNamespaceTest struct { keepCreatedResourcesForNextTest bool kubegresResource *postgresv1.Kubegres dbQueryTestCases testcases.DbQueryTestCases resourceCreator util.TestResourceCreator resourceRetriever util.TestResourceRetriever } func (r *CustomNamespaceTest) givenNewKubegresSpecIsSetTo(namespace string, specNbreReplicas int32) { r.kubegresResource = resourceConfigs.LoadKubegresYaml() r.kubegresResource.Namespace = namespace r.kubegresResource.Spec.Replicas = &specNbreReplicas } func (r *CustomNamespaceTest) givenExistingKubegresSpecIsSetTo(specNbreReplicas int32) { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } r.kubegresResource.Spec.Replicas = &specNbreReplicas } func (r *CustomNamespaceTest) whenKubegresIsCreated() { r.resourceCreator.CreateKubegres(r.kubegresResource) } func (r *CustomNamespaceTest) whenKubernetesIsUpdated() { r.resourceCreator.UpdateResource(r.kubegresResource, "Kubegres") } func (r *CustomNamespaceTest) thenErrorEventShouldBeLogged() { expectedErrorEvent := util.EventRecord{ Eventtype: v12.EventTypeWarning, Reason: "SpecCheckErr", Message: "In the Resources Spec the value of 'spec.replicas' is undefined. Please set a value otherwise this operator cannot work correctly.", } Eventually(func() bool { _, err := r.resourceRetriever.GetKubegres() if err != nil { return false } return eventRecorderTest.CheckEventExist(expectedErrorEvent) }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *CustomNamespaceTest) thenPodsStatesShouldBe(nbrePrimary, nbreReplicas int) bool { return Eventually(func() bool { pods, err := r.resourceRetriever.GetKubegresResources() if err != nil && !apierrors.IsNotFound(err) { log.Println("ERROR while retrieving Kubegres pods") return false } if pods.AreAllReady && pods.NbreDeployedPrimary == nbrePrimary && pods.NbreDeployedReplicas == nbreReplicas { time.Sleep(resourceConfigs.TestRetryInterval) log.Println("Deployed and Ready StatefulSets check successful") return true } return false }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *CustomNamespaceTest) thenDeployedKubegresSpecShouldBeSetTo(specNbreReplicas int32) { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } Expect(*r.kubegresResource.Spec.Replicas).Should(Equal(specNbreReplicas)) } <|start_filename|>test/spec_databaseSize_test.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" v12 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "log" postgresv1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/test/resourceConfigs" "reactive-tech.io/kubegres/test/util" "reactive-tech.io/kubegres/test/util/testcases" "time" ) var _ = Describe("Setting Kubegres specs 'database.size'", func() { var test = SpecDatabaseSizeTest{} BeforeEach(func() { //Skip("Temporarily skipping test") namespace := resourceConfigs.DefaultNamespace test.resourceRetriever = util.CreateTestResourceRetriever(k8sClientTest, namespace) test.resourceCreator = util.CreateTestResourceCreator(k8sClientTest, test.resourceRetriever, namespace) test.dbQueryTestCases = testcases.InitDbQueryTestCases(test.resourceCreator, resourceConfigs.KubegresResourceName) }) AfterEach(func() { if !test.keepCreatedResourcesForNextTest { test.resourceCreator.DeleteAllTestResources() } else { test.keepCreatedResourcesForNextTest = false } }) Context("GIVEN new Kubegres is created without spec 'database.size'", func() { It("THEN an error event should be logged", func() { log.Print("START OF: Test 'GIVEN new Kubegres is created without spec 'database.size''") test.givenNewKubegresSpecIsSetTo("", 3) test.whenKubegresIsCreated() test.thenErrorEventShouldBeLogged() log.Print("END OF: Test 'GIVEN new Kubegres is created without spec 'database.size'") }) }) Context("GIVEN new Kubegres is created with spec 'database.size' set to '300Mi' and spec 'replica' set to 3 and later 'database.size' is updated to '400Mi'", func() { It("GIVEN new Kubegres is created with spec 'database.size' set to '300Mi' and spec 'replica' set to 3 THEN 1 primary and 2 replica should be created with spec 'database.size' set to '300Mi'", func() { log.Print("START OF: Test 'GIVEN new Kubegres is created with spec 'database.size' set to '300Mi' and spec 'replica' set to 3") test.givenNewKubegresSpecIsSetTo("300Mi", 3) test.whenKubegresIsCreated() test.thenPodsStatesShouldBe("300Mi", 1, 2) test.thenDeployedKubegresSpecShouldBeSetTo("300Mi") test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() test.keepCreatedResourcesForNextTest = true log.Print("END OF: Test 'GIVEN new Kubegres is created with spec 'database.size' set to '300Mi' and spec 'replica' set to 3'") }) It("GIVEN existing Kubegres is updated with spec 'database.size' set from '300Mi' to '400Mi' THEN an error event should be logged", func() { log.Print("START OF: Test 'GIVEN existing Kubegres is updated with spec 'database.size' set from '300Mi' to '400Mi'") test.givenExistingKubegresSpecIsSetTo("400Mi") test.whenKubernetesIsUpdated() test.thenErrorEventShouldBeLoggedSayingCannotChangeStorageSize("300Mi", "400Mi") test.thenPodsStatesShouldBe("300Mi", 1, 2) test.thenDeployedKubegresSpecShouldBeSetTo("300Mi") test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() log.Print("END OF: Test 'GIVEN existing Kubegres is updated with spec 'database.size' set from '300Mi' to '400Mi'") }) }) }) type SpecDatabaseSizeTest struct { keepCreatedResourcesForNextTest bool kubegresResource *postgresv1.Kubegres dbQueryTestCases testcases.DbQueryTestCases resourceCreator util.TestResourceCreator resourceRetriever util.TestResourceRetriever } func (r *SpecDatabaseSizeTest) givenNewKubegresSpecIsSetTo(databaseSize string, specNbreReplicas int32) { r.kubegresResource = resourceConfigs.LoadKubegresYaml() r.kubegresResource.Spec.Database.Size = databaseSize r.kubegresResource.Spec.Replicas = &specNbreReplicas } func (r *SpecDatabaseSizeTest) givenExistingKubegresSpecIsSetTo(databaseSize string) { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } r.kubegresResource.Spec.Database.Size = databaseSize } func (r *SpecDatabaseSizeTest) whenKubegresIsCreated() { r.resourceCreator.CreateKubegres(r.kubegresResource) } func (r *SpecDatabaseSizeTest) whenKubernetesIsUpdated() { r.resourceCreator.UpdateResource(r.kubegresResource, "Kubegres") } func (r *SpecDatabaseSizeTest) thenErrorEventShouldBeLogged() { expectedErrorEvent := util.EventRecord{ Eventtype: v12.EventTypeWarning, Reason: "SpecCheckErr", Message: "In the Resources Spec the value of 'spec.database.size' is undefined. Please set a value otherwise this operator cannot work correctly.", } Eventually(func() bool { _, err := r.resourceRetriever.GetKubegres() if err != nil { return false } return eventRecorderTest.CheckEventExist(expectedErrorEvent) }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecDatabaseSizeTest) thenPodsStatesShouldBe(databaseSize string, nbrePrimary, nbreReplicas int) bool { return Eventually(func() bool { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil && !apierrors.IsNotFound(err) { log.Println("ERROR while retrieving Kubegres kubegresResources") return false } for _, resource := range kubegresResources.Resources { currentDatabaseSize := resource.Pvc.Spec.Resources.Requests["storage"] if currentDatabaseSize.String() != databaseSize { log.Println("Pod '" + resource.Pod.Name + "' doesn't have the expected database.size: '" + databaseSize + "'. " + "Current value: '" + currentDatabaseSize.String() + "'. Waiting...") return false } } if kubegresResources.AreAllReady && kubegresResources.NbreDeployedPrimary == nbrePrimary && kubegresResources.NbreDeployedReplicas == nbreReplicas { time.Sleep(resourceConfigs.TestRetryInterval) log.Println("Deployed and Ready StatefulSets check successful") return true } return false }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecDatabaseSizeTest) thenDeployedKubegresSpecShouldBeSetTo(databaseSize string) { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } Expect(r.kubegresResource.Spec.Database.Size).Should(Equal(databaseSize)) } func (r *SpecDatabaseSizeTest) thenErrorEventShouldBeLoggedSayingCannotChangeStorageSize(currentValue, newValue string) { expectedErrorEvent := util.EventRecord{ Eventtype: v12.EventTypeWarning, Reason: "SpecCheckErr", Message: "In the Resources Spec the value of 'spec.database.size' cannot be changed from '" + currentValue + "' to '" + newValue + "' after Pods were created. " + "The StorageClass does not allow volume expansion. The option AllowVolumeExpansion is set to false. " + "We roll-backed Kubegres spec to the currently working value '" + currentValue + "'. " + "If you know what you are doing, you can manually update that spec in every StatefulSet of your PostgreSql cluster and then Kubegres will automatically update itself.", } Eventually(func() bool { _, err := r.resourceRetriever.GetKubegres() if err != nil { return false } return eventRecorderTest.CheckEventExist(expectedErrorEvent) }, time.Second*10, time.Second*5).Should(BeTrue()) } <|start_filename|>test/spec_image_test.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" v12 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "log" postgresv1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/test/resourceConfigs" "reactive-tech.io/kubegres/test/util" "reactive-tech.io/kubegres/test/util/testcases" "time" ) var _ = Describe("Setting Kubegres spec 'image'", func() { var test = SpecImageTest{} BeforeEach(func() { //Skip("Temporarily skipping test") namespace := resourceConfigs.DefaultNamespace test.resourceRetriever = util.CreateTestResourceRetriever(k8sClientTest, namespace) test.resourceCreator = util.CreateTestResourceCreator(k8sClientTest, test.resourceRetriever, namespace) test.dbQueryTestCases = testcases.InitDbQueryTestCases(test.resourceCreator, resourceConfigs.KubegresResourceName) }) AfterEach(func() { if !test.keepCreatedResourcesForNextTest { test.resourceCreator.DeleteAllTestResources() } else { test.keepCreatedResourcesForNextTest = false } }) Context("GIVEN new Kubegres is created without spec 'image'", func() { It("THEN An error event should be logged", func() { log.Print("START OF: Test 'GIVEN new Kubegres is created without spec 'image''") test.givenNewKubegresSpecIsSetTo("", 3) test.whenKubegresIsCreated() test.thenErrorEventShouldBeLogged() log.Print("END OF: Test 'GIVEN new Kubegres is created without spec 'image''") }) }) Context("GIVEN new Kubegres is created with spec 'image' set to 'postgres:12.4' and spec 'replica' set to 3 and later 'image' is updated to 'postgres:12.5'", func() { It("GIVEN new Kubegres is created with spec 'image' set to 'postgres:12.4' and spec 'replica' set to 3 THEN 1 primary and 2 replica should be created with spec 'image' set to 'postgres:12.4'", func() { log.Print("START OF: Test 'GIVEN new Kubegres is created with spec 'image' set to 'postgres:12.4' and spec 'replica' set to 3") test.givenNewKubegresSpecIsSetTo("postgres:12.4", 3) test.whenKubegresIsCreated() test.thenPodsStatesShouldBe("postgres:12.4", 1, 2) test.thenDeployedKubegresSpecShouldBeSetTo("postgres:12.4") test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() test.keepCreatedResourcesForNextTest = true log.Print("END OF: Test 'GIVEN new Kubegres is created with spec 'image' set to 'postgres:12.4' and spec 'replica' set to 3'") }) It("GIVEN existing Kubegres is updated with spec 'image' set from 'postgres:12.4' to 'postgres:12.5' THEN 1 primary and 2 replica should be re-deployed with spec 'image' set to 'postgres:12.5'", func() { log.Print("START OF: Test 'GIVEN existing Kubegres is updated with spec 'image' set from 'postgres:12.4' to 'postgres:12.5'") test.givenExistingKubegresSpecIsSetTo("postgres:12.5") test.whenKubernetesIsUpdated() test.thenPodsStatesShouldBe("postgres:12.5", 1, 2) test.thenDeployedKubegresSpecShouldBeSetTo("postgres:12.5") test.dbQueryTestCases.ThenWeCanSqlQueryPrimaryDb() test.dbQueryTestCases.ThenWeCanSqlQueryReplicaDb() log.Print("END OF: Test 'GIVEN existing Kubegres is updated with spec 'image' set from 'postgres:12.4' to 'postgres:12.5'") }) }) }) type SpecImageTest struct { keepCreatedResourcesForNextTest bool kubegresResource *postgresv1.Kubegres dbQueryTestCases testcases.DbQueryTestCases resourceCreator util.TestResourceCreator resourceRetriever util.TestResourceRetriever } func (r *SpecImageTest) givenNewKubegresSpecIsSetTo(image string, specNbreReplicas int32) { r.kubegresResource = resourceConfigs.LoadKubegresYaml() r.kubegresResource.Spec.Image = image r.kubegresResource.Spec.Replicas = &specNbreReplicas } func (r *SpecImageTest) givenExistingKubegresSpecIsSetTo(image string) { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } r.kubegresResource.Spec.Image = image } func (r *SpecImageTest) whenKubegresIsCreated() { r.resourceCreator.CreateKubegres(r.kubegresResource) } func (r *SpecImageTest) whenKubernetesIsUpdated() { r.resourceCreator.UpdateResource(r.kubegresResource, "Kubegres") } func (r *SpecImageTest) thenErrorEventShouldBeLogged() { expectedErrorEvent := util.EventRecord{ Eventtype: v12.EventTypeWarning, Reason: "SpecCheckErr", Message: "In the Resources Spec the value of 'spec.image' is undefined. Please set a value otherwise this operator cannot work correctly.", } Eventually(func() bool { _, err := r.resourceRetriever.GetKubegres() if err != nil { return false } return eventRecorderTest.CheckEventExist(expectedErrorEvent) }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecImageTest) thenPodsStatesShouldBe(image string, nbrePrimary, nbreReplicas int) bool { return Eventually(func() bool { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil && !apierrors.IsNotFound(err) { log.Println("ERROR while retrieving Kubegres kubegresResources") return false } for _, resource := range kubegresResources.Resources { currentImage := resource.Pod.Spec.Containers[0].Image if currentImage != image { log.Println("Pod '" + resource.Pod.Name + "' doesn't have the expected image: '" + image + "'. " + "Current value: '" + currentImage + "'. Waiting...") return false } } if kubegresResources.AreAllReady && kubegresResources.NbreDeployedPrimary == nbrePrimary && kubegresResources.NbreDeployedReplicas == nbreReplicas { time.Sleep(resourceConfigs.TestRetryInterval) log.Println("Deployed and Ready StatefulSets check successful") return true } return false }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecImageTest) thenDeployedKubegresSpecShouldBeSetTo(image string) { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } Expect(r.kubegresResource.Spec.Image).Should(Equal(image)) } <|start_filename|>test/spec_failover_is_disabled_test.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" apierrors "k8s.io/apimachinery/pkg/api/errors" "log" postgresv1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/test/resourceConfigs" "reactive-tech.io/kubegres/test/util" "strconv" "time" ) var _ = Describe("Primary instances is not available, when failover is disabled checking NO failover should be triggered", func() { var test = SpecFailoverIsDisabledTest{} BeforeEach(func() { //Skip("Temporarily skipping test") namespace := resourceConfigs.DefaultNamespace test.resourceRetriever = util.CreateTestResourceRetriever(k8sClientTest, namespace) test.resourceCreator = util.CreateTestResourceCreator(k8sClientTest, test.resourceRetriever, namespace) test.connectionPrimaryDb = util.InitDbConnectionDbUtil(test.resourceCreator, resourceConfigs.KubegresResourceName, resourceConfigs.ServiceToSqlQueryPrimaryDbNodePort, true) test.connectionReplicaDb = util.InitDbConnectionDbUtil(test.resourceCreator, resourceConfigs.KubegresResourceName, resourceConfigs.ServiceToSqlQueryReplicaDbNodePort, false) }) AfterEach(func() { test.resourceCreator.DeleteAllTestResources() }) Context("GIVEN Kubegres is creating a cluster with changing values for the number of deployed replicas AND in YAML the flag 'failover.isDisabled' is true", func() { It("THEN a primary and a replica instances should be created as normal", func() { log.Print("START OF: Test 'GIVEN Kubegres is creating a cluster with changing values for the number of deployed replicas AND in YAML the flag 'failover.isDisabled' is true'") test.givenNewKubegresSpecIsSetTo(true, 3) test.whenKubegresIsCreated() test.thenPodsStatesShouldBe(1, 2) test.givenExistingKubegresSpecIsSetTo(true, 4) test.whenKubernetesIsUpdated() test.thenPodsStatesShouldBe(1, 3) test.givenExistingKubegresSpecIsSetTo(true, 2) test.whenKubernetesIsUpdated() test.thenPodsStatesShouldBe(1, 1) log.Print("END OF: Test 'GIVEN Kubegres is creating a cluster with changing values for the number of deployed replicas AND in YAML the flag 'failover.isDisabled' is true'") }) }) Context("GIVEN Kubegres with 1 primary and 2 replicas AND once deployed we update YAML with 'failover.isDisabled' is true AND we delete primary", func() { It("THEN the primary failover should NOT take place AND the deleted primary should NOT be replaced", func() { log.Print("START OF: Test 'GIVEN Kubegres with 1 primary and 2 replicas AND once deployed we update YAML with 'failover.isDisabled' is true AND we delete primary'") test.givenNewKubegresSpecIsSetTo(false, 3) test.whenKubegresIsCreated() test.thenPodsStatesShouldBe(1, 2) expectedNbreUsers := 0 test.givenUserAddedInPrimaryDb() expectedNbreUsers++ test.givenUserAddedInPrimaryDb() expectedNbreUsers++ test.givenExistingKubegresSpecIsSetTo(true, 3) test.whenKubernetesIsUpdated() time.Sleep(time.Second * 10) test.thenPodsStatesShouldBe(1, 2) test.whenPrimaryIsDeleted() time.Sleep(time.Second * 10) test.thenPodsStatesShouldBe(0, 2) test.thenReplicaDbContainsExpectedNbreUsers(expectedNbreUsers) log.Print("END OF: Test 'GIVEN Kubegres with 1 primary and 2 replicas AND once deployed we update YAML with 'failover.isDisabled' is true AND we delete primary'") }) }) Context("GIVEN Kubegres with 1 primary and 2 replicas AND once deployed we update YAML with 'failover.isDisabled' is true AND we delete a replica", func() { It("THEN the replica failover should NOT take place AND the deleted replica should NOT be replaced", func() { log.Print("START OF: Test 'GIVEN Kubegres with 1 primary and 2 replicas AND once deployed we update YAML with 'failover.isDisabled' is true AND we delete a replica'") test.givenNewKubegresSpecIsSetTo(false, 3) test.whenKubegresIsCreated() test.thenPodsStatesShouldBe(1, 2) expectedNbreUsers := 0 test.givenUserAddedInPrimaryDb() expectedNbreUsers++ test.givenUserAddedInPrimaryDb() expectedNbreUsers++ test.givenExistingKubegresSpecIsSetTo(true, 3) test.whenKubernetesIsUpdated() time.Sleep(time.Second * 10) test.thenPodsStatesShouldBe(1, 2) test.whenOneReplicaIsDeleted() time.Sleep(time.Second * 10) test.thenPodsStatesShouldBe(1, 1) test.thenReplicaDbContainsExpectedNbreUsers(expectedNbreUsers) log.Print("END OF: Test 'GIVEN Kubegres with 1 primary and 2 replicas AND once deployed we update YAML with 'failover.isDisabled' is true AND we delete a replica'") }) }) }) type SpecFailoverIsDisabledTest struct { kubegresResource *postgresv1.Kubegres connectionPrimaryDb util.DbConnectionDbUtil connectionReplicaDb util.DbConnectionDbUtil resourceCreator util.TestResourceCreator resourceRetriever util.TestResourceRetriever customEnvVariableName string customEnvVariableKey string } func (r *SpecFailoverIsDisabledTest) givenNewKubegresSpecIsSetTo(isFailoverDisabled bool, specNbreReplicas int32) { r.kubegresResource = resourceConfigs.LoadKubegresYaml() r.kubegresResource.Spec.Replicas = &specNbreReplicas r.kubegresResource.Spec.Failover.IsDisabled = isFailoverDisabled } func (r *SpecFailoverIsDisabledTest) givenExistingKubegresSpecIsSetTo(isFailoverDisabled bool, specNbreReplicas int32) { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } r.kubegresResource.Spec.Replicas = &specNbreReplicas r.kubegresResource.Spec.Failover.IsDisabled = isFailoverDisabled } func (r *SpecFailoverIsDisabledTest) givenUserAddedInPrimaryDb() { Eventually(func() bool { return r.connectionPrimaryDb.InsertUser() }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecFailoverIsDisabledTest) whenKubegresIsCreated() { r.resourceCreator.CreateKubegres(r.kubegresResource) } func (r *SpecFailoverIsDisabledTest) whenKubernetesIsUpdated() { r.resourceCreator.UpdateResource(r.kubegresResource, "Kubegres") } func (r *SpecFailoverIsDisabledTest) whenPrimaryIsDeleted() { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil { Expect(err).Should(Succeed()) return } nbreDeleted := 0 for _, kubegresResource := range kubegresResources.Resources { if kubegresResource.IsPrimary { log.Println("Attempting to delete StatefulSet: '" + kubegresResource.StatefulSet.Name + "'") if !r.resourceCreator.DeleteResource(kubegresResource.StatefulSet.Resource, kubegresResource.StatefulSet.Name) { log.Println("StatefulSet CANNOT BE deleted: '" + kubegresResource.StatefulSet.Name + "'") } else { nbreDeleted++ time.Sleep(5 * time.Second) } } } Expect(nbreDeleted).Should(Equal(1)) } func (r *SpecFailoverIsDisabledTest) whenOneReplicaIsDeleted() { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil { Expect(err).Should(Succeed()) return } nbreDeleted := 0 for _, kubegresResource := range kubegresResources.Resources { if nbreDeleted == 1 { break } if !kubegresResource.IsPrimary { log.Println("Attempting to delete StatefulSet: '" + kubegresResource.StatefulSet.Name + "'") if !r.resourceCreator.DeleteResource(kubegresResource.StatefulSet.Resource, kubegresResource.StatefulSet.Name) { log.Println("StatefulSet CANNOT BE deleted: '" + kubegresResource.StatefulSet.Name + "'") } else { nbreDeleted++ time.Sleep(5 * time.Second) } } } Expect(nbreDeleted).Should(Equal(1)) } func (r *SpecFailoverIsDisabledTest) thenPodsStatesShouldBe(nbrePrimary, nbreReplicas int) bool { nreInstancesInSpec := int(*r.kubegresResource.Spec.Replicas) nbreInstancesWanted := nbrePrimary + nbreReplicas return Eventually(func() bool { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil && !apierrors.IsNotFound(err) { log.Println("ERROR while retrieving Kubegres kubegresResources") return false } if (nreInstancesInSpec != nbreInstancesWanted || kubegresResources.AreAllReady) && kubegresResources.NbreDeployedPrimary == nbrePrimary && kubegresResources.NbreDeployedReplicas == nbreReplicas { time.Sleep(resourceConfigs.TestRetryInterval) log.Println("Deployed and Ready StatefulSets check successful") return true } return false }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecFailoverIsDisabledTest) thenReplicaDbContainsExpectedNbreUsers(expectedNbreUsers int) { Eventually(func() bool { users := r.connectionReplicaDb.GetUsers() r.connectionReplicaDb.Close() if len(users) != expectedNbreUsers || r.connectionReplicaDb.NbreInsertedUsers != expectedNbreUsers { log.Println("Replica DB does not contain the expected number of users: " + strconv.Itoa(expectedNbreUsers)) return false } return true }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } <|start_filename|>controllers/states/statefulset/PodsStates.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 statefulset import ( core "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "reactive-tech.io/kubegres/controllers/ctx" "sigs.k8s.io/controller-runtime/pkg/client" "strconv" ) type PodStates struct { pods []PodWrapper kubegresContext ctx.KubegresContext } type PodWrapper struct { IsDeployed bool IsReady bool IsStuck bool InstanceIndex int32 Pod core.Pod } func loadPodsStates(kubegresContext ctx.KubegresContext) (PodStates, error) { podStates := PodStates{kubegresContext: kubegresContext} err := podStates.loadStates() return podStates, err } func (r *PodStates) loadStates() (err error) { deployedPods, err := r.getDeployedPods() if err != nil { return err } for _, pod := range deployedPods.Items { isPodReady := r.isPodReady(pod) isPodStuck := r.isPodStuck(pod) podWrapper := PodWrapper{ IsDeployed: true, IsReady: isPodReady && !isPodStuck, IsStuck: isPodStuck, InstanceIndex: r.getInstanceIndex(pod), Pod: pod, } r.pods = append(r.pods, podWrapper) } return nil } func (r *PodStates) getDeployedPods() (*core.PodList, error) { list := &core.PodList{} opts := []client.ListOption{ client.InNamespace(r.kubegresContext.Kubegres.Namespace), client.MatchingLabels{"app": r.kubegresContext.Kubegres.Name}, } err := r.kubegresContext.Client.List(r.kubegresContext.Ctx, list, opts...) if err != nil { if apierrors.IsNotFound(err) { r.kubegresContext.Log.Info("There is not any deployed Pods yet", "Kubegres name", r.kubegresContext.Kubegres.Name) err = nil } else { r.kubegresContext.Log.ErrorEvent("PodLoadingErr", err, "Unable to load any deployed Pods.", "Kubegres name", r.kubegresContext.Kubegres.Name) } } return list, err } func (r *PodStates) isPodReady(pod core.Pod) bool { if len(pod.Status.ContainerStatuses) == 0 { return false } return pod.Status.ContainerStatuses[0].Ready } func (r *PodStates) isPodStuck(pod core.Pod) bool { if len(pod.Status.ContainerStatuses) == 0 || pod.Status.ContainerStatuses[0].State.Waiting == nil { return false } waitingReason := pod.Status.ContainerStatuses[0].State.Waiting.Reason if waitingReason == "CrashLoopBackOff" || waitingReason == "Error" { r.kubegresContext.Log.Info("POD is waiting", "Reason", waitingReason) return true } return false } func (r *PodStates) getInstanceIndex(pod core.Pod) int32 { instanceIndex, _ := strconv.ParseInt(pod.Labels["index"], 10, 32) return int32(instanceIndex) } <|start_filename|>test/spec_pod_manually_promoted_test.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" v12 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "log" postgresv1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/test/resourceConfigs" "reactive-tech.io/kubegres/test/util" "strconv" "time" ) var _ = Describe("Primary instances is not available, when the promotion of a PostgreSql instance is manually requested THEN promotion should be triggered.", func() { var test = SpecFailoverIsDisabledAndPromotePodAreSetTest{} BeforeEach(func() { //Skip("Temporarily skipping test") namespace := resourceConfigs.DefaultNamespace test.resourceRetriever = util.CreateTestResourceRetriever(k8sClientTest, namespace) test.resourceCreator = util.CreateTestResourceCreator(k8sClientTest, test.resourceRetriever, namespace) test.connectionPrimaryDb = util.InitDbConnectionDbUtil(test.resourceCreator, resourceConfigs.KubegresResourceName, resourceConfigs.ServiceToSqlQueryPrimaryDbNodePort, true) test.connectionReplicaDb = util.InitDbConnectionDbUtil(test.resourceCreator, resourceConfigs.KubegresResourceName, resourceConfigs.ServiceToSqlQueryReplicaDbNodePort, false) }) AfterEach(func() { test.resourceCreator.DeleteAllTestResources() }) Context("GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.promotePod' is set to a Pod name", func() { It("THEN the replica Pod set in spec 'failover.promotePod' should become the new primary AND a new replica should be created", func() { log.Print("START OF: Test 'GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.promotePod' is set to a Pod name'") test.givenNewKubegresSpecIsSetTo(2) test.whenKubegresIsCreated() test.thenPodsStatesShouldBe(1, 1) expectedNbreUsers := 0 test.givenUserAddedInPrimaryDb() expectedNbreUsers++ test.givenUserAddedInPrimaryDb() expectedNbreUsers++ replicaPodNameToPromote := test.getReplicaPodName() test.givenExistingKubegresSpecIsSetTo(replicaPodNameToPromote) test.whenKubernetesIsUpdated() time.Sleep(time.Second * 10) test.thenPodsStatesShouldBe(1, 1) test.thenPromotePodFieldInSpecShouldBeCleared() test.thenPrimaryPodNameMatches(replicaPodNameToPromote) test.thenPrimaryDbContainsExpectedNbreUsers(expectedNbreUsers) test.thenReplicaDbContainsExpectedNbreUsers(expectedNbreUsers) log.Print("END OF: Test 'GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.promotePod' is set to a Pod name'") }) }) Context("GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.isDisabled' is true AND with 'failover.promotePod' is set to a Pod name", func() { It("THEN the replica Pod set in spec 'failover.promotePod' should become the new primary AND a new replica should be created", func() { log.Print("START OF: Test 'GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.isDisabled' is true AND with 'failover.promotePod' is set to a Pod name'") test.givenNewKubegresSpecIsSetTo(2) test.whenKubegresIsCreated() test.thenPodsStatesShouldBe(1, 1) expectedNbreUsers := 0 test.givenUserAddedInPrimaryDb() expectedNbreUsers++ test.givenUserAddedInPrimaryDb() expectedNbreUsers++ replicaPodNameToPromote := test.getReplicaPodName() test.givenExistingKubegresSpecIsUpdatedTo(true, replicaPodNameToPromote) test.whenKubernetesIsUpdated() time.Sleep(time.Second * 10) test.thenPodsStatesShouldBe(1, 1) test.thenPromotePodFieldInSpecShouldBeCleared() test.thenPrimaryPodNameMatches(replicaPodNameToPromote) test.thenPrimaryDbContainsExpectedNbreUsers(expectedNbreUsers) test.thenReplicaDbContainsExpectedNbreUsers(expectedNbreUsers) log.Print("END OF: Test 'GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.isDisabled' is true AND with 'failover.promotePod' is set to a Pod name'") }) }) Context("GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.promotePod' is set to a Pod name which does NOT exist", func() { It("THEN nothing should happen AND an error message should be logged as event saying Pod does NOT exist", func() { log.Print("START OF: Test 'GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.promotePod' is set to a Pod name which does NOT exist'") test.givenNewKubegresSpecIsSetTo(2) test.whenKubegresIsCreated() test.thenPodsStatesShouldBe(1, 1) expectedNbreUsers := 0 test.givenUserAddedInPrimaryDb() expectedNbreUsers++ test.givenUserAddedInPrimaryDb() expectedNbreUsers++ primaryPodName, replicaPodName := test.getDeployedPodNames() replicaPodNameToPromote := "Pod_does_not_exist" test.givenExistingKubegresSpecIsSetTo(replicaPodNameToPromote) test.whenKubernetesIsUpdated() time.Sleep(time.Second * 10) test.thenPodsStatesShouldBe(1, 1) test.thenPromotePodFieldInSpecShouldBeCleared() test.thenErrorEventShouldBeLogged(replicaPodNameToPromote) test.thenDeployedPodNamesMatch(primaryPodName, replicaPodName) test.thenPrimaryDbContainsExpectedNbreUsers(expectedNbreUsers) test.thenReplicaDbContainsExpectedNbreUsers(expectedNbreUsers) log.Print("END OF: Test 'GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.promotePod' is set to a Pod name which does NOT exist'") }) }) Context("GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.promotePod' is set the Primary Pod name", func() { It("THEN nothing should happen", func() { log.Print("START OF: Test 'GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.promotePod' is set the Primary Pod name'") test.givenNewKubegresSpecIsSetTo(2) test.whenKubegresIsCreated() test.thenPodsStatesShouldBe(1, 1) expectedNbreUsers := 0 test.givenUserAddedInPrimaryDb() expectedNbreUsers++ test.givenUserAddedInPrimaryDb() expectedNbreUsers++ primaryPodName, replicaPodName := test.getDeployedPodNames() replicaPodNameToPromote := primaryPodName test.givenExistingKubegresSpecIsSetTo(replicaPodNameToPromote) test.whenKubernetesIsUpdated() time.Sleep(time.Second * 10) test.thenPodsStatesShouldBe(1, 1) test.thenPromotePodFieldInSpecShouldBeCleared() test.thenDeployedPodNamesMatch(primaryPodName, replicaPodName) test.thenPrimaryDbContainsExpectedNbreUsers(expectedNbreUsers) test.thenReplicaDbContainsExpectedNbreUsers(expectedNbreUsers) log.Print("END OF: Test 'GIVEN Kubegres with 1 primary and 1 replica AND once deployed we update YAML with 'failover.promotePod' is set the Primary Pod name'") }) }) }) type SpecFailoverIsDisabledAndPromotePodAreSetTest struct { kubegresResource *postgresv1.Kubegres connectionPrimaryDb util.DbConnectionDbUtil connectionReplicaDb util.DbConnectionDbUtil resourceCreator util.TestResourceCreator resourceRetriever util.TestResourceRetriever customEnvVariableName string customEnvVariableKey string } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) givenNewKubegresSpecIsSetTo(specNbreReplicas int32) { r.kubegresResource = resourceConfigs.LoadKubegresYaml() r.kubegresResource.Spec.Replicas = &specNbreReplicas } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) givenExistingKubegresSpecIsSetTo(promotePodName string) { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } r.kubegresResource.Spec.Failover.PromotePod = promotePodName } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) givenExistingKubegresSpecIsUpdatedTo(isFailoverDisabled bool, promotePodName string) { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } r.kubegresResource.Spec.Failover.IsDisabled = isFailoverDisabled r.kubegresResource.Spec.Failover.PromotePod = promotePodName } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) givenUserAddedInPrimaryDb() { Eventually(func() bool { return r.connectionPrimaryDb.InsertUser() }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) getDeployedPodNames() (primaryPodName, replicaPodName string) { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil { Expect(err).Should(Succeed()) return } for _, kubegresResource := range kubegresResources.Resources { if kubegresResource.IsPrimary { primaryPodName = kubegresResource.Pod.Name } else { replicaPodName = kubegresResource.Pod.Name } } return primaryPodName, replicaPodName } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) whenKubegresIsCreated() { r.resourceCreator.CreateKubegres(r.kubegresResource) } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) whenKubernetesIsUpdated() { r.resourceCreator.UpdateResource(r.kubegresResource, "Kubegres") } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) thenPrimaryPodNameMatches(expectedPromotedPod string) { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil { Expect(err).Should(Succeed()) return } primaryPodName := "" for _, kubegresResource := range kubegresResources.Resources { if kubegresResource.IsPrimary { primaryPodName = kubegresResource.Pod.Name break } } Expect(primaryPodName).Should(Equal(expectedPromotedPod)) } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) thenPodsStatesShouldBe(nbrePrimary, nbreReplicas int) bool { nreInstancesInSpec := int(*r.kubegresResource.Spec.Replicas) nbreInstancesWanted := nbrePrimary + nbreReplicas return Eventually(func() bool { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil && !apierrors.IsNotFound(err) { log.Println("ERROR while retrieving Kubegres kubegresResources") return false } if (nreInstancesInSpec != nbreInstancesWanted || kubegresResources.AreAllReady) && kubegresResources.NbreDeployedPrimary == nbrePrimary && kubegresResources.NbreDeployedReplicas == nbreReplicas { time.Sleep(resourceConfigs.TestRetryInterval) log.Println("Deployed and Ready StatefulSets check successful") return true } return false }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) thenErrorEventShouldBeLogged(podName string) { expectedErrorEvent := util.EventRecord{ Eventtype: v12.EventTypeWarning, Reason: "ManualFailoverCannotHappenAsConfigErr", Message: "The value of the field 'failover.promotePod' is set to '" + podName + "'. " + "That value is either the name of a Primary Pod OR a Replica Pod which is not ready OR a Pod which does not exist. " + "Please set the name of a Replica Pod that you would like to promote as a Primary Pod.", } Eventually(func() bool { _, err := r.resourceRetriever.GetKubegres() if err != nil { return false } return eventRecorderTest.CheckEventExist(expectedErrorEvent) }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) getReplicaPodName() string { kubegresResources, _ := r.resourceRetriever.GetKubegresResources() for _, kubegresResource := range kubegresResources.Resources { if !kubegresResource.IsPrimary { return kubegresResource.Pod.Name } } return "" } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) thenPrimaryDbContainsExpectedNbreUsers(expectedNbreUsers int) { Eventually(func() bool { users := r.connectionPrimaryDb.GetUsers() r.connectionPrimaryDb.Close() if len(users) != expectedNbreUsers || r.connectionPrimaryDb.NbreInsertedUsers != expectedNbreUsers { log.Println("Primary DB does not contain the expected number of users. Expected: " + strconv.Itoa(expectedNbreUsers) + " Given: " + strconv.Itoa(len(users))) return false } return true }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) thenReplicaDbContainsExpectedNbreUsers(expectedNbreUsers int) { Eventually(func() bool { users := r.connectionReplicaDb.GetUsers() r.connectionReplicaDb.Close() if len(users) != expectedNbreUsers || r.connectionReplicaDb.NbreInsertedUsers != expectedNbreUsers { log.Println("Replica DB does not contain the expected number of users: " + strconv.Itoa(expectedNbreUsers)) return false } return true }, resourceConfigs.TestTimeout, resourceConfigs.TestRetryInterval).Should(BeTrue()) } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) thenDeployedPodNamesMatch(primaryPodName, replicaPodName string) { kubegresResources, err := r.resourceRetriever.GetKubegresResources() if err != nil { Expect(err).Should(Succeed()) return } for _, kubegresResource := range kubegresResources.Resources { if kubegresResource.IsPrimary { if primaryPodName != kubegresResource.Pod.Name { Expect(err).Should(Succeed()) return } } else { if replicaPodName != kubegresResource.Pod.Name { Expect(err).Should(Succeed()) return } } } } func (r *SpecFailoverIsDisabledAndPromotePodAreSetTest) thenPromotePodFieldInSpecShouldBeCleared() { var err error r.kubegresResource, err = r.resourceRetriever.GetKubegres() if err != nil { log.Println("Error while getting Kubegres resource : ", err) Expect(err).Should(Succeed()) return } if r.kubegresResource.Spec.Failover.PromotePod != "" { Expect(err).Should(Succeed()) } } <|start_filename|>test/suite_test.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 test import ( "github.com/go-logr/zapr" "k8s.io/client-go/tools/record" "log" "path/filepath" "reactive-tech.io/kubegres/controllers" "reactive-tech.io/kubegres/test/util" "reactive-tech.io/kubegres/test/util/kindcluster" ctrl "sigs.k8s.io/controller-runtime" "testing" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/client-go/kubernetes/scheme" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" "sigs.k8s.io/controller-runtime/pkg/envtest/printer" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" postgresv1 "reactive-tech.io/kubegres/api/v1" // +kubebuilder:scaffold:imports ) // These tests use Ginkgo (BDD-style Go testing framework). Refer to // http://onsi.github.io/ginkgo/ to learn more about Ginkgo. var kindCluster kindcluster.KindTestClusterUtil //var cfgTest *rest.Config var k8sClientTest client.Client var testEnv *envtest.Environment var eventRecorderTest util.MockEventRecorderTestUtil func TestAPIs(t *testing.T) { RegisterFailHandler(Fail) RunSpecsWithDefaultAndCustomReporters(t, "Controller Suite", []Reporter{printer.NewlineReporter{}}) } var _ = BeforeSuite(func(done Done) { kindCluster.StartCluster() logf.SetLogger(zapr.NewLogger(zap.NewRaw(zap.UseDevMode(true), zap.WriteTo(GinkgoWriter)))) log.Print("START OF: BeforeSuite") By("bootstrapping test environment") useExistingCluster := true testEnv = &envtest.Environment{ CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")}, ErrorIfCRDPathMissing: true, UseExistingCluster: &useExistingCluster, } cfg, err := testEnv.Start() Expect(err).ToNot(HaveOccurred()) Expect(cfg).ToNot(BeNil()) err = postgresv1.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) // +kubebuilder:scaffold:scheme k8sClientTest, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) Expect(err).ToNot(HaveOccurred()) Expect(k8sClientTest).ToNot(BeNil()) k8sManager, err := ctrl.NewManager(cfg, ctrl.Options{ Scheme: scheme.Scheme, }) Expect(err).ToNot(HaveOccurred()) mockLogger := util.MockLogger{} eventRecorderTest = util.MockEventRecorderTestUtil{} err = (&controllers.KubegresReconciler{ Client: k8sManager.GetClient(), Logger: &mockLogger, Scheme: k8sManager.GetScheme(), Recorder: record.EventRecorder(&eventRecorderTest), }).SetupWithManager(k8sManager) Expect(err).ToNot(HaveOccurred()) go func() { err = k8sManager.Start(ctrl.SetupSignalHandler()) if err != nil { log.Fatal("ERROR while starting Kubernetes: ", err) } Expect(err).ToNot(HaveOccurred()) }() log.Println("Waiting for Kubernetes to start") log.Println("Kubernetes has started") k8sClientTest = k8sManager.GetClient() Expect(k8sClientTest).ToNot(BeNil()) log.Print("END OF: BeforeSuite") close(done) }, 180) var _ = AfterSuite(func() { log.Print("START OF: Suite AfterSuite") By("tearing down the test environment") err := testEnv.Stop() Expect(err).ToNot(HaveOccurred()) time.Sleep(5 * time.Second) kindCluster.DeleteCluster() log.Print("END OF: Suite AfterSuite") }) <|start_filename|>test/resourceConfigs/LoadTestYaml.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 resourceConfigs import ( "io/ioutil" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes/scheme" "log" kubegresv1 "reactive-tech.io/kubegres/api/v1" ) func LoadCustomConfigMapYaml(yamlFileName string) v1.ConfigMap { fileContents := getFileContents(yamlFileName) obj := decodeYaml(fileContents) return *obj.(*v1.ConfigMap) } func LoadBackUpPvcYaml() *v1.PersistentVolumeClaim { fileContents := getFileContents(BackUpPvcYamlFile) obj := decodeYaml(fileContents) return obj.(*v1.PersistentVolumeClaim) } func LoadKubegresYaml() *kubegresv1.Kubegres { fileContents := getFileContents(KubegresYamlFile) obj := decodeYaml(fileContents) return obj.(*kubegresv1.Kubegres) } func LoadSecretYaml() v1.Secret { fileContents := getFileContents(SecretYamlFile) obj := decodeYaml(fileContents) return *obj.(*v1.Secret) } func LoadYamlServiceToSqlQueryPrimaryDb() v1.Service { fileContents := getFileContents(ServiceToSqlQueryPrimaryDbYamlFile) obj := decodeYaml(fileContents) return *obj.(*v1.Service) } func LoadYamlServiceToSqlQueryReplicaDb() v1.Service { fileContents := getFileContents(ServiceToSqlQueryReplicaDbServiceYamlFile) obj := decodeYaml(fileContents) return *obj.(*v1.Service) } func getFileContents(filePath string) string { contents, err := ioutil.ReadFile(filePath) if err != nil { log.Fatal("Unable to find file '"+filePath+"'. Given error: ", err) } return string(contents) } func decodeYaml(yamlContents string) runtime.Object { decode := scheme.Codecs.UniversalDeserializer().Decode obj, _, err := decode([]byte(yamlContents), nil, nil) if err != nil { log.Fatal("Error in decode:", obj, err) } return obj } <|start_filename|>test/util/MockLogger.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 util import ( "github.com/go-logr/logr" "log" log2 "reactive-tech.io/kubegres/controllers/ctx/log" "strings" ) type MockLogger struct { InfoLogger logr.InfoLogger Name string } func (r *MockLogger) Info(msg string, keysAndValues ...interface{}) { log.Println(r.constructFullMsg(msg, keysAndValues)) } func (r *MockLogger) Error(err error, msg string, keysAndValues ...interface{}) { log.Println(r.constructFullErrMsg(err, msg, keysAndValues)) } func (r *MockLogger) Enabled() bool { return true } func (r *MockLogger) V(level int) logr.InfoLogger { return r } func (r *MockLogger) WithValues(keysAndValues ...interface{}) logr.Logger { return r } func (r *MockLogger) WithName(name string) logr.Logger { if !strings.Contains(r.Name, name) { r.Name += name + " - " } return r } func (r *MockLogger) constructFullErrMsg(err error, msg string, keysAndValues ...interface{}) string { msgToReturn := "" separator := "" customErrMsg := r.constructFullMsg(msg, keysAndValues...) if customErrMsg != "" { msgToReturn = customErrMsg separator = " - " } msgFromErr := err.Error() if msgFromErr != "" { msgToReturn += separator + msgFromErr } return msgToReturn } func (r *MockLogger) constructFullMsg(msg string, keysAndValues ...interface{}) string { if msg == "" { return r.Name + "" } keysAndValuesStr := log2.InterfacesToStr(keysAndValues...) if keysAndValuesStr != "" { return r.Name + msg + " " + keysAndValuesStr } return r.Name + msg } <|start_filename|>controllers/states/ServicesStates.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 states import ( core "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "reactive-tech.io/kubegres/controllers/ctx" "sigs.k8s.io/controller-runtime/pkg/client" ) type ServicesStates struct { Primary ServiceWrapper Replica ServiceWrapper kubegresContext ctx.KubegresContext } type ServiceWrapper struct { Name string IsDeployed bool Service core.Service } func loadServicesStates(kubegresContext ctx.KubegresContext) (ServicesStates, error) { servicesStates := ServicesStates{kubegresContext: kubegresContext} err := servicesStates.loadStates() return servicesStates, err } func (r *ServicesStates) loadStates() (err error) { deployedServices, err := r.getDeployedServices() if err != nil { return err } for _, service := range deployedServices.Items { serviceWrapper := ServiceWrapper{IsDeployed: true, Service: service} if r.isPrimary(service) { serviceWrapper.Name = r.kubegresContext.GetServiceResourceName(true) r.Primary = serviceWrapper } else { serviceWrapper.Name = r.kubegresContext.GetServiceResourceName(false) r.Replica = serviceWrapper } } return nil } func (r *ServicesStates) getDeployedServices() (*core.ServiceList, error) { list := &core.ServiceList{} opts := []client.ListOption{ client.InNamespace(r.kubegresContext.Kubegres.Namespace), client.MatchingFields{ctx.DeploymentOwnerKey: r.kubegresContext.Kubegres.Name}, } err := r.kubegresContext.Client.List(r.kubegresContext.Ctx, list, opts...) if err != nil { if apierrors.IsNotFound(err) { err = nil } else { r.kubegresContext.Log.ErrorEvent("ServiceLoadingErr", err, "Unable to load any deployed Services.", "Kubegres name", r.kubegresContext.Kubegres.Name) } } return list, err } func (r *ServicesStates) isPrimary(service core.Service) bool { return service.Labels["replicationRole"] == ctx.PrimaryRoleName } <|start_filename|>controllers/spec/enforcer/statefulset_spec/ImageSpecEnforcer.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 statefulset_spec import ( apps "k8s.io/api/apps/v1" "reactive-tech.io/kubegres/controllers/ctx" ) type ImageSpecEnforcer struct { kubegresContext ctx.KubegresContext } func CreateImageSpecEnforcer(kubegresContext ctx.KubegresContext) ImageSpecEnforcer { return ImageSpecEnforcer{kubegresContext: kubegresContext} } func (r *ImageSpecEnforcer) GetSpecName() string { return "Image" } func (r *ImageSpecEnforcer) CheckForSpecDifference(statefulSet *apps.StatefulSet) StatefulSetSpecDifference { current := statefulSet.Spec.Template.Spec.Containers[0].Image expected := r.kubegresContext.Kubegres.Spec.Image if current != expected { return StatefulSetSpecDifference{ SpecName: r.GetSpecName(), Current: current, Expected: expected, } } return StatefulSetSpecDifference{} } func (r *ImageSpecEnforcer) EnforceSpec(statefulSet *apps.StatefulSet) (wasSpecUpdated bool, err error) { statefulSet.Spec.Template.Spec.Containers[0].Image = r.kubegresContext.Kubegres.Spec.Image if len(statefulSet.Spec.Template.Spec.InitContainers) > 0 { statefulSet.Spec.Template.Spec.InitContainers[0].Image = r.kubegresContext.Kubegres.Spec.Image } return true, nil } func (r *ImageSpecEnforcer) OnSpecEnforcedSuccessfully(statefulSet *apps.StatefulSet) error { return nil } <|start_filename|>controllers/operation/BlockingOperationConfig.go<|end_filename|> package operation import v1 "reactive-tech.io/kubegres/api/v1" type IsOperationCompleted func(operation v1.KubegresBlockingOperation) bool type BlockingOperationConfig struct { OperationId string StepId string TimeOutInSeconds int64 CompletionChecker IsOperationCompleted // This flag is set to false by default, meaning once an operation is completed (operation = operationId + stepId), // it will be automatically removed as active operation and added as previous active operation. // // If this flag is set to false and the operation times-out, it is not removed and remain as an active operation // until it is manually removed. // // If this flag is set to true, after the completion of a stepId, we will add a new stepId and keep the same operationId. // The new stepId will be set to the value of the constant "BlockingOperation.transition_step_id". // This logic allows other types of operations (e.g. FailOver) to not start until an active operation (e.g. Spec update) // is either terminated manually or is waiting for the next step to start. AfterCompletionMoveToTransitionStep bool } const ( TransitionOperationStepId = "Transition step: waiting either for the next step to start or for the operation to be removed ..." OperationIdBaseConfigCountSpecEnforcement = "Base config count spec enforcement" OperationStepIdBaseConfigDeploying = "Base config is deploying" OperationIdPrimaryDbCountSpecEnforcement = "Primary DB count spec enforcement" OperationStepIdPrimaryDbDeploying = "Primary DB is deploying" OperationStepIdPrimaryDbWaitingBeforeFailingOver = "Waiting few seconds before failing over by promoting a Replica DB as a Primary DB" OperationStepIdPrimaryDbFailingOver = "Failing over by promoting a Replica DB as a Primary DB" OperationIdReplicaDbCountSpecEnforcement = "Replica DB count spec enforcement" OperationStepIdReplicaDbDeploying = "Replica DB is deploying" OperationStepIdReplicaDbUndeploying = "Replica DB is undeploying" OperationIdStatefulSetSpecEnforcing = "Enforcing StatefulSet's Spec" OperationStepIdStatefulSetSpecUpdating = "StatefulSet's spec is updating" OperationStepIdStatefulSetPodSpecUpdating = "StatefulSet Pod's spec is updating" OperationStepIdStatefulSetWaitingOnStuckPod = "Attempting to fix a stuck Pod by recreating it" ) <|start_filename|>controllers/spec/enforcer/statefulset_spec/StatefulSetsSpecEnforcer.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 statefulset_spec import ( apps "k8s.io/api/apps/v1" "reactive-tech.io/kubegres/controllers/ctx" ) type StatefulSetSpecEnforcer interface { GetSpecName() string CheckForSpecDifference(statefulSet *apps.StatefulSet) StatefulSetSpecDifference EnforceSpec(statefulSet *apps.StatefulSet) (wasSpecUpdated bool, err error) OnSpecEnforcedSuccessfully(statefulSet *apps.StatefulSet) error } type StatefulSetsSpecsEnforcer struct { kubegresContext ctx.KubegresContext registry []StatefulSetSpecEnforcer } func CreateStatefulSetsSpecsEnforcer(kubegresContext ctx.KubegresContext) StatefulSetsSpecsEnforcer { return StatefulSetsSpecsEnforcer{kubegresContext: kubegresContext} } func (r *StatefulSetsSpecsEnforcer) AddSpecEnforcer(specEnforcer StatefulSetSpecEnforcer) { r.registry = append(r.registry, specEnforcer) } func (r *StatefulSetsSpecsEnforcer) CheckForSpecDifferences(statefulSet *apps.StatefulSet) StatefulSetSpecDifferences { var specDifferences []StatefulSetSpecDifference for _, specEnforcer := range r.registry { specDifference := specEnforcer.CheckForSpecDifference(statefulSet) if specDifference.IsThereDifference() { specDifferences = append(specDifferences, specDifference) } } r.logSpecDifferences(specDifferences, statefulSet) return StatefulSetSpecDifferences{ Differences: specDifferences, } } func (r *StatefulSetsSpecsEnforcer) EnforceSpec(statefulSet *apps.StatefulSet) error { var updatedSpecDifferences []StatefulSetSpecDifference for _, specEnforcer := range r.registry { specDifference := specEnforcer.CheckForSpecDifference(statefulSet) if !specDifference.IsThereDifference() { continue } wasSpecUpdated, err := specEnforcer.EnforceSpec(statefulSet) if err != nil { return err } else if wasSpecUpdated { updatedSpecDifferences = append(updatedSpecDifferences, specDifference) } } if len(updatedSpecDifferences) > 0 { r.kubegresContext.Log.Info("Updating Spec of a StatefulSet", "StatefulSet name", statefulSet.Name) err := r.kubegresContext.Client.Update(r.kubegresContext.Ctx, statefulSet) if err != nil { return err } r.logUpdatedSpecDifferences(updatedSpecDifferences, statefulSet) } return nil } func (r *StatefulSetsSpecsEnforcer) OnSpecUpdatedSuccessfully(statefulSet *apps.StatefulSet) error { for _, specEnforcer := range r.registry { if err := specEnforcer.OnSpecEnforcedSuccessfully(statefulSet); err != nil { return err } } return nil } func (r *StatefulSetsSpecsEnforcer) logSpecDifferences(specDifferences []StatefulSetSpecDifference, statefulSet *apps.StatefulSet) { for _, specDifference := range specDifferences { r.kubegresContext.Log.InfoEvent("StatefulSetOperation", "The Spec is NOT up-to-date for a StatefulSet.", "StatefulSet name", statefulSet.Name, "SpecName", specDifference.SpecName, "Expected", specDifference.Expected, "Current", specDifference.Current) } } func (r *StatefulSetsSpecsEnforcer) logUpdatedSpecDifferences(specDiffBeforeUpdate []StatefulSetSpecDifference, statefulSet *apps.StatefulSet) { for _, specDifference := range specDiffBeforeUpdate { r.kubegresContext.Log.InfoEvent("StatefulSetOperation", "Updated a StatefulSet with up-to-date Spec.", "StatefulSet name", statefulSet.Name, "SpecName", specDifference.SpecName, "New", specDifference.Expected) } } <|start_filename|>test/util/TestResourceRetriever.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 util import ( "context" v1 "k8s.io/api/apps/v1" "k8s.io/api/batch/v1beta1" core "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "log" postgresv1 "reactive-tech.io/kubegres/api/v1" "reactive-tech.io/kubegres/controllers/ctx" "reactive-tech.io/kubegres/test/resourceConfigs" "sigs.k8s.io/controller-runtime/pkg/client" ) type TestResourceRetriever struct { client client.Client namespace string } type TestKubegresResources struct { NbreDeployedPrimary int NbreDeployedReplicas int AreAllReady bool Resources []TestKubegresResource BackUpCronJob TestKubegresBackUpCronJob } type TestKubegresResource struct { IsPrimary bool IsReady bool Pod TestKubegresPod StatefulSet TestKubegresStatefulSet Pvc TestKubegresPvc } type TestKubegresBackUpCronJob struct { Name string Spec v1beta1.CronJobSpec } type TestKubegresPod struct { Name string Metadata metav1.ObjectMeta Spec core.PodSpec Resource *core.Pod } type TestKubegresStatefulSet struct { Name string Metadata metav1.ObjectMeta Spec v1.StatefulSetSpec Resource *v1.StatefulSet } type TestKubegresPvc struct { Name string Spec core.PersistentVolumeClaimSpec Resource *core.PersistentVolumeClaim } func CreateTestResourceRetriever(k8sClient client.Client, namespace string) TestResourceRetriever { resourceRetriever := TestResourceRetriever{client: k8sClient, namespace: namespace} return resourceRetriever } func (r *TestResourceRetriever) GetServiceNameAllowingToSqlQueryDb(kubegresName string, isPrimaryDb bool) string { if isPrimaryDb { return resourceConfigs.ServiceToSqlQueryPrimaryDbResourceName + "-" + kubegresName } return resourceConfigs.ServiceToSqlQueryReplicaDbServiceResourceName + "-" + kubegresName } func (r *TestResourceRetriever) GetKubegres() (*postgresv1.Kubegres, error) { return r.GetKubegresByName(resourceConfigs.KubegresResourceName) } func (r *TestResourceRetriever) GetKubegresByName(resourceName string) (*postgresv1.Kubegres, error) { resourceToRetrieve := &postgresv1.Kubegres{} err := r.getResource(resourceName, resourceToRetrieve) return resourceToRetrieve, err } func (r *TestResourceRetriever) GetService(serviceResourceName string) (*core.Service, error) { resourceToRetrieve := &core.Service{} err := r.getResource(serviceResourceName, resourceToRetrieve) return resourceToRetrieve, err } func (r *TestResourceRetriever) GetBackUpPvc() (*core.PersistentVolumeClaim, error) { resourceToRetrieve := &core.PersistentVolumeClaim{} err := r.getResource(resourceConfigs.BackUpPvcResourceName, resourceToRetrieve) return resourceToRetrieve, err } func (r *TestResourceRetriever) GetKubegresPvc() (*core.PersistentVolumeClaimList, error) { return r.GetKubegresPvcByKubegresName(resourceConfigs.KubegresResourceName) } func (r *TestResourceRetriever) GetKubegresPvcByKubegresName(kubegresName string) (*core.PersistentVolumeClaimList, error) { list := &core.PersistentVolumeClaimList{} opts := []client.ListOption{ client.InNamespace(r.namespace), client.MatchingLabels{"app": kubegresName}, } ctx := context.Background() err := r.client.List(ctx, list, opts...) return list, err } func (r *TestResourceRetriever) getResource(resourceNameToRetrieve string, resourceToRetrieve client.Object) error { ctx := context.Background() lookupKey := types.NamespacedName{Name: resourceNameToRetrieve, Namespace: r.namespace} return r.client.Get(ctx, lookupKey, resourceToRetrieve) } /* func (r *TestResourceRetriever) doesResourceExist(resourceName string, resourceType runtime.Object) bool { err := r.getResource(resourceName, resourceType) return err != nil }*/ func (r *TestResourceRetriever) GetKubegresResources() (TestKubegresResources, error) { return r.GetKubegresResourcesByName(resourceConfigs.KubegresResourceName) } func (r *TestResourceRetriever) GetKubegresResourcesByName(kubegresName string) (TestKubegresResources, error) { testKubegresResources := TestKubegresResources{} statefulSetsList := &v1.StatefulSetList{} err := r.getResourcesList(kubegresName, statefulSetsList) if err != nil { return r.logAndReturnError("StatefulSetList", "-", err) } cronJobName := ctx.CronJobNamePrefix + kubegresName cronJob := &v1beta1.CronJob{} err = r.getResource(cronJobName, cronJob) if err == nil { testKubegresResources.BackUpCronJob = TestKubegresBackUpCronJob{ Name: cronJobName, Spec: cronJob.Spec, } } nbrePodsReady := 0 for _, statefulSet := range statefulSetsList.Items { podName := statefulSet.Name + "-0" pod := &core.Pod{} err = r.getResource(podName, pod) if err != nil { return r.logAndReturnError("Pod", podName, err) } pvcName := "postgres-db-" + statefulSet.Name + "-0" pvc := &core.PersistentVolumeClaim{} err = r.getResource(pvcName, pvc) if err != nil { return r.logAndReturnError("Pvc", pvcName, err) } isPrimaryPod := r.isPrimaryPod(pod) isPodReady := r.isPodReady(pod) if isPrimaryPod { testKubegresResources.NbreDeployedPrimary += 1 } else { testKubegresResources.NbreDeployedReplicas += 1 } if isPodReady { nbrePodsReady += 1 } statefulSetCopy := statefulSet kubegresPostgres := TestKubegresResource{ IsReady: isPodReady, IsPrimary: isPrimaryPod, Pod: TestKubegresPod{ Name: pod.Name, Metadata: pod.ObjectMeta, Spec: pod.Spec, Resource: pod, }, StatefulSet: TestKubegresStatefulSet{ Name: statefulSet.Name, Metadata: statefulSet.ObjectMeta, Spec: statefulSet.Spec, Resource: &statefulSetCopy, }, Pvc: TestKubegresPvc{ Name: pvc.Name, Spec: pvc.Spec, Resource: pvc, }, } testKubegresResources.Resources = append(testKubegresResources.Resources, kubegresPostgres) } if testKubegresResources.NbreDeployedPrimary > 0 { testKubegresResources.AreAllReady = nbrePodsReady == (testKubegresResources.NbreDeployedPrimary + testKubegresResources.NbreDeployedReplicas) } return testKubegresResources, nil } func (r *TestResourceRetriever) getResourcesList(kubegresName string, resourceTypeToRetrieve client.ObjectList) error { ctx := context.Background() opts := []client.ListOption{ client.InNamespace(r.namespace), client.MatchingLabels{"app": kubegresName}, } return r.client.List(ctx, resourceTypeToRetrieve, opts...) } func (r *TestResourceRetriever) isPodReady(pod *core.Pod) bool { if len(pod.Status.ContainerStatuses) == 0 { return false } return pod.Status.ContainerStatuses[0].Ready } func (r *TestResourceRetriever) isPrimaryPod(pod *core.Pod) bool { return pod.Labels["replicationRole"] == resourceConfigs.PrimaryReplicationRole } func (r *TestResourceRetriever) logAndReturnError(resourceType, resourceName string, err error) (TestKubegresResources, error) { if apierrors.IsNotFound(err) { log.Println("There is not any deployed Kubegres " + resourceType + " with name '" + resourceName + "' yet.") err = nil } else { log.Println("Error while retrieving Kubegres "+resourceType+" with name '"+resourceName+"'. Given error: ", err) } return TestKubegresResources{}, err } <|start_filename|>controllers/states/statefulset/StatefulSetWrappersSorting.go<|end_filename|> /* Copyright 2021 Reactive Tech Limited. "Reactive Tech Limited" is a company located in England, United Kingdom. https://www.reactive-tech.io Lead Developer: <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 statefulset import ( "strconv" ) type SortByInstanceIndex []StatefulSetWrapper type ReverseSortByInstanceIndex []StatefulSetWrapper func (f SortByInstanceIndex) Len() int { return len(f) } func (f SortByInstanceIndex) Less(i, j int) bool { return getInstanceIndex(f[i]) < getInstanceIndex(f[j]) } func (f SortByInstanceIndex) Swap(i, j int) { f[i], f[j] = f[j], f[i] } func (f ReverseSortByInstanceIndex) Len() int { return len(f) } func (f ReverseSortByInstanceIndex) Less(i, j int) bool { return getInstanceIndex(f[i]) > getInstanceIndex(f[j]) } func (f ReverseSortByInstanceIndex) Swap(i, j int) { f[i], f[j] = f[j], f[i] } func getInstanceIndex(statefulSet StatefulSetWrapper) int32 { instanceIndexStr := statefulSet.StatefulSet.Spec.Template.Labels["index"] instanceIndex, _ := strconv.ParseInt(instanceIndexStr, 10, 32) return int32(instanceIndex) }
Rickcy/kubegres
<|start_filename|>lib/editor.dart<|end_filename|> /* Copyright 2019 The dahliaOS Authors 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. */ import 'package:flutter/material.dart'; import 'dart:io'; extension CustomColorScheme on ColorScheme { Color get foregroundText => brightness == Brightness.light ? const Color(0xFF222222) : const Color(0xFFffffff); Color get cardColor => brightness == Brightness.light ? const Color(0xFFffffff) : const Color(0xFF333333); Color get barIconColor => brightness == Brightness.light ? const Color(0xFF454545) : const Color(0xFFffffff); Color get barColor => brightness == Brightness.light ? const Color(0xFFe0e0e0) : const Color(0xFF333333); } class TextEditorApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( theme: ThemeData( platform: TargetPlatform.fuchsia, brightness: Brightness.light, primarySwatch: Colors.amber, scaffoldBackgroundColor: Colors.grey[100]), darkTheme: ThemeData( platform: TargetPlatform.fuchsia, brightness: Brightness.dark, primarySwatch: Colors.amber, scaffoldBackgroundColor: Colors.grey[900], textTheme: TextTheme( bodyText1: TextStyle(color: Colors.white), ), ), /*themeMode: Pangolin.settingsBox.get("darkMode") ? ThemeMode.dark : ThemeMode.light,*/ title: 'Text Editor', // Start the app with the "/" named route. In this case, the app starts // on the FirstScreen widget. initialRoute: '/second', routes: { // When navigating to the "/" route, build the FirstScreen widget. '/': (context) => TextEditorHomePage(), // When navigating to the "/second" route, build the SecondScreen widget. '/second': (context) => SecondScreen(), }, ); } } class TextEditorHomePage extends StatefulWidget { TextEditorHomePage({Key? key}) : super(key: key); @override _TextEditorHomePageState createState() => new _TextEditorHomePageState(); } class _TextEditorHomePageState extends State<TextEditorHomePage> { @override Widget build(BuildContext context) { return new Scaffold( appBar: AppBar( title: Text('First Screen'), ), body: Center( child: ElevatedButton( child: Text('Launch screen'), onPressed: () { // Navigate to the second screen using a named route. Navigator.pushNamed(context, '/second'); }, ), ), ); } } class SecondScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: false, title: Text('Untitled Document'), actions: <Widget>[ // action button IconButton( icon: Icon(Icons.save), onPressed: () { Navigator.pushNamed(context, '/'); }, ), IconButton( icon: Icon(Icons.share), onPressed: () { Navigator.pushNamed(context, '/'); }, ), IconButton( icon: Icon(Icons.print), onPressed: () { Navigator.pushNamed(context, '/'); }, ), ], ), body: Column(children: [ Container( height: 40, width: MediaQuery.of(context).size.width, color: Theme.of(context).colorScheme.barColor, child: SingleChildScrollView( //padding: // new EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0), scrollDirection: Axis.horizontal, child: Row(children: [ Container( width: 40, height: 40, child: Center( child: Icon(Icons.undo, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), Container( width: 40, height: 40, child: Center( child: Icon(Icons.redo, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), VerticalDivider( endIndent: 10, indent: 10, color: Theme.of(context).colorScheme.barIconColor, ), Container( width: 40, height: 40, child: Center( child: Icon(Icons.format_bold, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), Container( width: 40, height: 40, child: Center( child: Icon(Icons.strikethrough_s, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), Container( width: 40, height: 40, child: Center( child: Icon(Icons.format_underlined, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), Container( width: 40, height: 40, child: Center( child: Icon(Icons.format_italic, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), Container( width: 40, height: 40, child: Center( child: Icon(Icons.format_quote, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), Container( width: 40, height: 40, child: Center( child: Icon(Icons.code, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), VerticalDivider( endIndent: 10, indent: 10, color: Theme.of(context).colorScheme.barIconColor, ), Container( width: 40, height: 40, child: Center( child: new Text( "H1", style: new TextStyle( fontSize: 15.0, color: Theme.of(context).colorScheme.barIconColor, fontWeight: FontWeight.w800, fontFamily: "Roboto"), ), )), Container( width: 40, height: 40, child: Center( child: new Text( "H2", style: new TextStyle( fontSize: 15.0, color: Theme.of(context).colorScheme.barIconColor, fontWeight: FontWeight.w800, fontFamily: "Roboto"), ), )), Container( width: 40, height: 40, child: Center( child: new Text( "H3", style: new TextStyle( fontSize: 15.0, color: Theme.of(context).colorScheme.barIconColor, fontWeight: FontWeight.w800, fontFamily: "Roboto"), ), )), Container( width: 40, height: 40, child: Center( child: new Text( "H4", style: new TextStyle( fontSize: 15.0, color: Theme.of(context).colorScheme.barIconColor, fontWeight: FontWeight.w800, fontFamily: "Roboto"), ), )), Container( width: 40, height: 40, child: Center( child: new Text( "H5", style: new TextStyle( fontSize: 15.0, color: Theme.of(context).colorScheme.barIconColor, fontWeight: FontWeight.w800, fontFamily: "Roboto"), ), )), Container( width: 40, height: 40, child: Center( child: new Text( "H6", style: new TextStyle( fontSize: 15.0, color: Theme.of(context).colorScheme.barIconColor, fontWeight: FontWeight.w800, fontFamily: "Roboto"), ), )), VerticalDivider( endIndent: 10, indent: 10, color: Theme.of(context).colorScheme.barIconColor, ), Container( width: 40, height: 40, child: Center( child: Icon(Icons.format_list_bulleted, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), Container( width: 40, height: 40, child: Center( child: Icon(Icons.format_list_numbered, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), VerticalDivider( endIndent: 10, indent: 10, color: Theme.of(context).colorScheme.barIconColor, ), Container( width: 40, height: 40, child: Center( child: Icon(Icons.link, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), Container( width: 40, height: 40, child: Center( child: Icon(Icons.image, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), Container( width: 40, height: 40, child: Center( child: Icon(Icons.table_chart, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), Container( width: 40, height: 40, child: Center( child: Icon(Icons.insert_emoticon, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), Container( width: 40, height: 40, child: Center( child: Icon(Icons.functions, size: 25, color: Theme.of(context) .colorScheme .barIconColor))), ]))), new Expanded( child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Container( margin: const EdgeInsets.all(25.0), width: 900, height: 1600, child: Card( color: Theme.of(context).colorScheme.cardColor, elevation: 1, child: Padding( padding: EdgeInsets.symmetric(horizontal: 30, vertical: 20), child: new TextFormField( onChanged: (text) { print("First text field: $text"); }, style: TextStyle( fontSize: 15.0, color: Theme.of(context).colorScheme.foregroundText, fontFamily: "Roboto", ), decoration: InputDecoration.collapsed(hintText: ""), autocorrect: false, minLines: null, maxLines: null, expands: true, cursorColor: Theme.of(context).colorScheme.foregroundText, ), ), ), ), )) ])); } } //Navigator.pop(context);
apgapg/text_editor
<|start_filename|>sample_addon/3_callbacks/nan/addon.cc<|end_filename|> #include <nan.h> void RunCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Function> cb = info[0].As<v8::Function>(); const unsigned argc = 1; v8::Local<v8::Value> argv[argc] = { Nan::New("hello world").ToLocalChecked() }; Nan::MakeCallback(Nan::GetCurrentContext()->Global(), cb, argc, argv); } void Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) { Nan::SetMethod(module, "exports", RunCallback); } NODE_MODULE(addon, Init) <|start_filename|>sample_addon/4_object_factory/nan/addon.cc<|end_filename|> #include <nan.h> void CreateObject(const Nan::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> obj = Nan::New<v8::Object>(); obj->Set(Nan::New("msg").ToLocalChecked(), info[0]->ToString()); info.GetReturnValue().Set(obj); } void Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) { module->Set(Nan::New("exports").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(CreateObject)->GetFunction()); } NODE_MODULE(addon, Init) <|start_filename|>sample_addon/8_passing_wrapped/nan/addon.cc<|end_filename|> #include <nan.h> #include "myobject.h" using namespace v8; void CreateObject(const Nan::FunctionCallbackInfo<v8::Value>& info) { info.GetReturnValue().Set(MyObject::NewInstance(info[0])); } void Add(const Nan::FunctionCallbackInfo<v8::Value>& info) { MyObject* obj1 = Nan::ObjectWrap::Unwrap<MyObject>(info[0]->ToObject()); MyObject* obj2 = Nan::ObjectWrap::Unwrap<MyObject>(info[1]->ToObject()); double sum = obj1->Val() + obj2->Val(); info.GetReturnValue().Set(Nan::New(sum)); } void InitAll(v8::Local<v8::Object> exports) { MyObject::Init(); exports->Set(Nan::New("createObject").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(CreateObject)->GetFunction()); exports->Set(Nan::New("add").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(Add)->GetFunction()); } NODE_MODULE(addon, InitAll) <|start_filename|>sample_addon/2_function_arguments/node_0.12/addon.js<|end_filename|> var addon = require('bindings')('addon.node') console.log('This should be eight:', addon.add(3, 5)) <|start_filename|>sample_addon/6_object_wrap/node_0.12/addon.js<|end_filename|> var addon = require('bindings')('addon'); var obj = new addon.MyObject(10); console.log( obj.plusOne() ); // 11 console.log( obj.plusOne() ); // 12 console.log( obj.plusOne() ); // 13 <|start_filename|>sample_addon/4_object_factory/node_0.10/addon.cc<|end_filename|> #include <node.h> using namespace v8; Handle<Value> CreateObject(const Arguments& args) { HandleScope scope; Local<Object> obj = Object::New(); obj->Set(String::NewSymbol("msg"), args[0]->ToString()); return scope.Close(obj); } void Init(Handle<Object> exports, Handle<Object> module) { module->Set(String::NewSymbol("exports"), FunctionTemplate::New(CreateObject)->GetFunction()); } NODE_MODULE(addon, Init) <|start_filename|>sample_addon/6_object_wrap/nan/addon.cc<|end_filename|> #include <nan.h> #include "myobject.h" void InitAll(v8::Local<v8::Object> exports) { MyObject::Init(exports); } NODE_MODULE(addon, InitAll) <|start_filename|>sample_addon/2_function_arguments/node_0.12/addon.cc<|end_filename|> #include <node.h> using namespace v8; void Add(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); if (args.Length() < 2) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Wrong number of arguments"))); return; } if (!args[0]->IsNumber() || !args[1]->IsNumber()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Wrong arguments"))); return; } double value = args[0]->NumberValue() + args[1]->NumberValue(); Local<Number> num = Number::New(isolate, value); args.GetReturnValue().Set(num); } void Init(Handle<Object> exports) { NODE_SET_METHOD(exports, "add", Add); } NODE_MODULE(addon, Init) <|start_filename|>sample_addon/6_object_wrap/node_0.10/myobject.cc<|end_filename|> #include <node.h> #include "myobject.h" using namespace v8; Persistent<Function> MyObject::constructor; MyObject::MyObject() {}; MyObject::~MyObject() {}; void MyObject::Init(Handle<Object> target) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("MyObject")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype NODE_SET_PROTOTYPE_METHOD(tpl, "value", GetValue); NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne); NODE_SET_PROTOTYPE_METHOD(tpl, "multiply", Multiply); constructor = Persistent<Function>::New(tpl->GetFunction()); target->Set(String::NewSymbol("MyObject"), constructor); } Handle<Value> MyObject::New(const Arguments& args) { HandleScope scope; MyObject* obj = new MyObject(); obj->value_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); obj->Wrap(args.This()); return args.This(); } Handle<Value> MyObject::GetValue(const Arguments& args) { HandleScope scope; MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder()); return scope.Close(Number::New(obj->value_)); } Handle<Value> MyObject::PlusOne(const Arguments& args) { HandleScope scope; MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This()); obj->value_ += 1; return scope.Close(Number::New(obj->value_)); } Handle<Value> MyObject::Multiply(const Arguments& args) { HandleScope scope; MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This()); double multiple = args[0]->IsUndefined() ? 1 : args[0]->NumberValue(); const int argc = 1; Local<Value> argv[argc] = { Number::New(obj->value_ * multiple) }; return scope.Close(constructor->NewInstance(argc, argv)); } <|start_filename|>sample_addon/8_passing_wrapped/node_0.10/addon.cc<|end_filename|> #include <node.h> #include "myobject.h" using namespace v8; Handle<Value> CreateObject(const Arguments& args) { HandleScope scope; return scope.Close(MyObject::NewInstance(args)); } Handle<Value> Add(const Arguments& args) { HandleScope scope; MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>( args[0]->ToObject()); MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>( args[1]->ToObject()); double sum = obj1->Val() + obj2->Val(); return scope.Close(Number::New(sum)); } void InitAll(Handle<Object> exports) { MyObject::Init(); exports->Set(String::NewSymbol("createObject"), FunctionTemplate::New(CreateObject)->GetFunction()); exports->Set(String::NewSymbol("add"), FunctionTemplate::New(Add)->GetFunction()); } NODE_MODULE(addon, InitAll) <|start_filename|>sample_addon/4_object_factory/node_0.12/addon.cc<|end_filename|> #include <node.h> using namespace v8; void CreateObject(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); Local<Object> obj = Object::New(isolate); obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString()); args.GetReturnValue().Set(obj); } void Init(Handle<Object> exports, Handle<Object> module) { NODE_SET_METHOD(module, "exports", CreateObject); } NODE_MODULE(addon, Init) <|start_filename|>sample_addon/7_factory_wrap/node_0.12/addon.js<|end_filename|> var createObject = require('bindings')('addon'); var obj = createObject(10); console.log( obj.plusOne() ); // 11 console.log( obj.plusOne() ); // 12 console.log( obj.plusOne() ); // 13 var obj2 = createObject(20); console.log( obj2.plusOne() ); // 21 console.log( obj2.plusOne() ); // 22 console.log( obj2.plusOne() ); // 23 <|start_filename|>sample_addon/1_hello_world/node_0.10/hello.cc<|end_filename|> #include <node.h> #include <v8.h> using namespace v8; Handle<Value> Method(const Arguments& args) { HandleScope scope; return scope.Close(String::New("world")); } void Init(Handle<Object> exports) { exports->Set(String::NewSymbol("hello"), FunctionTemplate::New(Method)->GetFunction()); } NODE_MODULE(hello, Init) <|start_filename|>sample_addon/5_function_factory/nan/addon.cc<|end_filename|> #include <nan.h> void MyFunction(const Nan::FunctionCallbackInfo<v8::Value>& info) { info.GetReturnValue().Set(Nan::New("hello world").ToLocalChecked()); } void CreateFunction(const Nan::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(MyFunction); v8::Local<v8::Function> fn = tpl->GetFunction(); // omit this to make it anonymous fn->SetName(Nan::New("theFunction").ToLocalChecked()); info.GetReturnValue().Set(fn); } void Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) { Nan::SetMethod(module, "exports", CreateFunction); } NODE_MODULE(addon, Init) <|start_filename|>sample_addon/6_object_wrap/node_0.10/addon.js<|end_filename|> var addon = require('bindings')('addon'); var obj = new addon.MyObject(10); console.log( obj.plusOne() ); // 11 console.log( obj.plusOne() ); // 12 console.log( obj.plusOne() ); // 13 console.log( obj.multiply().value() ); // 13 console.log( obj.multiply(10).value() ); // 130 var newobj = obj.multiply(-1); console.log( newobj.value() ); // -13 console.log( obj === newobj ); // false <|start_filename|>sample_addon/5_function_factory/node_0.10/addon.cc<|end_filename|> #include <node.h> using namespace v8; Handle<Value> MyFunction(const Arguments& args) { HandleScope scope; return scope.Close(String::New("hello world")); } Handle<Value> CreateFunction(const Arguments& args) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction); Local<Function> fn = tpl->GetFunction(); fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous return scope.Close(fn); } void Init(Handle<Object> exports, Handle<Object> module) { module->Set(String::NewSymbol("exports"), FunctionTemplate::New(CreateFunction)->GetFunction()); } NODE_MODULE(addon, Init) <|start_filename|>sample_addon/2_function_arguments/node_0.10/addon.cc<|end_filename|> #include <node.h> using namespace v8; Handle<Value> Add(const Arguments& args) { HandleScope scope; if (args.Length() < 2) { ThrowException(Exception::TypeError(String::New("Wrong number of arguments"))); return scope.Close(Undefined()); } if (!args[0]->IsNumber() || !args[1]->IsNumber()) { ThrowException(Exception::TypeError(String::New("Wrong arguments"))); return scope.Close(Undefined()); } double arg0 = args[0]->NumberValue(); double arg1 = args[1]->NumberValue(); Local<Number> num = Number::New(arg0 + arg1); return scope.Close(num); } void Init(Handle<Object> exports) { exports->Set(String::NewSymbol("add"), FunctionTemplate::New(Add)->GetFunction()); } NODE_MODULE(addon, Init) <|start_filename|>sample_addon/7_factory_wrap/node_0.10/myobject.cc<|end_filename|> #include <node.h> #include "myobject.h" using namespace v8; MyObject::MyObject() {}; MyObject::~MyObject() {}; Persistent<Function> MyObject::constructor; void MyObject::Init() { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("MyObject")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"), FunctionTemplate::New(PlusOne)->GetFunction()); constructor = Persistent<Function>::New(tpl->GetFunction()); } Handle<Value> MyObject::New(const Arguments& args) { HandleScope scope; MyObject* obj = new MyObject(); obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); obj->Wrap(args.This()); return args.This(); } Handle<Value> MyObject::NewInstance(const Arguments& args) { HandleScope scope; const unsigned argc = 1; Handle<Value> argv[argc] = { args[0] }; Local<Object> instance = constructor->NewInstance(argc, argv); return scope.Close(instance); } Handle<Value> MyObject::PlusOne(const Arguments& args) { HandleScope scope; MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This()); obj->counter_ += 1; return scope.Close(Number::New(obj->counter_)); } <|start_filename|>sample_addon/7_factory_wrap/node_0.12/addon.cc<|end_filename|> #include <node.h> #include "myobject.h" using namespace v8; void CreateObject(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); MyObject::NewInstance(args); } void InitAll(Handle<Object> exports, Handle<Object> module) { MyObject::Init(); NODE_SET_METHOD(module, "exports", CreateObject); } NODE_MODULE(addon, InitAll) <|start_filename|>sample_addon/5_function_factory/node_0.12/addon.js<|end_filename|> var addon = require('bindings')('addon'); var fn = addon(); console.log(fn()); // 'hello world' <|start_filename|>sample_addon/3_callbacks/node_0.10/addon.cc<|end_filename|> #include <node.h> using namespace v8; Handle<Value> RunCallback(const Arguments& args) { HandleScope scope; Local<Function> cb = Local<Function>::Cast(args[0]); const unsigned argc = 1; Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) }; cb->Call(Context::GetCurrent()->Global(), argc, argv); return scope.Close(Undefined()); } void Init(Handle<Object> exports, Handle<Object> module) { module->Set(String::NewSymbol("exports"), FunctionTemplate::New(RunCallback)->GetFunction()); } NODE_MODULE(addon, Init) <|start_filename|>sample_addon/7_factory_wrap/nan/addon.cc<|end_filename|> #include <nan.h> #include "myobject.h" void CreateObject(const Nan::FunctionCallbackInfo<v8::Value>& info) { info.GetReturnValue().Set(MyObject::NewInstance(info[0])); } void InitAll(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) { Nan::HandleScope scope; MyObject::Init(); module->Set(Nan::New("exports").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(CreateObject)->GetFunction()); } NODE_MODULE(addon, InitAll) <|start_filename|>sample_addon/3_callbacks/node_0.12/addon.js<|end_filename|> var addon = require('bindings')('addon'); addon(function(msg){ console.log(msg); // 'hello world' }); <|start_filename|>sample_addon/8_passing_wrapped/node_0.12/addon.cc<|end_filename|> #include <node.h> #include <node_object_wrap.h> #include "myobject.h" using namespace v8; void CreateObject(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); MyObject::NewInstance(args); } void Add(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>( args[0]->ToObject()); MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>( args[1]->ToObject()); double sum = obj1->value() + obj2->value(); args.GetReturnValue().Set(Number::New(isolate, sum)); } void InitAll(Handle<Object> exports) { MyObject::Init(); NODE_SET_METHOD(exports, "createObject", CreateObject); NODE_SET_METHOD(exports, "add", Add); } NODE_MODULE(addon, InitAll) <|start_filename|>sample_addon/7_factory_wrap/node_0.10/addon.cc<|end_filename|> #include <node.h> #include "myobject.h" using namespace v8; Handle<Value> CreateObject(const Arguments& args) { HandleScope scope; return scope.Close(MyObject::NewInstance(args)); } void InitAll(Handle<Object> exports, Handle<Object> module) { MyObject::Init(); module->Set(String::NewSymbol("exports"), FunctionTemplate::New(CreateObject)->GetFunction()); } NODE_MODULE(addon, InitAll)
Cereceres/SVD-
<|start_filename|>rollup.config.js<|end_filename|> import rollupTypescript from "rollup-plugin-typescript2"; import typescript from "typescript"; import packageJSON from "./package.json"; import compiler from "@ampproject/rollup-plugin-closure-compiler"; import summary from "rollup-plugin-summary"; export default { input: "src/index.ts", output: [ { file: `${packageJSON.module}`, format: "es", exports: "named", }, { file: `${packageJSON.main}`, format: "cjs", exports: "named", }, { file: `${packageJSON.unpkg}`, format: "umd", exports: "named", name: "Entangle", globals: { react: "React", }, }, ], // external: ["react"], plugins: [ rollupTypescript({ typescript: typescript, }), // Converts the TSX files to JS compiler(), // minifies the js bundle summary(), ], };
redbar0n/entangle
<|start_filename|>basic/lua/melt.lua<|end_filename|> local history_str = "" local history_oo = "" local history_ii = "" local history_uu = 1 -- 获取用户目录 local function getCurrentDir() function sum(a, b) return a + b end local info = debug.getinfo(sum) local path = info.source path = string.sub(path, 2, -1) -- 去掉开头的"@" path = string.match(path, "^(.*[\\/])") -- 捕获目录路径 local spacer = string.match(path,"[\\/]") path=string.gsub(path,'[\\/]',spacer) .. ".." .. spacer return path end -- 输出日期、ooii、词尾输入--保存词条到英文用户词库 local function get_date(input, seg, env) if (init_tran) then -- tran_init(env) end if ( input == "guid" or input == "uuid") then yield(Candidate("UUID", seg.start, seg._end, guid(), " -V4")) elseif ( input == "date") then yield(Candidate("date", seg.start, seg._end, os.date("%Y-%m-%d"), " -")) elseif ( input == "time" or input == "date---") then yield(Candidate("time", seg.start, seg._end, os.date("%H:%M"), " -")) yield(Candidate("time", seg.start, seg._end, os.date("%H:%M:%S"), " -")) yield(Candidate("time", seg.start, seg._end, os.date("%H%M%S"), " -")) elseif input == "oo" and string.len(history_oo)>0 then yield(Candidate("oo", seg.start, seg._end, history_oo, "get oo")) elseif input == "ii" and string.len(history_ii)>0 then yield(Candidate("oo", seg.start, seg._end, history_ii, "get ii")) elseif ( string.sub(input,-1) == "-") then if ( input == "date-" or input == "time--") then yield(Candidate("date", seg.start, seg._end, os.date("%m/%d"), "")) yield(Candidate("date", seg.start, seg._end, os.date("%Y/%m/%d"), "")) yield(Candidate("date", seg.start, seg._end, os.date("%Y-%m-%d"), "")) yield(Candidate("date", seg.start, seg._end, os.date("%Y.%m.%d"), "")) yield(Candidate("date", seg.start, seg._end, os.date("%Y%m%d"), "")) yield(Candidate("date", seg.start, seg._end, os.date("%B %d"), "")) yield(Candidate("date", seg.start, seg._end, string.gsub(os.date("%Y年%m月%d日"),"([年月])0","%1"), "")) elseif ( input == "time-" or input == "date--") then yield(Candidate("date", seg.start, seg._end, os.date("%m/%d %H:%M"), "")) yield(Candidate("date", seg.start, seg._end, os.date("%Y/%m/%d %H:%M"), "")) yield(Candidate("date", seg.start, seg._end, os.date("%Y-%m-%d %H:%M"), "")) yield(Candidate("date", seg.start, seg._end, os.date("%Y.%m.%d %H:%M"), "")) yield(Candidate("date", seg.start, seg._end, os.date("%Y%m%d%H%M%S"), "")) yield(Candidate("date", seg.start, seg._end, os.date("%B %d %H:%M"), "")) yield(Candidate("date", seg.start, seg._end, string.gsub(os.date("%Y年%m月%d日 %H:%M"),"([年月])0","%1"), "")) yield(Candidate("date", seg.start, seg._end, os.time() , "-秒")) else local inpu = string.gsub(input,"[-]+$","") if (string.len(inpu) > 1 and string.sub(input,1,1) ~= "-") then if ( string.sub(input,-2) == "--") then -- file = io.open("C:\\Users\\Yazii\\AppData\\Roaming\\Rime\\pinyin_simp_pin.txt", "a") -- user_path = (rime_api ~= nil and rime_api.get_user_data_dir ~= nil and {rime_api:get_user_data_dir()} or {'%appdata%\\Rime'})[1] ppath = getCurrentDir() .. "melt_eng_custom.dict.yaml" -- yield(Candidate("pin", seg.start, seg._end, ppath , "")) local file = io.open(ppath,"a") file:write("\n" .. inpu .. "\t" .. inpu .. "\t100") file:close() yield(Candidate("pin", seg.start, seg._end, inpu , " 已保存")) else yield(Candidate("pin", seg.start, seg._end, inpu , " -保存")) end end end end end -- 假名滤镜。 local function jpcharset_filter(input, env) sw = env.engine.context:get_option("jpcharset_filter") if( env.engine.context:get_option("jpcharset_c")) then for cand in input:iter() do local text = cand.text for i in utf8.codes(text) do local c = utf8.codepoint(text, i) if (c< 0x3041 or c> 0x30FF) then yield(cand) -- yield(Candidate("pin", seg.start, seg._end, text , string.format("%x %c",c,c))) break end end end elseif( env.engine.context:get_option("jpcharset_j")) then for cand in input:iter() do local text = cand.text for i in utf8.codes(text) do local c = utf8.codepoint(text, i) if (c>= 0x3041 and c<= 0x30FF) then yield(cand) break end end end else for cand in input:iter() do yield(cand) end end end -- 输入的内容大写前2个字符,自动转小写词条为全词大写;大写第一个字符,自动转写小写词条为首字母大写 local function autocap_filter(input, env) if true then -- if( env.engine.context:get_option("autocap_filter")) then for cand in input:iter() do local text = cand.text local commit = env.engine.context:get_commit_text() if (string.find(text, "^%l%l.*") and string.find(commit, "^%u%u.*")) then if(string.len(text) == 2) then yield(Candidate("cap", 0, 2, commit , "+" )) else yield(Candidate("cap", 0, string.len(commit), string.upper(text) , "+" .. string.sub(cand.comment, 2))) end --[[ 修改候选的注释 `cand.comment` 因复杂类型候选项的注释不能被直接修改, 因此使用 `get_genuine()` 得到其对应真实的候选项 cand:get_genuine().comment = cand.comment .. " " .. s --]] elseif (string.find(text, "^%l+$") and string.find(commit, "^%u+")) then local suffix = string.sub(text,string.len(commit)+1) yield(Candidate("cap", 0, string.len(commit), commit .. suffix , "+" .. suffix)) else yield(cand) end end else for cand in input:iter() do yield(cand) end end end -- 长词优先(从后方移动2个英文候选和3个中文长词,提前为第2-6候选;当后方候选长度全部不超过第一候选词时,不产生作用) local function long_word_filter(input) local l = {} -- 记录第一个候选词的长度,提前的候选词至少要比第一个候选词长 local length = 0 -- 记录筛选了多少个英语词条(只提升3个词的权重,并且对comment长度过长的候选进行过滤) local s1 = 0 -- 记录筛选了多少个汉语词条(只提升3个词的权重) local s2 = 0 for cand in input:iter() do leng = utf8.len(cand.text) if(length < 1 ) then length = leng yield(cand) elseif #table > 30 then table.insert(l, cand) elseif ((leng > length) and (s1 <2)) and(string.find(cand.text, "^[%w%p%s]+$")) then s1=s1+1 if( string.len(cand.text)/ string.len(cand.comment) > 1.5) then yield(cand) end elseif ((leng > length) and (s2 <3)) and(string.find(cand.text, "^[%w%p%s]+$")==nil) then yield(cand) s2=s2+1 else table.insert(l, cand) end end for i, cand in ipairs(l) do yield(cand) end end function guid() local seed={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'} local tb={} for i=1,32 do table.insert(tb,seed[math.random(1,16)]) end local sid=table.concat(tb) return string.format('%s-%s-%s-%s-%s', string.sub(sid,1,8), string.sub(sid,9,12), string.sub(sid,13,16), string.sub(sid,17,20), string.sub(sid,21,32) ) end local s=0 local start_time=os.clock() while s<50000 do s=s+1 print(s,guid()) end print('execute_time='..tostring(os.clock()-start_time)) -- 获取子字符串。根据UTF8编码规则,避免了末位输出乱码 local function get_sub_string(str, length) if string.len(str)<length then return str end local ch = string.byte(str, length) while( ch<=191 and ch >= 128) do length = length-1 ch = string.byte(str, length) end return string.sub(str,1,length-1) end -- Windows 小狼毫输出\r\n会崩溃,故需判断系统为Windows则只输出\r local next_line = "\n" if package.config:sub(1,1) == "\\" then next_line = "\r" end -- 包含3个功能:把Oo转换为变量值, <br>转换为换行, 过长的内容切分并缓存,在候选栏仅提供预览(节约屏幕空间的同时避免输入法崩溃) local oo_buffer= {} local function oo_filter(input,env) oo_buffer= {} local input_len = string.len(env.engine.context.input) if string.len(history_oo)>0 then for cand in input:iter() do local text= string.gsub(cand.text,"<br>",next_line) text= string.gsub(text,"&nbsp"," ") local comment = cand.comment if string.find(text, "Oo")~=nil then text = string.gsub(text,"Oo",history_oo) if string.len(history_ii)>0 then text = string.gsub(text,"Xx",history_ii) end comment = "=" .. history_oo end if string.len(text)>120 then local key = get_sub_string(text,100) -- local key = string.sub(text,0,100) oo_buffer[key] = text yield(Candidate(cand.type, 0,input_len, key, "..." .. comment )) elseif text ~= cand.text then yield(Candidate(cand.type, 0,input_len, text, comment )) else yield(cand) end end else for cand in input:iter() do local text = cand.text if string.len(text)>110 then text= string.gsub(text,"&nbsp"," ") local key = get_sub_string(text,100) -- local key = string.sub(text,0,100) text= string.gsub(text,"<br>",next_line) oo_buffer[key] = text yield(Candidate(cand.type, 0,input_len, key, "..." .. cand.comment )) else yield(cand) end end end end -- 包含2个功能,输入 值=oo 设置 history_oo,输入数字完成长候选词取值上屏 local function oo_processor(key, env) local context = env.engine.context local commit_text = context:get_commit_text() if commit_text == nil then return 2 end local ch = key.keycode local engine=env.engine local done=false if context:has_menu() then if key.keycode == 32 then done = true elseif ch <58 and ch>48 then local composition = context.composition local segment = composition:back() local index = segment.selected_index + ch -49 local candidate_count = segment.menu:candidate_count() if candidate_count <= index or index < 0 then return 2 end -- -48为键盘数字 -49 第一个候选序号0 commit_text = segment:get_candidate_at(index).text done = true end if string.len(commit_text)>80 and done then context:clear() if oo_buffer[commit_text] ~= nil then engine:commit_text(oo_buffer[commit_text]) else engine:commit_text(commit_text) end return 1 end end local v = commit_text:match("(.+)=") local k = context.input:match("=(.+)$") if k == nil or v == nil then return 2 end -- k 和 v只要能够匹配到,长度一定大于0 -- local file = io.open("C:\\Users\\Yazii\\AppData\\Roaming\\Rime\\history.txt","a") -- file:write("\n" .. commit_text .. "\tk=" .. k .. " v=" .. v) -- file:close() if(k == "oo") then history_oo = v context:clear() return 1 elseif (k == "ii") then history_ii = v context:clear() return 1 end return 2 end return {getdate= get_date, jpcharsetfilter= jpcharset_filter,autocapfilter=autocap_filter, longwordfilter=long_word_filter,ooprocessor=oo_processor ,oofilter=oo_filter}
DaoMingze/My-Rime-Config
<|start_filename|>aspnet-core/src/AbpCompanyName.AbpProjectName.Application/MultiTenancy/ITenantAppService.cs<|end_filename|> using Abp.Application.Services; using Abp.Application.Services.Dto; using AbpCompanyName.AbpProjectName.MultiTenancy.Dto; namespace AbpCompanyName.AbpProjectName.MultiTenancy { public interface ITenantAppService : IAsyncCrudAppService<TenantDto, int, PagedTenantResultRequestDto, CreateTenantDto, TenantDto> { } }
ltm0203/module-zero-core-template
<|start_filename|>tests/rollup/rollup.config.js<|end_filename|> import buble from 'rollup-plugin-buble'; export default { plugins: [ buble() ] };
iphydf/rules_node
<|start_filename|>public/css/custom.css<|end_filename|> .form-action { display: inline-block; } .alert p { margin-bottom: 0px !important; }
AXeL-dev/Larabye
<|start_filename|>awtrix-server/Dockerfile<|end_filename|> ARG BUILD_FROM=hassioaddons/base:7.0.3 FROM ${BUILD_FROM} WORKDIR /data SHELL ["/bin/bash", "-o", "pipefail", "-c"] RUN apk add --no-cache openjdk8-jre wget COPY rootfs / ADD datastore / ADD https://blueforcer.de/awtrix/stable/awtrix.jar /awtrix.jar EXPOSE 7000 EXPOSE 7001 CMD ["bashio" , "/run.sh"] <|start_filename|>awtrix-beta-server/Dockerfile<|end_filename|> ARG BUILD_FROM=hassioaddons/base:8.0.6 FROM $BUILD_FROM WORKDIR /data SHELL ["/bin/bash", "-o", "pipefail", "-c"] RUN apk add --no-cache openjdk11-jre wget nginx COPY rootfs / ADD https://blueforcer.de/awtrix/beta/awtrix.jar /beta.jar ADD https://blueforcer.de/awtrix/stable/awtrix.jar /stable.jar # Labels LABEL \ io.hass.name="Awtrix_host" \ io.hass.description="Server for the awtrix-8x32 RGB display." \ io.hass.type="addon" \ io.hass.version=${BUILD_VERSION}
lubeda/repository
<|start_filename|>script/run-unit-test-help.js<|end_filename|> /* eslint-disable no-console */ const commandLineUsage = require('command-line-usage'); const helpSections = [ { header: 'Unit test run script', }, { header: 'Examples', content: [ { desc: '1. Run all the unit tests ', example: '$ yarn test:unit', }, { desc: '2. Run tests for a specific app folder ', example: '$ yarn test:unit --app-folder vaos', }, { desc: '3. Run tests with extra error logging for a specific file', example: '$ yarn test:unit --log-level debug src/applications/vaos/tests/components/ExpressCareListItem.jsx', }, ], }, { header: 'Options', optionList: [ { name: 'log-level', typeLabel: '{underline log}, {underline debug}, {underline trace}', description: 'Set the log level for the unit test output. {underline debug} provides errors with stack traces scrubbed of node_modules lines.' + ' {underline trace} outputs all errors and warnings. Defaults to {underline log}, which hides errors outside of specific test failures', }, { name: 'coverage', typeLabel: '{underline boolean}', description: 'Runs the unit tests with code coverage metrics, and outputs the results to an html report in coverage/', }, { name: 'app-folder', typeLabel: '{underline folder name}', description: 'Run all tests in the specified folder in src/applications', defaultOption: true, }, { name: 'path', typeLabel: '{underline glob}', description: 'A file or glob to indicate which tests to run. This is the default option.', defaultOption: true, }, { name: 'help', typeLabel: '{underline boolean}', description: 'Show the usage guide', }, ], }, ]; module.exports = () => { console.log(commandLineUsage(helpSections)); }; <|start_filename|>src/platform/testing/unit/sentry.js<|end_filename|> import sentryTestkit from 'sentry-testkit'; export const { testkit, sentryTransport } = sentryTestkit(); <|start_filename|>src/site/constants/content-modeling.js<|end_filename|> /** * Represents the possible values for the "entityBundle" field * of Drupal (or generated) nodes. These values should align with * with the names of the files in the "src/site/layouts directory. */ const ENTITY_BUNDLES = { BASIC_LANDING_PAGE: 'basic_landing_page', BIOS_PAGE: 'bios_page', CHECKLIST: 'checklist', EVENT_LISTING: 'event_listing', EVENT: 'event', EVENTS_PAGE: 'events_page', FAQ_MULTIPLE_Q_A: 'faq_multiple_q_a', FULL_WIDTH_BANNER_ALERT: 'full_width_banner_alert', HEALTH_CARE_FACILITY_STATUS: 'health_care_facility_status', HEALTH_CARE_LOCAL_FACILITY: 'health_care_local_facility', HEALTH_CARE_LOCAL_HEALTH_SERVICE: 'health_care_local_health_service', HEALTH_CARE_REGION_DETAIL_PAGE: 'health_care_region_detail_page', HEALTH_CARE_REGION_LOCATIONS_PAGE: 'health_care_region_locations_page', HEALTH_CARE_REGION_PAGE: 'health_care_region_page', HEALTH_SERVICES_LISTING: 'health_services_listing', HOME: 'home', LANDING_PAGE: 'landing_page', LEADERSHIP_LISTING: 'leadership_listing', LOCATIONS_LISTING: 'locations_listing', MEDIA_LIST_IMAGES: 'media_list_images', MEDIA_LIST_VIDEOS: 'media_list_videos', NEWS_STORIES_PAGE: 'news_stories_page', NEWS_STORY: 'news_story', OFFICE: 'office', OUTREACH_ASSET: 'outreach_asset', PAGE: 'page', PERSON_PROFILE: 'person_profile', PRESS_RELEASE: 'press_release', PRESS_RELEASES_LISTING: 'press_releases_listing', PRESS_RELEASES_PAGE: 'press_releases_page', PUBLICATION_LISTING: 'publication_listing', Q_A: 'q_a', REGIONAL_HEALTH_CARE_SERVICE_DES: 'regional_health_care_service_des', STEP_BY_STEP: 'step_by_step', STORY_LISTING: 'story_listing', SUPPORT_RESOURCES_ARTICLE_LISTING: 'support_resources_article_listing', SUPPORT_RESOURCES_DETAIL_PAGE: 'support_resources_detail_page', SUPPORT_SERVICE: 'support_service', VA_FORM: 'va_form', VAMC_OPERATING_STATUS_AND_ALERTS: 'vamc_operating_status_and_alerts', }; module.exports = { ENTITY_BUNDLES, };
jbritt1/content-build
<|start_filename|>index.js<|end_filename|> /* MIT License http://www.opensource.org/licenses/mit-license.php Author <NAME> @bline */ var loaderUtils = require("loader-utils"); var Path = require('path'); module.exports = function(source) { this.cacheable && this.cacheable(true); var jade = require("jade"); var query = loaderUtils.parseQuery(this.query); var dirname = Path.dirname(this.resourcePath); var tmpl = jade.compileClientWithDependenciesTracked(source, { filename: this.resourcePath, self: query.self, pretty: query.pretty, locals: query, compileDebug: true, externalRuntime: false }); tmpl.dependencies.forEach(function(dep) { this.addDependency(dep); }.bind(this)); var opts = this.options; var loaders = opts.module ? opts.module.loaders : opts.resolve.loaders; var mopts = Object.keys(opts).reduce(function(acc, key) { acc[key] = opts[key]; return acc; }, {}); mopts.recursive = true; mopts.resolve = { loaders: loaders, extensions: opts.resolve.extensions, modulesDirectories: (opts.resolve.modulesDirectories || []).concat(opts.resolve.fallback || []) }; var er = 'var jade = require(' + resolve('jade/runtime') + ');\nrequire = require(' + resolve('enhanced-require') + ')(module, require(' + resolve('./json2regexp') + ')(' + JSON.stringify(mopts, toString) + '));\n'; var moduleBody = er + tmpl.body + '\n\nmodule.exports = template;\ntemplate.__require = require'; var mod = this.exec(moduleBody, this.resource); var _require = mod.__require; for (var file in _require.contentCache) { this.addDependency && this.addDependency(file); } return mod(query.locals || query); } function resolve(path) { return JSON.stringify(require.resolve(path)); } function toString(key, value) { if (!(value instanceof RegExp)) return value; return value.toString(); }
bline/jade-html-loader
<|start_filename|>kotlinpermissions/src/main/java/io/vrinda/kotlinpermissions/PermissionFragment.kt<|end_filename|> package io.vrinda.kotlinpermissions import android.content.pm.PackageManager import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.util.Log import android.widget.Toast /** * A simple [Fragment] subclass. * Activities that contain this fragment must implement the * [PermissionFragment.OnFragmentInteractionListener] interface * to handle interaction events. * Use the [PermissionFragment.newInstance] factory method to * create an instance of this fragment. */ abstract class PermissionFragment : Fragment() { private val REQUEST_PERMISSION = 1111 private val NEEDED_PERMISSIONS = 2222 var pCallback: PermissionCallBack? = null; var permissionsNeed: MutableList<String> = mutableListOf<String>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } fun AppCompatActivity.toast(msg: String) { Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show() } fun requestPermissions(arrays: Array<String>, permissionCallback: PermissionCallBack) { permissionsNeed.clear() pCallback = permissionCallback for (permission in arrays) { if (ActivityCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) { permissionsNeed.add(permission) } } if (permissionsNeed.size > 0) { Log.v("request", "permissions") reuestNeededPermission(permissionsNeed) } else { pCallback?.permissionGranted() // toast(activity,"Permissions Granted") } } fun requestPermissions(permission: String, permissionCallback: PermissionCallBack) { pCallback = permissionCallback if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { requestPermissions(arrayOf(permission), REQUEST_PERMISSION) } else { requestPermissions(arrayOf(permission), REQUEST_PERMISSION) } } fun reuestNeededPermission(permissionsNeed: MutableList<String>) { // if (ActivityCompat.shouldShowRequestPermissionRationale(this@PermissionsActivity,permissionsNeed.toTypedArray())) requestPermissions(permissionsNeed.toTypedArray(), NEEDED_PERMISSIONS) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (grantResults.isNotEmpty()) { Log.v("resultss", "" + grantResults[0] + grantResults.toString()) if (requestCode == REQUEST_PERMISSION) { if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Camera permission has been granted, preview can be displayed pCallback?.permissionGranted() } else { pCallback?.permissionDenied() } } else if (requestCode == NEEDED_PERMISSIONS) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { pCallback?.permissionGranted() } else { pCallback?.permissionDenied() } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } } }
AnirudhLoya/Kotlin-Android-Permissions
<|start_filename|>v1/onthisday.js<|end_filename|> 'use strict'; const P = require('bluebird'); const HyperSwitch = require('hyperswitch'); const Template = HyperSwitch.Template; const BaseFeed = require('../lib/base_feed'); const POSSIBLE_PARTS = [ 'selected', 'births', 'deaths', 'events', 'holidays' ]; const REQUEST_TEMPLATE = new Template({ uri: '{{options.host}}/{{domain}}/v1/feed/onthisday/{{type}}/{{mm}}/{{dd}}', headers: { 'accept-language': '{{accept-language}}' } }); class Feed extends BaseFeed { getDateAndKey(req) { return { date: undefined, // Never actually used key: `${req.params.mm}${req.params.dd}` }; } constructBody(result, req) { if (req.params.type === 'all') { const body = {}; Object.keys(result).forEach((key) => Object.assign(body, result[key].body)); return body; } return result.body; } _makeFeedRequests(hyper, req) { if (req.params.type === 'all') { const requests = {}; const reqCopy = Object.assign({}, req); POSSIBLE_PARTS.forEach((type) => { reqCopy.params = Object.assign({}, req.params, { type }); requests[type] = hyper.get(REQUEST_TEMPLATE.expand({ options: this.options, request: reqCopy })) .catch((e) => { hyper.logger.log('error/onthisday', { msg: `Error fetching ${type}`, error: e }); // Just ignore individual portions errors return undefined; }); }); return P.props(requests); } else { return hyper.get(REQUEST_TEMPLATE.expand({ options: this.options, request: req })); } } } const spec = HyperSwitch.utils.loadSpec(`${__dirname}/onthisday.yaml`); module.exports = (options) => { options.name = 'feed.onthisday'; // TODO: need a way to dynamically derive this options.content_type = 'application/json; charset=utf-8; ' + 'profile="https://www.mediawiki.org/wiki/Specs/onthisday-feed/0.5.0"'; options.spec = spec; return new Feed(options).getModuleDeclaration(); }; <|start_filename|>v1/lists.js<|end_filename|> 'use strict'; const P = require('bluebird'); const mwUtil = require('../lib/mwUtil'); const Title = require('mediawiki-title').Title; const HyperSwitch = require('hyperswitch'); const URI = HyperSwitch.URI; const spec = HyperSwitch.utils.loadSpec(`${__dirname}/lists.yaml`); class ReadingLists { /** * @param {!Object} options RESTBase options object. */ constructor(options) { this.options = options; } /** * Transform the continuation data into a string so it is easier for clients to deal with. * @param {!Object|undefined} continuation Continuation object returned by the MediaWiki API. * @return {!string|undefined} Continuation string. */ flattenContinuation(continuation) { return JSON.stringify(continuation); } /** * Inverse of flattenContinuation. * @param {!string|undefined} continuation Continuation string returned by * flattenContinuation() * @return {!Object} Continuation object. */ unflattenContinuation(continuation) { const sanitizedContinuation = {}; if (typeof continuation === 'string') { try { continuation = JSON.parse(continuation); // Make sure nothing malicious can be done by splicing the continuation data // into the API parameters. const allowedKeys = ['continue', 'rlcontinue', 'rlecontinue']; for (const key of allowedKeys) { if (typeof continuation[key] !== 'object') { sanitizedContinuation[key] = continuation[key]; } } } catch (e) { this.options.logger.log('error/unflatten', { msg: e.message, json: continuation }); throw new HyperSwitch.HTTPError({ status: 400, body: { type: 'server_error#invalid_paging_parameter', title: 'Invalid paging parameter', parameter: continuation } }); } } return sanitizedContinuation; } /** * Convert an array of values into the format expected by the MediaWiki API. * @param {!Array} list A list containing strings and numbers. * @return {!string} */ flattenMultivalue(list) { return list.join('|'); } /** * Takes an array of integers and formats them as an array of {<keyword>: <id>} objects. * @param {!Array} ids * @param {!string} keyword * @return {!Array} */ idsToObjects(ids, keyword) { return ids.map((id) => { // If the MW API has been updated to send objects, handle that gracefully. if (typeof id === 'object') { return id; } const o = {}; o[keyword] = id; return o; }); } /** * Get the sort parameters for the action API. * @param {!string} sort Sort mode ('name' or 'updated'). * @return {!Object} { sort: <rlsort/rlesort parameter>, dir: <rldir/rledir parameter> } */ getSortParameters(sort) { sort = sort || 'updated'; return { sort, dir: (sort === 'updated') ? 'descending' : 'ascending' }; } /** * Get a timestamp that's safe to use in GET /lists/changes/since/{timestamp} assuming * the client's state is based on the current response. This deals with things database rows * items being committed in a different order than their 'created' fields would suggest. * See T182706 for details. * * Normally the timstamp is just copied from the MediaWiki response, but for a transition * period we are going to generate it. * @param {!Object} responseBody The response object body. * @param {!string} next The continuation parameter submitted by the client. * @return {!string} An ISO 8601 timestamp. */ getContinueFrom(responseBody, next) { const timestamp = responseBody.query['readinglists-synctimestamp']; // Honor timestamps sent by the MW API. if (timestamp) { return timestamp; } // On continuation, it is expected to not have a timestamp - the client already received // it in an earlier request. if (next) { return undefined; } // Backdate by $wgMaxUserDBWriteDuration + 1 seconds. const lastSafeTime = new Date(Date.now() - 4000); return lastSafeTime.toISOString(); } /** * Handle the /list/{id}/entries endpoint (get entries of a list). * @param {!HyperSwitch} hyper * @param {!Object} req The request object as provided by HyperSwitch. * @return {!Promise<Object>} A response promise. */ getListEntries(hyper, req) { const sortParameters = this.getSortParameters(req.query.sort); return hyper.post({ uri: new URI([req.params.domain, 'sys', 'action', 'rawquery']), body: { action: 'query', list: 'readinglistentries', rlelists: req.params.id, rlesort: sortParameters.sort, rledir: sortParameters.dir, rlelimit: 'max', continue: this.unflattenContinuation(req.query.next).continue, rlecontinue: this.unflattenContinuation(req.query.next).rlecontinue } }) .then((res) => { const entries = res.body.query.readinglistentries; const next = this.flattenContinuation(res.body.continue); return this.hydrateSummaries({ status: 200, headers: { 'content-type': 'application/json; charset=utf-8;' + 'profile="https://www.mediawiki.org/wiki/Specs/Lists/0.1"', 'cache-control': 'max-age=0, s-maxage=0' }, body: { entries, next } }, hyper, req); }); } /** * Add data from the summary endpoint to an array of list entries. * @param {!Object} res Response object. * @param {!HyperSwitch} hyper Hyperswitch context * @param {!Object} req The request object as provided by HyperSwitch. * @return {!Promise<Array>} The objects, enriched with summaries. */ hydrateSummaries(res, hyper, req) { return P.map(res.body.entries, (entry) => { return mwUtil.getSiteInfo(hyper, req, entry.project).then((siteinfo) => { const title = Title.newFromText(entry.title, siteinfo).getPrefixedDBKey(); entry.summary = { $merge: [ `${siteinfo.baseUri}/page/summary/${encodeURIComponent(title)}` ] }; }).catch(() => {}); }) .then(() => mwUtil.hydrateResponse(res, (uri) => { return mwUtil.fetchSummary(hyper, uri).then((result) => { return result && result.summary; }); })); } } module.exports = (options) => { const rl = new ReadingLists(options); return { spec, globals: { options, flattenContinuation: rl.flattenContinuation.bind(rl), unflattenContinuation: rl.unflattenContinuation.bind(rl), flattenMultivalue: rl.flattenMultivalue.bind(rl), idsToObjects: rl.idsToObjects.bind(rl), stringify: JSON.stringify.bind(JSON), getSortParameters: rl.getSortParameters.bind(rl), getContinueFrom: rl.getContinueFrom.bind(rl) }, operations: { getListEntries: rl.getListEntries.bind(rl) } }; }; <|start_filename|>test/features/pagecontent/access_checks.js<|end_filename|> 'use strict'; /* eslint-disable max-len */ const assert = require('../../utils/assert.js'); const preq = require('preq'); const Server = require('../../utils/server.js'); const nock = require('nock'); // TODO: add support for nocked tests const NOCK_TESTS = false; // because of Parsoid/PHP which uses the same URI structure as the MW API describe('Access checks', () => { const server = new Server(); const deletedPageTitle = 'User:Pchelolo/Access_Check_Tests'; const deletedPageOlderRevision = 409433; const deletedPageRevision = 409434; const emptyResponse = { 'batchcomplete': '', 'query': { 'badrevids': { '292466': { 'revid': '292466' } } } }; function setUpNockResponse(api, title, revision) { if (!NOCK_TESTS) { return api; } return api.post('') .reply(200, { 'batchcomplete': '', 'query': { 'pages': { '49453581': { 'pageid': 49453581, 'ns': 0, title, 'pagelanguage': 'en', 'touched': '2015-05-22T08:49:39Z', 'lastrevid': revision, 'length': 2941, 'revisions': [{ 'revid': revision, 'user': '<NAME>', 'userid': 3606755, 'timestamp': '2015-03-25T20:29:50Z', 'size': 2941, 'sha1': 'c47571122e00f28402d2a1b75cff77a22e7bfecd', 'comment': 'Test', 'tags': [] }] } } } }); } before(() => { if (!nock.isActive()) { nock.activate(); } return server.start() // Do a preparation request to force siteinfo fetch so that we don't need to mock it .then(() => preq.get({ uri: `${server.config.bucketURL()}/html/Main_Page`, headers: { 'cache-control': 'no-cache' } })) // Load in the revisions .then(() => { let api = nock(server.config.apiURL()); api = setUpNockResponse(api, deletedPageTitle, deletedPageOlderRevision); api = setUpNockResponse(api, deletedPageTitle, deletedPageRevision); return preq.get({ uri: `${server.config.bucketURL()}/html/${encodeURIComponent(deletedPageTitle)}/${deletedPageOlderRevision}`, headers: { 'cache-control': 'no-cache' } }) .then((res) => { assert.deepEqual(res.status, 200); return preq.get({ uri: `${server.config.bucketURL()}/html/${encodeURIComponent(deletedPageTitle)}/${deletedPageRevision}`, headers: { 'cache-control': 'no-cache' } }); }) .then(res => assert.deepEqual(res.status, 200)) .then(() => api.done()) .finally(() => nock.cleanAll()); }); }); after(() => server.stop()); describe('Deleting', () => { it('should understand the page was deleted', () => { const api = nock(server.config.apiURL()) // Other requests return nothing as if the page is deleted. .post('').reply(200, emptyResponse); // Fetch the page return preq.get({ uri: `${server.config.bucketURL()}/title/${encodeURIComponent(deletedPageTitle)}`, headers: { 'cache-control': 'no-cache' } }) .then(() => { throw new Error('404 should have been returned for a deleted page'); }, (e) => { assert.deepEqual(e.status, 404); assert.contentType(e, 'application/problem+json'); }) .then(() => api.done()) .finally(() => nock.cleanAll()); }); }); function testAccess(contentVariant, restrictionType, title, rev) { let name = `should restrict access to ${restrictionType} page `; name += rev ? 'older revision' : 'latest'; name += ` ${contentVariant}`; it(name, () => { // Check that access is enforced to html let uri = `${server.config.bucketURL()}/${contentVariant}/${encodeURIComponent(title)}`; if (rev) { uri += `/${rev}`; } return preq.get({ uri }) .then((res) => { throw new Error('404 should have been returned for a deleted page'); }, (e) => { assert.deepEqual(e.status, 404); assert.contentType(e, 'application/problem+json'); }); }); } describe('Checking deletions', () => { it('should restrict access to deleted page latest revision', () => { // This is only required until the hack for no-cache header is in place const api = nock(server.config.apiURL()) .post('').reply(200, emptyResponse); return preq.get({ uri: `${server.config.bucketURL()}/title/${encodeURIComponent(deletedPageTitle)}/${deletedPageRevision}` }) .then(() => { throw new Error('404 should have been returned for a deleted page'); }, (e) => { assert.deepEqual(e.status, 404); assert.contentType(e, 'application/problem+json'); }) .then(() => api.done()) .finally(() => nock.cleanAll()); }); it('should restrict access to older revision of a deleted page', () => { // This is only required until the hack for no-cache header is in place const api = nock(server.config.apiURL()) .post('').reply(200, emptyResponse); return preq.get({ uri: `${server.config.bucketURL()}/title/${encodeURIComponent(deletedPageTitle)}/${deletedPageOlderRevision}` }) .then(() => { throw new Error('404 should have been returned for a deleted page'); }, (e) => { assert.deepEqual(e.status, 404); assert.contentType(e, 'application/problem+json'); }) .then(() => api.done()) .finally(() => nock.cleanAll()); }); testAccess('html', 'deleted', deletedPageTitle); testAccess('data-parsoid', 'deleted', deletedPageTitle); testAccess('html', 'deleted', deletedPageTitle, deletedPageOlderRevision); testAccess('data-parsoid', 'deleted', deletedPageTitle, deletedPageOlderRevision); testAccess('mobile-sections', 'deleted', deletedPageTitle); testAccess('mobile-sections-lead', 'deleted', deletedPageTitle); testAccess('mobile-sections-remaining', 'deleted', deletedPageTitle); testAccess('summary', 'deleted', deletedPageTitle); testAccess('mobile-html', 'deleted', deletedPageTitle); }); describe('Undeleting', () => { it('Should understand that the page was undeleted', () => { return preq.get({ uri: `${server.config.bucketURL()}/title/${encodeURIComponent(deletedPageTitle)}`, headers: { 'cache-control': 'no-cache' } }) .then((res) => { assert.deepEqual(res.status, 200); return preq.get({ uri: `${server.config.bucketURL()}/html/${encodeURIComponent(deletedPageTitle)}/${deletedPageOlderRevision}`, }); }) .then((res) => { assert.deepEqual(res.status, 200); }); }); it('should understand the page was deleted again', () => { const api = nock(server.config.apiURL()) // Other requests return nothing as if the page is deleted. .post('').reply(200, emptyResponse); // Fetch the page return preq.get({ uri: `${server.config.bucketURL()}/title/${encodeURIComponent(deletedPageTitle)}`, headers: { 'cache-control': 'no-cache' } }) .then(() => { throw new Error('404 should have been returned for a deleted page'); }, (e) => { assert.deepEqual(e.status, 404); assert.contentType(e, 'application/problem+json'); }) .then(() => api.done()) .finally(() => nock.cleanAll()); }); it('Should understand that the page was undeleted base on html request', () => { return preq.get({ uri: `${server.config.bucketURL()}/html/${encodeURIComponent(deletedPageTitle)}`, headers: { 'cache-control': 'no-cache' } }) .then((res) => { assert.deepEqual(res.status, 200); return preq.get({ uri: `${server.config.bucketURL()}/html/${encodeURIComponent(deletedPageTitle)}/${deletedPageOlderRevision}`, }); }) .then((res) => { assert.deepEqual(res.status, 200); }); }); }); describe('Restricting', () => { const pageTitle = 'User:Pchelolo/restriction_testing_mock'; const pageRev = 301375; it('should correctly fetch updated restrictions', () => { const normalRev = { "revid": pageRev, "user": "Pchelolo", "userid": 6591, "timestamp": "2015-02-03T21:15:55Z", "size": 7700, "tags": [] }; const normalResponse = { "pageid": 152993, "ns": 3, "title": pageTitle, "pagelanguage": "en", "pagelanguagehtmlcode": "en", "pagelanguagedir": "ltr", "touched": "2015-12-10T23:41:54Z", "lastrevid": pageRev, "length": 23950, "revisions": [normalRev] }; const restrictedRev = Object.assign({}, normalRev); restrictedRev.texthidden = true; restrictedRev.sha1hidden = true; const restrictedResponse = Object.assign({}, normalResponse); restrictedResponse.revisions = [restrictedRev]; const api = nock(server.config.apiURL('en.wikipedia.beta.wmflabs.org')) .post('').reply(200, { "batchcomplete": "", "query": { "pages": { "45161196": normalResponse } } }).post('').reply(200, { "batchcomplete": "", "query": { "pages": { "45161196": restrictedResponse } } }); // First fetch a non-restricted revision return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}/title/${encodeURIComponent(pageTitle)}` }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(res.body.items.length, 1); // Now fetch update with restrictions return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}/title/${encodeURIComponent(pageTitle)}`, headers: { 'cache-control': 'no-cache' } }); }).then(() => { throw new Error('403 should be thrown'); }, (e) => { assert.deepEqual(e.status, 403); }).then(() => api.done()) .finally(() => nock.cleanAll()); }); it('should store updated restrictions', () => { return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}/html/${encodeURIComponent(pageTitle)}` }) .then(() => { throw new Error('403 should be thrown'); }, (e) => { assert.deepEqual(e.status, 403); }); }); it('should restrict access to restricted revision html', () => { return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}/html/${encodeURIComponent(pageTitle)}/${pageRev}` }) .then(() => { throw new Error('403 should have been returned for a deleted page'); }, (e) => { assert.deepEqual(e.status, 403); assert.contentType(e, 'application/problem+json'); }); }); it('should allow to view content if restrictions disappeared', () => { return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}/title/${encodeURIComponent(pageTitle)}`, headers: { 'cache-control': 'no-cache' } }) .then((res) => { assert.deepEqual(res.status, 200); return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}/html/${encodeURIComponent(pageTitle)}/${pageRev}`, }); }) .then((res) => { assert.deepEqual(res.status, 200); }); }); }); }); <|start_filename|>v1/pdf.js<|end_filename|> 'use strict'; const HyperSwitch = require('hyperswitch'); const spec = HyperSwitch.utils.loadSpec(`${__dirname}/pdf.yaml`); /** * PDF filename formatting / escaping utilities. */ module.exports = (options) => ({ spec, globals: { options, filenameParameters(name) { // Return two parameters const encodedName = `${encodeURIComponent(name)}.pdf`; const quotedName = `"${encodedName.replace(/"/g, '\\"')}"`; return `filename=${quotedName}; filename*=UTF-8''${encodedName}`; } } }); <|start_filename|>test/features/pagecontent/rerendering.js<|end_filename|> 'use strict'; const assert = require('../../utils/assert.js'); const preq = require('preq'); const Server = require('../../utils/server.js'); const P = require('bluebird'); function getTid(etag) { return /^"[^\/]+\/([^"]+)"/.exec(etag)[1]; } describe('page re-rendering', function() { this.timeout(20000); const server = new Server(); before(() => server.start()); after(() => server.stop()); // A test page that includes the current date, so that it changes if // re-rendered more than a second apart. const dynamic1 = '/html/User:Pchelolo%2fDate/275850'; const dynamic2 = '/html/User:Pchelolo%2fDate/275851'; function hasTextContentType(res) { assert.contentType(res, server.config.conf.test.content_types.html); } it('should render & re-render independent revisions', () => { let r1etag1; let r1etag2; let r2etag1; return preq.get({uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${dynamic1}?stash=true`}) .then((res) => { assert.deepEqual(res.status, 200); r1etag1 = res.headers.etag; hasTextContentType(res); // delay for 1s to make sure that the timestamp differs on re-render return P.delay(1500) .then(() => { return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${dynamic1}?stash=true`, headers: { 'cache-control': 'no-cache' } }); }); }) .then((res) => { // Since this is a dynamic page which should render the same each // time, the tid should not change. r1etag2 = res.headers.etag; assert.notDeepEqual(r1etag2, r1etag1); assert.notDeepEqual(r1etag2, undefined); hasTextContentType(res); return preq.get({uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${dynamic1}}`}); }) .then((res) => { assert.deepEqual(res.headers.etag, r1etag2); hasTextContentType(res); return preq.get({uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${dynamic2}?stash=true`}); }) .then((res) => { r2etag1 = res.headers.etag; assert.deepEqual(res.status, 200); hasTextContentType(res); return preq.get({uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${dynamic2}`}); }) .then((res) => { assert.deepEqual(res.headers.etag, r2etag1); hasTextContentType(res); }); }); it('should render & re-render independent revisions, if-unmodified-since support', () => { return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${dynamic2}`, headers: { 'cache-control': 'no-cache', 'if-unmodified-since': 'Wed, 11 Dec 2013 16:00:00 GMT', } }) .then(() => { throw new Error('Expected a precondition failure'); }, (res) => { assert.deepEqual(res.status, 412); }); }); // A static test page const static1 = '/html/User:Pchelolo%2fStatic/275852'; const static2 = '/html/User:Pchelolo%2fStatic/275853'; it('should render & re-render independent revisions, but not update unchanged content', () => { let r1etag1; let r1etag2; let r2etag1; let tid; return preq.get({uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${static1}?stash=true`}) .then((res) => { assert.deepEqual(res.status, 200); r1etag1 = res.headers.etag; hasTextContentType(res); return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${static1}?stash=true`, headers: { 'cache-control': 'no-cache' } }); }) .then((res) => { // Since this is a static page which should render the same each // time, the tid should not change. r1etag2 = res.headers.etag; assert.deepEqual(r1etag2, r1etag1); assert.notDeepEqual(r1etag2, undefined); hasTextContentType(res); return preq.get({uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${static1}`}); }) .then((res) => { assert.deepEqual(res.headers.etag, r1etag1); hasTextContentType(res); return preq.get({uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${static1}`}); }) .then((res) => { assert.deepEqual(res.headers.etag, r1etag2); hasTextContentType(res); return preq.get({uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${static1}`}); }) .then((res) => { assert.deepEqual(res.headers.etag, r1etag2); hasTextContentType(res); return preq.get({uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${static2}?stash=true`}); }) .then((res) => { r2etag1 = res.headers.etag; assert.deepEqual(res.status, 200); hasTextContentType(res); return preq.get({uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}${static2}`}); }) .then((res) => { assert.deepEqual(res.headers.etag, r2etag1); hasTextContentType(res); }); }); }); <|start_filename|>test/features/mwutils.js<|end_filename|> 'use strict'; /** * Unit tests for util methods */ const P = require('bluebird'); const mwUtil = require('../../lib/mwUtil'); const assert = require('../utils/assert'); describe('Utils.hydrateResponse', () => { it('Should support $merge', () => { const response = { body: { non_existent: { $merge: ['you_shall_not_pass'] }, array: [ { $merge: ['you_shall_not_pass'] }, { $merge: ['you_shall_not_pass'] }, { prop: 'this_will_be_overwritten', $merge: ['prop_contained_here'] } ], object: { some_other_prop: 'hello', $merge: ['prop_contained_here'] } } }; return mwUtil.hydrateResponse(response, (uri) => { switch (uri) { case 'you_shall_not_pass': return P.resolve(undefined); case 'prop_contained_here': return P.resolve({ prop: 'prop_value' }); default: return P.reject(new Error('What?')); } }) .then((response) => { assert.deepEqual(response, { body: { array: [{ prop: 'prop_value' }], object: { some_other_prop: 'hello', prop: 'prop_value' } } }); }); }); }); describe('Utils.removeDuplicateTitles', () => { it('deduplicates and applies update function', () => { const data = [ { title: 'Foo', count: 1 }, { title: 'Foo', count: 1 } ]; const update = (orig, dupe) => { orig.count += dupe.count; return orig; }; const result = mwUtil.removeDuplicateTitles(data, update); assert.deepEqual(result.length, 1); assert.deepEqual(result[0].count, 2); }); }); <|start_filename|>test/utils/assert.js<|end_filename|> 'use strict'; const assert = require('assert'); const nock = require('nock'); const mwUtil = require('../../lib/mwUtil'); /** * Asserts whether content type was as expected */ function contentType(res, expected) { const actual = res.headers['content-type']; if (/^\/.+\/$/.test(expected)) { const expectedRegex = mwUtil.constructRegex([ expected ]); assert.ok(expectedRegex.test(actual), `Expected content type should match ${expected}`); } else { deepEqual(actual, expected, `Expected content-type to be ${expected} , but was ${actual}`); } } function recordRequests() { nock.recorder.rec({ dont_print: true, output_objects: true }) } function cleanupRecorder() { nock.restore(); nock.recorder.clear(); } /** * Asserts whether some requests in the given * slice were made to remote entities */ function remoteRequests(expected) { const remoteReqs = nock.recorder.play().some((req) => req && !/localhost/.test(req.scope)); deepEqual( remoteReqs, expected, expected ? 'Should have made a remote request' : 'Should not have made a remote request' ); } /** * Finds the first request to parsoid */ function findParsoidRequest() { return nock.recorder.play().find(function(line) { return line.slice && /^https?:\/\/parsoid/.test(line.scope); }); } function findRequests(predicate) { return nock.recorder.play().filter(predicate); } function isDeepEqual(result, expected, message) { try { if (typeof expected === 'string') { assert.ok(result === expected || (new RegExp('^' + expected + '$').test(result)), message); } else { assert.deepEqual(result, expected, message); } return true; } catch (e) { return false; } } function deepEqual(result, expected, message) { try { if (typeof expected === 'string') { assert.ok(result === expected || (new RegExp('^' + expected + '$').test(result))); } else { assert.deepEqual(result, expected, message); } } catch (e) { console.log('Expected:\n' + JSON.stringify(expected,null,2)); console.log('Result:\n' + JSON.stringify(result,null,2)); throw e; } } function isSuperset(parent, child) { var result = true; if (child instanceof Object) { for (var k in child) { isSuperset(parent[k], child[k]); } } else if (child instanceof Array) { for (var i = 0; i < child.length; i++) { isSuperset(parent[i], child[i]); } } else { deepEqual(parent, child); } } function notDeepEqual(result, expected, message) { try { assert.notDeepEqual(result, expected, message); } catch (e) { console.log('Not expected:\n' + JSON.stringify(expected,null,2)); console.log('Result:\n' + JSON.stringify(result,null,2)); throw e; } } function fails(promise, onRejected) { var failed = false; function trackFailure(e) { failed = true; return onRejected(e); } function check() { if (!failed) { throw new Error('expected error was not thrown'); } } return promise.catch(trackFailure).then(check); } function checkString(result, expected, message) { if (expected.constructor === RegExp) { assert.ok(expected.test(result), '' + expected + '.test(' + result + ') fails'); } else { var de = assert.deepStrictEqual || assert.deepEqual; de(result, expected, expected + ' !== ' + result); } } /** * Validates the comma-separated list of header names. * @param {string} headerList the list of header names * @param {Object} options the validator options * @param {array=} options.require list of header names required to be present. * Example: [ 'Accept', 'Accept-Encoding']. * Case-insensitive. * @param {array=} options.disallow list of header names NOT allowed. * Example: [ 'Accept-Language' ]. Case-insensitive. * @param {boolean} [options.allowDuplicates] whether duplicated entries could be present in * the `headerList`. Default: false **/ function validateListHeader(headerList, options) { if (!headerList) { throw new assert.AssertionError({ message: `Can not validate with empty headers` }); } if (headerList === '') { throw new assert.AssertionError({ message: `Header list should not be an empty string ('')` }); } const headerArray = headerList.split(',').map(header => header.trim().toLowerCase()); if (options.require) { options.require.forEach(header => { if (!headerArray.includes(header.trim().toLowerCase())) { throw new assert.AssertionError({ message: `Header does not contain ${header}` }); } }); } if (options.disallow) { options.disallow.forEach(header => { if (headerArray.includes(header.trim().toLowerCase())) { throw new assert.AssertionError({ message: `Header contains ${header} while it must not` }); } }); } if (!options.allowDuplicates) { const filterDuplicates = headerArray.filter((header, index) => headerArray.indexOf(header) === index); if (filterDuplicates.length !== headerArray.length) { throw new assert.AssertionError({ message: `${headerList} contains duplicates` }); } } } module.exports.ok = assert.ok; module.exports.AssertionError = assert.AssertionError; module.exports.fails = fails; module.exports.deepEqual = deepEqual; module.exports.isDeepEqual = isDeepEqual; module.exports.notDeepEqual = notDeepEqual; module.exports.isSuperset = isSuperset; module.exports.contentType = contentType; module.exports.recordRequests = recordRequests; module.exports.cleanupRecorder = cleanupRecorder; module.exports.remoteRequests = remoteRequests; module.exports.findParsoidRequest = findParsoidRequest; module.exports.findRequests = findRequests; module.exports.checkString = checkString; module.exports.validateListHeader = validateListHeader; <|start_filename|>test/features/router/misc.js<|end_filename|> 'use strict'; const assert = require('../../utils/assert.js'); const preq = require('preq'); const Server = require('../../utils/server.js'); function getHeader(res, name) { if (res.rawHeaders.indexOf(name) === -1) { return undefined; } return res.rawHeaders[res.rawHeaders.indexOf(name) + 1]; } describe('router - misc', function() { this.timeout(100000); const server = new Server(); before(() => server.start()); after(() => server.stop()); it('should deny access to /{domain}/sys', () => { return preq.get({uri: `${server.config.hostPort}/${server.config.defaultDomain}/sys/action/query`}) .catch((err) => { assert.deepEqual(err.status, 403); }); }); it('should set a request ID for each sub-request and return it', () => { assert.recordRequests(); return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}/html/Foobar`, headers: { 'Cache-Control': 'no-cache' } }) .then((res) => { const reqId = res.headers['x-request-id']; assert.notDeepEqual(reqId, undefined, 'Request ID not returned'); assert.findRequests(() => {}).forEach((req) => { assert.deepEqual(req.headers['x-request-id'], reqId, 'Request ID mismatch'); }); }) .finally(() => assert.cleanupRecorder()); }); it('should honour the provided request ID', () => { assert.recordRequests(); const reqId = 'b6c17ea83d634b31bb28d60aae1caaac'; return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}/html/Foobar`, headers: { 'X-Request-Id': reqId } }).then((res) => { assert.deepEqual(res.headers['x-request-id'], reqId, 'Returned request ID does not match the sent one'); assert.findRequests(() => true).forEach((req) => { assert.deepEqual(getHeader(req, 'x-request-id'), reqId, 'Request ID mismatch'); }); }) .finally(() => assert.cleanupRecorder()); }); it('should set the request ID for a 404', () => { const reqId = '9c54ff673d634b31bb28d60aae1cb43c'; assert.recordRequests(); return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}/foo-bucket/Foobar`, headers: { 'X-Request-Id': reqId } }).then((res) => { throw new Error(`Expected a 404, got ${res.status}`); }, (err) => { assert.deepEqual(err.headers['x-request-id'], reqId, 'Returned request ID does not match the sent one'); assert.findRequests(() => true).forEach((req) => { assert.deepEqual(getHeader(req, 'x-request-id'), reqId, 'Request ID mismatch'); }); }) .finally(() => assert.cleanupRecorder()); }); it('should truncate body upon HEAD request', () => { return preq.head({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}/html/Foobar` }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(res.headers['content-length'], undefined); assert.deepEqual(res.body, ''); }); }); it('should only use unique operationId', () => { return preq.get({ uri: `${server.config.baseURL()}/?spec` }) .then((res) => { const spec = res.body; const operations = []; Object.keys(spec.paths).forEach((path) => { const pathSpec = spec.paths[path]; Object.keys(pathSpec).forEach((method) => { const operationId = pathSpec[method].operationId; if (operationId) { if (operations.includes(operationId)) { throw new assert.AssertionError({ message: `Duplicated operationId ${operationId} at path ${path}:${method}` }); } operations.push(operationId); } }) }); }) }); }); <|start_filename|>test/features/security/security.js<|end_filename|> 'use strict'; const assert = require('../../utils/assert.js'); const preq = require('preq'); const Server = require('../../utils/server.js'); const nock = require('nock'); const P = require('bluebird'); describe('router - security', function() { this.timeout(20000); const server = new Server(); before(() => { if (!nock.isActive()) { nock.activate(); } return server.start() .then(() => { // Do preparation requests to force siteInfo fetch so that we don't need to mock it return P.join( preq.get({uri: `${server.config.bucketURL()}/title/Main_Page`}), preq.get({uri: `${server.config.bucketURL('ru.wikipedia.beta.wmflabs.org')}/title/${encodeURIComponent('Заглавная_страница')}`}) ); }); }); after(() => server.stop()); const sampleRightsResponse = { batchcomplete: '', query: { userinfo: { id: 1, name: 'Petr', rights: ['createaccount','read','edit'] } } }; const sampleApiResponse = { query: { pages: { '1': { ns: 0, pageid: 1, revisions: [1], title: 'test' } } } }; it('should forward cookies on request to api', () => { nock.enableNetConnect(); const apiURI = server.config.apiURL('ru.wikipedia.beta.wmflabs.org'); const api = nock(apiURI, { reqheaders: { cookie: 'test=test_cookie' } }) .post('', (body) => { return body && body.generator === 'allpages'; }) .reply(200, sampleApiResponse) .post('', (body) => { return body && body.meta === 'userinfo'; }) .reply(200, sampleRightsResponse) .post('', (body) => { return body && body.meta === 'userinfo'; }) .optionally() .reply(200, sampleRightsResponse); return preq.get({ uri: `${server.config.bucketURL('ru.wikipedia.beta.wmflabs.org')}/title/`, headers: { 'Cookie': 'test=test_cookie' } }) .then(() => { api.done(); }) .finally(() => { nock.cleanAll(); }); }); it('should forward cookies on request to parsoid', () => { nock.enableNetConnect(); const title = 'Б'; const revision = 1831; const api = nock(server.config.parsoidURI, { reqheaders: { cookie: 'test=test_cookie', host: 'ru.wikipedia.beta.wmflabs.org' } }) .get(`/ru.wikipedia.beta.wmflabs.org/v3/page/pagebundle/${encodeURIComponent(title)}/${revision}`) .reply(200, () => { return { 'html': { 'headers': { 'content-type': 'text/html' }, 'body': '<html></html>' }, 'data-parsoid': { 'headers': { 'content-type': 'application/json' }, 'body': { 'counter': 1, 'ids': { 'mwAA': { 'dsr': [0, 1, 0, 0] } }, 'sectionOffsets': { 'mwAQ': { 'html': [0, 1], 'wt': [2, 3] } } } } }; }); return preq.get({ uri: `${server.config.bucketURL('ru.wikipedia.beta.wmflabs.org')}/html/${encodeURIComponent(title)}/${revision}`, headers: { 'Cookie': 'test=test_cookie', 'Cache-control': 'no-cache' } }) .then(() => { api.done(); }) .finally(() => { nock.cleanAll(); }); }); it('should not forward cookies to external domains', () => { const externalURI = 'https://www.mediawiki.org'; nock.enableNetConnect(); const api = nock(externalURI, { badheaders: ['cookie'], }) .get('/') .reply(200); return preq.get({ uri: `${server.config.baseURL('fake.fakepedia.org')}/http/${encodeURIComponent(externalURI)}`, headers: { 'cookie': 'test=test_cookie' } }) .then(() => { api.done(); }) .finally(() => { nock.cleanAll(); }); }); it('should not send cookies to non-restricted domains', () => { const api = nock(server.config.apiURL(), { badheaders: ['cookie'] }) .post('', (body) => { return body && body.generator === 'allpages'; }) .reply(200, sampleApiResponse); return preq.get({ uri: `${server.config.bucketURL()}/title/`, headers: { 'Cookie': 'test=test_cookie' } }) .then(() => { api.done(); }) .finally(() => { nock.cleanAll(); }); }); it('should deny access to resources stored in restbase', () => { nock.enableNetConnect(); const title = 'TestingTitle'; const api = nock(server.config.apiURL('ru.wikipedia.beta.wmflabs.org')) .post('') .reply(200, { 'query': { 'userinfo': { 'id': 1, 'name': 'test', 'rights': ['som right', 'some other right'] } } }); return preq.get({ uri: `${server.config.bucketURL('ru.wikipedia.beta.wmflabs.org')}/title/${title}`, headers: { 'cache-control': 'no-cache' } }) .then(() => { throw new Error('Access denied should be posted'); }) .catch((e) => { assert.deepEqual(e.status, 401); assert.contentType(e, 'application/problem+json'); assert.deepEqual(e.body.detail.indexOf('read') >= 0, true); }) .then(() => { api.done(); }) .finally(() => { nock.cleanAll(); }); }); }); <|start_filename|>test/features/mobileapps.js<|end_filename|> 'use strict'; const assert = require('../utils/assert.js'); const Server = require('../utils/server.js'); const preq = require('preq'); describe('Mobile Content Service', () => { const server = new Server(); before(() => server.start()); after(() => server.stop()); const pageTitle = 'Foobar'; const pageRev = 385014; it('Should fetch latest mobile-sections', () => { return preq.get({ uri: `${server.config.bucketURL()}/mobile-sections/${pageTitle}` }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(/^application\/json/.test(res.headers['content-type']), true); assert.deepEqual(!!res.headers.etag, true); assert.deepEqual(!!res.body.lead, true); assert.deepEqual(!!res.body.remaining, true); }); }); it('Should fetch latest mobile-sections-lead', () => { return preq.get({ uri: `${server.config.bucketURL()}/mobile-sections-lead/${pageTitle}` }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(/^application\/json/.test(res.headers['content-type']), true); assert.deepEqual(!!res.headers.etag, true); }); }); it('Should fetch latest mobile-sections-remaining', () => { return preq.get({ uri: `${server.config.bucketURL()}/mobile-sections-remaining/${pageTitle}` }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(/^application\/json/.test(res.headers['content-type']), true); assert.deepEqual(!!res.headers.etag, true); }); }); it('Should fetch older mobile-sections', () => { return preq.get({ uri: `${server.config.bucketURL()}/mobile-sections/${pageTitle}/${pageRev}` }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(/^application\/json/.test(res.headers['content-type']), true); assert.deepEqual(new RegExp(`^"${pageRev}\/.+"$`).test(res.headers.etag), true); assert.deepEqual(!!res.body.lead, true); assert.deepEqual(!!res.body.remaining, true); assert.deepEqual(res.body.lead.revision, pageRev); }); }); it('Should fetch older mobile-sections-lead', () => { return preq.get({ uri: `${server.config.bucketURL()}/mobile-sections-lead/${pageTitle}/${pageRev}` }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(/^application\/json/.test(res.headers['content-type']), true); assert.deepEqual(new RegExp(`^"${pageRev}\/.+"$`).test(res.headers.etag), true); assert.deepEqual(res.body.revision, pageRev); }); }); it('Should fetch older mobile-sections-remaining', () => { return preq.get({ uri: `${server.config.bucketURL()}/mobile-sections-remaining/${pageTitle}/${pageRev}` }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(/^application\/json/.test(res.headers['content-type']), true); assert.deepEqual(new RegExp(`^"${pageRev}\/.+"$`).test(res.headers.etag), true); }); }); }); <|start_filename|>lib/content_location_filter.js<|end_filename|> 'use strict'; const HyperSwitch = require('hyperswitch'); const HTTPError = HyperSwitch.HTTPError; const URI = HyperSwitch.URI; const mwUtil = require('./mwUtil'); function isAbsoluteRedirect(location) { return /^https?:/.test(location); } function resolveRelativeRedirect(req, res) { const pathArr = req.uri.path.slice(0, -1).map(encodeURIComponent); pathArr.unshift(''); pathArr.push(res.headers.location); return pathArr.join('/'); } function resolvedRedirectResponse(hyper, req, res, redirectNum = 0) { let contentURI; if (isAbsoluteRedirect(res.headers.location)) { contentURI = res.headers.location; } else { contentURI = resolveRelativeRedirect(req, res); } return hyper.request({ method: req.method, uri: new URI(contentURI) // We don't pass the `origin` header further, so possible // redirect looping will be handled by normal redirect limiting in `preq` }) .then((res) => { if (res.status >= 300) { if (redirectNum > 10) { throw new HTTPError({ status: 504, body: { type: 'gateway_timeout', detail: 'Exceeded max redirects' } }); } redirectNum++; return resolvedRedirectResponse(hyper, req, res, redirectNum); } return res; }) .tap((res) => { res.headers = res.headers || {}; res.headers['cache-control'] = 'no-cache'; res.headers.vary = res.headers.vary ? `${res.headers.vary}, origin` : 'origin'; }); } module.exports = (hyper, req, next) => { if (req.method !== 'get') { return next(hyper, req); } else { const attachLocation = (res) => { res.headers = res.headers || {}; if (res.status === 301 || res.status === 302) { if (mwUtil.isCrossOrigin(req)) { return resolvedRedirectResponse(hyper, req, res); } return res; } return mwUtil.getSiteInfo(hyper, req) .then((siteInfo) => { Object.assign(res.headers, { 'content-location': siteInfo.baseUri + new URI(req.uri.path.slice(2)) + mwUtil.getQueryString(req) }); return res; }); }; return next(hyper, req) .then(attachLocation, attachLocation) .tap((res) => { if (res.status >= 400) { throw res; } }); } }; <|start_filename|>v1/mobileapps.js<|end_filename|> 'use strict'; const HyperSwitch = require('hyperswitch'); const URI = HyperSwitch.URI; const mwUtils = require('../lib/mwUtil'); const spec = HyperSwitch.utils.loadSpec(`${__dirname}/mobileapps.yaml`); const BUCKET_NAME = 'mobile-sections'; class MobileApps { constructor(options) { this._options = options; } _injectCacheControl(res) { res.headers = res.headers || {}; res.headers['cache-control'] = this._options.response_cache_control; return res; } getSections(hyper, req) { if (mwUtils.isNoCacheRequest(req)) { return this._fetchFromMCSAndStore(hyper, req) .tap(this._injectCacheControl.bind(this)); } const rp = req.params; return hyper.get({ uri: new URI([rp.domain, 'sys', 'key_value', BUCKET_NAME, rp.title]) }) .then((res) => { if (!rp.revision || `${mwUtils.parseETag(res.headers.etag).rev}` === `${rp.revision}`) { return res; } return this._fetchFromMCS(hyper, req); }) .catch({ status: 404 }, () => this._fetchFromMCSAndStore(hyper, req)) .tap(this._injectCacheControl.bind(this)); } getPart(part, hyper, req) { return this.getSections(hyper, req) .then((res) => { return { status: res.status, headers: res.headers, body: res.body[part] }; }); } _purgeURIs(hyper, req, revision, purgeLatest) { const rp = req.params; return mwUtils.getSiteInfo(hyper, req) .then((siteInfo) => { const prefix = `${siteInfo.baseUri}/page/mobile-sections`.replace(/^https?:/, ''); const title = encodeURIComponent(rp.title); const postfixes = ['', '-lead', '-remaining']; let purgeEvents = postfixes.map((postfix) => ({ meta: { uri: `${prefix}${postfix}/${title}/${revision}` } })); if (purgeLatest) { purgeEvents = purgeEvents.concat(postfixes.map((postfix) => ({ meta: { uri: `${prefix}${postfix}/${title}` }, tags: [ `mobile-sections${postfix}` ] }))); } return hyper.post({ uri: new URI([rp.domain, 'sys', 'events', '']), body: purgeEvents }) .catch({ status: 404 }, () => { }); }); } _fetchFromMCS(hyper, req) { const rp = req.params; let serviceURI = `${this._options.host}/${rp.domain}/v1/page/mobile-sections`; serviceURI += `/${encodeURIComponent(rp.title)}`; if (rp.revision) { serviceURI += `/${rp.revision}`; } return hyper.get({ uri: new URI(serviceURI), headers: { 'accept-language': req.headers['accept-language'] } }); } _fetchFromMCSAndStore(hyper, req) { const rp = req.params; return this._fetchFromMCS(hyper, req) .then((res) => { if (mwUtils.isNoStoreRequest(req)) { return res; } return hyper.put({ uri: new URI([rp.domain, 'sys', 'key_value', BUCKET_NAME, rp.title]), headers: { 'content-type': 'application/octet-stream', 'x-store-etag': res.headers.etag, 'x-store-content-language': res.headers['content-language'], 'x-store-content-type': res.headers['content-type'], 'x-store-vary': res.headers.vary }, body: Buffer.from(JSON.stringify(res.body)) }) .tap(() => this._purgeURIs(hyper, req, res.body.lead.revision, true)) .thenReturn(res); }); } } module.exports = (options) => { const mobileApps = new MobileApps(options); return { spec, operations: { getSections: mobileApps.getSections.bind(mobileApps), getSectionsWithRevision: mobileApps.getSections.bind(mobileApps), getSectionsLead: mobileApps.getPart.bind(mobileApps, 'lead'), getSectionsLeadWithRevision: mobileApps.getPart.bind(mobileApps, 'lead'), getSectionsRemaining: mobileApps.getPart.bind(mobileApps, 'remaining'), getSectionsRemainingWithRevision: mobileApps.getPart.bind(mobileApps, 'remaining') }, resources: [ { uri: `/{domain}/sys/key_value/${BUCKET_NAME}` } ] }; }; <|start_filename|>test/features/parsoid/transform.js<|end_filename|> 'use strict'; const assert = require('../../utils/assert.js'); const Server = require('../../utils/server.js'); const preq = require('preq'); const testPage = { title: 'User:Pchelolo%2fRestbase_Test', revision: '275854', wikitext: '<div id=bar>Selser test' // html is fetched dynamically }; describe('transform api', function() { this.timeout(20000); let contentTypes; const server = new Server(); before(() => { return server.start() .then(() => { contentTypes = server.config.conf.test.content_types; return preq.get({ uri: `${server.config.bucketURL('en.wikipedia.beta.wmflabs.org')}/html/${testPage.title}/${testPage.revision}` }); }) .then((res) => { testPage.html = res.body; }); }); after(() => server.stop()); it('wt2html', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/wikitext/to/html/${testPage.title}`, body: { wikitext: '== Heading ==' } }) .then((res) => { assert.deepEqual(res.status, 200); assert.contentType(res, contentTypes.html); const pattern = /<h2.*>Heading<\/h2>/; if (!pattern.test(res.body)) { throw new Error(`Expected pattern in response: ${pattern}\nSaw: ${res.body}`); } }); }); it('wt2html, title-recision for a new page', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/wikitext/to/html/User:Pchelolo%2FRESTBaseTestPage_transform/393301`, body: { wikitext: '== Heading ==' } }) .then((res) => { assert.deepEqual(res.status, 200); assert.contentType(res, contentTypes.html); const pattern = /<h2.*>Heading<\/h2>/; if (!pattern.test(res.body)) { throw new Error(`Expected pattern in response: ${pattern}\nSaw: ${res.body}`); } }); }); it('wt2html with body_only', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/wikitext/to/html/${testPage.title}`, body: { wikitext: '== Heading ==', body_only: true } }) .then((res) => { assert.deepEqual(res.status, 200); assert.contentType(res, contentTypes.html); const pattern = /^<h2.*>Heading<\/h2>$/; if (!pattern.test(res.body)) { throw new Error(`Expected pattern in response: ${pattern }\nSaw: ${res.body}`); } }); }); it('wt2lint', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/wikitext/to/lint`, body: { wikitext: '== Heading ==' } }).then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(res.body, []); }); }); it('wt2lint with errors', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/wikitext/to/lint`, body: { wikitext: '<div>No div ending' } }).then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(res.body.length, 1); }); }); it('html2wt, no-selser', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/html/to/wikitext/${testPage.title}`, body: { html: '<body>The modified HTML</body>' } }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(res.body, 'The modified HTML'); assert.contentType(res, contentTypes.wikitext); }); }); it('html2wt, selser', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/html/to/wikitext/${testPage.title}/${testPage.revision}`, body: { html: testPage.html } }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(res.body, testPage.wikitext); assert.contentType(res, contentTypes.wikitext); }); }); it('html2wt with scrub_wikitext', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/html/to/wikitext`, body: { html: '<h2></h2>', scrub_wikitext: 1 } }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(res.body, ''); }); }); it('supports reversed order of properties in TimeUuid meta', () => { const newHtml = testPage.html.replace(/<meta property="mw:TimeUuid" content="([^"]+)"\/?>/, '<meta content="$1" property="mw:TimeUuid" />'); return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/html/to/wikitext/${testPage.title}/${testPage.revision}`, body: { html: newHtml } }) .then((res) => { assert.deepEqual(res.status, 200); const pattern = /Selser test/; if (!pattern.test(res.body)) { throw new Error(`Expected pattern in response: ${pattern }\nSaw: ${JSON.stringify(res, null, 2)}`); } assert.contentType(res, contentTypes.wikitext); }); }); it('supports stashing content', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/wikitext/to/html/${testPage.title}/${testPage.revision}`, body: { wikitext: '== ABCDEF ==', stash: true } }) .then((res) => { assert.deepEqual(res.status, 200); const etag = res.headers.etag; assert.deepEqual(/\/stash"$/.test(etag), true); return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/html/to/wikitext/${testPage.title}/${testPage.revision}`, headers: { 'if-match': etag }, body: { html: res.body.replace('>ABCDEF<', '>FECDBA<') } }); }) .then((res) => { assert.deepEqual(res.status, 200); assert.deepEqual(res.body, '== FECDBA =='); }); }); it('substitutes 0 as revision if not provided for stashing', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/wikitext/to/html/${testPage.title}`, body: { wikitext: '== ABCDEF ==', stash: true } }) .then((res) => { assert.deepEqual(res.status, 200); const etag = res.headers.etag; assert.deepEqual(/^"0\/[^\/]+\/stash"$/.test(etag), true); }); }); it('does not allow stashing without title', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/wikitext/to/html`, body: { wikitext: '== ABCDEF ==', stash: true } }) .then(() => { throw new Error('Error should be thrown'); }, (e) => { assert.deepEqual(e.status, 400); }); }); it('does not allow to transform html with no tid', () => { return preq.post({ uri: `${server.config.baseURL('en.wikipedia.beta.wmflabs.org')}/transform/html/to/wikitext/${testPage.title}/${testPage.revision}`, body: { html: '<h1>A</h1>' } }) .then(() => { throw new Error('Error should be thrown'); }, (e) => { assert.deepEqual(e.status, 400); }); }); }); <|start_filename|>v1/transform-lang.js<|end_filename|> 'use strict'; const HyperSwitch = require('hyperswitch'); const mwUtil = require('../lib/mwUtil'); const spec = HyperSwitch.utils.loadSpec(`${__dirname}/transform-lang.yaml`); class TransformLang { constructor(options) { this._options = options; if (!this._options.cx_host) { throw new Error('transform-lang.js: option cx_host not present!'); } } doMT(hyper, req) { const rp = req.params; return mwUtil.getSiteInfo(hyper, req).get('general').get('lang').then((lang) => { let uri = `${this._options.cx_host}/v1/mt/${rp.from}/${lang}`; if (rp.provider) { uri += `/${rp.provider}`; } return hyper.post({ uri, body: req.body }); }); } doDict(hyper, req) { const rp = req.params; return mwUtil.getSiteInfo(hyper, req).get('general').get('lang').then((lang) => { let uri = `${this._options.cx_host}/v1/dictionary/${encodeURIComponent(rp.word)}/` + `${rp.from}/${lang}`; if (rp.provider) { uri += `/${rp.provider}`; } return hyper.get({ uri, body: req.body }); }); } } module.exports = (options) => { const transformLang = new TransformLang(options); return { spec, operations: { doMT: transformLang.doMT.bind(transformLang), doMTProvider: transformLang.doMT.bind(transformLang), doDict: transformLang.doDict.bind(transformLang), doDictProvider: transformLang.doDict.bind(transformLang) } }; };
lexnasser/restbase
<|start_filename|>src/models/__tests__/thurston-mosteller-full-series.test.js<|end_filename|> import { rate, rating } from '../..' // numbers in this test suite come from rank-1.02 based on 3 FFA games: // 0, 1, 2, 3, 4 with a score of 9, 7, 7, 5, 5 // 4, 2, 1 with a score of 9, 5, 5 // 3, 1, 2, 0 with a score of 9, 9, 7, 7 describe('thurstonMostellerFull#series', () => { it('runs as expected', () => { expect.assertions(10) const model = 'thurstonMostellerFull' const p00 = rating() const p10 = rating() const p20 = rating() const p30 = rating() const p40 = rating() const [[p01], [p11], [p21], [p31], [p41]] = rate( [[p00], [p10], [p20], [p30], [p40]], { model, epsilon: 0.1, score: [9, 7, 7, 5, 5], } ) const p02 = p01 const p32 = p31 const [[p42], [p22], [p12]] = rate([[p41], [p21], [p11]], { model, epsilon: 0.1, score: [9, 5, 5], }) const p43 = p42 const [[p33], [p13], [p23], [p03]] = rate([[p32], [p12], [p22], [p02]], { model, epsilon: 0.1, score: [9, 9, 7, 7], }) expect(p03.mu).toBeCloseTo(18.688153436) expect(p03.sigma).toBeCloseTo(3.374349435) expect(p13.mu).toBeCloseTo(27.015047867) expect(p13.sigma).toBeCloseTo(3.250038289) expect(p23.mu).toBeCloseTo(22.825795022) expect(p23.sigma).toBeCloseTo(3.261730104) expect(p33.mu).toBeCloseTo(27.281612237) expect(p33.sigma).toBeCloseTo(3.387011242) expect(p43.mu).toBeCloseTo(22.633338874) expect(p43.sigma).toBeCloseTo(3.747505007) }) }) <|start_filename|>src/models/index.js<|end_filename|> import plackettLuce from './plackett-luce' import bradleyTerryFull from './bradley-terry-full' import bradleyTerryPart from './bradley-terry-part' import thurstonMostellerFull from './thurston-mosteller-full' import thurstonMostellerPart from './thurston-mosteller-part' export default { plackettLuce, bradleyTerryFull, bradleyTerryPart, thurstonMostellerFull, thurstonMostellerPart, } <|start_filename|>src/models/__tests__/thurston-mosteller-part.test.js<|end_filename|> import { rating } from '../..' import rate from '../thurston-mosteller-part' describe('thurstonMostellerPart', () => { const r = rating() const team1 = [r] const team2 = [r, r] const team3 = [r, r, r] it('solo game does not change rating', () => { expect.assertions(1) expect(rate([team1])).toStrictEqual([team1]) }) it('2p FFA', () => { expect.assertions(1) expect(rate([team1, team1])).toStrictEqual([ [{ mu: 27.102616738180256, sigma: 8.24902473277454 }], [{ mu: 22.897383261819744, sigma: 8.24902473277454 }], ]) }) it('3p FFA', () => { expect.assertions(1) expect(rate([team1, team1, team1])).toStrictEqual([ [{ mu: 27.102616738180256, sigma: 8.24902473277454 }], [{ mu: 25, sigma: 8.163845517855398 }], [{ mu: 22.897383261819744, sigma: 8.24902473277454 }], ]) }) it('4p FFA', () => { expect.assertions(1) expect(rate([team1, team1, team1, team1])).toStrictEqual([ [{ mu: 27.102616738180256, sigma: 8.24902473277454 }], [{ mu: 25, sigma: 8.163845517855398 }], [{ mu: 25, sigma: 8.163845517855398 }], [{ mu: 22.897383261819744, sigma: 8.24902473277454 }], ]) }) it('5p FFA', () => { expect.assertions(1) expect(rate([team1, team1, team1, team1, team1])).toStrictEqual([ [{ mu: 27.102616738180256, sigma: 8.24902473277454 }], [{ mu: 25, sigma: 8.163845517855398 }], [{ mu: 25, sigma: 8.163845517855398 }], [{ mu: 25, sigma: 8.163845517855398 }], [{ mu: 22.897383261819744, sigma: 8.24902473277454 }], ]) }) it('3 teams different sized players', () => { expect.assertions(1) expect(rate([team3, team1, team2])).toStrictEqual([ [ { mu: 25.31287811922766, sigma: 8.309613085276991 }, { mu: 25.31287811922766, sigma: 8.309613085276991 }, { mu: 25.31287811922766, sigma: 8.309613085276991 }, ], [{ mu: 27.735657148831812, sigma: 8.257580565832717 }], [ { mu: 21.95146473194053, sigma: 8.245567434614435 }, { mu: 21.95146473194053, sigma: 8.245567434614435 }, ], ]) }) it('can use a custom gamma with k=2', () => { expect.assertions(1) expect(rate([team1, team1], { gamma: (_, k) => 1 / k })).toStrictEqual([ [{ mu: 27.102616738180256, sigma: 8.199631478529401 }], [{ mu: 22.897383261819744, sigma: 8.199631478529401 }], ]) }) it('can use a custom gamma with k=5', () => { expect.assertions(1) expect( rate([team1, team1, team1, team1, team1], { gamma: (_, k) => 1 / k }) ).toStrictEqual([ [{ mu: 27.102616738180256, sigma: 8.280111667130026 }], [{ mu: 25, sigma: 8.226545690375827 }], [{ mu: 25, sigma: 8.226545690375827 }], [{ mu: 25, sigma: 8.226545690375827 }], [{ mu: 22.897383261819744, sigma: 8.280111667130026 }], ]) }) })
philihp/openskill.js
<|start_filename|>wagtailmodelchoosers/client/wagtailmodelchoosers.test.js<|end_filename|> /* eslint-disable */ import ModelChooser, { BaseChooser, ModelPicker, initModelChooser } from './wagtailmodelchoosers'; describe('wagtailmodelchooser', () => { it('BaseChooser', () => { expect(BaseChooser).toBeDefined(); }); it('ModelChooser', () => { expect(ModelChooser).toBeDefined(); }); it('ModelPicker', () => { expect(ModelPicker).toBeDefined(); }); describe('initModelChooser', () => { it('exists', () => { expect(initModelChooser).toBeDefined(); }); }); }); <|start_filename|>wagtailmodelchoosers/client/webpack.config.dev.js<|end_filename|> const path = require('path'); const webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const outputPath = path.join(__dirname, '..', 'static', 'wagtailmodelchoosers'); module.exports = { entry: { wagtailmodelchoosers: './wagtailmodelchoosers/client/wagtailmodelchoosers.js', polyfills: './wagtailmodelchoosers/client/polyfills.js', }, output: { path: outputPath, filename: '[name].js', }, plugins: [ new webpack.NoEmitOnErrorsPlugin(), new ExtractTextPlugin('wagtailmodelchoosers.css'), ], module: { rules: [ { test: /\.js$/, use: ['babel-loader'], exclude: /node_modules/, }, { test: /\.css$/, use: ExtractTextPlugin.extract({ use: ['css-loader'], }), }, ], }, }; <|start_filename|>wagtailmodelchoosers/templates/wagtailmodelchoosers/widgets/remote_model_chooser.html<|end_filename|> {% extends 'wagtailmodelchoosers/widgets/model_chooser.html' %} {% block field_class %}remote-model-chooser{% endblock %} {% block react_mount_name %}data-remote-model-chooser-mount{% endblock %} <|start_filename|>wagtailmodelchoosers/client/components/RemoteModelChooser.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; import BaseChooser from './BaseChooser'; class RemoteModelChooser extends React.Component { constructor(props) { super(props); this.updateInputValue = this.updateInputValue.bind(this); } updateInputValue(item) { const { input, options: { fields_to_save: fieldsToSave } } = this.props; let newValue; if (item === null) { // Null state newValue = null; } else if (fieldsToSave) { // Create a new object with only the fields to save const clone = {}; fieldsToSave.forEach((field) => { clone[field] = item[field]; }); newValue = JSON.stringify(clone); } else { // Use the whole object. newValue = JSON.stringify(item); } // TODO: Props mutation WTF? input.value = newValue; } render() { const { input, options } = this.props; let initialValue; try { // TODO: Should we use safe-parse or something alike? initialValue = JSON.parse(input.value); } catch (err) { initialValue = {}; } return ( <BaseChooser initialValue={initialValue} updateInputValue={this.updateInputValue} {...options} /> ); } } RemoteModelChooser.propTypes = { // eslint-disable-next-line react/forbid-prop-types options: PropTypes.object.isRequired, // eslint-disable-next-line react/forbid-prop-types input: PropTypes.object.isRequired, }; export default RemoteModelChooser; <|start_filename|>wagtailmodelchoosers/client/polyfills.js<|end_filename|> /** * This file is automatically included in the JS bundle. * Don't import it manually. */ if (typeof Promise === 'undefined') { // Rejection tracking prevents a common issue where React gets into an // inconsistent state due to an error, but it gets swallowed by a Promise, // and the user has no idea what causes React's erratic future behavior. /* eslint-disable global-require */ require('promise/lib/rejection-tracking').enable(); window.Promise = require('promise/lib/es6-extensions.js'); /* eslint-enable */ } // fetch() polyfill for making API calls. // Uncomment this line to use fetch in your code. // It is left out by default, because the polyfill is big. require('whatwg-fetch'); /* eslint-disable */ // https://tc39.github.io/ecma262/#sec-array.prototype.find if (!Array.prototype.find) { Object.defineProperty(Array.prototype, 'find', { value: function(predicate) { // 1. Let O be ? ToObject(this value). if (this == null) { throw new TypeError('"this" is null or not defined'); } var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 3. If IsCallable(predicate) is false, throw a TypeError exception. if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. var thisArg = arguments[1]; // 5. Let k be 0. var k = 0; // 6. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). // b. Let kValue be ? Get(O, Pk). // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). // d. If testResult is true, return kValue. var kValue = o[k]; if (predicate.call(thisArg, kValue, k, o)) { return kValue; } // e. Increase k by 1. k++; } // 7. Return undefined. return undefined; } }); } /* eslint-enable */ <|start_filename|>wagtailmodelchoosers/client/utils.js<|end_filename|> // Translation function. export const tr = (defaultTranslations, customTranslations, key) => { if (customTranslations && key in customTranslations) { return customTranslations[key]; } if (key in defaultTranslations) { return defaultTranslations[key]; } return key.replace(/_/g, ' '); }; export const pluralize = ( defaultTranslations, customTranslations, singularKey, pluralKey, count, ) => { const singular = tr(defaultTranslations, customTranslations, singularKey); const plural = tr(defaultTranslations, customTranslations, pluralKey); return count === 1 ? singular : plural; }; <|start_filename|>wagtailmodelchoosers/client/wagtailmodelchoosers.js<|end_filename|> import React from 'react'; import ReactDOM from 'react-dom'; import './wagtailmodelchoosers.css'; import BaseChooser from './components/BaseChooser'; import ModelChooser from './components/ModelChooser'; import ModelPicker from './components/ModelPicker'; import RemoteModelChooser from './components/RemoteModelChooser'; import ModelSource from './sources/ModelSource'; import RemoteModelSource from './sources/RemoteModelSource'; const initModelChooser = (id, data) => { const input = document.getElementById(id); if (input) { const item = input.parentNode; const control = item.querySelector('[data-model-chooser-mount]'); ReactDOM.render(<ModelChooser input={input} options={data} />, control); } }; const initRemoteModelChooser = (id, data) => { const input = document.getElementById(id); if (input) { const item = input.parentNode; const control = item.querySelector('[data-remote-model-chooser-mount]'); ReactDOM.render(<RemoteModelChooser input={input} options={data} />, control); } }; window.wagtailModelChoosers = {}; window.wagtailModelChoosers.initModelChooser = initModelChooser; window.wagtailModelChoosers.initRemoteModelChooser = initRemoteModelChooser; // Add Sources if WagtailDraftail is available. if (Object.prototype.hasOwnProperty.call(window, 'wagtailDraftail')) { window.wagtailDraftail.registerSources({ ModelSource, RemoteModelSource }); } export default ModelChooser; export { BaseChooser, ModelPicker, RemoteModelChooser, initModelChooser, initRemoteModelChooser, }; <|start_filename|>wagtailmodelchoosers/client/sources/ModelSource.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; import { DraftUtils } from 'draftail'; import ModelPicker from '../components/ModelPicker'; const API_BASE_URL = '/admin/modelchoosers/api/v1/model/'; class ModelSource extends React.Component { constructor(props) { super(props); this.onClose = this.onClose.bind(this); this.onSelected = this.onSelected.bind(this); } onClose() { const { onClose } = this.props; onClose(); } onSelected(id, data) { const { editorState, onUpdate, options: { content_type, display = 'title', pk_name: pkName = 'uuid', type } } = this.props; let label; let entityMutability; if (display === '__selection__') { const selectionState = editorState.getSelection(); const anchorKey = selectionState.getAnchorKey(); const currentContent = editorState.getCurrentContent(); const currentContentBlock = currentContent.getBlockForKey(anchorKey); const start = selectionState.getStartOffset(); const end = selectionState.getEndOffset(); label = currentContentBlock.getText().slice(start, end); entityMutability = 'MUTABLE'; } else { if (Array.isArray(display)) { let i; for (i = 0; i < display.length; i + 1) { const fieldName = display[i]; if (fieldName in data && data[fieldName]) { label = data[fieldName]; break; } } } else if (display in data && data[display]) { label = data[display]; } if (label === undefined) { label = data[pkName]; } entityMutability = 'IMMUTABLE'; } const nextData = { id, label, content_type, }; const nextState = DraftUtils.createEntity( editorState, type, nextData, nextData.label, entityMutability, ); onUpdate(nextState); } render() { const { entity, options } = this.props; const endpoint = `${API_BASE_URL}${options.content_type}`; return ( <ModelPicker onChange={this.onSelected} onSelect={this.onSelected} onClose={this.onClose} entity={entity} endpoint={endpoint} value={null} required={false} {...options} /> ); } } ModelSource.propTypes = { // eslint-disable-next-line react/forbid-prop-types editorState: PropTypes.object.isRequired, // eslint-disable-next-line react/forbid-prop-types options: PropTypes.object.isRequired, // eslint-disable-next-line react/forbid-prop-types entity: PropTypes.object, onClose: PropTypes.func.isRequired, onUpdate: PropTypes.func.isRequired, }; ModelSource.defaultProps = { entity: {}, }; export default ModelSource; <|start_filename|>wagtailmodelchoosers/client/components/Buttons.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; const Button = ({ isActive, classes, label, onClick }) => { const buttonClasses = classes.slice(); buttonClasses.push('button'); if (!isActive) { buttonClasses.push('button--disabled'); } return ( <button type="button" onClick={onClick} className={buttonClasses.join(' ')} > {label} </button> ); }; Button.defaultProps = { isActive: true, classes: [], }; Button.propTypes = { isActive: PropTypes.bool, classes: PropTypes.arrayOf(PropTypes.string), label: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired, }; const CloseButton = ({ onClick }) => { const classes = ['close', 'icon', 'text-replace', 'icon-cross']; return <Button classes={classes} onClick={onClick} label="x" />; }; CloseButton.propTypes = { onClick: PropTypes.func.isRequired, }; const SecondaryButton = ({ label, onClick }) => { const classes = ['action-choose', 'button-small', 'button-secondary']; return <Button classes={classes} onClick={onClick} label={label} />; }; SecondaryButton.propTypes = { label: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired, }; export default Button; export { CloseButton, SecondaryButton, }; <|start_filename|>wagtailmodelchoosers/client/webpack.config.prod.js<|end_filename|> const webpack = require('webpack'); const config = require('./webpack.config.dev'); module.exports = Object.assign({}, config, { plugins: config.plugins.concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.UglifyJsPlugin({ compress: { screw_ie8: true, warnings: false, }, mangle: { screw_ie8: true, }, output: { comments: false, screw_ie8: true, }, }), ]), });
luccascorrea/wagtailmodelchoosers
<|start_filename|>scripts/inc_version.js<|end_filename|> // // Helper script to bump the version number // // TODO: a Node.js dependency in a Python package is not ideal. // var fs = require('fs'); var _ = require('underscore'); var version = (fs.readFileSync("VERSION", "utf8") || "1.0.0").replace(/\s+$/, ""); var newVersion = require("semver").inc(version, "patch"); fs.writeFileSync("VERSION", newVersion); fs.writeFileSync("lightstep/version.py", "LIGHTSTEP_PYTHON_TRACER_VERSION=\"" + newVersion + "\"\n"); // Naive micro-sed on setup.py var setuppy = _.map(fs.readFileSync("setup.py", "utf8").split("\n"), function(line) { return line.replace("'" + version + "'", "'" + newVersion + "'"); }).join("\n"); fs.writeFileSync("setup.py", setuppy); console.log(version + " -> " + newVersion);
wiedi/lightstep-tracer-python
<|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/runner/context/ContextDeflater.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.runner.context; import com.softwareverde.json.Json; public class ContextDeflater { public Json toJson(final TransactionContext transactionContext) { final Json json = new Json(); json.put("blockHeight", transactionContext.getBlockHeight()); json.put("medianBlockTime", transactionContext.getMedianBlockTime()); json.put("transaction", transactionContext.getTransaction()); json.put("transactionInputIndex", transactionContext.getTransactionInputIndex()); json.put("transactionInput", transactionContext.getTransactionInput()); json.put("transactionOutput", transactionContext.getTransactionOutput()); json.put("currentScript", transactionContext.getCurrentScript()); json.put("scriptIndex", transactionContext.getScriptIndex()); json.put("scriptLastCodeSeparatorIndex", transactionContext.getScriptLastCodeSeparatorIndex()); json.put("signatureOperationCount", transactionContext.getSignatureOperationCount()); return json; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/inflater/Inflater.java<|end_filename|> package com.softwareverde.bitcoin.inflater; public interface Inflater { } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/input/TransactionInput.java<|end_filename|> package com.softwareverde.bitcoin.transaction.input; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.script.ScriptBuilder; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.constable.Constable; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.json.Jsonable; public interface TransactionInput extends Constable<ImmutableTransactionInput>, Jsonable { /** * Creates a coinbase transaction with the provided blockHeight and coinbaseMessage as the contents of the TransactionInput's UnlockingScript. * The blockHeight and coinbaseMessage are transformed into PushOperations for the UnlockingScript. * If blockHeight is provided (it may be null), the blockHeight will be the first value pushed onto the UnlockingScript (as per Bip34). */ static TransactionInput createCoinbaseTransactionInput(final Long blockHeight, final String coinbaseMessage) { final UnlockingScript unlockingScript; { // Initialize unlockingScript... final ScriptBuilder scriptBuilder = new ScriptBuilder(); if (blockHeight != null) { scriptBuilder.pushInteger(blockHeight); } scriptBuilder.pushString(coinbaseMessage); unlockingScript = scriptBuilder.buildUnlockingScript(); } final MutableTransactionInput coinbaseTransactionInput = new MutableTransactionInput(); coinbaseTransactionInput.setPreviousOutputTransactionHash(TransactionOutputIdentifier.COINBASE.getTransactionHash()); coinbaseTransactionInput.setPreviousOutputIndex(TransactionOutputIdentifier.COINBASE.getOutputIndex()); coinbaseTransactionInput.setUnlockingScript(unlockingScript); return coinbaseTransactionInput; } /** * Creates a coinbase transaction with the provided blockHeight and coinbaseMessage as the contents of the TransactionInput's UnlockingScript. * This function is nearly identical to TransactionInput.createCoinbaseTransactionInput(), except an additional PushOperation is added to the end of the UnlockingScript. * This value is all zeroes, and is extraNonceByteCount bytes long. */ static TransactionInput createCoinbaseTransactionInputWithExtraNonce(final Long blockHeight, final String coinbaseMessage, final Integer extraNonceByteCount) { final UnlockingScript unlockingScript; { // Initialize unlockingScript... final ScriptBuilder scriptBuilder = new ScriptBuilder(); if (blockHeight != null) { scriptBuilder.pushInteger(blockHeight); } scriptBuilder.pushString(coinbaseMessage); scriptBuilder.pushBytes(new MutableByteArray(extraNonceByteCount)); // Pad the coinbaseTransactionInput with extraNonceByteCount bytes. (Which adds the appropriate opcode in addition to extraNonceByteCount bytes...) unlockingScript = scriptBuilder.buildUnlockingScript(); } final MutableTransactionInput coinbaseTransactionInput = new MutableTransactionInput(); coinbaseTransactionInput.setPreviousOutputTransactionHash(Sha256Hash.EMPTY_HASH); coinbaseTransactionInput.setPreviousOutputIndex(-1); coinbaseTransactionInput.setUnlockingScript(unlockingScript); return coinbaseTransactionInput; } Sha256Hash getPreviousOutputTransactionHash(); Integer getPreviousOutputIndex(); UnlockingScript getUnlockingScript(); SequenceNumber getSequenceNumber(); @Override ImmutableTransactionInput asConst(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/handler/BlockInventoryMessageHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.handler; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.server.SynchronizationStatus; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.node.fullnode.FullNodeBitcoinNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.manager.banfilter.BanFilter; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; public class BlockInventoryMessageHandler implements BitcoinNode.BlockInventoryAnnouncementHandler { public interface NewInventoryReceivedCallback { default void onNewBlockHashesReceived(List<Sha256Hash> blockHashes) { } default void onNewBlockHeadersReceived(BitcoinNode bitcoinNode, List<BlockHeader> blockHeaders) { } } public static final BitcoinNode.BlockInventoryAnnouncementHandler IGNORE_INVENTORY_HANDLER = new BitcoinNode.BlockInventoryAnnouncementHandler() { @Override public void onNewInventory(final BitcoinNode bitcoinNode, final List<Sha256Hash> blockHashes) { } @Override public void onNewHeaders(final BitcoinNode bitcoinNode, final List<BlockHeader> blockHeaders) { } }; protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; protected final SynchronizationStatus _synchronizationStatus; protected final BanFilter _banFilter; protected NewInventoryReceivedCallback _newInventoryReceivedCallback; protected Runnable _nodeInventoryUpdatedCallback; static class StoreBlockHashesResult { public Boolean nodeInventoryWasUpdated = false; public Boolean newBlockHashWasReceived = false; } protected StoreBlockHashesResult _storeBlockHashes(final BitcoinNode bitcoinNode, final List<Sha256Hash> blockHashes) { final StoreBlockHashesResult storeBlockHashesResult = new StoreBlockHashesResult(); try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final FullNodeBitcoinNodeDatabaseManager nodeDatabaseManager = databaseManager.getNodeDatabaseManager(); final int blockHashCount = blockHashes.getCount(); final Sha256Hash firstBlockHash = blockHashes.get(0); final Sha256Hash lastBlockHash = blockHashes.get(blockHashCount - 1); final BlockId lastBlockId = blockHeaderDatabaseManager.getBlockHeaderId(lastBlockHash); if (lastBlockId != null) { final Long lastBlockHeight = blockHeaderDatabaseManager.getBlockHeight(lastBlockId); final Boolean isNewHeightForNode = nodeDatabaseManager.updateBlockInventory(bitcoinNode, lastBlockHeight, lastBlockHash); Logger.debug("HeadBlock for " + bitcoinNode + " height=" + lastBlockHeight + " hash=" + lastBlockHash); storeBlockHashesResult.nodeInventoryWasUpdated = isNewHeightForNode; storeBlockHashesResult.newBlockHashWasReceived = false; } else { final BlockId firstBlockId = blockHeaderDatabaseManager.getBlockHeaderId(firstBlockHash); if (firstBlockId != null) { final Long firstBlockHeight = blockHeaderDatabaseManager.getBlockHeight(firstBlockId); final BlockInventoryMessageHandlerUtil.NodeInventory nodeInventory = BlockInventoryMessageHandlerUtil.getHeadBlockInventory(firstBlockHeight, blockHashes, new BlockInventoryMessageHandlerUtil.BlockIdStore() { @Override public BlockId getBlockId(final Sha256Hash blockHash) throws Exception { return blockHeaderDatabaseManager.getBlockHeaderId(blockHash); } }); Logger.debug("HeadBlock for " + bitcoinNode + " height=" + nodeInventory.blockHeight + " hash=" + nodeInventory.blockHash); final Boolean isNewHeightForNode = nodeDatabaseManager.updateBlockInventory(bitcoinNode, nodeInventory.blockHeight, nodeInventory.blockHash); storeBlockHashesResult.nodeInventoryWasUpdated = isNewHeightForNode; storeBlockHashesResult.newBlockHashWasReceived = true; } else { Logger.debug("Unknown HeadBlock for " + bitcoinNode + " hash=" + firstBlockHash); // The block hash does not match a known header, therefore its block height cannot be determined and it is ignored. storeBlockHashesResult.nodeInventoryWasUpdated = false; storeBlockHashesResult.newBlockHashWasReceived = false; } } } catch (final Exception exception) { Logger.warn(exception); } return storeBlockHashesResult; } public BlockInventoryMessageHandler(final FullNodeDatabaseManagerFactory databaseManagerFactory, final SynchronizationStatus synchronizationStatus, final BanFilter banFilter) { _databaseManagerFactory = databaseManagerFactory; _synchronizationStatus = synchronizationStatus; _banFilter = banFilter; } public void setNewInventoryReceivedCallback(final NewInventoryReceivedCallback newInventoryReceivedCallback) { _newInventoryReceivedCallback = newInventoryReceivedCallback; } public void setNodeInventoryUpdatedCallback(final Runnable nodeInventoryUpdatedCallback) { _nodeInventoryUpdatedCallback = nodeInventoryUpdatedCallback; } @Override public void onNewInventory(final BitcoinNode bitcoinNode, final List<Sha256Hash> blockHashes) { if (_banFilter != null) { final Boolean shouldAcceptInventory = _banFilter.onInventoryReceived(bitcoinNode, blockHashes); if (! shouldAcceptInventory) { Logger.info("Received invalid inventory from " + bitcoinNode + "."); bitcoinNode.disconnect(); return; } } final StoreBlockHashesResult storeBlockHashesResult = _storeBlockHashes(bitcoinNode, blockHashes); if (storeBlockHashesResult.newBlockHashWasReceived) { final NewInventoryReceivedCallback newBlockHashesCallback = _newInventoryReceivedCallback; if (newBlockHashesCallback != null) { newBlockHashesCallback.onNewBlockHashesReceived(blockHashes); } } else if (storeBlockHashesResult.nodeInventoryWasUpdated) { final Runnable inventoryUpdatedCallback = _nodeInventoryUpdatedCallback; if (inventoryUpdatedCallback != null) { inventoryUpdatedCallback.run(); } } } @Override public void onNewHeaders(final BitcoinNode bitcoinNode, final List<BlockHeader> blockHeaders) { final MutableList<BlockHeader> unknownBlockHeaders = new MutableList<BlockHeader>(); try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); boolean hasUnknownHeader = false; for (final BlockHeader blockHeader : blockHeaders) { final Sha256Hash blockHash = blockHeader.getHash(); final BlockId blockId = blockHeaderDatabaseManager.getBlockHeaderId(blockHash); if (blockId == null) { hasUnknownHeader = true; } if (hasUnknownHeader) { unknownBlockHeaders.add(blockHeader); } } } catch (final Exception exception) { Logger.warn(exception); return; } if (! unknownBlockHeaders.isEmpty()) { final NewInventoryReceivedCallback newBlockHashesCallback = _newInventoryReceivedCallback; if (newBlockHashesCallback != null) { newBlockHashesCallback.onNewBlockHeadersReceived(bitcoinNode, unknownBlockHeaders); } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/unlocking/MutableUnlockingScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.unlocking; import com.softwareverde.bitcoin.transaction.script.MutableScript; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.constable.bytearray.ByteArray; public class MutableUnlockingScript extends MutableScript implements UnlockingScript { public MutableUnlockingScript() { super(); } public MutableUnlockingScript(final ByteArray bytes) { super(bytes); } public MutableUnlockingScript(final Script script) { super(script); } @Override public ImmutableUnlockingScript asConst() { return new ImmutableUnlockingScript(this); } } <|start_filename|>src/main/resources/css/main.css<|end_filename|> #root { -fx-background-color: #222222; -fx-text-fill: #EEEEEE; } .tab-pane .tab-header-area .tab-header-background { -fx-opacity: 0.2; } .tab { -fx-background-color: #242424; -fx-text-fill: #EEEEEE; -fx-border-style: none; -fx-focus-color: transparent; -fx-faint-focus-color: transparent; } .tab:selected { -fx-background-color: #79A890; -fx-text-fill: #000000; -fx-font-weight: bold; } .label { -fx-text-fill: #FFFFFF; } .text-field { -fx-text-fill: #EEEEEE; -fx-background-color: #505050, #383838, #383838; -fx-background-insets: 0 -2 -2 -2, 0 0 0 0, 0 -2 3 -2; } .text-field:focused { -fx-text-fill: #EEEEEE; -fx-background-color: #606060, #383838, #383838; -fx-background-insets: 0 -2 -2 -2, 0 0 0 0, 0 -2 3 -2; } .context-menu { -fx-text-fill: #EEEEEE; -fx-background-color: #656565; } .context-menu .menu-item { -fx-text-fill: #EEEEEE; -fx-background-color: #656565; } .list-view { -fx-background-color: #000000; -fx-background-insets: 0; } .list-cell { -fx-background-color: #000000; -fx-font-size: 8pt; } .list-cell:filled:selected:focused, .list-cell:filled:selected { -fx-text-fill: #FFFFFF; } .list-cell:even { -fx-background-color: #101010; } .list-cell:filled:hover { -fx-text-fill: #FFFFFF; -fx-background-color: #202020; } .list-cell:empty { -fx-background-color: #000000; } .scroll-pane { -fx-background-color: #000000; -fx-font-size: 5px; } .scroll-bar:horizontal, .scroll-bar:vertical { -fx-background-color: transparent; } .increment-button, .decrement-button { -fx-background-color: transparent; -fx-border-color: transparent; } .scroll-bar:horizontal .track, .scroll-bar:vertical .track { -fx-background-color: transparent; -fx-border-color: transparent; -fx-background-radius: 0em; } .scroll-bar:horizontal .thumb, .scroll-bar:vertical .thumb { -fx-background-color: #303030; -fx-background-radius: 5em; } .scroll-bar:vertical { -fx-pref-width: 10; -fx-padding: 1; } .scroll-bar:horizontal { -fx-pref-height: 10; -fx-padding: 1; } .scroll-bar, .scroll-bar:pressed, .scroll-bar:focused { -fx-font-size: 15; } .corner { -fx-background-color: #000000; } .label.spent { -fx-text-fill: #EFABCD; } .label.unspent { -fx-text-fill: #ABEFCD; } .status-bar { -fx-padding: 0 10 10 10; } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/validator/TransactionValidatorTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction.validator; import com.softwareverde.bitcoin.CoreInflater; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.context.core.TransactionValidatorContext; import com.softwareverde.bitcoin.inflater.MasterInflater; import com.softwareverde.bitcoin.test.UnitTest; import com.softwareverde.bitcoin.test.fake.FakeStaticMedianBlockTimeContext; import com.softwareverde.bitcoin.test.fake.FakeUnspentTransactionOutputContext; import com.softwareverde.bitcoin.test.util.TransactionTestUtil; import com.softwareverde.bitcoin.transaction.MutableTransaction; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.signer.HashMapTransactionOutputRepository; import com.softwareverde.bitcoin.transaction.signer.TransactionOutputRepository; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.network.time.MutableNetworkTime; import com.softwareverde.util.HexUtil; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TransactionValidatorTests extends UnitTest { @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } @Test public void should_validate_valid_transaction() throws Exception { // Setup final MasterInflater masterInflater = new CoreInflater(); final FakeUnspentTransactionOutputContext unspentTransactionOutputContext = new FakeUnspentTransactionOutputContext(); final TransactionValidatorContext transactionValidatorContext = new TransactionValidatorContext(masterInflater, new MutableNetworkTime(), FakeStaticMedianBlockTimeContext.MAX_MEDIAN_BLOCK_TIME, unspentTransactionOutputContext); final TransactionValidator transactionValidator = new TransactionValidatorCore(transactionValidatorContext); final TransactionInflater transactionInflater = new TransactionInflater(); final Transaction previousTransaction = transactionInflater.fromBytes(HexUtil.hexStringToByteArray("0100000001E7FCF39EE6B86F1595C55B16B60BF4F297988CB9519F5D42597E7FB721E591C6010000008B483045022100AC572B43E78089851202CFD9386750B08AFC175318C537F04EB364BF5A0070D402203F0E829D4BAEA982FEAF987CB9F14C85097D2FBE89FBA3F283F6925B3214A97E0141048922FA4DC891F9BB39F315635C03E60E019FF9EC1559C8B581324B4C3B7589A57550F9B0B80BC72D0F959FDDF6CA65F07223C37A8499076BD7027AE5C325FAC5FFFFFFFF0140420F00000000001976A914C4EB47ECFDCF609A1848EE79ACC2FA49D3CAAD7088AC00000000")); unspentTransactionOutputContext.addTransaction(previousTransaction, Sha256Hash.fromHexString("0000000000004273D89D3F220A9D3DBD45A4FD1C028B51E170F478DA11352187"), 99811L, false); final byte[] transactionBytes = HexUtil.hexStringToByteArray("01000000010B6072B386D4A773235237F64C1126AC3B240C84B917A3909BA1C43DED5F51F4000000008C493046022100BB1AD26DF930A51CCE110CF44F7A48C3C561FD977500B1AE5D6B6FD13D0B3F4A022100C5B42951ACEDFF14ABBA2736FD574BDB465F3E6F8DA12E2C5303954ACA7F78F3014104A7135BFE824C97ECC01EC7D7E336185C81E2AA2C41AB175407C09484CE9694B44953FCB751206564A9C24DD094D42FDBFDD5AAD3E063CE6AF4CFAAEA4EA14FBBFFFFFFFF0140420F00000000001976A91439AA3D569E06A1D7926DC4BE1193C99BF2EB9EE088AC00000000"); final Transaction transaction = transactionInflater.fromBytes(transactionBytes); final Long blockHeight = 100000L; // Action final TransactionValidationResult transactionValidationResult = transactionValidator.validateTransaction(blockHeight, transaction); // Assert Assert.assertTrue(transactionValidationResult.isValid); } @Test public void should_create_signed_transaction_and_unlock_it() throws Exception { // Setup final MasterInflater masterInflater = new CoreInflater(); final FakeUnspentTransactionOutputContext unspentTransactionOutputContext = new FakeUnspentTransactionOutputContext(); final TransactionValidatorContext transactionValidatorContext = new TransactionValidatorContext(masterInflater, new MutableNetworkTime(), FakeStaticMedianBlockTimeContext.MAX_MEDIAN_BLOCK_TIME, unspentTransactionOutputContext); final TransactionValidator transactionValidator = new TransactionValidatorCore(transactionValidatorContext); final AddressInflater addressInflater = new AddressInflater(); final PrivateKey privateKey = PrivateKey.createNewKey(); // Create a transaction that will be spent in the test's signed transaction. // This transaction creates an output that can be spent by the test's private key. final Transaction transactionToSpend = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(privateKey); unspentTransactionOutputContext.addTransaction(transactionToSpend, null, 1L, false); // Create an unsigned transaction that spends the test's previous transaction, and send the test's payment to an irrelevant address. final Transaction unsignedTransaction; { final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); final TransactionOutputIdentifier transactionOutputIdentifierToSpend = new TransactionOutputIdentifier(transactionToSpend.getHash(), 0); final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(transactionOutputIdentifierToSpend); mutableTransaction.addTransactionInput(transactionInput); final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput(addressInflater.fromPrivateKey(privateKey, true)); mutableTransaction.addTransactionOutput(transactionOutput); unsignedTransaction = mutableTransaction; } final TransactionOutputRepository transactionOutputRepository = TransactionTestUtil.createTransactionOutputRepository(transactionToSpend); final Transaction signedTransaction = TransactionTestUtil.signTransaction(transactionOutputRepository, unsignedTransaction, privateKey); // Action final TransactionValidationResult transactionValidationResult = transactionValidator.validateTransaction(1L, signedTransaction); // Assert Assert.assertTrue(transactionValidationResult.isValid); } @Test public void should_not_validate_a_transaction_attempting_to_spend_an_output_with_the_wrong_key() throws Exception { // Setup final MasterInflater masterInflater = new CoreInflater(); final AddressInflater addressInflater = masterInflater.getAddressInflater(); final FakeUnspentTransactionOutputContext unspentTransactionOutputContext = new FakeUnspentTransactionOutputContext(); final TransactionValidatorContext transactionValidatorContext = new TransactionValidatorContext(masterInflater, new MutableNetworkTime(), FakeStaticMedianBlockTimeContext.MAX_MEDIAN_BLOCK_TIME, unspentTransactionOutputContext); final TransactionValidator transactionValidator = new TransactionValidatorCore(transactionValidatorContext); final PrivateKey privateKey = PrivateKey.createNewKey(); // Create a transaction that will be spent in the test's signed transaction. // This transaction output is being sent to an address we don't have access to. final Transaction transactionToSpend = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(PrivateKey.createNewKey()); unspentTransactionOutputContext.addTransaction(transactionToSpend, null, 1L, false); // Create an unsigned transaction that spends the test's previous transaction, and send the test's payment to an irrelevant address. final Transaction unsignedTransaction; { final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionToSpend.getHash(), 0); final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(transactionOutputIdentifier); mutableTransaction.addTransactionInput(transactionInput); final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput(addressInflater.fromPrivateKey(privateKey, true)); mutableTransaction.addTransactionOutput(transactionOutput); unsignedTransaction = mutableTransaction; } // Sign the unsigned transaction with the test's key that does not match the address given to transactionToSpend. final TransactionOutputRepository transactionOutputRepository = TransactionTestUtil.createTransactionOutputRepository(transactionToSpend); final Transaction signedTransaction = TransactionTestUtil.signTransaction(transactionOutputRepository, unsignedTransaction, privateKey); // Action final TransactionValidationResult transactionValidationResult = transactionValidator.validateTransaction(1L, signedTransaction); // Assert Assert.assertFalse(transactionValidationResult.isValid); } @Test public void should_not_validate_transaction_that_spends_the_same_input_twice() throws Exception { // Setup final MasterInflater masterInflater = new CoreInflater(); final AddressInflater addressInflater = masterInflater.getAddressInflater(); final FakeUnspentTransactionOutputContext unspentTransactionOutputContext = new FakeUnspentTransactionOutputContext(); final TransactionValidatorContext transactionValidatorContext = new TransactionValidatorContext(masterInflater, new MutableNetworkTime(), FakeStaticMedianBlockTimeContext.MAX_MEDIAN_BLOCK_TIME, unspentTransactionOutputContext); final TransactionValidator transactionValidator = new TransactionValidatorCore(transactionValidatorContext); final PrivateKey privateKey = PrivateKey.createNewKey(); // Create a transaction that will be spent in the test's signed transaction. // This transaction will create an output that can be spent by the test's private key. final Transaction transactionToSpend = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(privateKey); unspentTransactionOutputContext.addTransaction(transactionToSpend, null, 1L, false); // Create an unsigned transaction that spends the test's previous transaction, and send the test's payment to an irrelevant address. final Transaction unsignedTransaction; { final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); // Add two inputs that attempt to spend the same output... final TransactionOutputIdentifier transactionOutputIdentifierToSpend = new TransactionOutputIdentifier(transactionToSpend.getHash(), 0); final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(transactionOutputIdentifierToSpend); mutableTransaction.addTransactionInput(transactionInput); mutableTransaction.addTransactionInput(transactionInput); final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput(addressInflater.fromPrivateKey(privateKey, true)); mutableTransaction.addTransactionOutput(transactionOutput); unsignedTransaction = mutableTransaction; } // Sign the unsigned transaction. final TransactionOutputRepository transactionOutputRepository = TransactionTestUtil.createTransactionOutputRepository(transactionToSpend); final Transaction signedTransaction = TransactionTestUtil.signTransaction(transactionOutputRepository, unsignedTransaction, privateKey); // Action final TransactionValidationResult transactionValidationResult = transactionValidator.validateTransaction(1L, signedTransaction); // Assert Assert.assertFalse(transactionValidationResult.isValid); } @Test public void should_not_validate_transaction_that_spends_more_than_the_input_amount() throws Exception { // Setup final MasterInflater masterInflater = new CoreInflater(); final AddressInflater addressInflater = masterInflater.getAddressInflater(); final FakeUnspentTransactionOutputContext unspentTransactionOutputContext = new FakeUnspentTransactionOutputContext(); final TransactionValidatorContext transactionValidatorContext = new TransactionValidatorContext(masterInflater, new MutableNetworkTime(), FakeStaticMedianBlockTimeContext.MAX_MEDIAN_BLOCK_TIME, unspentTransactionOutputContext); final TransactionValidator transactionValidator = new TransactionValidatorCore(transactionValidatorContext); final PrivateKey privateKey = PrivateKey.createNewKey(); final Transaction transactionToSpend = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(privateKey, (10L * Transaction.SATOSHIS_PER_BITCOIN)); unspentTransactionOutputContext.addTransaction(transactionToSpend, null, 1L, false); // Create an unsigned transaction that spends more than the test's previous transaction provides... final Transaction unsignedTransaction; { final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); final TransactionOutputIdentifier transactionOutputIdentifierToSpend = new TransactionOutputIdentifier(transactionToSpend.getHash(), 0); final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(transactionOutputIdentifierToSpend); mutableTransaction.addTransactionInput(transactionInput); // NOTE: The output amount is greater than the coinbase amount. final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput((50L * Transaction.SATOSHIS_PER_BITCOIN), addressInflater.fromPrivateKey(privateKey, true)); mutableTransaction.addTransactionOutput(transactionOutput); unsignedTransaction = mutableTransaction; } final TransactionOutputRepository transactionOutputRepository = TransactionTestUtil.createTransactionOutputRepository(transactionToSpend); final Transaction signedTransaction = TransactionTestUtil.signTransaction(transactionOutputRepository, unsignedTransaction, privateKey); // Action final TransactionValidationResult transactionValidationResult = transactionValidator.validateTransaction(1L, signedTransaction); // Assert Assert.assertFalse(transactionValidationResult.isValid); } @Test public void should_not_accept_transaction_with_previous_output_that_does_not_exist() throws Exception { // Setup final MasterInflater masterInflater = new CoreInflater(); final AddressInflater addressInflater = masterInflater.getAddressInflater(); final FakeUnspentTransactionOutputContext unspentTransactionOutputContext = new FakeUnspentTransactionOutputContext(); final TransactionValidatorContext transactionValidatorContext = new TransactionValidatorContext(masterInflater, new MutableNetworkTime(), FakeStaticMedianBlockTimeContext.MAX_MEDIAN_BLOCK_TIME, unspentTransactionOutputContext); final TransactionValidator transactionValidator = new TransactionValidatorCore(transactionValidatorContext); final PrivateKey privateKey = PrivateKey.createNewKey(); final Transaction transactionToSpend = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(privateKey); unspentTransactionOutputContext.addTransaction(transactionToSpend, null, 1L, false); final int outputIndexToSpend = 1; // Is greater than the number of outputs within transactionToSpend... // Create an unsigned transaction that spends an unknown/unavailable output (previous output index does not exist)... final Transaction unsignedTransaction; { final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); final TransactionOutputIdentifier transactionOutputIdentifierToSpend = new TransactionOutputIdentifier(transactionToSpend.getHash(), outputIndexToSpend); // NOTE: Output index does not exist. final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(transactionOutputIdentifierToSpend); mutableTransaction.addTransactionInput(transactionInput); final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput(addressInflater.fromBase58Check("149uLAy8vkn1Gm68t5NoLQtUqBtngjySLF", false)); mutableTransaction.addTransactionOutput(transactionOutput); unsignedTransaction = mutableTransaction; } final Transaction signedTransaction; { // Sign the transaction as if it was spending the output that does actually exist to ensure the Transaction is invalid only because of the non-existing output, not a bad signature... final HashMapTransactionOutputRepository transactionOutputRepository = new HashMapTransactionOutputRepository(); final List<TransactionOutput> transactionOutputsToSpend = transactionToSpend.getTransactionOutputs(); transactionOutputRepository.put(new TransactionOutputIdentifier(transactionToSpend.getHash(), outputIndexToSpend), transactionOutputsToSpend.get(0)); signedTransaction = TransactionTestUtil.signTransaction(transactionOutputRepository, unsignedTransaction, privateKey); } // Action final TransactionValidationResult transactionValidationResult = transactionValidator.validateTransaction(2L, signedTransaction); // Assert Assert.assertFalse(transactionValidationResult.isValid); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeNodeConnection.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.network.p2p.message.ProtocolMessage; import com.softwareverde.network.p2p.node.NodeConnection; public class FakeNodeConnection extends NodeConnection { public final FakeBinarySocket fakeBinarySocket; protected final MutableList<ProtocolMessage> _outboundMessageQueue = new MutableList<ProtocolMessage>(); public FakeNodeConnection(final FakeBinarySocket fakeBinarySocket, final ThreadPool threadPool) { super(fakeBinarySocket, threadPool); this.fakeBinarySocket = fakeBinarySocket; } @Override protected void _processOutboundMessageQueue() { } @Override protected void _writeOrQueueMessage(final ProtocolMessage message) { _outboundMessageQueue.add(message); } public List<ProtocolMessage> getSentMessages() { try { Thread.sleep(500L); } catch (final Exception e) { } // Required to wait for messageQueue... return _outboundMessageQueue; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/fullnode/FullNodeDatabaseManagerFactory.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.fullnode; import com.softwareverde.bitcoin.inflater.MasterInflater; import com.softwareverde.bitcoin.server.configuration.CheckpointConfiguration; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.UnspentTransactionOutputDatabaseManager; import com.softwareverde.bitcoin.server.module.node.store.PendingBlockStore; import com.softwareverde.database.DatabaseException; public class FullNodeDatabaseManagerFactory implements DatabaseManagerFactory { protected final DatabaseConnectionFactory _databaseConnectionFactory; protected final Integer _maxQueryBatchSize; protected final PendingBlockStore _blockStore; protected final MasterInflater _masterInflater; protected final CheckpointConfiguration _checkpointConfiguration; protected final Long _maxUtxoCount; protected final Float _utxoPurgePercent; public FullNodeDatabaseManagerFactory(final DatabaseConnectionFactory databaseConnectionFactory, final Integer maxQueryBatchSize, final PendingBlockStore blockStore, final MasterInflater masterInflater, final CheckpointConfiguration checkpointConfiguration) { this(databaseConnectionFactory, maxQueryBatchSize, blockStore, masterInflater, checkpointConfiguration, UnspentTransactionOutputDatabaseManager.DEFAULT_MAX_UTXO_CACHE_COUNT, UnspentTransactionOutputDatabaseManager.DEFAULT_PURGE_PERCENT); } public FullNodeDatabaseManagerFactory(final DatabaseConnectionFactory databaseConnectionFactory, final Integer maxQueryBatchSize, final PendingBlockStore blockStore, final MasterInflater masterInflater, final CheckpointConfiguration checkpointConfiguration, final Long maxUtxoCount, final Float utxoPurgePercent) { _databaseConnectionFactory = databaseConnectionFactory; _maxQueryBatchSize = maxQueryBatchSize; _blockStore = blockStore; _masterInflater = masterInflater; _maxUtxoCount = maxUtxoCount; _utxoPurgePercent = utxoPurgePercent; _checkpointConfiguration = checkpointConfiguration; } @Override public FullNodeDatabaseManager newDatabaseManager() throws DatabaseException { final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection(); return new FullNodeDatabaseManager(databaseConnection, _maxQueryBatchSize, _blockStore, _masterInflater, _checkpointConfiguration, _maxUtxoCount, _utxoPurgePercent); } @Override public DatabaseConnectionFactory getDatabaseConnectionFactory() { return _databaseConnectionFactory; } @Override public FullNodeDatabaseManagerFactory newDatabaseManagerFactory(final DatabaseConnectionFactory databaseConnectionFactory) { return new FullNodeDatabaseManagerFactory(databaseConnectionFactory, _maxQueryBatchSize, _blockStore, _masterInflater, _checkpointConfiguration, _maxUtxoCount, _utxoPurgePercent); } @Override public Integer getMaxQueryBatchSize() { return _maxQueryBatchSize; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/block/header/difficulty/DifficultyTests.java<|end_filename|> package com.softwareverde.bitcoin.block.header.difficulty; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; public class DifficultyTests { @Test public void should_return_bytes_from_exponent_and_significand_0() { // Setup final Difficulty difficulty = new ImmutableDifficulty(ByteArray.fromHexString("FFFF"), (0x1D - 0x03)); final ByteArray expectedBytes = ByteArray.fromHexString("00000000FFFF0000000000000000000000000000000000000000000000000000"); // Action final ByteArray bytes = difficulty.getBytes(); // Assert Assert.assertEquals(expectedBytes, bytes); } @Test public void should_return_bytes_from_exponent_and_significand_1() { // Setup final Difficulty difficulty = new ImmutableDifficulty(ByteArray.fromHexString("00FFFF"), (0x1D - 0x03)); final ByteArray expectedBytes = ByteArray.fromHexString("00000000FFFF0000000000000000000000000000000000000000000000000000"); // Action final ByteArray bytes = difficulty.getBytes(); // Assert Assert.assertEquals(expectedBytes, bytes); } @Test public void should_return_bytes_from_exponent_and_significand_2() { // Setup final Difficulty difficulty = new ImmutableDifficulty(ByteArray.fromHexString("00A429"), (0x1A - 0x03)); final ByteArray expectedBytes = ByteArray.fromHexString("00000000000000A4290000000000000000000000000000000000000000000000"); // Action final ByteArray bytes = difficulty.getBytes(); // Assert Assert.assertEquals(expectedBytes, bytes); } @Test public void should_not_be_satisfied_by_larger_hash() { // Setup final Difficulty difficulty = new ImmutableDifficulty(ByteArray.fromHexString("00FFFF"), (0x1D - 0x03)); Assert.assertEquals(ByteArray.fromHexString( "00000000FFFF0000000000000000000000000000000000000000000000000000"), difficulty.getBytes()); // Ensure the test's decoding is sane... final Sha256Hash sha256Hash = Sha256Hash.fromHexString("00000001FFFF0000000000000000000000000000000000000000000000000000"); // Action final Boolean isSatisfied = difficulty.isSatisfiedBy(sha256Hash); // Assert Assert.assertFalse(isSatisfied); } @Test public void should_be_satisfied_by_equal_hash() { // Setup final Difficulty difficulty = new ImmutableDifficulty(ByteArray.fromHexString("00FFFF"), (0x1D - 0x03)); Assert.assertEquals(ByteArray.fromHexString( "00000000FFFF0000000000000000000000000000000000000000000000000000"), difficulty.getBytes()); // Ensure the test's decoding is sane... final Sha256Hash sha256Hash = Sha256Hash.fromHexString("00000000FFFF0000000000000000000000000000000000000000000000000000"); // Action final Boolean isSatisfied = difficulty.isSatisfiedBy(sha256Hash); // Assert Assert.assertTrue(isSatisfied); } @Test public void should_be_satisfied_by_smaller_hash_0() { // Setup final Difficulty difficulty = new ImmutableDifficulty(ByteArray.fromHexString("00FFFF"), (0x1D - 0x03)); Assert.assertEquals(ByteArray.fromHexString( "00000000FFFF0000000000000000000000000000000000000000000000000000"), difficulty.getBytes()); // Ensure the test's decoding is sane... final Sha256Hash sha256Hash = Sha256Hash.fromHexString("00000000FFFE0000000000000000000000000000000000000000000000000000"); // Action final Boolean isSatisfied = difficulty.isSatisfiedBy(sha256Hash); // Assert Assert.assertTrue(isSatisfied); } @Test public void should_be_satisfied_by_smaller_hash_1() { // Setup final Difficulty difficulty = new ImmutableDifficulty(ByteArray.fromHexString("00FFFF"), (0x1D - 0x03)); Assert.assertEquals(ByteArray.fromHexString( "00000000FFFF0000000000000000000000000000000000000000000000000000"), difficulty.getBytes()); // Ensure the test's decoding is sane... final Sha256Hash sha256Hash = Sha256Hash.fromHexString("000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); // Action final Boolean isSatisfied = difficulty.isSatisfiedBy(sha256Hash); // Assert Assert.assertTrue(isSatisfied); } @Test public void should_encode_base_difficulty() { // Setup final Difficulty difficulty = new ImmutableDifficulty(ByteArray.fromHexString("00FFFF"), (0x1D - 0x03)); final ByteArray expectedEncoding = ByteArray.fromHexString("1D00FFFF"); // Action final ByteArray encodedBytes = difficulty.encode(); // Assert Assert.assertEquals(expectedEncoding, encodedBytes); } @Test public void should_return_bytes_from_small_exponent_and_significand_0() { // Setup final Difficulty difficulty = new ImmutableDifficulty(ByteArray.fromHexString("01"), 0x00); final ByteArray expectedBytes = ByteArray.fromHexString("0000000000000000000000000000000000000000000000000000000000000001"); // Action final ByteArray bytes = difficulty.getBytes(); // Assert Assert.assertEquals(expectedBytes, bytes); } @Test public void should_return_bytes_from_small_exponent_and_significand_1() { // Setup final Difficulty difficulty = new ImmutableDifficulty(ByteArray.fromHexString("FF"), 0x01); final ByteArray expectedBytes = ByteArray.fromHexString("000000000000000000000000000000000000000000000000000000000000FF00"); // Action final ByteArray bytes = difficulty.getBytes(); // Assert Assert.assertEquals(expectedBytes, bytes); } @Test public void should_encode_and_decode_bytes_from_small_exponent_and_significand() { // Setup final Difficulty difficulty = new ImmutableDifficulty(ByteArray.fromHexString("FF"), 0x00); final ByteArray expectedEncodedBytes = ByteArray.fromHexString("030000FF"); final ByteArray expectedRawBytes = ByteArray.fromHexString("00000000000000000000000000000000000000000000000000000000000000FF"); // Action final ByteArray encodedBytes = difficulty.encode(); final ByteArray rawBytes0 = difficulty.getBytes(); final ByteArray rawBytes1 = Difficulty.decode(encodedBytes).getBytes(); // Assert Assert.assertEquals(expectedEncodedBytes, encodedBytes); Assert.assertEquals(expectedRawBytes, rawBytes0); Assert.assertEquals(expectedRawBytes, rawBytes1); } @Test public void should_encode_and_decode_base_difficulty() { // Setup final ByteArray encodedBaseDifficulty = ByteArray.fromHexString("1D00FFFF"); final ByteArray expectedRawBytes = ByteArray.fromHexString("00000000FFFF0000000000000000000000000000000000000000000000000000"); final Difficulty difficulty0, difficulty1; // Action difficulty0 = Difficulty.decode(encodedBaseDifficulty); final ByteArray encodedBytes0 = difficulty0.encode(); difficulty1 = Difficulty.decode(encodedBytes0); final ByteArray rawBytes0 = difficulty0.getBytes(); final ByteArray rawBytes1 = difficulty1.getBytes(); // Assert Assert.assertEquals(expectedRawBytes, rawBytes0); Assert.assertEquals(expectedRawBytes, rawBytes1); } @Test public void should_create_correct_difficulty_ratio() { // Setup final String difficultyEncodedString = "18031849"; // Difficulty for Block 0000000000000000019215F45AC2190F5316FF2E4BB6ED300104585384269F93 final BigDecimal expectedDifficultyRatio = new BigDecimal("355264363497.1042"); final Difficulty difficulty = Difficulty.decode(ByteArray.fromHexString(difficultyEncodedString)); // Action final BigDecimal difficultyRatio = difficulty.getDifficultyRatio(); // Assert Assert.assertEquals(expectedDifficultyRatio, difficultyRatio); } @Test public void multiplying_difficulty_by_1_should_not_change_its_value() { // Setup final Difficulty difficulty = Difficulty.BASE_DIFFICULTY; // Action final Difficulty multipliedDifficulty = difficulty.multiplyBy(1.0F); // Assert Assert.assertEquals(difficulty, multipliedDifficulty); } @Test public void should_recreate_first_difficulty_adjustment_based_on_ratio() { // Setup final Difficulty difficulty = Difficulty.BASE_DIFFICULTY; // NOTE: The listed difficulty adjustment on blockchain.info is 1.18. // However, when investigating the actual difficulty, it is 1.182899... // Command To Verify: bitcoin-cli getblockhash 32256 | xargs bitcoin-cli getblock final Float firstDifficultyAdjustment = 1.0F / 1.182899534312841F; final Difficulty expectedDifficulty = Difficulty.decode(ByteArray.fromHexString("1D00D86A")); // Action final Difficulty multipliedDifficulty = difficulty.multiplyBy(firstDifficultyAdjustment); // Assert Assert.assertEquals(expectedDifficulty, multipliedDifficulty); } @Test public void higher_difficulty_value_should_be_less_difficult() { // Setup final Difficulty difficulty = Difficulty.decode(ByteArray.fromHexString("1D01B304")); final Difficulty baseDifficulty = Difficulty.BASE_DIFFICULTY; // Action final Boolean isLessThan = difficulty.isLessDifficultThan(baseDifficulty); // Assert Assert.assertTrue(isLessThan); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/thin/request/block/RequestExtraThinBlockMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.thin.request.block; import com.softwareverde.bitcoin.bloomfilter.BloomFilterDeflater; import com.softwareverde.bitcoin.inflater.BloomFilterInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItem; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItemInflater; import com.softwareverde.bloomfilter.BloomFilter; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.util.bytearray.ByteArrayBuilder; public class RequestExtraThinBlockMessage extends BitcoinProtocolMessage { protected final BloomFilterInflaters _bloomFilterInflaters; protected InventoryItem _inventoryItem = null; protected BloomFilter _bloomFilter = null; public RequestExtraThinBlockMessage(final BloomFilterInflaters bloomFilterInflaters) { super(MessageType.REQUEST_EXTRA_THIN_BLOCK); _bloomFilterInflaters = bloomFilterInflaters; } public InventoryItem getInventoryItem() { return _inventoryItem; } public BloomFilter getBloomFilter() { return _bloomFilter; } public void setInventoryItem(final InventoryItem inventoryItem) { _inventoryItem = inventoryItem; } public void setBloomFilter(final BloomFilter bloomFilter) { _bloomFilter = bloomFilter; } @Override protected ByteArray _getPayload() { final BloomFilterDeflater bloomFilterDeflater = _bloomFilterInflaters.getBloomFilterDeflater(); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(_inventoryItem.getBytes()); byteArrayBuilder.appendBytes(bloomFilterDeflater.toBytes(_bloomFilter)); return byteArrayBuilder; } @Override protected Integer _getPayloadByteCount() { final BloomFilterDeflater bloomFilterDeflater = _bloomFilterInflaters.getBloomFilterDeflater(); return (InventoryItemInflater.BYTE_COUNT + bloomFilterDeflater.getByteCount(_bloomFilter)); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/rpc/blockchain/BlockchainMetadataBuilder.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.rpc.blockchain; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; public class BlockchainMetadataBuilder { protected BlockchainMetadata _blockchainMetadata = null; protected void _ensureObjectExists() { if (_blockchainMetadata == null) { _blockchainMetadata = new BlockchainMetadata(); } } public void setBlockchainSegmentId(final BlockchainSegmentId blockchainSegmentId) { _ensureObjectExists(); _blockchainMetadata._blockchainSegmentId = blockchainSegmentId; } public void setParentBlockchainSegmentId(final BlockchainSegmentId blockchainSegmentId) { _ensureObjectExists(); _blockchainMetadata._parentBlockchainSegmentId = blockchainSegmentId; } public void setNestedSet(final Integer nestedSetLeft, final Integer nestedSetRight) { _ensureObjectExists(); _blockchainMetadata._nestedSetLeft = nestedSetLeft; _blockchainMetadata._nestedSetRight = nestedSetRight; } public void setBlockCount(final Long blockCount) { _ensureObjectExists(); _blockchainMetadata._blockCount = blockCount; } public void setBlockHeight(final Long minBlockHeight, final Long maxBlockHeight) { _ensureObjectExists(); _blockchainMetadata._minBlockHeight = minBlockHeight; _blockchainMetadata._maxBlockHeight = maxBlockHeight; } public BlockchainMetadata build() { final BlockchainMetadata blockchainMetadata = _blockchainMetadata; _blockchainMetadata = null; return blockchainMetadata; } } <|start_filename|>src/main/java/com/softwareverde/constable/list/JavaListWrapper.java<|end_filename|> package com.softwareverde.constable.list; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.util.Util; import java.util.Iterator; public class JavaListWrapper<T> implements List<T> { public static <T> List<T> wrap(final Iterable<T> javaIterable) { if (javaIterable instanceof List) { return (List<T>) javaIterable; } return new JavaListWrapper<T>(javaIterable); } protected final Iterable<T> _javaUtilIterable; protected JavaListWrapper(final Iterable<T> javaUtilIterable) { _javaUtilIterable = javaUtilIterable; } @Override public T get(final int index) { if (index < 0) { throw new IndexOutOfBoundsException(); } int i = 0; for (final T item : _javaUtilIterable) { if (i == index) { return item; } i += 1; } throw new IndexOutOfBoundsException(); } @Deprecated @Override public int getSize() { int i = 0; for (final T item : _javaUtilIterable) { i += 1; } return i; } @Override public boolean isEmpty() { for (final T item : _javaUtilIterable) { return false; } return true; } @Override public boolean contains(final T desiredItem) { for (final T item : _javaUtilIterable) { if (Util.areEqual(desiredItem, item)) { return true; } } return false; } @Override public int indexOf(final T desiredItem) { int i = 0; for (final T item : _javaUtilIterable) { if (Util.areEqual(desiredItem, item)) { return i; } } return -1; } @Override public ImmutableList<T> asConst() { final ImmutableListBuilder<T> immutableListBuilder = new ImmutableListBuilder<T>(); for (final T item : _javaUtilIterable) { immutableListBuilder.add(item); } return immutableListBuilder.build(); } @Override public Iterator<T> iterator() { return new ImmutableJavaUtilListIterator<T>(_javaUtilIterable); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/validator/TransactionValidator.java<|end_filename|> package com.softwareverde.bitcoin.transaction.validator; import com.softwareverde.bitcoin.context.MedianBlockTimeContext; import com.softwareverde.bitcoin.context.NetworkTimeContext; import com.softwareverde.bitcoin.context.UnspentTransactionOutputContext; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; public interface TransactionValidator { interface Context extends MedianBlockTimeContext, NetworkTimeContext, UnspentTransactionOutputContext, TransactionInflaters { } Long COINBASE_MATURITY = 100L; // Number of Blocks before a coinbase transaction may be spent. Integer MAX_SIGNATURE_OPERATIONS = 3000; // Number of Signature operations allowed per Transaction. SequenceNumber FINAL_SEQUENCE_NUMBER = SequenceNumber.MAX_SEQUENCE_NUMBER; // If all inputs are "FINAL" then ignore lock time /** * Returns true iff the transaction would be valid for the provided blockHeight. * For acceptance into the mempool, blockHeight should be 1 greater than the current blockchain's head blockHeight. */ TransactionValidationResult validateTransaction(Long blockHeight, Transaction transaction); } <|start_filename|>explorer/www/css/documentation.css<|end_filename|> #main a, #main a:hover, #main a:visited, #main a:active { text-decoration: none; color: #B56200; } #header { z-index: 1; } #main { margin-top: 5px; } .sidebar { background: #FFFFFF; float: left; position: fixed; box-sizing: border-box; border-right: solid 2px #ADADAD; height: 100%; width: 19em; max-width: 25vw; word-break: break-word; } #sidebar-underlay { top: 0px; z-index: -1; text-align: center; padding-top: 1em; overflow: hidden; } #sidebar-underlay h1 { background-color: #262626; margin-top: -2em; padding-top: 2em; padding-bottom: 1em; color: #FFFFFF; border-bottom: solid 2px #F99300; box-shadow: 0px 1px 25px #262626; } #sidebar { padding-right: 2em; padding-top: 0; padding-left: 1em; } #outline { } #content { float: right; width: calc(100% - 19em); box-sizing: border-box; padding-right: 2em; padding-top: 3em; } pre, tt { background-color: #FFFFFF; color: #731212; font-family: consolas, monospace; font-size: 0.75em; } tt { display: inline-block; position: relative; top: -2px; vertical-align: middle; padding: 1px; padding-left: 0.5em; padding-right: 0.5em; border: solid 1px #ADADAD; border-radius: 0.5em; } pre { padding-left: 1em; padding-right: 1em; padding-top: 0.5em; padding-bottom: 0.5em; margin-left: 2em; border: solid 1px #E0E0E0; border-left: solid 2px #731212; overflow-x: scroll; } .section { margin-bottom: 2em; border-bottom: solid 2px #F7931D; padding-bottom: 1em; padding-left: 2em; } .section h1, .section h2, .section h3, .section th { font-family: 'Bree Serif', serif; word-break: break-word; } .section h2 { padding-left: 1.33em; } .section .h2-content { padding-left: 2em; } .section h3 { padding-left: 1.71em; } .section .h3-content { padding-left: 2em; } .section table { margin-left: 2em; border: solid 1px #B0B0B0; border-collapse: collapse; } .section table th { background-color: rgba(0, 0, 0, 0.05); border-bottom: solid 1px #B0B0B0; padding: 0.25em; } .section table tr:nth-child(odd) { background-color: rgba(0, 0, 0, 0.05); } .section table td { padding: 0.25em; font-size: 0.85em; } .section table.configuration td:nth-child(2), .section table.configuration td:nth-child(3) { font-family: consolas, monospace; width: 10%; text-align: center; } .section table.configuration td:nth-child(3) { width: auto; } .section table.rpc td:nth-child(1), .section table.rpc td:nth-child(2) { font-family: consolas, monospace; width: 10%; text-align: center; } .section table.rpc td:nth-child(3) { text-align: center; } .parameter { display: inline-block; font-family: consolas, monospace; } .parameter::before { content: '<'; } .parameter::after { content: '>'; } .parameter.optional { font-style: italic; } .parameter.mandatory { font-weight: bold; } .section::before { font-family: 'Bree Serif', serif; font-size: 150%; font-weight: bold; margin-bottom: 0.5em; margin-top: 1em; } .section.getting-started::before { content: 'Getting Started'; } .section.purpose::before { content: 'Purpose'; } .section.project-structure::before { content: 'Project Structure'; } .section.build::before { content: 'Build'; } .section.run::before { content: 'Run'; } .section.configuration::before { content: 'Configuration'; } .section.rpc::before { content: 'RPC'; } .section.technical-notes::before { content: 'Development/Technical Notes'; } .section:last-child { margin-bottom: 90vh; } /* @media only screen and (max-width: 1000px) { */ @media only screen and (max-width: 1024px) { .section { padding-left: 0; padding-right: 0; } .sidebar { position: initial; width: 100%; max-width: unset; border: none; } #sidebar-underlay h1 { background: none; color: #262626; padding-top: 1.5em; margin-top: -1em; box-shadow: none; margin-bottom: 0; border-bottom: none; background: #EEEEEE; } #sidebar { position: fixed; height: auto; left: 0; right: 0; bottom: 0; border-top: solid 2px #b3b3b3; text-align: center; z-index: 1; background: #FFF; padding: 0.5em; } #sidebar ol { padding: 0; margin: 0; display: flex; flex-wrap: wrap; } #sidebar ol li { text-decoration: none; border: solid 1px #e2e2e2; padding: 0.5em; font-size: 85%; font-weight: bold; margin: 1px; display: inline-flex; padding-left: 0.5em; padding-right: 0.5em; flex-direction: column; flex-grow: 1; } #sidebar ol li a { color: #262626 !important; } #sidebar ol li.technical-notes { /* max-width: 10%;*/ } #sidebar ol li.technical-notes a { word-break: normal; height: 1em; overflow: hidden; } #sidebar ol li.technical-notes a::before { content: 'Notes\A'; display: block; color: #202020; text-align: center; } #content { width: auto; float: none; padding-left: 1em; padding-right: 1em; margin: 0; padding-top: 0; } .section h2, .section .h2-content, .section h3, .section .h3-content { padding-left: 0; } .section table { margin-left: 0; } } <|start_filename|>src/main/java/com/softwareverde/network/socket/PacketBuffer.java<|end_filename|> package com.softwareverde.network.socket; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.logging.Logger; import com.softwareverde.network.p2p.message.ProtocolMessage; import com.softwareverde.network.p2p.message.ProtocolMessageFactory; import com.softwareverde.network.p2p.message.ProtocolMessageHeader; import com.softwareverde.network.p2p.message.ProtocolMessageHeaderInflater; import com.softwareverde.util.ByteBuffer; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.HexUtil; import com.softwareverde.util.Util; public class PacketBuffer extends ByteBuffer { protected final ByteArray _reverseEndianMagicNumber; protected final ProtocolMessageHeaderInflater _protocolMessageHeaderInflater; protected final ProtocolMessageFactory<?> _protocolMessageFactory; @Override protected boolean _shouldAllowNewBuffer(final byte[] byteBuffer, final int byteCount) { final boolean shouldAllowNewBuffer = super._shouldAllowNewBuffer(byteBuffer, byteCount); if (! shouldAllowNewBuffer) { Logger.warn("Packet buffer exceeded max size, clearing buffer."); _resetBuffer(); } return true; } protected ProtocolMessageHeader _peakProtocolHeader() { final int headerByteCount = _protocolMessageHeaderInflater.getHeaderByteCount(); if (_byteCount < headerByteCount) { return null; } final byte[] packetHeader = _peakContiguousBytes(headerByteCount); return _protocolMessageHeaderInflater.fromBytes(packetHeader); } public PacketBuffer(final BinaryPacketFormat binaryPacketFormat) { final ByteArray magicNumber = binaryPacketFormat.getMagicNumber(); _reverseEndianMagicNumber = magicNumber.toReverseEndian(); _protocolMessageHeaderInflater = binaryPacketFormat.getProtocolMessageHeaderInflater(); _protocolMessageFactory = binaryPacketFormat.getProtocolMessageFactory(); } public boolean hasMessage() { final ProtocolMessageHeader protocolMessageHeader = _peakProtocolHeader(); if (protocolMessageHeader == null) { return false; } final int expectedMessageLength = (protocolMessageHeader.getPayloadByteCount() + _protocolMessageHeaderInflater.getHeaderByteCount()); return (_byteCount >= expectedMessageLength); } public void evictCorruptedPackets() { final int magicNumberByteCount = _reverseEndianMagicNumber.getByteCount(); if (magicNumberByteCount <= 0) { return; } final int headerByteCount = _protocolMessageHeaderInflater.getHeaderByteCount(); if (headerByteCount <= 0) { return; } while (_byteCount > 0) { final byte[] bytes = _peakContiguousBytes(Math.min(magicNumberByteCount, _byteCount)); boolean matched = true; for (int i = 0; i < bytes.length; ++i) { final byte requiredByte = _reverseEndianMagicNumber.getByte(i); final byte foundByte = bytes[i]; if (foundByte != requiredByte) { final byte[] discardedBytes = _consumeContiguousBytes(i + 1); Logger.trace("Discarded: " + HexUtil.toHexString(discardedBytes)); matched = false; break; } } if (matched) { break; } } } public ProtocolMessage popMessage() { final ProtocolMessageHeader protocolMessageHeader = _peakProtocolHeader(); if (protocolMessageHeader == null) { return null; } final int headerByteCount = _protocolMessageHeaderInflater.getHeaderByteCount(); final int payloadByteCount = protocolMessageHeader.getPayloadByteCount(); if (_byteCount < payloadByteCount) { Logger.debug("PacketBuffer.popMessage: Insufficient byte count."); return null; } final int fullPacketByteCount = (headerByteCount + payloadByteCount); final byte[] fullPacket = _consumeContiguousBytes(fullPacketByteCount); if (fullPacketByteCount > Util.coalesce(_protocolMessageHeaderInflater.getMaxPacketByteCount(protocolMessageHeader), Integer.MAX_VALUE)) { Logger.debug("Dropping packet. Packet exceeded max byte count: " + fullPacketByteCount); return null; } final ProtocolMessage protocolMessage = _protocolMessageFactory.fromBytes(fullPacket); if (protocolMessage == null) { Logger.debug("Error inflating message: " + HexUtil.toHexString(ByteUtil.copyBytes(fullPacket, 0, Math.min(fullPacket.length, 128))) + " (+"+ ( (fullPacket.length > 128) ? (fullPacket.length - 128) : 0 ) +" bytes)"); } return protocolMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/header/ImmutableBlockHeader.java<|end_filename|> package com.softwareverde.bitcoin.block.header; import com.softwareverde.bitcoin.block.BlockHasher; import com.softwareverde.constable.Const; public class ImmutableBlockHeader extends BlockHeaderCore implements BlockHeader, Const { protected ImmutableBlockHeader(final BlockHasher blockHasher) { super(blockHasher); } public ImmutableBlockHeader() { } public ImmutableBlockHeader(final BlockHeader blockHeader) { super(blockHeader); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/thin/request/block/RequestExtraThinBlockMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.thin.request.block; import com.softwareverde.bitcoin.bloomfilter.BloomFilterInflater; import com.softwareverde.bitcoin.inflater.BloomFilterInflaters; import com.softwareverde.bitcoin.inflater.InventoryItemInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItem; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItemInflater; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.bloomfilter.BloomFilter; public class RequestExtraThinBlockMessageInflater extends BitcoinProtocolMessageInflater { protected final InventoryItemInflaters _inventoryItemInflaters; protected final BloomFilterInflaters _bloomFilterInflaters; public RequestExtraThinBlockMessageInflater(final InventoryItemInflaters inventoryItemInflaters, final BloomFilterInflaters bloomFilterInflaters) { _inventoryItemInflaters = inventoryItemInflaters; _bloomFilterInflaters = bloomFilterInflaters; } @Override public RequestExtraThinBlockMessage fromBytes(final byte[] bytes) { final RequestExtraThinBlockMessage requestExtraThinBlockMessage = new RequestExtraThinBlockMessage(_bloomFilterInflaters); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.REQUEST_DATA); if (protocolMessageHeader == null) { return null; } final InventoryItemInflater inventoryItemInflater = _inventoryItemInflaters.getInventoryItemInflater(); final InventoryItem inventoryItem = inventoryItemInflater.fromBytes(byteArrayReader); requestExtraThinBlockMessage.setInventoryItem(inventoryItem); final BloomFilterInflater bloomFilterInflater = _bloomFilterInflaters.getBloomFilterInflater(); final BloomFilter bloomFilter = bloomFilterInflater.fromBytes(byteArrayReader); requestExtraThinBlockMessage.setBloomFilter(bloomFilter); if (byteArrayReader.didOverflow()) { return null; } return requestExtraThinBlockMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/thin/transaction/ThinTransactionsMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.thin.transaction; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class ThinTransactionsMessage extends BitcoinProtocolMessage { protected final TransactionInflaters _transactionInflaters; protected Sha256Hash _blockHash; protected List<Transaction> _transactions = new MutableList<Transaction>(0); public ThinTransactionsMessage(final TransactionInflaters transactionInflaters) { super(MessageType.THIN_TRANSACTIONS); _transactionInflaters = transactionInflaters; } public Sha256Hash getBlockHash() { return _blockHash; } public List<Transaction> getTransactions() { return _transactions; } public void setBlockHash(final Sha256Hash blockHash) { _blockHash = blockHash; } public void setTransactions(final List<Transaction> transactions) { _transactions = transactions.asConst(); } @Override protected ByteArray _getPayload() { final TransactionDeflater transactionDeflater = _transactionInflaters.getTransactionDeflater(); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); { // Block Hash... byteArrayBuilder.appendBytes(_blockHash, Endian.LITTLE); } { // Transactions... final int transactionCount = _transactions.getCount(); byteArrayBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(transactionCount)); for (final Transaction transaction : _transactions) { byteArrayBuilder.appendBytes(transactionDeflater.toBytes(transaction)); } } return byteArrayBuilder; } @Override protected Integer _getPayloadByteCount() { final TransactionDeflater transactionDeflater = _transactionInflaters.getTransactionDeflater(); int totalTransactionByteCount = 0; for (final Transaction transaction : _transactions) { totalTransactionByteCount += transactionDeflater.getByteCount(transaction); } final int transactionCount = _transactions.getCount(); final byte[] transactionCountBytes = ByteUtil.variableLengthIntegerToBytes(transactionCount); return (Sha256Hash.BYTE_COUNT + transactionCountBytes.length + totalTransactionByteCount); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/Environment.java<|end_filename|> package com.softwareverde.bitcoin.server; import com.softwareverde.bitcoin.server.database.Database; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; public class Environment { protected final Database _database; protected final DatabaseConnectionFactory _databaseConnectionFactory; public Environment(final Database database, final DatabaseConnectionFactory databaseConnectionFactory) { _database = database; _databaseConnectionFactory = databaseConnectionFactory; } public Database getDatabase() { return _database; } public DatabaseConnectionFactory getDatabaseConnectionFactory() { return _databaseConnectionFactory; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/task/StratumMineBlockTaskBuilderFactory.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.task; public interface StratumMineBlockTaskBuilderFactory { ConfigurableStratumMineBlockTaskBuilder newStratumMineBlockTaskBuilder(Integer totalExtraNonceByteCount); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/validator/difficulty/AsertReferenceBlock.java<|end_filename|> package com.softwareverde.bitcoin.block.validator.difficulty; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import java.math.BigInteger; public class AsertReferenceBlock { protected final BigInteger blockHeight; /** * parentBlockTime is the timestamp of the Anchor's parent block. * It is not the MedianBlockTime (or the MedianTimePast) of the Anchor Block. * parentBlockTime is in seconds. */ protected final Long parentBlockTimestamp; protected final Difficulty difficulty; public AsertReferenceBlock(final Long blockHeight, final Long parentBlockTimestamp, final Difficulty difficulty) { this.blockHeight = BigInteger.valueOf(blockHeight); this.parentBlockTimestamp = parentBlockTimestamp; this.difficulty = difficulty; } public AsertReferenceBlock(final BigInteger blockHeight, final Long parentBlockTimestamp, final Difficulty difficulty) { this.blockHeight = blockHeight; this.parentBlockTimestamp = parentBlockTimestamp; this.difficulty = difficulty; } } <|start_filename|>src/main/java/com/softwareverde/network/ip/Ipv4.java<|end_filename|> package com.softwareverde.network.ip; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.ImmutableByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.StringUtil; import com.softwareverde.util.Util; import java.util.List; public class Ipv4 implements Ip { public static final Integer BYTE_COUNT = 4; protected static byte[] _parse(final String string) { final String trimmedString = string.trim(); final String strippedIp = trimmedString.replaceAll("[^0-9\\.]", ""); final Boolean stringContainedInvalidCharacters = (strippedIp.length() != trimmedString.length()); if (stringContainedInvalidCharacters) { return null; } final List<String> ipSegments = StringUtil.pregMatch("^([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)$", strippedIp); final byte[] bytes = new byte[ipSegments.size()]; for (int i = 0; i < bytes.length; ++i) { final String ipSegment = ipSegments.get(i); final Integer intValue = Util.parseInt(ipSegment); if (intValue > 255) { return null; } bytes[i] = (byte) intValue.intValue(); } return bytes; } public static Ipv4 fromBytes(final byte[] bytes) { if (bytes.length != 4) { return null; } return new Ipv4(bytes); } public static Ipv4 parse(final String string) { if (string == null) { return null; } final byte[] segments = _parse(string); if (segments == null) { return null; } if (segments.length != BYTE_COUNT) { return null; } return new Ipv4(segments); } private final ByteArray _bytes; public Ipv4() { _bytes = new MutableByteArray(BYTE_COUNT); } public Ipv4(final byte[] ipByteSegments) { if (ipByteSegments.length == BYTE_COUNT) { _bytes = new ImmutableByteArray(ipByteSegments); } else { _bytes = new MutableByteArray(BYTE_COUNT); } } @Override public ByteArray getBytes() { return _bytes; } @Override public String toString() { final StringBuilder stringBuilder = new StringBuilder(); String separator = ""; for (int i = 0; i < BYTE_COUNT; ++i) { final byte b = _bytes.getByte(i); final int byteInteger = ByteUtil.byteToInteger(b); stringBuilder.append(separator); stringBuilder.append(byteInteger); separator = "."; } return stringBuilder.toString(); } @Override public boolean equals(final Object object) { if (object == null) { return false; } if (! (object instanceof Ipv4)) { return false; } final Ipv4 ipv4 = (Ipv4) object; return Util.areEqual(_bytes, ipv4._bytes); } @Override public int hashCode() { return _bytes.hashCode(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/manager/banfilter/BanFilter.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager.banfilter; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.network.ip.Ip; import java.util.regex.Pattern; public interface BanFilter { Boolean isIpBanned(Ip ip); void banIp(Ip ip); void unbanIp(Ip ip); void addToWhitelist(Ip ip); void removeIpFromWhitelist(Ip ip); void addToUserAgentBlacklist(Pattern pattern); void removePatternFromUserAgentBlacklist(Pattern pattern); void onNodeConnected(Ip ip); void onNodeHandshakeComplete(BitcoinNode bitcoinNode); void onNodeDisconnected(Ip ip); /** * Returns false if bad inventory was received and marks the node as banned. */ Boolean onInventoryReceived(BitcoinNode bitcoinNode, List<Sha256Hash> blockInventory); /** * Returns false if bad block headers were received and marks the node as banned. */ Boolean onHeadersReceived(BitcoinNode bitcoinNode, List<BlockHeader> blockHeaders); } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/sync/SlpTransactionProcessorAccumulatorTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.context.core.BlockProcessorContext; import com.softwareverde.bitcoin.context.core.BlockchainBuilderContext; import com.softwareverde.bitcoin.context.core.PendingBlockLoaderContext; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.module.node.BlockProcessor; import com.softwareverde.bitcoin.server.module.node.database.block.pending.fullnode.FullNodePendingBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.sync.blockloader.PendingBlockLoader; import com.softwareverde.bitcoin.slp.validator.TransactionAccumulator; import com.softwareverde.bitcoin.test.BlockData; import com.softwareverde.bitcoin.test.FakeBlockStore; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.concurrent.service.SleepyService; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.network.time.MutableNetworkTime; import com.softwareverde.util.HexUtil; import org.junit.Assert; import org.junit.Test; import java.util.Map; public class SlpTransactionProcessorAccumulatorTests extends IntegrationTest { @Test public void accumulator_should_load_existing_confirmed_transaction() throws Exception { // Setup final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final TransactionInflaters transactionInflaters = _masterInflater; final FakeBlockStore blockStore = new FakeBlockStore(); final BlockchainBuilderTests.FakeBitcoinNodeManager bitcoinNodeManager = new BlockchainBuilderTests.FakeBitcoinNodeManager(); final BlockInflaters blockInflaters = BlockchainBuilderTests.FAKE_BLOCK_INFLATERS; final BlockProcessorContext blockProcessorContext = new BlockProcessorContext(blockInflaters, transactionInflaters, blockStore, _fullNodeDatabaseManagerFactory, new MutableNetworkTime(), _synchronizationStatus, _transactionValidatorFactory); final PendingBlockLoaderContext pendingBlockLoaderContext = new PendingBlockLoaderContext(blockInflaters, _fullNodeDatabaseManagerFactory, _threadPool); final BlockchainBuilderContext blockchainBuilderContext = new BlockchainBuilderContext(blockInflaters, _fullNodeDatabaseManagerFactory, bitcoinNodeManager, _threadPool); final BlockProcessor blockProcessor = new BlockProcessor(blockProcessorContext); final PendingBlockLoader pendingBlockLoader = new PendingBlockLoader(pendingBlockLoaderContext, 1); try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final FullNodePendingBlockDatabaseManager pendingBlockDatabaseManager = databaseManager.getPendingBlockDatabaseManager(); for (final String blockData : new String[]{ BlockData.MainChain.GENESIS_BLOCK, BlockData.MainChain.BLOCK_1, BlockData.MainChain.BLOCK_2 }) { final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(blockData)); pendingBlockDatabaseManager.storeBlock(block); } // Store Unconfirmed transactions... // final PendingTransactionDatabaseManager pendingTransactionDatabaseManager = databaseManager.getPendingTransactionDatabaseManager(); // pendingTransactionDatabaseManager.storeTransaction(signedTransaction0); } try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final TransactionAccumulator transactionAccumulator = SlpTransactionProcessor.createTransactionAccumulator(databaseManager, null); { // Store the prerequisite blocks which contains the transaction to lookup... final BlockchainBuilder blockchainBuilder = new BlockchainBuilder(blockchainBuilderContext, blockProcessor, pendingBlockLoader, BlockchainBuilderTests.FAKE_DOWNLOAD_STATUS_MONITOR, BlockchainBuilderTests.FAKE_BLOCK_DOWNLOAD_REQUESTER); final BlockchainBuilder.StatusMonitor statusMonitor = blockchainBuilder.getStatusMonitor(); blockchainBuilder.start(); final int maxSleepCount = 10; int sleepCount = 0; do { Thread.sleep(250L); sleepCount += 1; if (sleepCount >= maxSleepCount) { throw new RuntimeException("Test execution timeout exceeded."); } } while (statusMonitor.getStatus() != SleepyService.Status.SLEEPING); blockchainBuilder.stop(); } final Sha256Hash transactionHash0 = Sha256Hash.fromHexString("0E3E2357E806B6CDB1F70B54C3A3A17B6714EE1F0E68BEBB44A74B1EFD512098"); final Sha256Hash transactionHash1 = Sha256Hash.fromHexString("9B0FC92260312CE44E74EF369F5C66BBB85848F2EDDD5A7A1CDE251E54CCFDD5"); final List<Sha256Hash> transactionHashes = new ImmutableList<Sha256Hash>( transactionHash0, transactionHash1 ); // Action final Map<Sha256Hash, Transaction> transactions = transactionAccumulator.getTransactions(transactionHashes, false); // Assert final Transaction transaction0 = transactions.get(transactionHash0); final Transaction transaction1 = transactions.get(transactionHash1); Assert.assertNotNull(transaction0); Assert.assertNotNull(transaction1); Assert.assertEquals(transactionHash0, transaction0.getHash()); Assert.assertEquals(transactionHash1, transaction1.getHash()); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/util/BitcoinUtil.java<|end_filename|> package com.softwareverde.bitcoin.util; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.secp256k1.signature.BitcoinMessageSignature; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.secp256k1.Secp256k1; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.cryptography.secp256k1.key.PublicKey; import com.softwareverde.cryptography.secp256k1.signature.Secp256k1Signature; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.logging.Logger; import com.softwareverde.util.Base32Util; import com.softwareverde.util.Base58Util; import com.softwareverde.util.Container; import com.softwareverde.util.bytearray.ByteArrayBuilder; import java.nio.charset.StandardCharsets; public class BitcoinUtil { protected static Sha256Hash _getBitcoinMessagePreImage(final String message) { final String preamble = "Bitcoin Signed Message:\n"; final byte[] preambleBytes = preamble.getBytes(StandardCharsets.UTF_8); final byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendByte((byte) (preambleBytes.length & 0xFF)); byteArrayBuilder.appendBytes(preambleBytes); byteArrayBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(messageBytes.length)); byteArrayBuilder.appendBytes(messageBytes); return HashUtil.doubleSha256(MutableByteArray.wrap(byteArrayBuilder.build())); } public static String toBase58String(final byte[] bytes) { return Base58Util.toBase58String(bytes); } public static byte[] base58StringToBytes(final String base58String) { return Base58Util.base58StringToByteArray(base58String); } public static String toBase32String(final byte[] bytes) { return Base32Util.toBase32String(bytes); } public static byte[] base32StringToBytes(final String base58String) { return Base32Util.base32StringToByteArray(base58String); } public static String reverseEndianString(final String string) { final int charCount = string.length(); final char[] reverseArray = new char[charCount]; for (int i = 0; i < (charCount / 2); ++i) { int index = (charCount - (i * 2)) - 1; reverseArray[i * 2] = string.charAt(index - 1); reverseArray[(i * 2) + 1] = string.charAt(index); } return new String(reverseArray); } public static BitcoinMessageSignature signBitcoinMessage(final PrivateKey privateKey, final String message, final Boolean useCompressedAddress) { final PublicKey publicKey = privateKey.getPublicKey(); final Sha256Hash preImage = _getBitcoinMessagePreImage(message); final Secp256k1Signature signature = Secp256k1.sign(privateKey, preImage.getBytes()); boolean signatureSuccessful = false; final Container<Integer> recoveryId = new Container<Integer>(-1); for (int i = 0; i < 4; ++i) { if (recoveryId.value >= 4) { break; } // PublicKey::fromSignature may also update the recoveryId... recoveryId.value = Math.max(i, (recoveryId.value + 1)); final PublicKey publicKeyUsedForSigning = PublicKey.fromSignature(signature, preImage, recoveryId); if (publicKeyUsedForSigning == null) { continue; } if (Util.areEqual(publicKey, publicKeyUsedForSigning)) { signatureSuccessful = true; break; } } if (! signatureSuccessful) { return null; } return BitcoinMessageSignature.fromSignature(signature, recoveryId.value, useCompressedAddress); } public static Boolean verifyBitcoinMessage(final String message, final Address address, final BitcoinMessageSignature bitcoinMessageSignature) { final AddressInflater addressInflater = new AddressInflater(); final Container<Integer> recoveryId = new Container<Integer>(); final Sha256Hash preImage = _getBitcoinMessagePreImage(message); final Boolean isCompressedAddress = bitcoinMessageSignature.isCompressedAddress(); recoveryId.value = bitcoinMessageSignature.getRecoveryId(); final Secp256k1Signature secp256k1Signature = bitcoinMessageSignature.getSignature(); final PublicKey publicKeyUsedForSigning = PublicKey.fromSignature(secp256k1Signature, preImage, recoveryId); if (publicKeyUsedForSigning == null) { return false; } if (! Util.areEqual(bitcoinMessageSignature.getRecoveryId(), recoveryId.value)) { return false; } // The provided recoveryId was incorrect. final Address publicKeyAddress = addressInflater.fromPublicKey(publicKeyUsedForSigning, isCompressedAddress); if (! Util.areEqual(address, publicKeyAddress)) { return false; } return Secp256k1.verifySignature(secp256k1Signature, publicKeyUsedForSigning, preImage.getBytes()); } /** * Returns the Log (base2) of x, rounded down. * Ex: log2(65280) -> 15 (Mathematically this value is 15.99...) */ public static int log2(int x) { int log = 0; if ((x & 0xffff0000) != 0) { x >>>= 16; log = 16; } if (x >= 256) { x >>>= 8; log += 8; } if (x >= 16) { x >>>= 4; log += 4; } if (x >= 4) { x >>>= 2; log += 2; } return log + (x >>> 1); } public static void exitFailure() { Logger.flush(); System.exit(1); } public static void exitSuccess() { Logger.flush(); System.exit(0); } protected BitcoinUtil() { } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/v1/get/ListBlockHeadersHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.v1.get; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.bitcoin.server.module.explorer.api.endpoint.BlocksApi; import com.softwareverde.bitcoin.server.module.node.rpc.NodeJsonRpcConnection; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.http.server.servlet.routed.RequestHandler; import com.softwareverde.json.Json; import com.softwareverde.util.Util; import java.util.Map; public class ListBlockHeadersHandler implements RequestHandler<Environment> { /** * LIST BLOCK HEADERS * Requires GET: [blockHeight=null], [maxBlockCount] * Requires POST: */ @Override public Response handleRequest(final Request request, final Environment environment, final Map<String, String> parameters) throws Exception { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); try (final NodeJsonRpcConnection nodeJsonRpcConnection = environment.getNodeJsonRpcConnection()) { if (nodeJsonRpcConnection == null) { final BlocksApi.RecentBlocksResult result = new BlocksApi.RecentBlocksResult(); result.setWasSuccess(false); result.setErrorMessage("Unable to connect to node."); return new JsonResponse(Response.Codes.SERVER_ERROR, result); } final Json blockHeadersJson; { final Long blockHeight = (getParameters.containsKey("blockHeight") ? Util.parseLong(getParameters.get("blockHeight"), null) : null); final Integer maxBlockCount = (getParameters.containsKey("maxBlockCount") ? Util.parseInt(getParameters.get("maxBlockCount"), null) : null); final Json rpcResponseJson = nodeJsonRpcConnection.getBlockHeaders(blockHeight, maxBlockCount, false); if (rpcResponseJson == null) { return new JsonResponse(Response.Codes.SERVER_ERROR, new ApiResult(false, "Request timed out.")); } if (! rpcResponseJson.getBoolean("wasSuccess")) { final String errorMessage = rpcResponseJson.getString("errorMessage"); return new JsonResponse(Response.Codes.SERVER_ERROR, new ApiResult(false, errorMessage)); } blockHeadersJson = rpcResponseJson.get("blockHeaders"); } final BlocksApi.RecentBlocksResult recentBlocksResult = new BlocksApi.RecentBlocksResult(); recentBlocksResult.setWasSuccess(true); recentBlocksResult.setBlockHeadersJson(blockHeadersJson); return new JsonResponse(Response.Codes.OK, recentBlocksResult); } } } <|start_filename|>explorer/www/css/blockchain.css<|end_filename|> html, body { min-height: 100vh; } #main { min-height: calc(100vh - 100px); position: relative; } h1 { text-align: center; width: 75vw; } #blockchain-metadata { width: 75vw; height: 50vh; margin: 0; margin-top: 2em; overflow: hidden; box-sizing: border-box; } #blockchain-metadata-details { width: 25vw; box-sizing: border-box; margin: 0; padding: 1em; background-color: #FFFFFF; position: absolute; right: 0; top: 0; bottom: 0; } #blockchain-metadata-details div::before { margin-right: 0.5em; display: inline-block; width: 10em; font-weight: bold; font-size: 75%; } #blockchain-metadata-details .blockchain-segment-id.empty::before { content: ''; } #blockchain-metadata-details .blockchain-segment-id::before { content: 'ID:'; width: auto; } #blockchain-metadata-details .blockchain-segment-id { text-align: center; margin-bottom: 1em; } #blockchain-metadata-details .blockchain-segment-block-count.empty::before { content: ''; } #blockchain-metadata-details .blockchain-segment-block-count::before { content: 'Block Count:'; } #blockchain-metadata-details .blockchain-segment-block-count { } #blockchain-metadata-details .blockchain-segment-min-height.empty::before { content: ''; } #blockchain-metadata-details .blockchain-segment-min-height::before { content: 'Min Block Height: #'; } #blockchain-metadata-details .blockchain-segment-min-height { cursor: pointer; } #blockchain-metadata-details .blockchain-segment-max-height.empty::before { content: ''; } #blockchain-metadata-details .blockchain-segment-max-height::before { content: 'Max Block Height: #'; } #blockchain-metadata-details .blockchain-segment-max-height { cursor: pointer; } @media only screen and (max-width: 1000px) { #blockchain-metadata-details .blockchain-segment-id::before { content: 'Id:' !important; } #blockchain-metadata-details .blockchain-segment-block-count::before { content: 'Count:' !important; } #blockchain-metadata-details .blockchain-segment-min-height::before { content: 'Min Height:' !important; } #blockchain-metadata-details .blockchain-segment-max-height::before { content: 'Max Height:' !important; } #blockchain-metadata-details { position: initial; width: auto; float: none; height: auto; border: none; display: flex; flex-direction: row; flex-wrap: wrap; font-size: 1em !important; justify-content: space-between; } #blockchain-metadata-details div { margin: 0; width: 50%; box-sizing: border-box; white-space: nowrap; word-break: keep-all; overflow-x: hidden; } #blockchain-metadata-details div::before { font-size: 0.8em !important; font-family: 'Bree Serif', serif; font-weight: normal !important; width: auto; text-overflow: ellipsis; } #blockchain-metadata-details .blockchain-segment-id { text-align: left; margin-bottom: 0; } #blockchain-metadata { width: 99vw; border-radius: 0; } h1 { width: auto; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/node/BitcoinNodeUtil.java<|end_filename|> package com.softwareverde.bitcoin.server.node; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.util.Util; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; public class BitcoinNodeUtil { public BitcoinNodeUtil() { } /** * Returns true iff a callback was executed. */ public static <T, S extends BitcoinNode.BitcoinNodeCallback> Boolean executeAndClearCallbacks(final ThreadPool threadPool, final Map<T, Set<BitcoinNode.PendingRequest<S>>> callbackMap, final Map<RequestId, FailableRequest> failableRequests, final T key, final BitcoinNode.CallbackExecutor<S> callbackExecutor) { synchronized (callbackMap) { final Set<BitcoinNode.PendingRequest<S>> pendingRequests = callbackMap.remove(key); if ((pendingRequests == null) || (pendingRequests.isEmpty())) { return false; } for (final BitcoinNode.PendingRequest<S> pendingRequest : pendingRequests) { threadPool.execute(new Runnable() { @Override public void run() { callbackExecutor.onResult(pendingRequest); } }); failableRequests.remove(pendingRequest.requestId); } return true; } } public static <T, S> void storeInMapSet(final Map<T, Set<S>> destinationMap, final T key, final S value) { synchronized (destinationMap) { Set<S> destinationSet = destinationMap.get(key); if (destinationSet == null) { destinationSet = new HashSet<S>(); destinationMap.put(key, destinationSet); } destinationSet.add(value); } } public static <T, S> void storeInMapList(final Map<T, MutableList<S>> destinationList, final T key, final S value) { synchronized (destinationList) { MutableList<S> destinationSet = destinationList.get(key); if (destinationSet == null) { destinationSet = new MutableList<S>(); destinationList.put(key, destinationSet); } destinationSet.add(value); } } public static <T, S extends BitcoinNode.BitcoinNodeCallback> void removeValueFromMapSet(final Map<T, Set<BitcoinNode.PendingRequest<S>>> sourceMap, final RequestId requestId) { synchronized (sourceMap) { final Iterator<Set<BitcoinNode.PendingRequest<S>>> sourceMapIterator = sourceMap.values().iterator(); while (sourceMapIterator.hasNext()) { final Set<BitcoinNode.PendingRequest<S>> callbackSet = sourceMapIterator.next(); final Iterator<BitcoinNode.PendingRequest<S>> pendingRequestSetIterator = callbackSet.iterator(); while (pendingRequestSetIterator.hasNext()) { final BitcoinNode.PendingRequest<S> pendingRequest = pendingRequestSetIterator.next(); if (Util.areEqual(pendingRequest.requestId, requestId)) { pendingRequestSetIterator.remove(); } } if (callbackSet.isEmpty()) { sourceMapIterator.remove(); } } } } public static <T, U, S extends BitcoinNode.FailableBitcoinNodeRequestCallback<U, T>> void failPendingRequests(final ThreadPool threadPool, final Map<T, Set<BitcoinNode.PendingRequest<S>>> pendingRequests, final Map<RequestId, FailableRequest> failableRequests, final BitcoinNode bitcoinNode) { synchronized (pendingRequests) { for (final T key : pendingRequests.keySet()) { for (final BitcoinNode.PendingRequest<S> pendingRequest : pendingRequests.get(key)) { final RequestId requestId = pendingRequest.requestId; final S callback = pendingRequest.callback; failableRequests.remove(requestId); threadPool.execute(new Runnable() { @Override public void run() { callback.onFailure(requestId, bitcoinNode, key); } }); } } pendingRequests.clear(); } } public static <T, U, S extends BitcoinNode.FailableBitcoinNodeRequestCallback<U, Void>> void failPendingVoidRequests(final ThreadPool threadPool, final Map<T, Set<BitcoinNode.PendingRequest<S>>> pendingRequests, final Map<RequestId, FailableRequest> failableRequests, final BitcoinNode bitcoinNode) { synchronized (pendingRequests) { for (final T key : pendingRequests.keySet()) { for (final BitcoinNode.PendingRequest<S> pendingRequest : pendingRequests.get(key)) { final RequestId requestId = pendingRequest.requestId; final S callback = pendingRequest.callback; failableRequests.remove(requestId); threadPool.execute(new Runnable() { @Override public void run() { callback.onFailure(requestId, bitcoinNode, null); } }); } } pendingRequests.clear(); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/configuration/ExplorerProperties.java<|end_filename|> package com.softwareverde.bitcoin.server.configuration; public class ExplorerProperties { public static final Integer HTTP_PORT = 8081; public static final Integer TLS_PORT = 4481; protected Integer _port; protected String _rootDirectory; protected String _bitcoinRpcUrl; protected Integer _bitcoinRpcPort; protected String _stratumRpcUrl; protected Integer _stratumRpcPort; protected Integer _tlsPort; protected String _tlsKeyFile; protected String _tlsCertificateFile; public Integer getPort() { return _port; } public String getRootDirectory() { return _rootDirectory; } public String getBitcoinRpcUrl() { return _bitcoinRpcUrl; } public Integer getBitcoinRpcPort() { return _bitcoinRpcPort; } public String getStratumRpcUrl() { return _stratumRpcUrl; } public Integer getStratumRpcPort() { return _stratumRpcPort; } public Integer getTlsPort() { return _tlsPort; } public String getTlsKeyFile() { return _tlsKeyFile; } public String getTlsCertificateFile() { return _tlsCertificateFile; } } <|start_filename|>src/main/java/com/softwareverde/constable/list/immutable/ImmutableArrayList.java<|end_filename|> package com.softwareverde.constable.list.immutable; import com.softwareverde.constable.Const; import com.softwareverde.constable.list.List; import com.softwareverde.util.Util; import java.util.Collection; import java.util.Iterator; public class ImmutableArrayList<T> implements List<T>, Const { /** * Creates an ImmutableArrayList using the provided list as its implementation. * Use this function carefully, as leaking a reference to the provided list will break immutability. */ protected static <T> ImmutableArrayList<T> wrap(final T[] objectArray) { return new ImmutableArrayList<T>(objectArray); } public static <T> ImmutableArrayList<T> copyOf(final T[] objectArray) { final T[] copiedObjectArray = Util.copyArray(objectArray); return new ImmutableArrayList<T>(copiedObjectArray); } protected final T[] _items; protected ImmutableArrayList(final T[] items) { _items = items; } @SuppressWarnings("unchecked") public ImmutableArrayList(final Collection<T> list) { final int itemCount = list.size(); _items = (T[]) (new Object[itemCount]); int index = 0; for (final T item : list) { _items[index] = item; index += 1; } } @SuppressWarnings("unchecked") public ImmutableArrayList(final List<T> list) { final int itemCount = list.getCount(); _items = (T[]) (new Object[itemCount]); for (int i = 0; i < itemCount; ++i) { final T item = list.get(i); _items[i] = item; } } @Override public T get(final int index) { return _items[index]; } @Override @Deprecated public int getSize() { return _items.length; } @Override public boolean isEmpty() { return (_items.length == 0); } @Override public boolean contains(final T itemNeedle) { for (final T item : _items) { if (Util.areEqual(itemNeedle, item)) { return true; } } return false; } @Override public int indexOf(final T item) { for (int i = 0; i < _items.length; ++i) { if (Util.areEqual(_items[i], item)) { return i; } } return -1; } @Override public ImmutableList<T> asConst() { return new ImmutableList<T>(this); } @Override public Iterator<T> iterator() { return new ImmutableListIterator<T>(this); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/bloomfilter/update/UpdateTransactionBloomFilterMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.bloomfilter.update; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.constable.bytearray.ByteArray; public class UpdateTransactionBloomFilterMessage extends BitcoinProtocolMessage { protected ByteArray _item = null; public UpdateTransactionBloomFilterMessage() { super(MessageType.UPDATE_TRANSACTION_BLOOM_FILTER); } public ByteArray getItem() { return _item; } public void setItem(final ByteArray item) { _item = item.asConst(); } @Override protected ByteArray _getPayload() { return _item; } @Override protected Integer _getPayloadByteCount() { return _item.getByteCount(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/sync/inventory/BitcoinNodeHeadBlockFinder.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync.inventory; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.manager.banfilter.BanFilter; import com.softwareverde.bitcoin.server.module.node.sync.BlockFinderHashesBuilder; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.bitcoin.server.node.RequestId; import com.softwareverde.concurrent.Pin; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import java.util.concurrent.atomic.AtomicBoolean; public class BitcoinNodeHeadBlockFinder { public interface Callback { void onHeadBlockDetermined(Long blockHeight, Sha256Hash blockHash); default void onFailure() { } } protected final DatabaseManagerFactory _databaseManagerFactory; protected final ThreadPool _threadPool; protected final BanFilter _banFilter; public BitcoinNodeHeadBlockFinder(final DatabaseManagerFactory databaseManagerFactory, final ThreadPool threadPool, final BanFilter banFilter) { _databaseManagerFactory = databaseManagerFactory; _threadPool = threadPool; _banFilter = banFilter; } public void determineHeadBlock(final BitcoinNode bitcoinNode, final Callback callback) { final List<Sha256Hash> blockHashes; try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BlockFinderHashesBuilder blockFinderHashesBuilder = new BlockFinderHashesBuilder(databaseManager); blockHashes = blockFinderHashesBuilder.createBlockHeaderFinderBlockHashes(1); } catch (final Exception exception) { callback.onFailure(); return; } final Long bitcoinNodePing = bitcoinNode.getAveragePing(); final Long maxTimeout = Math.min(Math.max(1000L, bitcoinNodePing), 5000L); final AtomicBoolean didRespond = new AtomicBoolean(false); final Pin pin = new Pin(); _threadPool.execute(new Runnable() { @Override public void run() { try { pin.waitForRelease(maxTimeout); } catch (final Exception exception) { } if (! didRespond.get()) { callback.onFailure(); } } }); Logger.trace("Finding Head Block for " + bitcoinNode + ", sending: " + blockHashes.get(0)); bitcoinNode.requestBlockHeadersAfter(blockHashes, new BitcoinNode.DownloadBlockHeadersCallback() { @Override public void onResult(final RequestId requestId, final BitcoinNode bitcoinNode, final List<BlockHeader> blockHeaders) { didRespond.set(true); pin.release(); if (_banFilter != null) { final boolean shouldAcceptHeaders = _banFilter.onHeadersReceived(bitcoinNode, blockHeaders); if (! shouldAcceptHeaders) { Logger.info("Received invalid headers from " + bitcoinNode + "."); bitcoinNode.disconnect(); callback.onFailure(); return; } } if (blockHeaders.isEmpty()) { Logger.debug("onFailure: " + bitcoinNode + " " + blockHeaders.getCount()); callback.onFailure(); return; } final int blockHeaderCount = blockHeaders.getCount(); final BlockHeader firstBlockHeader = blockHeaders.get(0); final BlockHeader lastBlockHeader = blockHeaders.get(blockHeaderCount - 1); try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final Sha256Hash sharedAncestorBlockHash = firstBlockHeader.getPreviousBlockHash(); final BlockId sharedAncestorBlockId = blockHeaderDatabaseManager.getBlockHeaderId(sharedAncestorBlockHash); if (sharedAncestorBlockId == null) { Logger.debug("onFailure: " + bitcoinNode + " " + blockHeaders.getCount()); callback.onFailure(); return; } final Long sharedAncestorBlockHeight = blockHeaderDatabaseManager.getBlockHeight(sharedAncestorBlockId); final Long maxBlockHeight = (sharedAncestorBlockHeight + blockHeaderCount); final Sha256Hash lastBlockHash = lastBlockHeader.getHash(); Logger.trace(bitcoinNode + " head block " + maxBlockHeight + " / " + lastBlockHash); callback.onHeadBlockDetermined(maxBlockHeight, lastBlockHash); } catch (final Exception exception) { Logger.debug("onFailure: " + bitcoinNode + " " + blockHeaders.getCount()); Logger.debug(exception); callback.onFailure(); } } }); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/FullDatabaseContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; public interface FullDatabaseContext extends DatabaseContext { @Override FullNodeDatabaseManager getDatabaseManager(); } <|start_filename|>src/test/java/com/softwareverde/network/socket/PacketBufferTests.java<|end_filename|> package com.softwareverde.network.socket; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.test.util.TestUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.util.HexUtil; import org.junit.Assert; import org.junit.Test; public class PacketBufferTests { private byte[] _hexStringToByteArray(final String hexString, final Integer extraByteCount) { final byte[] bytes = HexUtil.hexStringToByteArray(hexString.replaceAll(" ", "")); if (bytes == null) { return null; } final byte[] bytesWithExtra = new byte[bytes.length + extraByteCount]; for (int i = 0; i < bytes.length; ++i) { bytesWithExtra[i] = bytes[i]; } return bytesWithExtra; } @Test public void should_read_multiple_sets_of_appended_bytes_in_order() { // Setup final PacketBuffer packetBuffer = new PacketBuffer(BitcoinProtocolMessage.BINARY_PACKET_FORMAT); final byte[] magicNumber = _hexStringToByteArray("E3E1 F3E8", 6); final byte[] command = _hexStringToByteArray("7665 7273 696F 6E00 0000 0000", 0); final byte[] payloadByteCount = _hexStringToByteArray("7E00 0000", 6); final byte[] checksum = _hexStringToByteArray("419D 9392", 6); packetBuffer.appendBytes(magicNumber, 4); packetBuffer.appendBytes(command, 12); packetBuffer.appendBytes(payloadByteCount, 4); packetBuffer.appendBytes(checksum, 4); Assert.assertEquals(24, packetBuffer.getByteCount()); // Action final byte[] bytes = packetBuffer.readBytes(24); // Assert TestUtil.assertMatchesMaskedHexString("E3E1 F3E8 7665 7273 696F 6E00 0000 0000 7E00 0000 419D 9392", bytes); } @Test public void should_be_recycle_byte_arrays_after_reading() { // Setup final PacketBuffer packetBuffer = new PacketBuffer(BitcoinProtocolMessage.BINARY_PACKET_FORMAT); final byte[] magicNumber = _hexStringToByteArray("FFFF FFFF FFFF FFFF FFFF", 0); final byte[] command = _hexStringToByteArray("FFFF FFFF FFFF FFFF FFFF", 5); final byte[] payloadByteCount = _hexStringToByteArray("FFFF FFFF FFFF FFFF FFFF", 10); final byte[] checksum = _hexStringToByteArray("FFFF FFFF FFFF FFFF FFFF", 15); packetBuffer.appendBytes(magicNumber, 10); packetBuffer.appendBytes(command, 10); packetBuffer.appendBytes(payloadByteCount, 10); packetBuffer.appendBytes(checksum, 10); Assert.assertEquals(40, packetBuffer.getByteCount()); // Action // First read the "easy" pattern of "FFFF"... After reading, this will recycle the internal byte arrays... final byte[] readBytes0 = packetBuffer.readBytes(40); int x = 0; for (int i = 0; i < 4; ++i) { final byte[] recycledBytes = packetBuffer.getRecycledBuffer(); Assert.assertEquals(((i * 5) + 10), recycledBytes.length); // Ensure that the byte[] from above are being recycled (sizes in order: 0, 5, 10, 15)... for (int j = 0; j < recycledBytes.length; ++j) { if (j < 10) { // Byte Index is within the "usable" range, so populate them with request we want... recycledBytes[j] = (byte) x; x += 1; } else { // Bytes Index is outside the "usable" range, so populate them with request we would recognize that we don't want... recycledBytes[j] = 0x77; } } packetBuffer.appendBytes(recycledBytes, 10); } final byte[] readBytes1 = packetBuffer.readBytes(40); // Assert // The first byte[] should consist of the "easy "pattern... TestUtil.assertMatchesMaskedHexString("FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF", readBytes0); // The second byte[] should increment from 0x00 to 0x27, since we were telling the packetBuffer to only use the first 10 bytes of each buffer (i.e. packetBuffer.appendBytes(..., 10)) TestUtil.assertMatchesMaskedHexString("0001 0203 0405 0607 0809 0A0B 0C0D 0E0F 1011 1213 1415 1617 1819 1A1B 1C1D 1E1F 2021 2223 2425 2627", readBytes1); } @Test public void should_not_evict_uncorrupted_bytes() { // Setup final PacketBuffer packetBuffer = new PacketBuffer(BitcoinProtocolMessage.BINARY_PACKET_FORMAT); final ByteArray inventoryMessageBytes = ByteArray.fromHexString("E3E1F3E8696E7600000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA"); packetBuffer.appendBytes(inventoryMessageBytes.getBytes(), inventoryMessageBytes.getByteCount()); // Action packetBuffer.evictCorruptedPackets(); // Assert final int remainingByteCount = packetBuffer.getByteCount(); final ByteArray bytes = ByteArray.wrap(packetBuffer.readBytes(remainingByteCount)); Assert.assertEquals(inventoryMessageBytes, bytes); } @Test public void should_evict_corrupted_bytes_until_header_found() { // Setup final PacketBuffer packetBuffer = new PacketBuffer(BitcoinProtocolMessage.BINARY_PACKET_FORMAT); final ByteArray inventoryMessageBytes = ByteArray.fromHexString( "E3E1F3E8696E7600000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA"); final ByteArray inventoryMessageBytesWithGarbage = ByteArray.fromHexString("E3E1E8F369" + "E3E1F3E8696E7600000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA"); packetBuffer.appendBytes(inventoryMessageBytesWithGarbage.getBytes(), inventoryMessageBytesWithGarbage.getByteCount()); // Action packetBuffer.evictCorruptedPackets(); // Assert final int remainingByteCount = packetBuffer.getByteCount(); final ByteArray bytes = ByteArray.wrap(packetBuffer.readBytes(remainingByteCount)); Assert.assertEquals(inventoryMessageBytes, bytes); } @Test public void should_evict_all_bytes_when_no_magic_number_is_found() { // Setup final PacketBuffer packetBuffer = new PacketBuffer(BitcoinProtocolMessage.BINARY_PACKET_FORMAT); final ByteArray expectedBytes = new MutableByteArray(0); final ByteArray inventoryMessageBytesWithoutMagicNumber = ByteArray.fromHexString("00000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA"); packetBuffer.appendBytes(inventoryMessageBytesWithoutMagicNumber.getBytes(), inventoryMessageBytesWithoutMagicNumber.getByteCount()); // Action packetBuffer.evictCorruptedPackets(); // Assert final int remainingByteCount = packetBuffer.getByteCount(); final ByteArray bytes = ByteArray.wrap(packetBuffer.readBytes(remainingByteCount)); Assert.assertEquals(expectedBytes, bytes); } @Test public void should_evict_corrupted_bytes_until_header_found_when_multiple_messages_queued() { // Setup final PacketBuffer packetBuffer = new PacketBuffer(BitcoinProtocolMessage.BINARY_PACKET_FORMAT); final ByteArray inventoryMessageBytes = ByteArray.fromHexString( "E3E1F3E8696E7600000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA"); final ByteArray twoInventoryMessageBytesWithGarbage = ByteArray.fromHexString("E3E1E8696E7E1F" + "E3E1F3E8696E7600000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA" + "E3E1F3E8696E7600000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA"); packetBuffer.appendBytes(twoInventoryMessageBytesWithGarbage.getBytes(), twoInventoryMessageBytesWithGarbage.getByteCount()); // Action packetBuffer.evictCorruptedPackets(); // Assert final ByteArray bytes0 = ByteArray.wrap(packetBuffer.readBytes(inventoryMessageBytes.getByteCount())); final ByteArray bytes1 = ByteArray.wrap(packetBuffer.readBytes(inventoryMessageBytes.getByteCount())); Assert.assertEquals(inventoryMessageBytes, bytes0); Assert.assertEquals(inventoryMessageBytes, bytes1); } @Test public void should_evict_corrupted_bytes_when_double_magic_is_provided() { // Setup final PacketBuffer packetBuffer = new PacketBuffer(BitcoinProtocolMessage.BINARY_PACKET_FORMAT); final int magicNumberCount = 4; final ByteArray inventoryMessageBytes = ByteArray.fromHexString( "E3E1F3E8696E7600000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA"); final ByteArray twoInventoryMessageBytesWithDoubleMagic = ByteArray.fromHexString("E3E1F3E8" + "E3E1F3E8696E7600000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA" + "E3E1F3E8696E7600000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA"); packetBuffer.appendBytes(twoInventoryMessageBytesWithDoubleMagic.getBytes(), twoInventoryMessageBytesWithDoubleMagic.getByteCount()); // Action packetBuffer.evictCorruptedPackets(); // Assert final ByteArray bytes0 = ByteArray.wrap(packetBuffer.readBytes(inventoryMessageBytes.getByteCount() + magicNumberCount)); final ByteArray bytes1 = ByteArray.wrap(packetBuffer.readBytes(inventoryMessageBytes.getByteCount())); Assert.assertEquals(ByteArray.fromHexString("E3E1F3E8"), ByteArray.wrap(bytes0.getBytes(0, magicNumberCount))); Assert.assertEquals(inventoryMessageBytes, ByteArray.wrap(bytes0.getBytes(magicNumberCount, (bytes0.getByteCount() - magicNumberCount)))); Assert.assertEquals(inventoryMessageBytes, bytes1); } @Test public void should_consume_bytes_for_unsupported_message() { // Setup final PacketBuffer packetBuffer = new PacketBuffer(BitcoinProtocolMessage.BINARY_PACKET_FORMAT); final ByteArray inventoryMessageBytes = ByteArray.fromHexString("E3E1F3E8696E7600000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA"); final ByteArray zVersionMessageBytes = ByteArray.fromHexString("E3E1F3E87A76657273696F6E0000000071000000EFD064BA0EFE0000020003FD8D20FE010002000106FE020002000101FE030002000102FE040002000100FE050002000100FE060002000100FE070002000100FE080002000101FE0900020003FDF401FE0A00020005FEA0D21E00FE0B00020003FDF401FE0C00020005FEA0D21E00FE0D0002000101"); packetBuffer.appendBytes(zVersionMessageBytes.getBytes(), zVersionMessageBytes.getByteCount()); packetBuffer.appendBytes(inventoryMessageBytes.getBytes(), inventoryMessageBytes.getByteCount()); final MutableList<BitcoinProtocolMessage> protocolMessages = new MutableList<BitcoinProtocolMessage>(); // Action packetBuffer.evictCorruptedPackets(); while (packetBuffer.hasMessage()) { final BitcoinProtocolMessage protocolMessage = (BitcoinProtocolMessage) packetBuffer.popMessage(); protocolMessages.add(protocolMessage); packetBuffer.evictCorruptedPackets(); } // Assert Assert.assertEquals(2, protocolMessages.getCount()); Assert.assertNull(protocolMessages.get(0)); Assert.assertEquals(MessageType.INVENTORY, protocolMessages.get(1).getCommand()); } @Test public void should_consume_bytes_for_unsupported_message_and_bad_payload() { // Setup final PacketBuffer packetBuffer = new PacketBuffer(BitcoinProtocolMessage.BINARY_PACKET_FORMAT); final ByteArray inventoryMessageBytes = ByteArray.fromHexString("E3E1F3E8696E7600000000000000000025000000166E09440101000000BA5F4826BC0C20BF0DAFAD3E4858D110F549040174A8EA924F3D4E409EB0D1EA"); // NOTE: The payload size indicates 1 more byte than was actually provided. final ByteArray zVersionMessageBytes = ByteArray.fromHexString("E3E1F3E87A76657273696F6E0000000072000000EFD064BA0EFE0000020003FD8D20FE010002000106FE020002000101FE030002000102FE040002000100FE050002000100FE060002000100FE070002000100FE080002000101FE0900020003FDF401FE0A00020005FEA0D21E00FE0B00020003FDF401FE0C00020005FEA0D21E00FE0D0002000101"); packetBuffer.appendBytes(zVersionMessageBytes.getBytes(), zVersionMessageBytes.getByteCount()); packetBuffer.appendBytes(inventoryMessageBytes.getBytes(), inventoryMessageBytes.getByteCount()); // Message becomes mangled by the off-by-one in zVersion. packetBuffer.appendBytes(inventoryMessageBytes.getBytes(), inventoryMessageBytes.getByteCount()); final MutableList<BitcoinProtocolMessage> protocolMessages = new MutableList<BitcoinProtocolMessage>(); // Action packetBuffer.evictCorruptedPackets(); while (packetBuffer.hasMessage()) { final BitcoinProtocolMessage protocolMessage = (BitcoinProtocolMessage) packetBuffer.popMessage(); protocolMessages.add(protocolMessage); packetBuffer.evictCorruptedPackets(); } // Assert Assert.assertEquals(2, protocolMessages.getCount()); Assert.assertNull(protocolMessages.get(0)); Assert.assertEquals(MessageType.INVENTORY, protocolMessages.get(1).getCommand()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/output/TransactionOutput.java<|end_filename|> package com.softwareverde.bitcoin.transaction.output; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.transaction.script.ScriptBuilder; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.constable.Constable; import com.softwareverde.json.Jsonable; public interface TransactionOutput extends Constable<ImmutableTransactionOutput>, Jsonable { static TransactionOutput createPayToAddressTransactionOutput(final Address payToAddress, final Long satoshis) { final LockingScript lockingScript = ScriptBuilder.payToAddress(payToAddress); final MutableTransactionOutput transactionOutput = new MutableTransactionOutput(); transactionOutput.setLockingScript(lockingScript); transactionOutput.setAmount(satoshis); return transactionOutput; } Long getAmount(); Integer getIndex(); LockingScript getLockingScript(); @Override ImmutableTransactionOutput asConst(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/opcode/DynamicValueOperation.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode; import com.softwareverde.bitcoin.transaction.script.runner.ControlState; import com.softwareverde.bitcoin.transaction.script.runner.context.MutableTransactionContext; import com.softwareverde.bitcoin.transaction.script.stack.Stack; import com.softwareverde.bitcoin.transaction.script.stack.Value; import com.softwareverde.util.bytearray.ByteArrayReader; public class DynamicValueOperation extends SubTypedOperation { public static final Type TYPE = Type.OP_DYNAMIC_VALUE; public static final DynamicValueOperation PUSH_STACK_SIZE = new DynamicValueOperation(Opcode.PUSH_STACK_SIZE.getValue(), Opcode.PUSH_STACK_SIZE); public static final DynamicValueOperation COPY_1ST = new DynamicValueOperation(Opcode.COPY_1ST.getValue(), Opcode.COPY_1ST); public static final DynamicValueOperation COPY_NTH = new DynamicValueOperation(Opcode.COPY_NTH.getValue(), Opcode.COPY_NTH); public static final DynamicValueOperation COPY_2ND = new DynamicValueOperation(Opcode.COPY_2ND.getValue(), Opcode.COPY_2ND); public static final DynamicValueOperation COPY_2ND_THEN_1ST = new DynamicValueOperation(Opcode.COPY_2ND_THEN_1ST.getValue(), Opcode.COPY_2ND_THEN_1ST); public static final DynamicValueOperation COPY_3RD_THEN_2ND_THEN_1ST = new DynamicValueOperation(Opcode.COPY_3RD_THEN_2ND_THEN_1ST.getValue(), Opcode.COPY_3RD_THEN_2ND_THEN_1ST); public static final DynamicValueOperation COPY_4TH_THEN_3RD = new DynamicValueOperation(Opcode.COPY_4TH_THEN_3RD.getValue(), Opcode.COPY_4TH_THEN_3RD); public static final DynamicValueOperation COPY_1ST_THEN_MOVE_TO_3RD = new DynamicValueOperation(Opcode.COPY_1ST_THEN_MOVE_TO_3RD.getValue(), Opcode.COPY_1ST_THEN_MOVE_TO_3RD); protected static DynamicValueOperation fromBytes(final ByteArrayReader byteArrayReader) { if (! byteArrayReader.hasBytes()) { return null; } final byte opcodeByte = byteArrayReader.readByte(); final Type type = Type.getType(opcodeByte); if (type != TYPE) { return null; } final Opcode opcode = TYPE.getSubtype(opcodeByte); if (opcode == null) { return null; } return new DynamicValueOperation(opcodeByte, opcode); } protected DynamicValueOperation(final byte value, final Opcode opcode) { super(value, TYPE, opcode); } @Override public Boolean applyTo(final Stack stack, final ControlState controlState, final MutableTransactionContext context) { switch (_opcode) { case PUSH_STACK_SIZE: { stack.push(Value.fromInteger(stack.getSize().longValue())); return true; } case COPY_1ST: { stack.push(stack.peak()); return (! stack.didOverflow()); } case COPY_NTH: { final Value nValue = stack.pop(); if (! Operation.validateMinimalEncoding(nValue, context)) { return false; } final Integer n = nValue.asInteger(); stack.push(stack.peak(n)); return (! stack.didOverflow()); } case COPY_2ND: { final Value value = stack.peak(1); stack.push(value); return (! stack.didOverflow()); } case COPY_2ND_THEN_1ST: { final Value value0 = stack.peak(0); final Value value1 = stack.peak(1); stack.push(value1); stack.push(value0); return (! stack.didOverflow()); } case COPY_3RD_THEN_2ND_THEN_1ST: { final Value value0 = stack.peak(0); final Value value1 = stack.peak(1); final Value value2 = stack.peak(2); stack.push(value2); stack.push(value1); stack.push(value0); return (! stack.didOverflow()); } case COPY_4TH_THEN_3RD: { final Value value2 = stack.peak(2); final Value value3 = stack.peak(3); stack.push(value3); stack.push(value2); return (! stack.didOverflow()); } case COPY_1ST_THEN_MOVE_TO_3RD: { // 4 3 2 1 final Value copiedValue = stack.peak(); final Value firstValue = stack.pop(); // 4 3 2 final Value secondValue = stack.pop(); // 4 3 stack.push(copiedValue); // 4 3 1 stack.push(secondValue); // 4 3 1 2 stack.push(firstValue); // 4 3 1 2 1 return (! stack.didOverflow()); } default: { return false; } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/rpc/handler/ServiceInquisitor.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.rpc.handler; import com.softwareverde.bitcoin.server.module.node.rpc.NodeRpcHandler; import com.softwareverde.concurrent.service.SleepyService; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ServiceInquisitor implements NodeRpcHandler.ServiceInquisitor { protected final ConcurrentHashMap<String, SleepyService.StatusMonitor> _services = new ConcurrentHashMap<String, SleepyService.StatusMonitor>(); public void addService(final String serviceName, final SleepyService.StatusMonitor statusMonitor) { _services.put(serviceName, statusMonitor); } @Override public Map<String, String> getServiceStatuses() { final HashMap<String, String> serviceStatuses = new HashMap<String, String>(_services.size()); for (final String serviceName : _services.keySet()) { final SleepyService.StatusMonitor statusMonitor = _services.get(serviceName); serviceStatuses.put(serviceName, statusMonitor.getStatus().toString()); } return serviceStatuses; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/input/TransactionInputDeflater.java<|end_filename|> package com.softwareverde.bitcoin.transaction.input; import com.softwareverde.bitcoin.bytearray.FragmentedBytes; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.json.Json; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class TransactionInputDeflater { protected void _toFragmentedBytes(final TransactionInput transactionInput, final ByteArrayBuilder headBytes, final ByteArrayBuilder tailBytes) { final byte[] sequenceBytes = new byte[4]; final SequenceNumber sequenceNumber = transactionInput.getSequenceNumber(); ByteUtil.setBytes(sequenceBytes, ByteUtil.integerToBytes(sequenceNumber.getValue())); final byte[] indexBytes = new byte[4]; ByteUtil.setBytes(indexBytes, ByteUtil.integerToBytes(transactionInput.getPreviousOutputIndex())); final ByteArray unlockingScriptBytes = transactionInput.getUnlockingScript().getBytes(); final Sha256Hash previousOutputTransactionHash = transactionInput.getPreviousOutputTransactionHash(); headBytes.appendBytes(previousOutputTransactionHash.getBytes(), Endian.LITTLE); headBytes.appendBytes(indexBytes, Endian.LITTLE); headBytes.appendBytes(ByteUtil.variableLengthIntegerToBytes(unlockingScriptBytes.getByteCount()), Endian.BIG); headBytes.appendBytes(unlockingScriptBytes, Endian.BIG); tailBytes.appendBytes(sequenceBytes, Endian.LITTLE); } protected ByteArray _toBytes(final TransactionInput transactionInput) { final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); _toFragmentedBytes(transactionInput, byteArrayBuilder, byteArrayBuilder); return MutableByteArray.wrap(byteArrayBuilder.build()); } public Integer getByteCount(final TransactionInput transactionInput) { final Integer indexByteCount = 4; final Integer previousTransactionOutputHashByteCount = Sha256Hash.BYTE_COUNT; final Integer scriptByteCount; { final Script unlockingScript = transactionInput.getUnlockingScript(); Integer byteCount = 0; byteCount += ByteUtil.variableLengthIntegerToBytes(unlockingScript.getByteCount()).length; byteCount += unlockingScript.getByteCount(); scriptByteCount = byteCount; } final Integer sequenceByteCount = 4; return (indexByteCount + previousTransactionOutputHashByteCount + scriptByteCount + sequenceByteCount); } public ByteArray toBytes(final TransactionInput transactionInput) { return _toBytes(transactionInput); } public FragmentedBytes fragmentTransactionInput(final TransactionInput transactionInput) { final ByteArrayBuilder headBytesBuilder = new ByteArrayBuilder(); final ByteArrayBuilder tailBytesBuilder = new ByteArrayBuilder(); _toFragmentedBytes(transactionInput, headBytesBuilder, tailBytesBuilder); return new FragmentedBytes(headBytesBuilder.build(), tailBytesBuilder.build()); } public Json toJson(final TransactionInput transactionInput) { final UnlockingScript unlockingScript = transactionInput.getUnlockingScript(); final Json json = new Json(); json.put("previousOutputTransactionHash", transactionInput.getPreviousOutputTransactionHash()); json.put("previousOutputIndex", transactionInput.getPreviousOutputIndex()); json.put("unlockingScript", unlockingScript); json.put("sequenceNumber", transactionInput.getSequenceNumber()); // json.put("bytes", HexUtil.toHexString(_toBytes(transactionInput))); return json; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/indexer/AddressTransactions.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.indexer; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.json.Json; import com.softwareverde.json.Jsonable; import java.util.HashMap; import java.util.Map; class AddressTransactions implements Jsonable { public final BlockchainSegmentId blockchainSegmentId; public final List<TransactionId> transactionIds; public final Map<TransactionId, MutableList<Integer>> spentOutputs; public final Map<TransactionId, MutableList<Integer>> previousOutputs; public AddressTransactions(final BlockchainSegmentId blockchainSegmentId) { this.blockchainSegmentId = blockchainSegmentId; this.transactionIds = new ImmutableList<TransactionId>(); this.spentOutputs = new HashMap<TransactionId, MutableList<Integer>>(0); this.previousOutputs = new HashMap<TransactionId, MutableList<Integer>>(0); } public AddressTransactions(final BlockchainSegmentId blockchainSegmentId, final List<TransactionId> transactionIds, final HashMap<TransactionId, MutableList<Integer>> previousOutputs, final HashMap<TransactionId, MutableList<Integer>> spentOutputs) { this.blockchainSegmentId = blockchainSegmentId; this.transactionIds = transactionIds; this.previousOutputs = previousOutputs; this.spentOutputs = spentOutputs; } @Override public Json toJson() { final Json json = new Json(false); json.put("blockchainSegmentId", this.blockchainSegmentId); { // transactionIds final Json transactionIds = new Json(true); for (final TransactionId transactionId : this.transactionIds) { transactionIds.add(transactionId); } json.put("transactionIds", transactionIds); } { // outputIndexes final Json outputIndexesJson = new Json(false); for (final TransactionId transactionId : this.spentOutputs.keySet()) { final List<Integer> indexList = this.spentOutputs.get(transactionId); final Json indexesJson = new Json(true); for (final Integer index : indexList) { indexesJson.add(index); } outputIndexesJson.put(transactionId.toString(), indexesJson); } json.put("spentOutputs", outputIndexesJson); } { // previousOutputs final Json outputIndexesJson = new Json(false); for (final TransactionId transactionId : this.previousOutputs.keySet()) { final List<Integer> indexList = this.previousOutputs.get(transactionId); final Json indexesJson = new Json(true); for (final Integer index : indexList) { indexesJson.add(index); } outputIndexesJson.put(transactionId.toString(), indexesJson); } json.put("previousOutputs", outputIndexesJson); } return json; } @Override public String toString() { final Json json = this.toJson(); return json.toString(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/validator/difficulty/AsertDifficultyCalculator.java<|end_filename|> package com.softwareverde.bitcoin.block.validator.difficulty; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.logging.Logger; import java.math.BigInteger; /** * BCH Difficulty Calculation via aserti3-2d algorithm. * The aserti3-2d difficulty adjustment algorithm (ASERT DAA) on Bitcoin Cash (BCH) on November 15th, 2020, as designed by <NAME> and implemented by <NAME>. * https://gitlab.com/bitcoin-cash-node/bchn-sw/qa-assets/-/tree/master/test_vectors/aserti3-2d * https://github.com/pokkst/bitcoincashj/blob/master/core/src/main/java/org/bitcoinj/params/AbstractBitcoinNetParams.java */ public class AsertDifficultyCalculator { public static final Long TARGET_BLOCK_SPACING = (10L * 60L); // 10 minutes per block. public static final Long HALF_LIFE = (2L * 24L * 60L * 60L); // 2 Days, in seconds. protected BigInteger _getHalfLife() { return BigInteger.valueOf(AsertDifficultyCalculator.HALF_LIFE); } protected Difficulty _computeAsertTarget(final AsertReferenceBlock referenceBlock, final Long previousBlockTimestamp, final BigInteger previousBlockHeight) { final int shiftBitCount = 16; final Long referenceBlockTime = referenceBlock.parentBlockTimestamp; final BigInteger heightDiff = previousBlockHeight.subtract(referenceBlock.blockHeight); final long blockTimeDifferenceInSeconds = (previousBlockTimestamp - referenceBlockTime); Logger.trace("anchor_bits=" + referenceBlock.difficulty.encode() + ", time_diff=" + blockTimeDifferenceInSeconds + ", height_diff=" + heightDiff); final BigInteger heightDifferenceWithOffset = heightDiff.add(BigInteger.ONE); final BigInteger desiredHeight = BigInteger.valueOf(TARGET_BLOCK_SPACING).multiply(heightDifferenceWithOffset); final int shiftCount; final BigInteger exponent; { final BigInteger halfLifeBigInteger = _getHalfLife(); final BigInteger value = (((BigInteger.valueOf(blockTimeDifferenceInSeconds).subtract(desiredHeight)).shiftLeft(shiftBitCount)).divide(halfLifeBigInteger)); shiftCount = (value.shiftRight(shiftBitCount)).intValue(); exponent = value.subtract(BigInteger.valueOf(shiftCount << shiftBitCount)); } final BigInteger target; { // factor = ((195766423245049 * exponent) + (971821376 * exponent^2) + (5127 * exponent^3) + 2^47) >> 48 final BigInteger factor = BigInteger.valueOf(195766423245049L) .multiply(exponent) .add(BigInteger.valueOf(971821376L).multiply(exponent.pow(2))) .add(BigInteger.valueOf(5127L).multiply(exponent.pow(3))) .add(BigInteger.valueOf(2L).pow(47)) .shiftRight(48); final BigInteger radix = BigInteger.ONE.shiftLeft(shiftBitCount); // 1 << shiftBitCount final BigInteger referenceBlockDifficulty = Difficulty.toBigInteger(referenceBlock.difficulty); final BigInteger unshiftedTargetDifficulty = referenceBlockDifficulty.multiply(radix.add(factor)); // referenceBlockDifficulty * (radix + factor) final BigInteger shiftedTargetDifficulty; if (shiftCount < 0) { shiftedTargetDifficulty = unshiftedTargetDifficulty.shiftRight(Math.abs(shiftCount)); } else { shiftedTargetDifficulty = unshiftedTargetDifficulty.shiftLeft(shiftCount); } target = shiftedTargetDifficulty.shiftRight(shiftBitCount); } if (target.equals(BigInteger.ZERO)) { return Difficulty.fromBigInteger(BigInteger.ONE); } final BigInteger maxDifficulty = Difficulty.toBigInteger(Difficulty.MAX_DIFFICULTY); if (target.compareTo(maxDifficulty) > 0) { return Difficulty.MAX_DIFFICULTY; } return Difficulty.fromBigInteger(target); } public Difficulty computeAsertTarget(final AsertReferenceBlock referenceBlock, final Long previousBlockTimestamp, final Long blockHeight) { // For calculating the Difficulty of blockHeight N, the parent height, while technically an arbitrary choice, is used in due to the evolution of the algorithm. final BigInteger previousBlockHeightBigInteger = BigInteger.valueOf(blockHeight - 1L); return _computeAsertTarget(referenceBlock, previousBlockTimestamp, previousBlockHeightBigInteger); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/BlockInflater.java<|end_filename|> package com.softwareverde.bitcoin.block; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.util.ByteUtil; public class BlockInflater { public static final Integer MAX_BYTE_COUNT = (int) (32L * ByteUtil.Unit.Si.MEGABYTES); public static final Integer MAX_TRANSACTION_COUNT = (BlockInflater.MAX_BYTE_COUNT / TransactionInflater.MIN_BYTE_COUNT); protected MutableBlock _fromByteArrayReader(final ByteArrayReader byteArrayReader) { final BlockHeaderInflater blockHeaderInflater = new BlockHeaderInflater(); final TransactionInflater transactionInflater = new TransactionInflater(); final Integer startPosition = byteArrayReader.getPosition(); final BlockHeader blockHeader = blockHeaderInflater.fromBytes(byteArrayReader); if (blockHeader == null) { return null; } final int transactionCount = byteArrayReader.readVariableSizedInteger().intValue(); if (transactionCount > MAX_TRANSACTION_COUNT) { return null; } final MutableList<Transaction> transactions = new MutableList<Transaction>(transactionCount); for (int i = 0; i < transactionCount; ++i) { final Transaction transaction = transactionInflater.fromBytes(byteArrayReader); if (transaction == null) { return null; } transactions.add(transaction); } if (byteArrayReader.didOverflow()) { return null; } final Integer endPosition = byteArrayReader.getPosition(); final Integer byteCount = (endPosition - startPosition); final MutableBlock mutableBlock = new MutableBlock(blockHeader, transactions); mutableBlock.cacheByteCount(byteCount); return mutableBlock; } public MutableBlock fromBytes(final ByteArrayReader byteArrayReader) { if (byteArrayReader == null) { return null; } return _fromByteArrayReader(byteArrayReader); } public MutableBlock fromBytes(final ByteArray byteArray) { if (byteArray == null) { return null; } return _fromByteArrayReader(new ByteArrayReader(byteArray)); } public MutableBlock fromBytes(final byte[] bytes) { if (bytes == null) { return null; } final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); return _fromByteArrayReader(byteArrayReader); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/send/MutableSlpSendScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp.send; import com.softwareverde.bitcoin.slp.SlpTokenId; public class MutableSlpSendScript extends SlpSendScriptCore { public MutableSlpSendScript() { } public MutableSlpSendScript(final SlpSendScript slpSendScript) { super(slpSendScript); } public void setTokenId(final SlpTokenId tokenId) { _tokenId = tokenId; } /** * Sets the spendAmount. * If transactionOutputIndex is less than 0 or greater than or equal to MAX_OUTPUT_COUNT, an IndexOutOfBounds exception is thrown. * Attempting to set the 0th index does nothing. * Setting an amount to a non-null value sets all lesser indexes to zero if they have not been set. * Setting an amount to null will unset all indexes after transactionOutputIndex. */ public void setAmount(final Integer transactionOutputIndex, final Long amount) { if (transactionOutputIndex < 0) { throw new IndexOutOfBoundsException(); } if (transactionOutputIndex >= MAX_OUTPUT_COUNT) { throw new IndexOutOfBoundsException(); } if (transactionOutputIndex == 0) { return; } _amounts[transactionOutputIndex] = amount; { // Maintain integrity... if (amount == null) { for (int i = (transactionOutputIndex + 1); i < MAX_OUTPUT_COUNT; ++i) { _amounts[i] = null; } } else { for (int i = 1; i < transactionOutputIndex; ++i) { if (_amounts[i] == null) { _amounts[i] = 0L; } } } } } @Override public ImmutableSlpSendScript asConst() { return new ImmutableSlpSendScript(this); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/Bip65.java<|end_filename|> package com.softwareverde.bitcoin.bip; import com.softwareverde.util.Util; public class Bip65 { public static final Long ACTIVATION_BLOCK_HEIGHT = 388167L; // OP_CHECKLOCKTIMEVERIFY -- https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki public static Boolean isEnabled(final Long blockHeight) { // http://data.bitcoinity.org/bitcoin/block_version/5y?c=block_version&r=day&t=l // https://www.reddit.com/r/Bitcoin/comments/3vwvxq/a_new_era_of_op_hodl_is_on_us_bip65_has_activated/ // https://blockchain.info/block/000000000000000005de239ca0d781cc9e78add7c48e94e2264223aa31fc6256 // The last v3 block was mined at height 388166. Technically, Bip65 likely activated a few days before this. return (Util.coalesce(blockHeight, Long.MAX_VALUE) >= ACTIVATION_BLOCK_HEIGHT); } protected Bip65() { } } <|start_filename|>stratum/www/css/main.css<|end_filename|> .block .transactions { display: flex; flex-direction: row; flex-wrap: wrap; } .block .transaction.collapsed { margin: auto; padding: 0; flex-grow: 1; } .transaction.collapsed .hash span.value::before { display: none; } .block .transaction.collapsed .io { display: none; } .block .transaction.collapsed > div > div { padding: 0.25em; margin: 0.25em; border: solid 1px rgba(0, 0, 0, 0.05); background-color: rgba(0, 0, 0, 0.025); box-sizing: border-box; } .transaction.collapsed .hash .value { margin: auto; } .transaction:first-child { flex-basis: 100%; margin-top: 0.5em; } .transaction:not(.collapsed):first-child { background-color: rgba(255, 255, 255, 0.33); border: solid 1px #C1C1C1; } .transaction.collapsed:first-child .hash { background-color: rgba(255, 255, 255, 0.33); border: solid 1px #C1C1C1; } .transaction:first-child::before { content: 'Coinbase Transaction:'; } .transaction:not(.collapsed) { display: block; flex-basis: 100%; } .block .transactions .transaction.collapsed:hover { box-shadow: none; } .block .block-header div.transaction-count { display: block; width: calc(100% - 0.5em); } .block-header .hash, .block-header .nonce, .block-header .byte-count, .block-header .reward { display: none; } .transaction .byte-count, .transaction .fee, .transaction .block-hashes { display: none !important; } .block .transaction { overflow: hidden; } h1 { padding-left: 1em; text-align: center; } #pool-hash-rate::after { content: 'h/s'; padding-left: 0.5em; color: rgba(0, 0, 0, 0.33); font-size: 0.5em; vertical-align: text-top; } #pool-hash-rate.kilo::after { content: 'kH/s'; } #pool-hash-rate.mega::after { content: 'MH/s'; } #pool-hash-rate.giga::after { content: 'GH/s'; } #pool-hash-rate.tera::after { content: 'TH/s'; } #pool-hash-rate.peta::after { content: 'PH/s'; } #pool-hash-rate.exa::after { content: 'EH/s'; } @media only screen and (max-width: 500px) { h1 { position: relative; text-align: center; padding-left: 1.33em; } h1 > i { position: absolute; top: 50%; transform: translateY(-50%); left: 0.5em; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/endpoint/StatusApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.endpoint; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.bitcoin.server.module.explorer.api.v1.get.GetStatusHandler; import com.softwareverde.http.HttpMethod; import com.softwareverde.json.Json; public class StatusApi extends ExplorerApiEndpoint { public static class StatusResult extends ApiResult { private Json _serverLoad = new Json(); private Json _statistics = new Json(true); private Json _utxoCacheStatus = new Json(); private Json _serviceStatuses = new Json(); private String _status; public void setServerLoad(final Json serverLoad) { _serverLoad = serverLoad; } public void setStatistics(final Json statistics) { _statistics = statistics; } public void setUtxoCacheStatus(final Json utxoCacheStatus) { _utxoCacheStatus = utxoCacheStatus; } public void setServiceStatuses(final Json serviceStatuses) { _serviceStatuses = serviceStatuses; } public void setStatus(final String status) { _status = status; } @Override public Json toJson() { final Json json = super.toJson(); json.put("status", _status); json.put("statistics", _statistics); json.put("utxoCacheStatus", _utxoCacheStatus); json.put("serverLoad", _serverLoad); json.put("serviceStatuses", _serviceStatuses); return json; } } public StatusApi(final String apiPrePath, final Environment environment) { super(environment); _defineEndpoint((apiPrePath + "/status"), HttpMethod.GET, new GetStatusHandler()); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/manager/banfilter/BanFilterTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager.banfilter; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.node.BitcoinNodeDatabaseManager; import com.softwareverde.bitcoin.test.UnitTest; import com.softwareverde.bitcoin.test.fake.FakeBitcoinNode; import com.softwareverde.bitcoin.test.fake.database.FakeBitcoinNodeDatabaseManager; import com.softwareverde.bitcoin.test.fake.database.FakeDatabaseManager; import com.softwareverde.bitcoin.test.fake.database.FakeDatabaseManagerFactory; import com.softwareverde.network.ip.Ip; import com.softwareverde.util.Container; import com.softwareverde.util.Tuple; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.regex.Pattern; public class BanFilterTests extends UnitTest { @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } @Test public void should_ban_node_matching_user_agent_blacklist() throws Exception { // Setup final String userAgent = "/Bitcoin SV:1.0.3/"; final Pattern pattern = Pattern.compile(".*Bitcoin SV.*"); final Tuple<Ip, Boolean> wasBanned = new Tuple<>(); final Container<Boolean> wasDisconnected = new Container<>(false); final BanFilterCore banFilter = new BanFilterCore(new FakeDatabaseManagerFactory() { @Override public DatabaseManager newDatabaseManager() { return new FakeDatabaseManager() { @Override public BitcoinNodeDatabaseManager getNodeDatabaseManager() { return new FakeBitcoinNodeDatabaseManager() { @Override public void setIsBanned(final Ip ip, final Boolean isBanned) { wasBanned.first = ip; wasBanned.second = isBanned; } }; } }; } }); banFilter.addToUserAgentBlacklist(pattern); final FakeBitcoinNode fakeBitcoinNode = new FakeBitcoinNode("1.2.3.4", 8333, null, null) { @Override public void disconnect() { wasDisconnected.value = true; } @Override public String getUserAgent() { return userAgent; } }; // Action banFilter.onNodeConnected(fakeBitcoinNode.getIp()); banFilter.onNodeHandshakeComplete(fakeBitcoinNode); // Assert Assert.assertTrue(wasBanned.second); Assert.assertTrue(wasDisconnected.value); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/manager/NodeFilter.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager; import com.softwareverde.bitcoin.server.node.BitcoinNode; public interface NodeFilter { Boolean meetsCriteria(BitcoinNode bitcoinNode); } <|start_filename|>www-shared/css/core.css<|end_filename|> html { background-color: #EEEEEE; } body { color: #303030; font-family: 'Work Sans', sans-serif; margin: 0px; } a { color: inherit; text-decoration: inherit; } .bold { font-weight: bold; } #header { background-color: #262626; min-height: 100px; overflow: auto; padding-bottom: 0.5em; box-shadow: 0 0 2px 2px #000000; padding-top: 0.2em; } .navigation ul { display: flex; margin: 0px; flex-direction: row; } .navigation ul li { list-style: none; line-height: 2em; text-align: center; color: #EEEEEE; font-weight: bold; cursor: pointer; padding: 0; overflow: hidden; display: inline-block; } .navigation ul li a { display: block; padding: 1em; } .navigation ul li i { margin-right: 0.25em; } .navigation ul li:hover { color: #FFFFFF; background-color: rgba(255, 255, 255, 0.1); } #header .brand .logo { width: 20em; max-width: 50%; margin: 0.25em; position: relative; top: 0.35em; } #header .brand .title { color: #EEEEEE; font-size: 1.5em; margin-top: 0.88em; margin-left: 0.1em; position: relative; display: inline-block; margin-top: 0.5em; min-width: 5em; } #header .brand .title:before { content: 'Bitcoin Verde'; color: #1AB326; font-weight: bold; font-size: 0.75em; font-family: 'Bree Serif', serif; position: absolute; left: 0; top: -1.0em; } #header .search { clear: left; margin-top: 0.5em; margin-left: 0.5em; } #header .search #search { max-width: 42em; width: calc(100% - 5em); font-size: 1em; font-weight: bold; padding: 0.5em; background-color: rgba(255, 255, 255, 0.05); border: none; border-bottom: solid 2px #F7931D; color: #F7931D; /* text-transform: uppercase; */ } #header .search #search:focus { outline: solid 2px #F7931D; } #header .search .loading { height: 2em; margin-left: 1em; visibility: hidden; vertical-align: middle; } #header input:-webkit-autofill, #header input:-webkit-autofill:hover, #header input:-webkit-autofill:focus { border: solid 1px #F7931D; -webkit-text-fill-color: #F7931D; -webkit-box-shadow: 0 0 0px 1000px rgba(255, 255, 255, 0.15) inset; transition: background-color 5000s ease-in-out 0s; } #templates { display: none; } .fixed { font-family: monospace; overflow-x: auto; -ms-overflow-style: none; overflow: -moz-scrollbars-none; white-space: nowrap; line-height: 1.5em; } .fixed::-webkit-scrollbar { display: none; } .clickable { display: table !important; /* Treats item as an inline-block on a newline... */ } .clickable:hover { cursor: pointer; color: #F7931D; } .copy { display: inline-block !important; height: 1em; width: 1em; background: transparent url('/img/copy.svg'); background-repeat: no-repeat; background-size: 95% 95%; cursor: pointer; margin-left: 0.5em; background-position-y: 100%; vertical-align: text-bottom; } .clearfix::after { content: ""; clear: both; display: table; } @media only screen and (max-width: 700px) { #header .navigation { float: none; } #header .navigation ul { float: none; display: flex; } #header .navigation ul li { font-size: 0.5em; min-width: 5em; display: inline; display: inline-flex; flex-direction: column; flex-grow: 1; } #header .navigation ul li i { margin-right: 0; font-size: 2.5em; display: block; } } @media only screen and (max-width: 600px) { #header .navigation ul { padding-left: 0; } } @media only screen and (max-width: 320px) { * { font-size: 95%; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/block/SpvBlockDatabaseManager.java<|end_filename|> /* package com.softwareverde.bitcoin.server.module.node.database.block; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.merkleroot.PartialMerkleTree; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.constable.list.List; import com.softwareverde.database.DatabaseException; public interface SpvBlockDatabaseManager extends BlockDatabaseManager { List<BlockId> getBlockIdsWithTransactions() throws DatabaseException; void storePartialMerkleTree(BlockId blockId, PartialMerkleTree partialMerkleTree) throws DatabaseException; BlockId selectNextIncompleteBlock(Long minBlockHeight) throws DatabaseException; void addTransactionToBlock(BlockId blockId, TransactionId transactionId) throws DatabaseException; } */ <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/validator/BatchedBlockHeaders.java<|end_filename|> package com.softwareverde.bitcoin.block.validator; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.block.header.difficulty.work.BlockWork; import com.softwareverde.bitcoin.block.header.difficulty.work.ChainWork; public class BatchedBlockHeaders { protected ChainWork _currentChainWork = null; protected Long _startingBlockHeight = null; protected Long _endBlockHeight = 0L; protected final BlockHeader[] _blockHeaders; protected final ChainWork[] _chainWorks; public BatchedBlockHeaders(final Integer blockHeaderCount) { _blockHeaders = new BlockHeader[blockHeaderCount]; _chainWorks = new ChainWork[blockHeaderCount]; } public Long getStartingBlockHeight() { return _startingBlockHeight; } public Long getEndBlockHeight() { return _endBlockHeight; } /** * Sets the ChainWork for the current state of the chain. * The startingChainWork should be the ChainWork of the parent block of the first added BlockHeader. * ::setCurrentChainWork should be invoked before the first call to ::put. */ public void setCurrentChainWork(final ChainWork startingChainWork) { _currentChainWork = startingChainWork; } /** * Stores the BlockHeader (and its blockHeight) for batch validation. * Only ::MAX_BATCH_COUNT headers may be stored. * Stored Headers must be sequential and in ascending order. * If CurrentChainWork is set, the ChainWork for the blockHeader will be calculated and cached. */ public void put(final Long blockHeight, final BlockHeader blockHeader) { if (_startingBlockHeight == null) { _startingBlockHeight = blockHeight; } if (blockHeight >= _endBlockHeight) { _endBlockHeight = blockHeight; } if (blockHeight < _startingBlockHeight) { throw new IndexOutOfBoundsException("Attempting to batch non-sequential headers. _startingBlockHeight=" + _startingBlockHeight + " blockHeight=" + blockHeight); } final int index = (int) (blockHeight - _startingBlockHeight); if (index >= _blockHeaders.length) { throw new IndexOutOfBoundsException("Attempting to batch extra sparse headers. _startingBlockHeight=" + _startingBlockHeight + " blockHeight=" + blockHeight); } _blockHeaders[index] = blockHeader; if (_currentChainWork != null) { final Difficulty difficulty = blockHeader.getDifficulty(); final BlockWork blockWork = difficulty.calculateWork(); _currentChainWork = ChainWork.add(_currentChainWork, blockWork); _chainWorks[index] = _currentChainWork; } } /** * Returns the BlockHeader from the batch by its blockHeight. * If the BlockHeight is not contained within this batch, null is returned. */ public BlockHeader getBlockHeader(final Long blockHeight) { if (blockHeight < _startingBlockHeight) { return null; } if (blockHeight > (_startingBlockHeight + _blockHeaders.length)) { return null; } final int index = (int) (blockHeight - _startingBlockHeight); return _blockHeaders[index]; } public ChainWork getChainWork(final Long blockHeight) { if (blockHeight < _startingBlockHeight) { return null; } if (blockHeight > (_startingBlockHeight + _blockHeaders.length)) { return null; } final int index = (int) (blockHeight - _startingBlockHeight); return _chainWorks[index]; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/validator/BlockHeaderValidator.java<|end_filename|> package com.softwareverde.bitcoin.block.validator; import com.softwareverde.bitcoin.bip.Bip113; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.block.validator.difficulty.DifficultyCalculator; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.context.BlockHeaderContext; import com.softwareverde.bitcoin.context.ChainWorkContext; import com.softwareverde.bitcoin.context.DifficultyCalculatorContext; import com.softwareverde.bitcoin.context.MedianBlockTimeContext; import com.softwareverde.bitcoin.context.NetworkTimeContext; import com.softwareverde.bitcoin.util.Util; import com.softwareverde.network.time.NetworkTime; public class BlockHeaderValidator { public interface Context extends BlockHeaderContext, ChainWorkContext, MedianBlockTimeContext, NetworkTimeContext, DifficultyCalculatorContext { } public static class BlockHeaderValidationResult { public static BlockHeaderValidationResult valid() { return new BlockHeaderValidationResult(true, null); } public static BlockHeaderValidationResult invalid(final String errorMessage) { return new BlockHeaderValidationResult(false, errorMessage); } public final Boolean isValid; public final String errorMessage; public BlockHeaderValidationResult(final Boolean isValid, final String errorMessage) { this.isValid = isValid; this.errorMessage = errorMessage; } } protected final Context _context; public BlockHeaderValidator(final Context context) { _context = context; } public BlockHeaderValidationResult validateBlockHeader(final BlockHeader blockHeader, final Long blockHeight) { if (! blockHeader.isValid()) { return BlockHeaderValidationResult.invalid("Block header is invalid."); } { // Validate Block Timestamp... final Long blockTime = blockHeader.getTimestamp(); final Long minimumTimeInSeconds; { if (Bip113.isEnabled(blockHeight)) { final Long previousBlockHeight = (blockHeight - 1L); final MedianBlockTime medianBlockTime = _context.getMedianBlockTime(previousBlockHeight); minimumTimeInSeconds = medianBlockTime.getCurrentTimeInSeconds(); } else { minimumTimeInSeconds = 0L; } } final NetworkTime networkTime = _context.getNetworkTime(); final Long currentNetworkTimeInSeconds = networkTime.getCurrentTimeInSeconds(); final long secondsInTwoHours = 7200L; final long maximumNetworkTime = (currentNetworkTimeInSeconds + secondsInTwoHours); if (blockTime < minimumTimeInSeconds) { return BlockHeaderValidationResult.invalid("Invalid block. Header invalid. BlockTime < MedianBlockTime. BlockTime: " + blockTime + " Minimum: " + minimumTimeInSeconds); } if (blockTime > maximumNetworkTime) { return BlockHeaderValidationResult.invalid("Invalid block. Header invalid. BlockTime > NetworkTime. BlockTime: " + blockTime + " Maximum: " + maximumNetworkTime); } } { // Validate block (calculated) difficulty... final DifficultyCalculator difficultyCalculator = new DifficultyCalculator(_context); final Difficulty calculatedRequiredDifficulty = difficultyCalculator.calculateRequiredDifficulty(blockHeight); if (calculatedRequiredDifficulty == null) { return BlockHeaderValidationResult.invalid("Unable to calculate required difficulty for block: " + blockHeader.getHash()); } final boolean difficultyIsCorrect = Util.areEqual(calculatedRequiredDifficulty, blockHeader.getDifficulty()); if (! difficultyIsCorrect) { return BlockHeaderValidationResult.invalid("Invalid difficulty for block " + blockHeader.getHash() + " at height: " + blockHeight + ". Required: " + calculatedRequiredDifficulty.encode() + " Found: " + blockHeader.getDifficulty().encode()); } } return BlockHeaderValidationResult.valid(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/lazy/LazyAtomicTransactionOutputIndexerContext.java<|end_filename|> package com.softwareverde.bitcoin.context.lazy; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.context.AtomicTransactionOutputIndexerContext; import com.softwareverde.bitcoin.context.ContextException; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.indexer.BlockchainIndexerDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.indexer.TransactionOutputId; import com.softwareverde.bitcoin.server.module.node.database.transaction.TransactionDatabaseManager; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.util.TransactionUtil; import com.softwareverde.logging.Logger; import com.softwareverde.util.timer.NanoTimer; import java.util.TreeMap; public class LazyAtomicTransactionOutputIndexerContext implements AtomicTransactionOutputIndexerContext { protected static class QueuedOutputs { public final MutableList<TransactionId> transactionIds = new MutableList<TransactionId>(); public final MutableList<Integer> outputIndexes = new MutableList<Integer>(); public final MutableList<Long> amounts = new MutableList<Long>(); public final MutableList<ScriptType> scriptTypes = new MutableList<ScriptType>(); public final MutableList<Address> addresses = new MutableList<Address>(); public final MutableList<TransactionId> slpTransactionIds = new MutableList<TransactionId>(); } protected static class QueuedInputs { public final MutableList<TransactionId> transactionIds = new MutableList<TransactionId>(); public final MutableList<Integer> inputIndexes = new MutableList<Integer>(); public final MutableList<TransactionOutputId> transactionOutputIds = new MutableList<TransactionOutputId>(); } protected final FullNodeDatabaseManager _databaseManager; protected final QueuedInputs _queuedInputs = new QueuedInputs(); protected final QueuedOutputs _queuedOutputs = new QueuedOutputs(); protected Double _storeAddressMs = 0D; protected Double _getUnprocessedTransactionsMs = 0D; protected Double _dequeueTransactionsForProcessingMs = 0D; protected Double _getTransactionIdMs = 0D; protected Double _getTransactionMs = 0D; protected Double _indexTransactionOutputMs = 0D; protected Double _indexTransactionInputMs = 0D; protected TransactionId _getTransactionId(final Sha256Hash transactionHash) throws ContextException { try { final TransactionDatabaseManager transactionDatabaseManager = _databaseManager.getTransactionDatabaseManager(); final NanoTimer nanoTimer = new NanoTimer(); nanoTimer.start(); final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); nanoTimer.stop(); _getTransactionIdMs += nanoTimer.getMillisecondsElapsed(); return transactionId; } catch (final DatabaseException databaseException) { throw new ContextException(databaseException); } } protected Transaction _getTransaction(final TransactionId transactionId) throws ContextException { try { final TransactionDatabaseManager transactionDatabaseManager = _databaseManager.getTransactionDatabaseManager(); final NanoTimer nanoTimer = new NanoTimer(); nanoTimer.start(); final Transaction transaction = transactionDatabaseManager.getTransaction(transactionId); nanoTimer.stop(); _getTransactionMs += nanoTimer.getMillisecondsElapsed(); return transaction; } catch (final DatabaseException databaseException) { throw new ContextException(databaseException); } } public LazyAtomicTransactionOutputIndexerContext(final FullNodeDatabaseManager databaseManager) { _databaseManager = databaseManager; } @Override public void startDatabaseTransaction() throws ContextException { try { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); TransactionUtil.startTransaction(databaseConnection); } catch (final Exception databaseException) { throw new ContextException(databaseException); } } @Override public void commitDatabaseTransaction() throws ContextException { try { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final BlockchainIndexerDatabaseManager blockchainIndexerDatabaseManager = _databaseManager.getBlockchainIndexerDatabaseManager(); { final NanoTimer nanoTimer = new NanoTimer(); nanoTimer.start(); final QueuedOutputs queuedOutputs = new QueuedOutputs(); { // Sort the items... final int itemCount = _queuedOutputs.transactionIds.getCount(); final TreeMap<TransactionOutputId, Integer> treeMap = new TreeMap<TransactionOutputId, Integer>(); for (int i = 0; i < itemCount; ++i) { final TransactionId transactionId = _queuedOutputs.transactionIds.get(i); final Integer outputIndex = _queuedOutputs.outputIndexes.get(i); treeMap.put(new TransactionOutputId(transactionId, outputIndex), i); } for (final TransactionOutputId transactionOutputId : treeMap.keySet()) { final int index = treeMap.get(transactionOutputId); queuedOutputs.transactionIds.add(_queuedOutputs.transactionIds.get(index)); queuedOutputs.outputIndexes.add(_queuedOutputs.outputIndexes.get(index)); queuedOutputs.amounts.add(_queuedOutputs.amounts.get(index)); queuedOutputs.scriptTypes.add(_queuedOutputs.scriptTypes.get(index)); queuedOutputs.addresses.add(_queuedOutputs.addresses.get(index)); queuedOutputs.slpTransactionIds.add(_queuedOutputs.slpTransactionIds.get(index)); } } blockchainIndexerDatabaseManager.indexTransactionOutputs(queuedOutputs.transactionIds, queuedOutputs.outputIndexes, queuedOutputs.amounts, queuedOutputs.scriptTypes, queuedOutputs.addresses, queuedOutputs.slpTransactionIds); nanoTimer.stop(); _indexTransactionOutputMs += nanoTimer.getMillisecondsElapsed(); } { final NanoTimer nanoTimer = new NanoTimer(); nanoTimer.start(); final QueuedInputs queuedInputs = new QueuedInputs(); { // Sort the items... final int itemCount = _queuedInputs.transactionIds.getCount(); final TreeMap<TransactionOutputId, Integer> treeMap = new TreeMap<TransactionOutputId, Integer>(); for (int i = 0; i < itemCount; ++i) { final TransactionId transactionId = _queuedInputs.transactionIds.get(i); final Integer inputIndex = _queuedInputs.inputIndexes.get(i); treeMap.put(new TransactionOutputId(transactionId, inputIndex), i); } for (final TransactionOutputId transactionOutputId : treeMap.keySet()) { final int index = treeMap.get(transactionOutputId); queuedInputs.transactionIds.add(_queuedInputs.transactionIds.get(index)); queuedInputs.inputIndexes.add(_queuedInputs.inputIndexes.get(index)); queuedInputs.transactionOutputIds.add(_queuedInputs.transactionOutputIds.get(index)); } } blockchainIndexerDatabaseManager.indexTransactionInputs(queuedInputs.transactionIds, queuedInputs.inputIndexes, queuedInputs.transactionOutputIds); nanoTimer.stop(); _indexTransactionInputMs += nanoTimer.getMillisecondsElapsed(); } TransactionUtil.commitTransaction(databaseConnection); Logger.trace("_storeAddressMs=" + _storeAddressMs + "ms, _getUnprocessedTransactionsMs=" + _getUnprocessedTransactionsMs + "ms, _dequeueTransactionsForProcessingMs=" + _dequeueTransactionsForProcessingMs + "ms, _getTransactionIdMs=" + _getTransactionIdMs + "ms, _getTransactionMs=" + _getTransactionMs + "ms, _indexTransactionOutputMs=" + _indexTransactionOutputMs + "ms, _indexTransactionInputMs=" + _indexTransactionInputMs + "ms"); } catch (final DatabaseException databaseException) { throw new ContextException(databaseException); } } @Override public void rollbackDatabaseTransaction() { try { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); TransactionUtil.rollbackTransaction(databaseConnection); } catch (final DatabaseException databaseException) { Logger.debug(databaseException); } } @Override public List<TransactionId> getUnprocessedTransactions(final Integer batchSize) throws ContextException { try { final BlockchainIndexerDatabaseManager blockchainIndexerDatabaseManager = _databaseManager.getBlockchainIndexerDatabaseManager(); final NanoTimer nanoTimer = new NanoTimer(); nanoTimer.start(); final List<TransactionId> transactionIds = blockchainIndexerDatabaseManager.getUnprocessedTransactions(batchSize); nanoTimer.stop(); _getUnprocessedTransactionsMs += nanoTimer.getMillisecondsElapsed(); return transactionIds; } catch (final DatabaseException databaseException) { throw new ContextException(databaseException); } } @Override public void dequeueTransactionsForProcessing(final List<TransactionId> transactionIds) throws ContextException { try { final BlockchainIndexerDatabaseManager blockchainIndexerDatabaseManager = _databaseManager.getBlockchainIndexerDatabaseManager(); final NanoTimer nanoTimer = new NanoTimer(); nanoTimer.start(); blockchainIndexerDatabaseManager.dequeueTransactionsForProcessing(transactionIds); nanoTimer.stop(); _dequeueTransactionsForProcessingMs += nanoTimer.getMillisecondsElapsed(); } catch (final DatabaseException databaseException) { throw new ContextException(databaseException); } } @Override public TransactionId getTransactionId(final Sha256Hash transactionHash) throws ContextException { return _getTransactionId(transactionHash); } @Override public TransactionId getTransactionId(final SlpTokenId slpTokenId) throws ContextException { return _getTransactionId(slpTokenId); } @Override public Transaction getTransaction(final TransactionId transactionId) throws ContextException { return _getTransaction(transactionId); } @Override public void indexTransactionOutput(final TransactionId transactionId, final Integer outputIndex, final Long amount, final ScriptType scriptType, final Address address, final TransactionId slpTransactionId) throws ContextException { _queuedOutputs.transactionIds.add(transactionId); _queuedOutputs.outputIndexes.add(outputIndex); _queuedOutputs.amounts.add(amount); _queuedOutputs.scriptTypes.add(scriptType); _queuedOutputs.addresses.add(address); _queuedOutputs.slpTransactionIds.add(slpTransactionId); } @Override public void indexTransactionInput(final TransactionId transactionId, final Integer inputIndex, final TransactionOutputId transactionOutputId) throws ContextException { _queuedInputs.transactionIds.add(transactionId); _queuedInputs.inputIndexes.add(inputIndex); _queuedInputs.transactionOutputIds.add(transactionOutputId); } @Override public void close() throws ContextException { try { _databaseManager.close(); } catch (final Exception databaseException) { throw new ContextException(databaseException); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/opcode/LockTimeOperation.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode; import com.softwareverde.bitcoin.bip.Bip112; import com.softwareverde.bitcoin.bip.Bip65; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.locktime.LockTime; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; import com.softwareverde.bitcoin.transaction.script.runner.ControlState; import com.softwareverde.bitcoin.transaction.script.runner.context.MutableTransactionContext; import com.softwareverde.bitcoin.transaction.script.stack.Stack; import com.softwareverde.bitcoin.transaction.script.stack.Value; import com.softwareverde.util.bytearray.ByteArrayReader; public class LockTimeOperation extends SubTypedOperation { public static final Type TYPE = Type.OP_LOCK_TIME; protected static LockTimeOperation fromBytes(final ByteArrayReader byteArrayReader) { if (! byteArrayReader.hasBytes()) { return null; } final byte opcodeByte = byteArrayReader.readByte(); final Type type = Type.getType(opcodeByte); if (type != TYPE) { return null; } final Opcode opcode = TYPE.getSubtype(opcodeByte); if (opcode == null) { return null; } return new LockTimeOperation(opcodeByte, opcode); } protected LockTimeOperation(final byte value, final Opcode opcode) { super(value, TYPE, opcode); } @Override public Boolean applyTo(final Stack stack, final ControlState controlState, final MutableTransactionContext context) { switch (_opcode) { case CHECK_LOCK_TIME_THEN_VERIFY: { final Boolean operationIsEnabled = Bip65.isEnabled(context.getBlockHeight()); if (! operationIsEnabled) { return true; // NOTE: Before Bip65, CHECK_LOCK_TIME_THEN_VERIFY performed as a NOP... } // CheckLockTimeThenVerify fails if... // the stack is empty; or // the top item on the stack is less than 0; or // the lock-time type (height vs. timestamp) of the top stack item and the nLockTime field are not the same; or // the top stack item is greater than the transaction's nLockTime field; or // the nSequence field of the txin is 0xffffffff final Transaction transaction = context.getTransaction(); final LockTime transactionLockTime = transaction.getLockTime(); final Value requiredLockTimeValue = stack.peak(); if (requiredLockTimeValue.asLong() < 0L) { return false; } // NOTE: This is possible since 5-bytes are permitted when parsing Lock/SequenceNumbers... final LockTime stackLockTime = requiredLockTimeValue.asLockTime(); if (stackLockTime.getType() != transactionLockTime.getType()) { return false; } if (stackLockTime.getValue() > transactionLockTime.getValue()) { return false; } final TransactionInput transactionInput = context.getTransactionInput(); final SequenceNumber transactionInputSequenceNumber = transactionInput.getSequenceNumber(); if (SequenceNumber.MAX_SEQUENCE_NUMBER.equals(transactionInputSequenceNumber)) { return false; } return (! stack.didOverflow()); } case CHECK_SEQUENCE_NUMBER_THEN_VERIFY: { final Boolean operationIsEnabled = (Bip112.isEnabled(context.getBlockHeight())); if (! operationIsEnabled) { return true; // NOTE: Before Bip112, the operation is considered a NOP... } // CheckSequenceVerify fails if... // the stack is empty; or // the top item on the stack is less than 0; or // the top item on the stack has the disable flag (1 << 31) unset; and { // the transaction version is less than 2; or // the transaction input sequence number disable flag (1 << 31) is set; or // the relative lock-time type is not the same; or // the top stack item is greater than the transaction sequence (when masked according to the BIP68); // } final Transaction transaction = context.getTransaction(); final TransactionInput transactionInput = context.getTransactionInput(); final Value stackSequenceNumberValue = stack.peak(); if (stackSequenceNumberValue.asLong() < 0L) { return false; } // NOTE: This is possible due to the value's weird encoding rules and/or also possible since 5-bytes are permitted when parsing SequenceNumbers... final SequenceNumber stackSequenceNumber = stackSequenceNumberValue.asSequenceNumber(); if (! stackSequenceNumber.isRelativeLockTimeDisabled()) { if (transaction.getVersion() < 2) { return false; } final SequenceNumber transactionInputSequenceNumber = transactionInput.getSequenceNumber(); if (transactionInputSequenceNumber.isRelativeLockTimeDisabled()) { return false; } if (stackSequenceNumber.getType() != transactionInputSequenceNumber.getType()) { return false; } if (stackSequenceNumber.getMaskedValue() > transactionInputSequenceNumber.getMaskedValue()) { return false; } } return (! stack.didOverflow()); } default: { return false; } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/header/difficulty/work/ImmutableBlockWork.java<|end_filename|> package com.softwareverde.bitcoin.block.header.difficulty.work; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.ImmutableByteArray; public class ImmutableBlockWork extends ImmutableByteArray implements BlockWork { protected ImmutableBlockWork(final ByteArray byteArray) { super(byteArray); } public ImmutableBlockWork() { super(new byte[32]); } public ImmutableBlockWork(final BlockWork blockWork) { super(blockWork); } public MutableChainWork add(final Work work) { final MutableChainWork chainWork = new MutableChainWork(this); chainWork.add(work); return chainWork; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/TransactionWithFee.java<|end_filename|> package com.softwareverde.bitcoin.transaction; public class TransactionWithFee { public final Transaction transaction; public final Long transactionFee; public TransactionWithFee(final Transaction transaction, final Long transactionFee) { this.transaction = transaction.asConst(); this.transactionFee = transactionFee; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/merkleroot/PartialMerkleTree.java<|end_filename|> package com.softwareverde.bitcoin.block.merkleroot; import com.softwareverde.bitcoin.merkleroot.MerkleRoot; import com.softwareverde.bitcoin.merkleroot.MutableMerkleRoot; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.constable.Const; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.Util; public class PartialMerkleTree implements Const { public static PartialMerkleTree build(final Integer itemCount, final List<Sha256Hash> hashes, final ByteArray flags) { return new PartialMerkleTree(itemCount, hashes, flags); } protected final Integer _itemCount; protected final ByteArray _flags; protected final List<Sha256Hash> _hashes; protected PartialMerkleTreeNode<Transaction> _cachedMerkleTree; protected List<Sha256Hash> _cachedTransactionHashes; protected MerkleRoot _cachedMerkleRoot; protected PartialMerkleTree(final Integer itemCount, final List<Sha256Hash> hashes, final ByteArray flags) { _itemCount = itemCount; _flags = flags.asConst(); _hashes = hashes.asConst(); } /** * Returns the cached PartialMerkleTree if cached, or builds and caches the tree and returns the new instance. * NOTE: Since PartialMerkleTreeNode is not const, it should not be exposed; use ::_buildPartialMerkleTree instead. */ protected PartialMerkleTreeNode<Transaction> _getPartialMerkleTree() { if (_cachedMerkleTree != null) { return _cachedMerkleTree; } _cachedMerkleTree = _buildPartialMerkleTree(); return _cachedMerkleTree; } /** * Returns the cached List of Transaction Hashes (leaf nodes) if cached, or builds and caches the List and returns the new instance. */ protected List<Sha256Hash> _getTransactionHashes() { if (_cachedTransactionHashes != null) { return _cachedTransactionHashes; } final PartialMerkleTreeNode<Transaction> partialMerkleTreeRoot = _getPartialMerkleTree(); if (_cachedMerkleRoot == null) { final Sha256Hash rootHash = partialMerkleTreeRoot.getHash(); _cachedMerkleRoot = MutableMerkleRoot.wrap(rootHash.getBytes()); } final MutableList<Sha256Hash> leafNodes = new MutableList<Sha256Hash>(); partialMerkleTreeRoot.visit(new PartialMerkleTreeNode.Visitor<Transaction>() { @Override public void visit(final PartialMerkleTreeNode<Transaction> partialMerkleTreeNode) { if (partialMerkleTreeNode.isLeafNode()) { leafNodes.add(partialMerkleTreeNode.value); } } }); _cachedTransactionHashes = leafNodes; return leafNodes; } protected PartialMerkleTreeNode<Transaction> _buildPartialMerkleTree() { final int maxHashIndex = _hashes.getCount(); final int maxFlagsIndex = (_flags.getByteCount() * 8); int flagIndex = 0; int hashIndex = 0; final PartialMerkleTreeNode<Transaction> rootMerkleNode = PartialMerkleTreeNode.newRootNode(_itemCount); PartialMerkleTreeNode currentNode = rootMerkleNode; while (currentNode != null) { if (hashIndex >= maxHashIndex) { break; } if (flagIndex >= maxFlagsIndex) { break; } if ( (currentNode.left != null) && (currentNode.right != null) ) { currentNode = currentNode.parent; if (currentNode == null) { break; } continue; } if (currentNode.left != null) { currentNode = currentNode.newRightNode(); } final boolean isMatchOrParentOfMatch = _flags.getBit(flagIndex); flagIndex += 1; if (isMatchOrParentOfMatch) { if (currentNode.isLeafNode()) { currentNode.value = _hashes.get(hashIndex); hashIndex += 1; currentNode = currentNode.parent; } else { if (currentNode.left == null) { currentNode = currentNode.newLeftNode(); } else if (currentNode.right == null) { currentNode = currentNode.newRightNode(); } else { currentNode = currentNode.parent; } } } else { currentNode.value = _hashes.get(hashIndex); hashIndex += 1; currentNode = currentNode.parent; } } if (hashIndex != maxHashIndex) { return null; } // All hashes were not consumed... for (int i = flagIndex; i < maxFlagsIndex; ++i) { final boolean flag = _flags.getBit(i); if (flag) { return null; } // All non-padding flag bits were not consumed... } return rootMerkleNode; } public List<Sha256Hash> getHashes() { return _hashes; } /** * Returns the total number of items in the tree. * This value is equivalent to the number of items in a block. * It is not necessarily the same as the number of hashes returned by ::getHashes or ::getTransactionHashes. */ public Integer getItemCount() { return _itemCount; } public ByteArray getFlags() { return _flags; } public synchronized MerkleRoot getMerkleRoot() { if (_cachedMerkleRoot == null) { final PartialMerkleTreeNode partialMerkleTreeRoot = _getPartialMerkleTree(); final Sha256Hash rootHash = partialMerkleTreeRoot.getHash(); _cachedMerkleRoot = MutableMerkleRoot.wrap(rootHash.getBytes()); } return _cachedMerkleRoot; } public synchronized PartialMerkleTreeNode<Transaction> getMerkleRootNode() { final PartialMerkleTreeNode<Transaction> partialMerkleTreeRoot = _buildPartialMerkleTree(); if (_cachedMerkleRoot == null) { final Sha256Hash rootHash = partialMerkleTreeRoot.getHash(); _cachedMerkleRoot = MutableMerkleRoot.wrap(rootHash.getBytes()); } return partialMerkleTreeRoot; } public synchronized List<Sha256Hash> getTransactionHashes() { return _getTransactionHashes(); } public synchronized Boolean containsTransaction(final Sha256Hash transactionHash) { final List<Sha256Hash> transactionHashes = _getTransactionHashes(); for (final Sha256Hash existingTransactionHash : transactionHashes) { if (Util.areEqual(existingTransactionHash, transactionHash)) { return true; } } return false; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/AtomicTransactionOutputIndexerContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.server.module.node.database.indexer.TransactionOutputId; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface AtomicTransactionOutputIndexerContext extends AutoCloseable { void startDatabaseTransaction() throws ContextException; void commitDatabaseTransaction() throws ContextException; void rollbackDatabaseTransaction(); List<TransactionId> getUnprocessedTransactions(Integer batchSize) throws ContextException; void dequeueTransactionsForProcessing(List<TransactionId> transactionIds) throws ContextException; TransactionId getTransactionId(Sha256Hash transactionHash) throws ContextException; TransactionId getTransactionId(SlpTokenId slpTokenId) throws ContextException; Transaction getTransaction(TransactionId transactionId) throws ContextException; void indexTransactionOutput(TransactionId transactionId, Integer outputIndex, Long amount, ScriptType scriptType, Address address, TransactionId slpTransactionId) throws ContextException; void indexTransactionInput(TransactionId transactionId, Integer inputIndex, TransactionOutputId transactionOutputId) throws ContextException; @Override void close() throws ContextException; } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/mint/SlpMintScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp.mint; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.transaction.script.slp.SlpScript; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptType; import com.softwareverde.constable.Constable; import com.softwareverde.util.Util; public interface SlpMintScript extends SlpScript, Constable<ImmutableSlpMintScript> { Integer RECEIVER_TRANSACTION_OUTPUT_INDEX = 1; SlpTokenId getTokenId(); Integer getBatonOutputIndex(); Long getTokenCount(); @Override ImmutableSlpMintScript asConst(); } abstract class SlpMintScriptCore implements SlpMintScript { protected SlpTokenId _tokenId; protected Integer _batonOutputIndex; protected Long _tokenCount; public SlpMintScriptCore() { } public SlpMintScriptCore(final SlpMintScript slpMintScript) { _tokenId = slpMintScript.getTokenId().asConst(); _batonOutputIndex = slpMintScript.getBatonOutputIndex(); _tokenCount = slpMintScript.getTokenCount(); } @Override public SlpScriptType getType() { return SlpScriptType.MINT; } @Override public Integer getMinimumTransactionOutputCount() { return Math.max(2, (Util.coalesce(_batonOutputIndex) + 1)); // Requires at least 1 Script Output and 1 Receiver Output... } @Override public SlpTokenId getTokenId() { return _tokenId; } @Override public Integer getBatonOutputIndex() { return _batonOutputIndex; } @Override public Long getTokenCount() { return _tokenCount; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/secp256k1/Secp256k1.java<|end_filename|> package com.softwareverde.bitcoin.secp256k1; import com.softwareverde.bitcoin.jni.NativeSecp256k1; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.secp256k1.key.PublicKey; import com.softwareverde.cryptography.secp256k1.signature.Signature; import com.softwareverde.logging.Logger; public class Secp256k1 extends com.softwareverde.cryptography.secp256k1.Secp256k1 { protected static Boolean _verifySignatureViaJni(final Signature signature, final PublicKey publicKey, final ByteArray message) { try { final Signature canonicalSignature = signature.asCanonical(); final ByteArray canonicalSignatureBytes = canonicalSignature.encode(); return NativeSecp256k1.verifySignature(message, canonicalSignatureBytes, publicKey); } catch (final Exception exception) { Logger.warn(exception); return false; } } public static Boolean verifySignature(final Signature signature, final PublicKey publicKey, final byte[] message) { if (NativeSecp256k1.isEnabled()) { return _verifySignatureViaJni(signature, publicKey, ByteArray.wrap(message)); } // Fallback to BouncyCastle if the libsecp256k1 failed to load for this architecture... return _verifySignatureViaBouncyCastle(signature, publicKey, message); } public static Boolean verifySignature(final Signature signature, final PublicKey publicKey, final ByteArray message) { if (NativeSecp256k1.isEnabled()) { return _verifySignatureViaJni(signature, publicKey, message); } // Fallback to BouncyCastle if the libsecp256k1 failed to load for this architecture... return _verifySignatureViaBouncyCastle(signature, publicKey, message.getBytes()); } protected Secp256k1() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/thin/transaction/ThinTransactionsMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.thin.transaction; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.bytearray.Endian; public class ThinTransactionsMessageInflater extends BitcoinProtocolMessageInflater { protected final TransactionInflaters _transactionInflaters; public ThinTransactionsMessageInflater(final TransactionInflaters transactionInflaters) { _transactionInflaters = transactionInflaters; } @Override public ThinTransactionsMessage fromBytes(final byte[] bytes) { final ThinTransactionsMessage thinTransactionsMessage = new ThinTransactionsMessage(_transactionInflaters); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.THIN_TRANSACTIONS); if (protocolMessageHeader == null) { return null; } final Sha256Hash blockHash = MutableSha256Hash.wrap(byteArrayReader.readBytes(32, Endian.LITTLE)); thinTransactionsMessage.setBlockHash(blockHash); final Integer transactionCount = byteArrayReader.readVariableSizedInteger().intValue(); if (transactionCount > BlockInflater.MAX_TRANSACTION_COUNT) { return null; } final TransactionInflater transactionInflater = _transactionInflaters.getTransactionInflater(); final ImmutableListBuilder<Transaction> transactionListBuilder = new ImmutableListBuilder<Transaction>(transactionCount); for (int i = 0; i < transactionCount; ++i) { final Transaction transaction = transactionInflater.fromBytes(byteArrayReader); if (transaction == null) { return null; } transactionListBuilder.add(transaction); } thinTransactionsMessage.setTransactions(transactionListBuilder.build()); if (byteArrayReader.didOverflow()) { return null; } return thinTransactionsMessage; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/script/signature/ScriptSignatureTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.signature; import com.softwareverde.constable.bytearray.ByteArray; import org.junit.Assert; import org.junit.Test; public class ScriptSignatureTests { @Test public void should_inflate_signature_from_20190515HF() { // Script Signature has hash type byte provided... final ByteArray byteArray = ByteArray.fromHexString("BD49BBF18F6EFD604AD8EE21A7C361561618E54B0C59B8F1C442FBBB8255CE9FF36160C0551DD6E1CC6A95BE43D628E6A186A7B8C391F32A57CE27E3AF5A3A9D41"); final ScriptSignature scriptSignature = ScriptSignature.fromBytes(byteArray, ScriptSignatureContext.CHECK_SIGNATURE); Assert.assertNotNull(scriptSignature); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/lazy/LazyMedianBlockTimeContext.java<|end_filename|> package com.softwareverde.bitcoin.context.lazy; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.context.MedianBlockTimeContext; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManager; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; public class LazyMedianBlockTimeContext implements MedianBlockTimeContext { protected final DatabaseManager _databaseManager; protected BlockchainSegmentId _getHeadBlockchainSegmentId() throws DatabaseException { final BlockchainDatabaseManager blockchainDatabaseManager = _databaseManager.getBlockchainDatabaseManager(); return blockchainDatabaseManager.getHeadBlockchainSegmentId(); } protected BlockId _getBlockId(final Long blockHeight) throws DatabaseException { final BlockchainSegmentId blockchainSegmentId = _getHeadBlockchainSegmentId(); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = _databaseManager.getBlockHeaderDatabaseManager(); return blockHeaderDatabaseManager.getBlockIdAtHeight(blockchainSegmentId, blockHeight); } public LazyMedianBlockTimeContext(final DatabaseManager databaseManager) { _databaseManager = databaseManager; } @Override public MedianBlockTime getMedianBlockTime(final Long blockHeight) { try { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = _databaseManager.getBlockHeaderDatabaseManager(); final BlockId blockId = _getBlockId(blockHeight); if (blockId == null) { return null; } return blockHeaderDatabaseManager.getMedianBlockTime(blockId); } catch (final DatabaseException exception) { Logger.debug(exception); return null; } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/Bip112.java<|end_filename|> package com.softwareverde.bitcoin.bip; import com.softwareverde.util.Util; public class Bip112 { public static final Long ACTIVATION_BLOCK_HEIGHT = 419328L; // https://www.reddit.com/r/Bitcoin/comments/4r9tiv/csv_soft_fork_has_activated_as_of_block_419328 // OP_CHECKSEQUENCEVERIFY -- https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki public static Boolean isEnabled(final Long blockHeight) { return (Util.coalesce(blockHeight, Long.MAX_VALUE) >= ACTIVATION_BLOCK_HEIGHT); } protected Bip112() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/util/ByteBuffer.java<|end_filename|> package com.softwareverde.bitcoin.util; public class ByteBuffer extends com.softwareverde.util.ByteBuffer { public void recycleBuffer(final byte[] buffer) { _recycledByteArrays.addLast(new Buffer(buffer, 0, 0)); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/thin/ThinBlockAssembler.java<|end_filename|> package com.softwareverde.bitcoin.block.thin; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.server.module.node.MemoryPoolEnquirer; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import java.util.HashMap; import java.util.Map; public class ThinBlockAssembler { protected final MemoryPoolEnquirer _memoryPoolEnquirer; public ThinBlockAssembler(final MemoryPoolEnquirer memoryPoolEnquirer) { _memoryPoolEnquirer = memoryPoolEnquirer; } public AssembleThinBlockResult assembleThinBlock(final BlockHeader blockHeader, final List<Sha256Hash> transactionHashes, final List<Transaction> extraTransactions) { final HashMap<Sha256Hash, Transaction> mappedTransactions = new HashMap<Sha256Hash, Transaction>(); for (final Transaction transaction : extraTransactions) { final Sha256Hash transactionHash = transaction.getHash(); mappedTransactions.put(transactionHash, transaction); } final MutableBlock mutableBlock = new MutableBlock(blockHeader); for (final Sha256Hash transactionHash : transactionHashes) { final Transaction cachedTransaction = mappedTransactions.get(transactionHash); if (cachedTransaction != null) { mutableBlock.addTransaction(cachedTransaction); } else { final Transaction transaction = _memoryPoolEnquirer.getTransaction(transactionHash); if (transaction == null) { break; } mappedTransactions.put(transactionHash, transaction); mutableBlock.addTransaction(transaction); } } final Block block = (mutableBlock.isValid() ? mutableBlock : null); final AssembleThinBlockResult assembleThinBlockResult = new AssembleThinBlockResult(block, transactionHashes); assembleThinBlockResult.allowReassembly(blockHeader, transactionHashes, mappedTransactions); return assembleThinBlockResult; } public Block reassembleThinBlock(final AssembleThinBlockResult assembleThinBlockResult, final List<Transaction> missingTransactions) { if (! assembleThinBlockResult.canBeReassembled()) { return null; } final BlockHeader blockHeader = assembleThinBlockResult.getBlockHeader(); final List<Sha256Hash> transactionHashes = assembleThinBlockResult.getTransactionHashes(); final Map<Sha256Hash, Transaction> mappedTransactions = assembleThinBlockResult.getMappedTransactions(); for (final Transaction transaction : missingTransactions) { final Sha256Hash transactionHash = transaction.getHash(); mappedTransactions.put(transactionHash, transaction); } final MutableBlock mutableBlock = new MutableBlock(blockHeader); for (final Sha256Hash transactionHash : transactionHashes) { final Transaction cachedTransaction = mappedTransactions.get(transactionHash); if (cachedTransaction != null) { mutableBlock.addTransaction(cachedTransaction); } else { final Transaction transaction = _memoryPoolEnquirer.getTransaction(transactionHash); if (transaction == null) { return null; } mutableBlock.addTransaction(transaction); } } return (mutableBlock.isValid() ? mutableBlock : null); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/rpc/handler/MetadataHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.rpc.handler; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.work.ChainWork; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.BlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.indexer.BlockchainIndexerDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.TransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.slp.SlpTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.rpc.NodeRpcHandler; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.slp.SlpUtil; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.ScriptPatternMatcher; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptInflater; import com.softwareverde.bitcoin.transaction.script.slp.genesis.SlpGenesisScript; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.json.Json; import com.softwareverde.logging.Logger; import com.softwareverde.util.Util; import java.util.HashMap; public class MetadataHandler implements NodeRpcHandler.MetadataHandler { protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; protected static void _addMetadataForBlockHeaderToJson(final Sha256Hash blockHash, final Json blockJson, final DatabaseManager databaseConnection) throws DatabaseException { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseConnection.getBlockHeaderDatabaseManager(); final BlockDatabaseManager blockDatabaseManager = databaseConnection.getBlockDatabaseManager(); final BlockId blockId = blockHeaderDatabaseManager.getBlockHeaderId(blockHash); final MedianBlockTime medianTimePast = blockHeaderDatabaseManager.getMedianTimePast(blockId); final MedianBlockTime medianBlockTime = blockHeaderDatabaseManager.getMedianBlockTime(blockId); { // Include Extra Block Metadata... final Long blockHeight = blockHeaderDatabaseManager.getBlockHeight(blockId); final Integer transactionCount = blockDatabaseManager.getTransactionCount(blockId); final ChainWork chainWork = blockHeaderDatabaseManager.getChainWork(blockId); blockJson.put("height", blockHeight); blockJson.put("reward", BlockHeader.calculateBlockReward(blockHeight)); blockJson.put("byteCount", blockHeaderDatabaseManager.getBlockByteCount(blockId)); blockJson.put("transactionCount", transactionCount); blockJson.put("medianBlockTime", medianBlockTime.getCurrentTimeInSeconds()); blockJson.put("medianTimePast", medianTimePast.getCurrentTimeInSeconds()); blockJson.put("chainWork", chainWork); } } protected static void _addMetadataForTransactionToJson(final Transaction transaction, final Json transactionJson, final FullNodeDatabaseManager databaseManager) throws DatabaseException { final Sha256Hash transactionHash = transaction.getHash(); final String transactionHashString = transactionHash.toString(); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final TransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); final BlockchainIndexerDatabaseManager blockchainIndexerDatabaseManager = databaseManager.getBlockchainIndexerDatabaseManager(); final SlpTransactionDatabaseManager slpTransactionDatabaseManager = databaseManager.getSlpTransactionDatabaseManager(); final ScriptPatternMatcher scriptPatternMatcher = new ScriptPatternMatcher(); final TransactionDeflater transactionDeflater = new TransactionDeflater(); final ByteArray transactionData = transactionDeflater.toBytes(transaction); transactionJson.put("byteCount", transactionData.getByteCount()); final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); final SlpTokenId slpTokenId = blockchainIndexerDatabaseManager.getSlpTokenId(transactionId); final Boolean hasSlpData = (slpTokenId != null); final Boolean isSlpValid; if (hasSlpData) { isSlpValid = slpTransactionDatabaseManager.getSlpTransactionValidationResult(transactionId); } else { isSlpValid = null; } Long transactionFee = 0L; { // Include Block hashes which include this transaction... final Json blockHashesJson = new Json(true); final List<BlockId> blockIds = transactionDatabaseManager.getBlockIds(transactionHash); for (final BlockId blockId : blockIds) { final Sha256Hash blockHash = blockHeaderDatabaseManager.getBlockHash(blockId); blockHashesJson.add(blockHash); } transactionJson.put("blocks", blockHashesJson); } { // Process TransactionInputs... final HashMap<Sha256Hash, Transaction> cachedTransactions = new HashMap<Sha256Hash, Transaction>(8); int transactionInputIndex = 0; for (final TransactionInput transactionInput : transaction.getTransactionInputs()) { final Sha256Hash previousOutputTransactionHash = transactionInput.getPreviousOutputTransactionHash(); final Transaction previousTransaction; { final Transaction cachedTransaction = cachedTransactions.get(previousOutputTransactionHash); if (cachedTransaction != null) { previousTransaction = cachedTransaction; } else { final TransactionId previousOutputTransactionId = transactionDatabaseManager.getTransactionId(previousOutputTransactionHash); previousTransaction = (previousOutputTransactionId != null ? transactionDatabaseManager.getTransaction(previousOutputTransactionId) : null); cachedTransactions.put(previousOutputTransactionHash, previousTransaction); } } if (previousTransaction == null) { transactionFee = null; // Abort calculating the transaction fee but continue with the rest of the processing... } final TransactionOutput previousTransactionOutput; if (previousTransaction != null) { final List<TransactionOutput> previousOutputs = previousTransaction.getTransactionOutputs(); final Integer previousOutputIndex = transactionInput.getPreviousOutputIndex(); previousTransactionOutput = previousOutputs.get(previousOutputIndex); } else { previousTransactionOutput = null; } final Long previousTransactionOutputAmount = ( previousTransactionOutput != null ? previousTransactionOutput.getAmount() : null ); if (transactionFee != null) { transactionFee += Util.coalesce(previousTransactionOutputAmount); } final String addressString; final String cashAddressString; { if (previousTransactionOutput != null) { final LockingScript lockingScript = previousTransactionOutput.getLockingScript(); final ScriptType scriptType = scriptPatternMatcher.getScriptType(lockingScript); final Address address = scriptPatternMatcher.extractAddress(scriptType, lockingScript); addressString = address.toBase58CheckEncoded(); cashAddressString = address.toBase32CheckEncoded(true); } else { addressString = null; cashAddressString = null; } } final Json transactionInputJson = transactionJson.get("inputs").get(transactionInputIndex); transactionInputJson.put("previousTransactionAmount", previousTransactionOutputAmount); transactionInputJson.put("address", addressString); transactionInputJson.put("cashAddress", cashAddressString); if (hasSlpData && Util.coalesce(isSlpValid, false)) { final Integer previousOutputIndex = transactionInput.getPreviousOutputIndex(); if (previousTransaction != null) { final Boolean isSlpOutput = SlpUtil.isSlpTokenOutput(previousTransaction, previousOutputIndex); if (isSlpOutput) { final Long slpTokenAmount = SlpUtil.getOutputTokenAmount(previousTransaction, previousOutputIndex); final Boolean isSlpBatonOutput = SlpUtil.isSlpTokenBatonHolder(previousTransaction, previousOutputIndex); final Json slpOutputJson = new Json(false); slpOutputJson.put("tokenAmount", slpTokenAmount); slpOutputJson.put("isBaton", isSlpBatonOutput); transactionInputJson.put("slp", slpOutputJson); } } } transactionInputIndex += 1; } } { // Process TransactionOutputs... int transactionOutputIndex = 0; for (final TransactionOutput transactionOutput : transaction.getTransactionOutputs()) { if (transactionFee != null) { transactionFee -= transactionOutput.getAmount(); } { // Add extra TransactionOutput json fields... final String addressString; final String cashAddressString; { final LockingScript lockingScript = transactionOutput.getLockingScript(); final ScriptType scriptType = scriptPatternMatcher.getScriptType(lockingScript); final Address address = scriptPatternMatcher.extractAddress(scriptType, lockingScript); addressString = (address != null ? address.toBase58CheckEncoded() : null); cashAddressString = (address != null ? address.toBase32CheckEncoded(true) : null); } final Json transactionOutputJson = transactionJson.get("outputs").get(transactionOutputIndex); transactionOutputJson.put("address", addressString); transactionOutputJson.put("cashAddress", cashAddressString); if (hasSlpData && Util.coalesce(isSlpValid, false)) { final Boolean isSlpOutput = SlpUtil.isSlpTokenOutput(transaction, transactionOutputIndex); if (isSlpOutput) { final Long slpTokenAmount = SlpUtil.getOutputTokenAmount(transaction, transactionOutputIndex); final Boolean isSlpBatonOutput = SlpUtil.isSlpTokenBatonHolder(transaction, transactionOutputIndex); final Json slpOutputJson = new Json(false); slpOutputJson.put("tokenAmount", slpTokenAmount); slpOutputJson.put("isBaton",isSlpBatonOutput); transactionOutputJson.put("slp", slpOutputJson); } } } transactionOutputIndex += 1; } } transactionJson.put("fee", transactionFee); final Json slpJson; if (hasSlpData) { final TransactionId slpGenesisTransactionId = transactionDatabaseManager.getTransactionId(slpTokenId); final Transaction slpGenesisTransaction = transactionDatabaseManager.getTransaction(slpGenesisTransactionId); final SlpGenesisScript slpGenesisScript; { if (slpGenesisTransaction != null) { final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); final List<TransactionOutput> transactionOutputs = slpGenesisTransaction.getTransactionOutputs(); final TransactionOutput transactionOutput = transactionOutputs.get(0); final LockingScript lockingScript = transactionOutput.getLockingScript(); slpGenesisScript = slpScriptInflater.genesisScriptFromScript(lockingScript); } else { slpGenesisScript = null; } } if (slpGenesisScript != null) { slpJson = slpGenesisScript.toJson(); slpJson.put("tokenId", slpTokenId); slpJson.put("isValid", isSlpValid); } else { slpJson = null; } } else { slpJson = null; } transactionJson.put("slp", slpJson); } public MetadataHandler(final FullNodeDatabaseManagerFactory databaseManagerFactory) { _databaseManagerFactory = databaseManagerFactory; } @Override public void applyMetadataToBlockHeader(final Sha256Hash blockHash, final Json blockJson) { try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { _addMetadataForBlockHeaderToJson(blockHash, blockJson, databaseManager); } catch (final DatabaseException exception) { Logger.warn(exception); } } @Override public void applyMetadataToTransaction(final Transaction transaction, final Json transactionJson) { try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { _addMetadataForTransactionToJson(transaction, transactionJson, databaseManager); } catch (final DatabaseException exception) { Logger.warn(exception); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/TransactionInflater.java<|end_filename|> package com.softwareverde.bitcoin.transaction; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.transaction.input.MutableTransactionInput; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.input.TransactionInputInflater; import com.softwareverde.bitcoin.transaction.locktime.ImmutableLockTime; import com.softwareverde.bitcoin.transaction.output.MutableTransactionOutput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.TransactionOutputInflater; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.HexUtil; import com.softwareverde.util.bytearray.Endian; public class TransactionInflater { public static final Integer MIN_BYTE_COUNT = 100; public static final Integer MAX_BYTE_COUNT = (int) (2L * ByteUtil.Unit.Si.MEGABYTES); protected MutableTransaction _fromByteArrayReader(final ByteArrayReader byteArrayReader) { // NOTE: The min Transaction size rule was activated on HF20181115 and therefore cannot be enforced here. final Integer startPosition = byteArrayReader.getPosition(); final MutableTransaction transaction = new MutableTransaction(); transaction._version = byteArrayReader.readLong(4, Endian.LITTLE); final TransactionInputInflater transactionInputInflater = new TransactionInputInflater(); final Long transactionInputCount = byteArrayReader.readVariableSizedInteger(); for (int i = 0; i < transactionInputCount; ++i) { if (byteArrayReader.remainingByteCount() < 1) { return null; } final MutableTransactionInput transactionInput = transactionInputInflater.fromBytes(byteArrayReader); if (transactionInput == null) { return null; } transaction._transactionInputs.add(transactionInput); } final TransactionOutputInflater transactionOutputInflater = new TransactionOutputInflater(); final Long transactionOutputCount = byteArrayReader.readVariableSizedInteger(); for (int i = 0; i < transactionOutputCount; ++i) { if (byteArrayReader.remainingByteCount() < 1) { return null; } final MutableTransactionOutput transactionOutput = transactionOutputInflater.fromBytes(i, byteArrayReader); if (transactionOutput == null) { return null; } transaction._transactionOutputs.add(transactionOutput); } { // Read Transaction LockTime... final Long lockTimeValue = byteArrayReader.readLong(4, Endian.LITTLE); transaction._lockTime = new ImmutableLockTime(lockTimeValue); } if (byteArrayReader.didOverflow()) { return null; } final int totalByteCount; { // Enforce maximum transaction size... // NOTE: At this point, the bytes are already in memory and limited by the PacketBuffer max size, so incremental checks are not performed. final Integer endPosition = byteArrayReader.getPosition(); totalByteCount = (endPosition - startPosition); if (totalByteCount > TransactionInflater.MAX_BYTE_COUNT) { return null; } } transaction.cacheByteCount(totalByteCount); return transaction; } public void debugBytes(final ByteArrayReader byteArrayReader) { System.out.println("Version: " + HexUtil.toHexString(byteArrayReader.readBytes(4))); { final ByteArrayReader.VariableSizedInteger inputCount = byteArrayReader.peakVariableSizedInteger(); System.out.println("Tx Input Count: " + HexUtil.toHexString(byteArrayReader.readBytes(inputCount.bytesConsumedCount))); final TransactionInputInflater transactionInputInflater = new TransactionInputInflater(); for (int i = 0; i < inputCount.value; ++i) { transactionInputInflater._debugBytes(byteArrayReader); } } { final ByteArrayReader.VariableSizedInteger outputCount = byteArrayReader.peakVariableSizedInteger(); System.out.println("Tx Output Count: " + HexUtil.toHexString(byteArrayReader.readBytes(outputCount.bytesConsumedCount))); final TransactionOutputInflater transactionOutputInflater = new TransactionOutputInflater(); for (int i = 0; i < outputCount.value; ++i) { transactionOutputInflater._debugBytes(byteArrayReader); } } System.out.println("LockTime: " + HexUtil.toHexString(byteArrayReader.readBytes(4))); } public Transaction fromBytes(final ByteArrayReader byteArrayReader) { if (byteArrayReader == null) { return null; } return _fromByteArrayReader(byteArrayReader); } public Transaction fromBytes(final byte[] bytes) { if (bytes == null) { return null; } final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); return _fromByteArrayReader(byteArrayReader); } public Transaction fromBytes(final ByteArray bytes) { if (bytes == null) { return null; } final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); return _fromByteArrayReader(byteArrayReader); } public Transaction createCoinbaseTransaction(final Long blockHeight, final String coinbaseMessage, final Address address, final Long satoshis) { final MutableTransaction coinbaseTransaction = new MutableTransaction(); coinbaseTransaction.addTransactionInput(TransactionInput.createCoinbaseTransactionInput(blockHeight, coinbaseMessage)); coinbaseTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address, satoshis)); return coinbaseTransaction; } public Transaction createCoinbaseTransactionWithExtraNonce(final Long blockHeight, final String coinbaseMessage, final Integer extraNonceByteCount, final Address address, final Long satoshis) { final MutableTransaction coinbaseTransaction = new MutableTransaction(); coinbaseTransaction.addTransactionInput(TransactionInput.createCoinbaseTransactionInputWithExtraNonce(blockHeight, coinbaseMessage, extraNonceByteCount)); coinbaseTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address, satoshis)); return coinbaseTransaction; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/address/CompressedAddress.java<|end_filename|> package com.softwareverde.bitcoin.address; public class CompressedAddress extends Address { public static final byte PREFIX = (byte) 0x00; @Override protected byte _getPrefix() { return PREFIX; } protected CompressedAddress(final byte[] bytes) { super(bytes); } @Override public Boolean isCompressed() { return true; } @Override public CompressedAddress asConst() { return this; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/locktime/LockTimeType.java<|end_filename|> package com.softwareverde.bitcoin.transaction.locktime; public enum LockTimeType { TIMESTAMP, BLOCK_HEIGHT } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/script/ScriptInflaterTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script; import com.softwareverde.bitcoin.test.util.TestUtil; import com.softwareverde.bitcoin.transaction.script.opcode.Operation; import com.softwareverde.bitcoin.transaction.script.opcode.PushOperation; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.util.HexUtil; import org.junit.Assert; import org.junit.Test; public class ScriptInflaterTests { @Test public void should_inflate_basic_unlocking_script() { // Setup final String unlockingScriptHexString = "47304402201AFBFFC4EA7D41F2D71CFC2F7DC2AFBA406819DA44D363CB1163EFF5DA2C96BA02201E46E79DF44D324086F233AC0B9C0675C82122F96F6837C9058588DDFB986E26014104751C030813B7624983C30AC932ACD2FEBAA9AA9337C27BF03B875B2466E859064ADA52820195A81D83CE0D28FD8BD217B4BBBDA1A76B256A46A9E5FDB8EA435A"; final Script expectedScript; final ScriptBuilder scriptBuilder = new ScriptBuilder(); scriptBuilder.pushBytes(MutableByteArray.wrap(HexUtil.hexStringToByteArray("304402201AFBFFC4EA7D41F2D71CFC2F7DC2AFBA406819DA44D363CB1163EFF5DA2C96BA02201E46E79DF44D324086F233AC0B9C0675C82122F96F6837C9058588DDFB986E2601"))); scriptBuilder.pushBytes(MutableByteArray.wrap(HexUtil.hexStringToByteArray("04751C030813B7624983C30AC932ACD2FEBAA9AA9337C27BF03B875B2466E859064ADA52820195A81D83CE0D28FD8BD217B4BBBDA1A76B256A46A9E5FDB8EA435A"))); expectedScript = scriptBuilder.build(); final ScriptInflater scriptInflater = new ScriptInflater(); // Action final Script script = scriptInflater.fromBytes(HexUtil.hexStringToByteArray(unlockingScriptHexString)); // Assert TestUtil.assertEqual(expectedScript.getBytes().getBytes(), script.getBytes().getBytes()); final List<Operation> operations = script.getOperations(); Assert.assertEquals(2, operations.getCount()); Assert.assertEquals(Operation.Type.OP_PUSH, operations.get(0).getType()); Assert.assertEquals(Operation.Type.OP_PUSH, operations.get(1).getType()); Assert.assertEquals(0x47, operations.get(0).getOpcodeByte()); Assert.assertEquals(0x41, operations.get(1).getOpcodeByte()); final PushOperation pushOperation0 = (PushOperation) operations.get(0); TestUtil.assertEqual(HexUtil.hexStringToByteArray("304402201AFBFFC4EA7D41F2D71CFC2F7DC2AFBA406819DA44D363CB1163EFF5DA2C96BA02201E46E79DF44D324086F233AC0B9C0675C82122F96F6837C9058588DDFB986E2601"), pushOperation0.getValue().getBytes()); final PushOperation pushOperation1 = (PushOperation) operations.get(1); TestUtil.assertEqual(HexUtil.hexStringToByteArray("04751C030813B7624983C30AC932ACD2FEBAA9AA9337C27BF03B875B2466E859064ADA52820195A81D83CE0D28FD8BD217B4BBBDA1A76B256A46A9E5FDB8EA435A"), pushOperation1.getValue().getBytes()); } @Test public void should_inflate_poorly_formed_coinbase_script() { // Block 00000000000000001371D439D02C92C514146E6C3A801399DAAB4742FB707BB1 has a coinbase that contains invalid opcodes... // The ScriptInflater should inflate these as OP_INVALID. // Setup final String hexString = "03937405E4B883E5BDA9E7A59EE4BB99E9B1BCFABE6D6DE5C01B6F48B22335B821F00B179D9A4B03C561F73453D3E91C7B356095F2254D10000000000000000068D65924BD00004D696E656420627920736F6E676C656936363636"; final ScriptInflater scriptInflater = new ScriptInflater(); // Action final Script script = scriptInflater.fromBytes(HexUtil.hexStringToByteArray(hexString)); // Assert Assert.assertNotNull(script); final List<Operation> operations = script.getOperations(); Assert.assertEquals(24, operations.getCount()); Assert.assertEquals(Operation.Type.OP_PUSH, operations.get(0).getType()); Assert.assertEquals(Operation.Type.OP_INVALID, operations.get(1).getType()); TestUtil.assertEqual(HexUtil.hexStringToByteArray("E4"), operations.get(1).getBytes()); TestUtil.assertEqual(HexUtil.hexStringToByteArray(hexString), script.getBytes().getBytes()); } } <|start_filename|>src/main/java/org/bitcoin/Secp256k1Context.java<|end_filename|> package org.bitcoin; public class Secp256k1Context { public static native long secp256k1_init_context(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/validator/thread/TotalExpenditureTaskHandler.java<|end_filename|> package com.softwareverde.bitcoin.block.validator.thread; import com.softwareverde.bitcoin.constable.util.ConstUtil; import com.softwareverde.bitcoin.context.UnspentTransactionOutputContext; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.validator.BlockOutputs; import com.softwareverde.bitcoin.transaction.validator.SpentOutputsTracker; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; /** * Calculates the total fees available for all Transactions sent to executeTask. * If any expenditures are invalid (i.e. inputs < outputs), then ExpenditureResult.isValid will be false. */ public class TotalExpenditureTaskHandler implements TaskHandler<Transaction, TotalExpenditureTaskHandler.ExpenditureResult> { public static class ExpenditureResult { public static ExpenditureResult invalid(final Transaction invalidTransaction) { final ImmutableListBuilder<Sha256Hash> invalidTransactions = new ImmutableListBuilder<Sha256Hash>(1); invalidTransactions.add(invalidTransaction.getHash()); return new ExpenditureResult(false, null, invalidTransactions.build()); } public static ExpenditureResult invalid(final List<Transaction> invalidTransactions) { final ImmutableListBuilder<Sha256Hash> invalidTransactionHashes = new ImmutableListBuilder<Sha256Hash>(1); for (final Transaction transaction : invalidTransactions) { invalidTransactionHashes.add(transaction.getHash()); } return new ExpenditureResult(false, null, invalidTransactionHashes.build()); } public static ExpenditureResult valid(final Long totalFees) { return new ExpenditureResult(true, totalFees, null); } public final Boolean isValid; public final Long totalFees; public final List<Sha256Hash> invalidTransactions; public ExpenditureResult(final Boolean isValid, final Long totalFees, final List<Sha256Hash> invalidTransactions) { this.isValid = isValid; this.totalFees = totalFees; this.invalidTransactions = ConstUtil.asConstOrNull(invalidTransactions); } } protected final UnspentTransactionOutputContext _unspentTransactionOutputSet; protected final BlockOutputs _blockOutputs; protected final SpentOutputsTracker _spentOutputsTracker; protected final MutableList<Transaction> _invalidTransactions = new MutableList<Transaction>(0); protected TransactionOutput _getUnspentTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { { // Ensure the output hasn't been spent already by this block... final Boolean wasAlreadySpent = _spentOutputsTracker.markOutputAsSpent(transactionOutputIdentifier); if (wasAlreadySpent) { Logger.debug("Output already spent within Block: " + transactionOutputIdentifier); return null; } } final UnspentTransactionOutputContext unspentTransactionOutputSet = _unspentTransactionOutputSet; if (unspentTransactionOutputSet != null) { final TransactionOutput transactionOutput = unspentTransactionOutputSet.getTransactionOutput(transactionOutputIdentifier); if (transactionOutput != null) { return transactionOutput; } } final BlockOutputs blockOutputs = _blockOutputs; if (blockOutputs != null) { final TransactionOutput transactionOutput = blockOutputs.getTransactionOutput(transactionOutputIdentifier); if (transactionOutput != null) { return transactionOutput; } } return null; } protected Long _calculateTotalTransactionInputs(final Transaction transaction) { long totalInputValue = 0L; final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); for (int i = 0; i < transactionInputs.getCount(); ++i) { final TransactionInput transactionInput = transactionInputs.get(i); final TransactionOutputIdentifier transactionOutputIdentifier = TransactionOutputIdentifier.fromTransactionInput(transactionInput); final TransactionOutput transactionOutput = _getUnspentTransactionOutput(transactionOutputIdentifier); if (transactionOutput == null) { Logger.debug("Tx Input, Output Not Found: " + transactionOutputIdentifier); return -1L; } totalInputValue += transactionOutput.getAmount(); } return totalInputValue; } protected Long _totalFees = 0L; public TotalExpenditureTaskHandler(final UnspentTransactionOutputContext unspentTransactionOutputSet, final BlockOutputs blockOutputs, final SpentOutputsTracker spentOutputsTracker) { _unspentTransactionOutputSet = unspentTransactionOutputSet; _blockOutputs = blockOutputs; _spentOutputsTracker = spentOutputsTracker; } @Override public void init() { } @Override public void executeTask(final Transaction transaction) { if (! _invalidTransactions.isEmpty()) { return; } final Long totalOutputValue = transaction.getTotalOutputValue(); final Long totalInputValue = _calculateTotalTransactionInputs(transaction); final boolean transactionExpenditureIsValid = (totalOutputValue <= totalInputValue); if (! transactionExpenditureIsValid) { _invalidTransactions.add(transaction); return; } _totalFees += (totalInputValue - totalOutputValue); } @Override public ExpenditureResult getResult() { if (! _invalidTransactions.isEmpty()) { return ExpenditureResult.invalid(_invalidTransactions); } return ExpenditureResult.valid(_totalFees); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/rpc/handler/ShutdownHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.rpc.handler; import com.softwareverde.bitcoin.server.State; import com.softwareverde.bitcoin.server.module.node.handler.SynchronizationStatusHandler; import com.softwareverde.bitcoin.server.module.node.rpc.NodeRpcHandler; public class ShutdownHandler implements NodeRpcHandler.ShutdownHandler { protected final Thread _mainThread; protected final SynchronizationStatusHandler _synchronizationStatusHandler; public ShutdownHandler(final Thread mainThread, final SynchronizationStatusHandler synchronizationStatusHandler) { _mainThread = mainThread; _synchronizationStatusHandler = synchronizationStatusHandler; } @Override public Boolean shutdown() { _synchronizationStatusHandler.setState(State.SHUTTING_DOWN); _mainThread.interrupt(); return true; } } <|start_filename|>src/main/java/com/softwareverde/network/p2p/message/type/AcknowledgeVersionMessage.java<|end_filename|> package com.softwareverde.network.p2p.message.type; import com.softwareverde.network.p2p.message.ProtocolMessage; public interface AcknowledgeVersionMessage extends ProtocolMessage { } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/mint/MutableSlpMintScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp.mint; import com.softwareverde.bitcoin.slp.SlpTokenId; public class MutableSlpMintScript extends SlpMintScriptCore { public MutableSlpMintScript() { } public MutableSlpMintScript(final SlpMintScript slpMintScript) { super(slpMintScript); } public void setTokenId(final SlpTokenId tokenId) { _tokenId = tokenId; } public void setBatonOutputIndex(final Integer batonOutputIndex) { _batonOutputIndex = batonOutputIndex; } public void setTokenCount(final Long tokenCount) { _tokenCount = tokenCount; } @Override public ImmutableSlpMintScript asConst() { return new ImmutableSlpMintScript(this); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/message/type/query/response/hash/InventoryItemTests.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response.hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import org.junit.Assert; import org.junit.Test; public class InventoryItemTests { @Test public void identical_inventory_items_should_be_equal() { final InventoryItem item0 = new InventoryItem(InventoryItemType.BLOCK, Sha256Hash.fromHexString("000000000000000001EA1109A7F613BC23C4FD83C504FE8110B892551ACF3761")); final InventoryItem item1 = new InventoryItem(InventoryItemType.BLOCK, Sha256Hash.fromHexString("000000000000000001EA1109A7F613BC23C4FD83C504FE8110B892551ACF3761")); Assert.assertEquals(item0, item1); Assert.assertEquals(item0.hashCode(), item1.hashCode()); } @Test public void inventory_items_of_different_type_should_not_be_equal() { final InventoryItem item0 = new InventoryItem(InventoryItemType.MERKLE_BLOCK, Sha256Hash.fromHexString("000000000000000001EA1109A7F613BC23C4FD83C504FE8110B892551ACF3761")); final InventoryItem item1 = new InventoryItem(InventoryItemType.BLOCK, Sha256Hash.fromHexString("000000000000000001EA1109A7F613BC23C4FD83C504FE8110B892551ACF3761")); Assert.assertNotEquals(item0, item1); Assert.assertNotEquals(item0.hashCode(), item1.hashCode()); // Technically possible to have a collision, but unlikely... } @Test public void inventory_items_of_value_should_not_be_equal() { final InventoryItem item0 = new InventoryItem(InventoryItemType.TRANSACTION, Sha256Hash.fromHexString("000000000000000001EA1109A7F613BC23C4FD83C504FE8110B892551ACF3761")); final InventoryItem item1 = new InventoryItem(InventoryItemType.TRANSACTION, Sha256Hash.fromHexString("0000000000000000000000000000000000000000000000000000000000000000")); Assert.assertNotEquals(item0, item1); Assert.assertNotEquals(item0.hashCode(), item1.hashCode()); // Technically possible to have a collision, but unlikely... } } <|start_filename|>src/main/java/com/softwareverde/constable/list/immutable/ImmutableArrayListBuilder.java<|end_filename|> package com.softwareverde.constable.list.immutable; import com.softwareverde.constable.list.List; public class ImmutableArrayListBuilder<T> { protected final Integer _objectCount; private T[] _objectArray; private int _index = 0; @SuppressWarnings("unchecked") protected void _initObjectArray() { if (_objectArray != null) { return; } _objectArray = (T[]) (new Object[_objectCount]); _index = 0; } public ImmutableArrayListBuilder(final int exactSize) { _objectCount = exactSize; _initObjectArray(); } public void add(final T item) { _initObjectArray(); if (_index >= _objectArray.length) { return; } _objectArray[_index] = item; _index += 1; } public int getCount() { return _index; } public void addAll(final java.util.Collection<T> collection) { _initObjectArray(); for (final T item : collection) { if (_index >= _objectArray.length) { return; } _objectArray[_index] = item; _index += 1; } } public void addAll(final List<T> collection) { _initObjectArray(); for (final T item : collection) { if (_index >= _objectArray.length) { return; } _objectArray[_index] = item; _index += 1; } } public ImmutableArrayList<T> build() { final ImmutableArrayList<T> immutableList = ImmutableArrayList.wrap(_objectArray); _objectArray = null; _index = 0; return immutableList; } } <|start_filename|>src/main/java/com/softwareverde/concurrent/pool/SimpleThreadPool.java<|end_filename|> package com.softwareverde.concurrent.pool; import com.softwareverde.logging.Logger; import java.util.concurrent.LinkedBlockingQueue; public class SimpleThreadPool implements ThreadPool { protected final LinkedBlockingQueue<Runnable> _blockingQueue = new LinkedBlockingQueue<Runnable>(); protected final Thread _thread = new Thread(new Runnable() { @Override public void run() { final Thread currentThread = Thread.currentThread(); try { while (! currentThread.isInterrupted()) { final Runnable runnable = _blockingQueue.take(); try { runnable.run(); } catch (final Exception exception) { Logger.debug(exception); } } } catch (final InterruptedException exception) { // Exit. } } }); @Override public void execute(final Runnable runnable) { _blockingQueue.offer(runnable); } public void start() { _thread.start(); } public void stop() { _thread.interrupt(); try { _thread.join(); } catch (InterruptedException exception) { // Nothing. } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/inflater/BloomFilterInflaters.java<|end_filename|> package com.softwareverde.bitcoin.inflater; import com.softwareverde.bitcoin.bloomfilter.BloomFilterDeflater; import com.softwareverde.bitcoin.bloomfilter.BloomFilterInflater; public interface BloomFilterInflaters extends Inflater { BloomFilterInflater getBloomFilterInflater(); BloomFilterDeflater getBloomFilterDeflater(); } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeBitcoinNode.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.node.feature.LocalNodeFeatures; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.network.p2p.message.ProtocolMessage; import com.softwareverde.network.socket.BinarySocket; public class FakeBitcoinNode extends BitcoinNode { protected final MutableList<ProtocolMessage> _outboundMessageQueue = new MutableList<ProtocolMessage>(); @Override protected void _initConnection() { // Nothing. } public FakeBitcoinNode(final String host, final Integer port, final ThreadPool threadPool, final LocalNodeFeatures localNodeFeatures) { super(host, port, threadPool, localNodeFeatures); } public FakeBitcoinNode(final BinarySocket binarySocket, final ThreadPool threadPool, final LocalNodeFeatures localNodeFeatures) { super(binarySocket, threadPool, localNodeFeatures); } @Override public void connect() { // Nothing. } @Override public void disconnect() { // Nothing. } @Override public void queueMessage(final BitcoinProtocolMessage protocolMessage) { _outboundMessageQueue.add(protocolMessage); } public List<ProtocolMessage> getSentMessages() { try { Thread.sleep(500L); } catch (final Exception exception) { } // Required to wait for messageQueue... return _outboundMessageQueue; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/stack/Value.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.stack; import com.softwareverde.bitcoin.transaction.locktime.ImmutableLockTime; import com.softwareverde.bitcoin.transaction.locktime.ImmutableSequenceNumber; import com.softwareverde.bitcoin.transaction.locktime.LockTime; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; import com.softwareverde.bitcoin.transaction.script.signature.ScriptSignature; import com.softwareverde.bitcoin.transaction.script.signature.ScriptSignatureContext; import com.softwareverde.bitcoin.util.BitcoinUtil; import com.softwareverde.constable.Const; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.ImmutableByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.secp256k1.key.PublicKey; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.StringUtil; public class Value extends ImmutableByteArray implements Const { public static Integer MAX_BYTE_COUNT = 520; // https://en.bitcoin.it/wiki/Script#Arithmetic public static final Value ZERO = Value.fromInteger(0L); /** * Returns a new copy of littleEndianBytes as if it were a minimally encoded integer (despite being too long for a normal integer). * This function should be identical to Value::_longToBytes for byteArrays of 4 bytes or less... */ public static Value minimallyEncodeBytes(final ByteArray littleEndianBytes) { if (littleEndianBytes.getByteCount() > MAX_BYTE_COUNT) { return null; } if (littleEndianBytes.isEmpty()) { return ZERO; } final ByteArray bytes = MutableByteArray.wrap(ByteUtil.reverseEndian(littleEndianBytes.getBytes())); // If the first byte is not 0x00 or 0x80, then bytes is minimally encoded... final byte signByte = bytes.getByte(0); if ( (signByte != 0x00) && (signByte != (byte) 0x80) ) { return Value.fromBytes(littleEndianBytes); } // If bytes is one exactly byte, then the value is zero, which is encoded as an empty array... if (bytes.getByteCount() == 1) { return ZERO; } // If the next byte has its sign bit set, then it is minimally encoded... final byte secondByte = bytes.getByte(1); if ( (secondByte & 0x80) != 0x00 ) { return Value.fromBytes(littleEndianBytes); } // Otherwise, bytes was not minimally encoded... for (int i = 1; i < bytes.getByteCount(); ++i) { final byte b = bytes.getByte(i); // Start encoding after the first non-zero byte... if (b != 0x00) { final int copiedByteCount = (bytes.getByteCount() - i); final ByteArray copiedBytes = MutableByteArray.wrap(bytes.getBytes(i, copiedByteCount)); final MutableByteArray byteArray; final boolean signBitIsSet = ( (b & 0x80) != 0x00 ); if (signBitIsSet) { // The sign-bit is set, so the returned value must have an extra byte... byteArray = new MutableByteArray( copiedByteCount + 1); ByteUtil.setBytes(byteArray, copiedBytes, 1); byteArray.setByte(0, signByte); } else { // The sign bit isn't set, so the returned value can just set the signed bit... byteArray = new MutableByteArray(copiedBytes); byteArray.setByte(0, (byte) (byteArray.getByte(0) | signByte)); } return Value.fromBytes(ByteUtil.reverseEndian(byteArray.unwrap())); } } // All of the values within bytes were zero... return ZERO; } // NOTE: Bitcoin uses "MPI" encoding for its numeric values on the stack. // This fact and/or a specification for how MPI is encoded is not on the wiki (...of course). // It appears MPI is a minimum-byte-encoding, with a sign bit if negative, similar(ish) to DER encoding. // As an exception, Zero is encoded as zero bytes... Not sure why. // Ex: -65280 // MPI: 0x80FF00 // Signed Hex: -0xFF00 // 2's Complement: 0xFFFFFFFFFFFF0100 // The returned byte array is little-endian. protected static byte[] _longToBytes(final Long value) { if (value == 0L) { return new byte[0]; } final boolean isNegative = (value < 0); final long absValue = Math.abs(value); final int unsignedByteCount = ( (BitcoinUtil.log2((int) absValue) / 8) + 1 ); final byte[] absValueBytes = ByteUtil.integerToBytes(absValue); final boolean requiresSignPadding = ((absValueBytes[absValueBytes.length - unsignedByteCount] & 0x80) == 0x80); final byte[] bytes = new byte[(requiresSignPadding ? unsignedByteCount + 1 : unsignedByteCount)]; ByteUtil.setBytes(bytes, ByteUtil.reverseEndian(absValueBytes)); if (isNegative) { bytes[bytes.length - 1] |= (byte) 0x80; } return bytes; } public static Value fromInteger(final Long longValue) { final byte[] bytes = _longToBytes(longValue); return new Value(bytes); } public static Value fromBoolean(final Boolean booleanValue) { final byte[] bytes = _longToBytes(booleanValue ? 1L : 0L); return new Value(bytes); } public static Value fromBytes(final byte[] bytes) { if (bytes.length > MAX_BYTE_COUNT) { return null; } return new Value(bytes); } public static Value fromBytes(final ByteArray bytes) { if (bytes.getByteCount() > MAX_BYTE_COUNT) { return null; } return new Value(bytes.getBytes()); } protected static boolean _isNegativeNumber(final byte[] bytes) { final byte mostSignificantByte = bytes[0]; return ( (mostSignificantByte & ((byte) 0x80)) != ((byte) 0x00) ); } protected Integer _asInteger() { if (_bytes.length == 0) { return 0; } final byte[] bigEndianBytes = ByteUtil.reverseEndian(_bytes); final boolean isNegative = _isNegativeNumber(bigEndianBytes); { // Remove the sign bit... (only matters when _bytes.length is less than the byteCount of an integer) bigEndianBytes[0] &= (byte) 0x7F; } final Integer value = ByteUtil.bytesToInteger(bigEndianBytes); return (isNegative ? -value : value); } protected Long _asLong() { if (_bytes.length == 0) { return 0L; } final byte[] bigEndianBytes = ByteUtil.reverseEndian(_bytes); final boolean isNegative = _isNegativeNumber(bigEndianBytes); { // Remove the sign bit... (only matters when _bytes.length is less than the byteCount of a long) bigEndianBytes[0] &= (byte) 0x7F; } final Long value = ByteUtil.bytesToLong(bigEndianBytes); return (isNegative ? -value : value); } protected Boolean _asBoolean() { if (_bytes.length == 0) { return false; } for (int i = 0; i < _bytes.length; ++i) { if ( (i == (_bytes.length - 1)) && (_bytes[i] == (byte) 0x80) ) { continue; } // Negative zero can still be false... (Little-Endian) if (_bytes[i] != 0x00) { return true; } } return false; } protected Value(final byte[] bytes) { super(bytes); } /** * Interprets _bytes as a signed, little-endian, variable-length integer value. * If _bytes is empty, zero is returned. */ public Integer asInteger() { return _asInteger(); } public Long asLong() { return _asLong(); } public Boolean asBoolean() { return _asBoolean(); } public Boolean isMinimallyEncodedInteger() { final Integer asInteger = _asInteger(); final byte[] minimallyEncodedBytes = _longToBytes(asInteger.longValue()); return ByteUtil.areEqual(minimallyEncodedBytes, _bytes); } public Boolean isMinimallyEncodedLong() { final Long asLong = _asLong(); final byte[] minimallyEncodedBytes = _longToBytes(asLong); return ByteUtil.areEqual(minimallyEncodedBytes, _bytes); } public LockTime asLockTime() { return new ImmutableLockTime(ByteUtil.bytesToLong(ByteUtil.reverseEndian(_bytes))); } public SequenceNumber asSequenceNumber() { return new ImmutableSequenceNumber(ByteUtil.bytesToLong(ByteUtil.reverseEndian(_bytes))); } public ScriptSignature asScriptSignature(final ScriptSignatureContext scriptSignatureContext) { return ScriptSignature.fromBytes(this, scriptSignatureContext); } public PublicKey asPublicKey() { return PublicKey.fromBytes(this); } public String asString() { return StringUtil.bytesToString(_bytes); // UTF-8 } @Override public Value asConst() { return this; } } <|start_filename|>src/main/java/com/softwareverde/constable/list/ImmutableJavaUtilListIterator.java<|end_filename|> package com.softwareverde.constable.list; import java.util.Iterator; class ImmutableJavaUtilListIterator<T> implements Iterator<T> { private final Iterator<T> _iterator; public ImmutableJavaUtilListIterator(final Iterable<T> items) { _iterator = items.iterator(); } @Override public boolean hasNext() { return _iterator.hasNext(); } @Override public T next() { return _iterator.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/fullnode/utxo/jvm/UtxoValue.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.jvm; public class UtxoValue { public final int spentStateCode; public final long blockHeight; public UtxoValue(final JvmSpentState jvmSpentState, final long blockHeight) { this.spentStateCode = jvmSpentState.intValue(); this.blockHeight = blockHeight; } public UtxoValue(final int spentStateCode, final long blockHeight) { this.spentStateCode = spentStateCode; this.blockHeight = blockHeight; } public JvmSpentState getSpentState() { return new JvmSpentState(this.spentStateCode); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/MultiConnectionFullDatabaseContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; public interface MultiConnectionFullDatabaseContext extends MultiConnectionDatabaseContext { @Override FullNodeDatabaseManagerFactory getDatabaseManagerFactory(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/response/InventoryMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItem; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItemType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.bytearray.Endian; public class InventoryMessageInflater extends BitcoinProtocolMessageInflater { public static final Integer HASH_BYTE_COUNT = 32; @Override public InventoryMessage fromBytes(final byte[] bytes) { final InventoryMessage inventoryMessage = new InventoryMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.INVENTORY); if (protocolMessageHeader == null) { return null; } final Long inventoryCount = byteArrayReader.readVariableSizedInteger(); for (int i = 0; i < inventoryCount; ++i) { final Integer inventoryTypeCode = byteArrayReader.readInteger(4, Endian.LITTLE); final Sha256Hash objectHash = MutableSha256Hash.wrap(byteArrayReader.readBytes(HASH_BYTE_COUNT, Endian.LITTLE)); final InventoryItemType dataType = InventoryItemType.fromValue(inventoryTypeCode); final InventoryItem inventoryItem = new InventoryItem(dataType, objectHash); inventoryMessage.addInventoryItem(inventoryItem); } if (byteArrayReader.didOverflow()) { return null; } return inventoryMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/sync/transaction/TransactionProcessor.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync.transaction; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.context.MedianBlockTimeContext; import com.softwareverde.bitcoin.context.MultiConnectionFullDatabaseContext; import com.softwareverde.bitcoin.context.NetworkTimeContext; import com.softwareverde.bitcoin.context.SystemTimeContext; import com.softwareverde.bitcoin.context.TransactionValidatorFactory; import com.softwareverde.bitcoin.context.UnspentTransactionOutputContext; import com.softwareverde.bitcoin.context.core.TransactionValidatorContext; import com.softwareverde.bitcoin.context.lazy.LazyMedianBlockTimeContext; import com.softwareverde.bitcoin.context.lazy.LazyUnconfirmedTransactionUtxoSet; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.indexer.BlockchainIndexerDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.FullNodeTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.pending.PendingTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.sync.transaction.pending.PendingTransactionId; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.validator.TransactionValidationResult; import com.softwareverde.bitcoin.transaction.validator.TransactionValidator; import com.softwareverde.concurrent.service.SleepyService; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.util.TransactionUtil; import com.softwareverde.logging.Logger; import com.softwareverde.network.time.VolatileNetworkTime; import com.softwareverde.util.timer.MilliTimer; import com.softwareverde.util.type.time.SystemTime; import java.util.HashMap; public class TransactionProcessor extends SleepyService { public interface Context extends TransactionInflaters, MultiConnectionFullDatabaseContext, TransactionValidatorFactory, NetworkTimeContext, SystemTimeContext { } public interface Callback { void onNewTransactions(List<Transaction> transactions); } protected static final Long MIN_MILLISECONDS_BEFORE_ORPHAN_PURGE = 5000L; protected final Context _context; protected Long _lastOrphanPurgeTime; protected Callback _newTransactionProcessedCallback; protected void _deletePendingTransaction(final FullNodeDatabaseManager databaseManager, final PendingTransactionId pendingTransactionId) { final DatabaseConnection databaseConnection = databaseManager.getDatabaseConnection(); final PendingTransactionDatabaseManager pendingTransactionDatabaseManager = databaseManager.getPendingTransactionDatabaseManager(); try { TransactionUtil.startTransaction(databaseConnection); pendingTransactionDatabaseManager.deletePendingTransaction(pendingTransactionId); TransactionUtil.commitTransaction(databaseConnection); } catch (final DatabaseException exception) { Logger.warn(exception); } } @Override protected void _onStart() { } @Override public Boolean _run() { final FullNodeDatabaseManagerFactory databaseManagerFactory = _context.getDatabaseManagerFactory(); final VolatileNetworkTime networkTime = _context.getNetworkTime(); final SystemTime systemTime = _context.getSystemTime(); final Thread thread = Thread.currentThread(); try (final FullNodeDatabaseManager databaseManager = databaseManagerFactory.newDatabaseManager()) { final DatabaseConnection databaseConnection = databaseManager.getDatabaseConnection(); final PendingTransactionDatabaseManager pendingTransactionDatabaseManager = databaseManager.getPendingTransactionDatabaseManager(); final FullNodeTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockchainIndexerDatabaseManager blockchainIndexerDatabaseManager = databaseManager.getBlockchainIndexerDatabaseManager(); final TransactionInflaters transactionInflaters = _context; final UnspentTransactionOutputContext unconfirmedTransactionUtxoSet = new LazyUnconfirmedTransactionUtxoSet(databaseManager, true); final MedianBlockTimeContext medianBlockTimeContext = new LazyMedianBlockTimeContext(databaseManager); final TransactionValidatorContext transactionValidatorContext = new TransactionValidatorContext(transactionInflaters, networkTime, medianBlockTimeContext, unconfirmedTransactionUtxoSet); final TransactionValidator transactionValidator = _context.getUnconfirmedTransactionValidator(transactionValidatorContext); final Long now = systemTime.getCurrentTimeInMilliSeconds(); if ((now - _lastOrphanPurgeTime) > MIN_MILLISECONDS_BEFORE_ORPHAN_PURGE) { final MilliTimer purgeOrphanedTransactionsTimer = new MilliTimer(); purgeOrphanedTransactionsTimer.start(); pendingTransactionDatabaseManager.purgeExpiredOrphanedTransactions(); purgeOrphanedTransactionsTimer.stop(); Logger.info("Purge Orphaned Transactions: " + purgeOrphanedTransactionsTimer.getMillisecondsElapsed() + "ms"); _lastOrphanPurgeTime = systemTime.getCurrentTimeInMilliSeconds(); } while (! thread.isInterrupted()) { final List<PendingTransactionId> pendingTransactionIds = pendingTransactionDatabaseManager.selectCandidatePendingTransactionIds(); if (pendingTransactionIds.isEmpty()) { return false; } final HashMap<Sha256Hash, PendingTransactionId> pendingTransactionIdMap = new HashMap<Sha256Hash, PendingTransactionId>(pendingTransactionIds.getCount()); final List<Transaction> transactionsToStore; { final ImmutableListBuilder<Transaction> listBuilder = new ImmutableListBuilder<Transaction>(pendingTransactionIds.getCount()); for (final PendingTransactionId pendingTransactionId : pendingTransactionIds) { if (thread.isInterrupted()) { return false; } final Transaction transaction = pendingTransactionDatabaseManager.getPendingTransaction(pendingTransactionId); if (transaction == null) { continue; } final Boolean transactionCanBeStored = transactionDatabaseManager.previousOutputsExist(transaction); if (! transactionCanBeStored) { pendingTransactionDatabaseManager.updateTransactionDependencies(transaction); continue; } pendingTransactionIdMap.put(transaction.getHash(), pendingTransactionId); listBuilder.add(transaction); } transactionsToStore = listBuilder.build(); } final BlockId blockId = blockHeaderDatabaseManager.getHeadBlockHeaderId(); final BlockchainSegmentId blockchainSegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(blockId); final Long headBlockHeight = blockHeaderDatabaseManager.getBlockHeight(blockId); final MutableList<Transaction> validTransactions = new MutableList<Transaction>(transactionsToStore.getCount()); final MutableList<TransactionId> validTransactionIds = new MutableList<TransactionId>(transactionsToStore.getCount()); int invalidTransactionCount = 0; final MilliTimer storeTransactionsTimer = new MilliTimer(); storeTransactionsTimer.start(); for (final Transaction transaction : transactionsToStore) { if (thread.isInterrupted()) { break; } final Sha256Hash transactionHash = transaction.getHash(); final PendingTransactionId pendingTransactionId = pendingTransactionIdMap.get(transactionHash); if (pendingTransactionId == null) { continue; } // NOTE: The transaction cannot be stored before it is validated, otherwise the LazyUtxoSet will believe the output has already been spent (by itself). final TransactionValidationResult transactionValidationResult = transactionValidator.validateTransaction((headBlockHeight + 1L), transaction); if (! transactionValidationResult.isValid) { _deletePendingTransaction(databaseManager, pendingTransactionId); invalidTransactionCount += 1; Logger.info("Invalid MemoryPool Transaction: " + transactionHash); Logger.info(transactionValidationResult.errorMessage); continue; } TransactionUtil.startTransaction(databaseConnection); final TransactionId transactionId = transactionDatabaseManager.storeUnconfirmedTransaction(transaction); final boolean isUnconfirmedTransaction = (transactionDatabaseManager.getBlockId(blockchainSegmentId, transactionId) == null); // TODO: This check is likely redundant... if (isUnconfirmedTransaction) { transactionDatabaseManager.addToUnconfirmedTransactions(transactionId); } TransactionUtil.commitTransaction(databaseConnection); _deletePendingTransaction(databaseManager, pendingTransactionId); validTransactions.add(transaction); validTransactionIds.add(transactionId); } storeTransactionsTimer.stop(); blockchainIndexerDatabaseManager.queueTransactionsForProcessing(validTransactionIds); Logger.info("Committed " + (transactionsToStore.getCount() - invalidTransactionCount) + " transactions to the MemoryPool in " + storeTransactionsTimer.getMillisecondsElapsed() + "ms. (" + String.format("%.2f", (transactionsToStore.getCount() / storeTransactionsTimer.getMillisecondsElapsed().floatValue() * 1000F)) + "tps) (" + invalidTransactionCount + " invalid)"); final Callback newTransactionProcessedCallback = _newTransactionProcessedCallback; if (newTransactionProcessedCallback != null) { newTransactionProcessedCallback.onNewTransactions(validTransactions); } } } catch (final DatabaseException exception) { Logger.warn(exception); } return false; } @Override protected void _onSleep() { } public TransactionProcessor(final Context context) { _context = context; _lastOrphanPurgeTime = 0L; } public void setNewTransactionProcessedCallback(final Callback newTransactionProcessedCallback) { _newTransactionProcessedCallback = newTransactionProcessedCallback; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/input/MutableTransactionInput.java<|end_filename|> package com.softwareverde.bitcoin.transaction.input; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.json.Json; import com.softwareverde.util.Util; public class MutableTransactionInput implements TransactionInput { protected Sha256Hash _previousOutputTransactionHash = Sha256Hash.EMPTY_HASH; protected Integer _previousOutputIndex = 0; protected UnlockingScript _unlockingScript = UnlockingScript.EMPTY_SCRIPT; protected SequenceNumber _sequenceNumber = SequenceNumber.MAX_SEQUENCE_NUMBER; protected Integer _cachedHashCode = null; public MutableTransactionInput() { } public MutableTransactionInput(final TransactionInput transactionInput) { _previousOutputTransactionHash = transactionInput.getPreviousOutputTransactionHash().asConst(); _previousOutputIndex = transactionInput.getPreviousOutputIndex(); _unlockingScript = transactionInput.getUnlockingScript().asConst(); _sequenceNumber = transactionInput.getSequenceNumber(); } @Override public Sha256Hash getPreviousOutputTransactionHash() { return _previousOutputTransactionHash; } public void setPreviousOutputTransactionHash(final Sha256Hash previousOutputTransactionHash) { _previousOutputTransactionHash = previousOutputTransactionHash.asConst(); _cachedHashCode = null; } @Override public Integer getPreviousOutputIndex() { return _previousOutputIndex; } public void setPreviousOutputIndex(final Integer index) { _previousOutputIndex = index; _cachedHashCode = null; } @Override public UnlockingScript getUnlockingScript() { return _unlockingScript; } public void setUnlockingScript(final UnlockingScript signatureScript) { _unlockingScript = signatureScript.asConst(); _cachedHashCode = null; } @Override public SequenceNumber getSequenceNumber() { return _sequenceNumber; } public void setSequenceNumber(final SequenceNumber sequenceNumber) { _sequenceNumber = sequenceNumber.asConst(); _cachedHashCode = null; } @Override public ImmutableTransactionInput asConst() { return new ImmutableTransactionInput(this); } @Override public Json toJson() { final TransactionInputDeflater transactionInputDeflater = new TransactionInputDeflater(); return transactionInputDeflater.toJson(this); } @Override public int hashCode() { final Integer cachedHashCode = _cachedHashCode; if (cachedHashCode != null) { return cachedHashCode; } final TransactionInputDeflater transactionInputDeflater = new TransactionInputDeflater(); final Integer hashCode = transactionInputDeflater.toBytes(this).hashCode(); _cachedHashCode = hashCode; return hashCode; } @Override public boolean equals(final Object object) { if (! (object instanceof TransactionInput)) { return false; } final TransactionInput transactionInput = (TransactionInput) object; if (! Util.areEqual(_previousOutputTransactionHash, transactionInput.getPreviousOutputTransactionHash())) { return false; } if (! Util.areEqual(_previousOutputIndex, transactionInput.getPreviousOutputIndex())) { return false; } if (! Util.areEqual(_sequenceNumber, transactionInput.getSequenceNumber())) { return false; } if (! Util.areEqual(_unlockingScript, transactionInput.getUnlockingScript())) { return false; } return true; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/PendingBlockStoreContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.server.module.node.store.PendingBlockStore; public interface PendingBlockStoreContext { PendingBlockStore getPendingBlockStore(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/SynchronizationStatusContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.server.SynchronizationStatus; public interface SynchronizationStatusContext { SynchronizationStatus getSynchronizationStatus(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/sync/BlockchainIndexer.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.context.AtomicTransactionOutputIndexerContext; import com.softwareverde.bitcoin.context.ContextException; import com.softwareverde.bitcoin.context.TransactionOutputIndexerContext; import com.softwareverde.bitcoin.server.database.BatchRunner; import com.softwareverde.bitcoin.server.module.node.database.indexer.TransactionOutputId; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.script.ScriptPatternMatcher; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.slp.SlpScript; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptInflater; import com.softwareverde.bitcoin.transaction.script.slp.commit.SlpCommitScript; import com.softwareverde.bitcoin.transaction.script.slp.genesis.SlpGenesisScript; import com.softwareverde.bitcoin.transaction.script.slp.mint.SlpMintScript; import com.softwareverde.bitcoin.transaction.script.slp.send.SlpSendScript; import com.softwareverde.concurrent.service.SleepyService; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import com.softwareverde.util.Util; import com.softwareverde.util.timer.NanoTimer; import java.util.HashMap; import java.util.Map; public class BlockchainIndexer extends SleepyService { public static final Integer BATCH_SIZE = 1024; protected static class OutputIndexData { TransactionId transactionId; Integer outputIndex; Long amount; ScriptType scriptType; Address address; TransactionId slpTransactionId; } protected static class InputIndexData { TransactionId transactionId; Integer inputIndex; TransactionOutputId transactionOutputId; } protected final Integer _threadCount; protected final TransactionOutputIndexerContext _context; protected final ScriptPatternMatcher _scriptPatternMatcher = new ScriptPatternMatcher(); protected final SlpScriptInflater _slpScriptInflater = new SlpScriptInflater(); protected Runnable _onSleepCallback; protected TransactionId _getSlpTokenTransactionId(final TransactionId transactionId, final SlpScript slpScript) throws ContextException { final SlpTokenId slpTokenId; switch (slpScript.getType()) { case GENESIS: { return transactionId; } case SEND: { final SlpSendScript slpSendScript = (SlpSendScript) slpScript; slpTokenId = slpSendScript.getTokenId(); } break; case MINT: { final SlpMintScript slpMintScript = (SlpMintScript) slpScript; slpTokenId = slpMintScript.getTokenId(); } break; case COMMIT: { final SlpCommitScript slpCommitScript = (SlpCommitScript) slpScript; slpTokenId = slpCommitScript.getTokenId(); } break; default: { slpTokenId = null; } break; } if (slpTokenId == null) { return null; } try (final AtomicTransactionOutputIndexerContext context = _context.newTransactionOutputIndexerContext()) { return context.getTransactionId(slpTokenId); } } protected List<InputIndexData> _indexTransactionInputs(final AtomicTransactionOutputIndexerContext context, final TransactionId transactionId, final Transaction transaction) throws ContextException { final MutableList<InputIndexData> inputIndexDataList = new MutableList<InputIndexData>(); final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); final int transactionInputCount = transactionInputs.getCount(); for (int inputIndex = 0; inputIndex < transactionInputCount; ++inputIndex) { final TransactionInput transactionInput = transactionInputs.get(inputIndex); final Integer previousTransactionOutputIndex = transactionInput.getPreviousOutputIndex(); final Sha256Hash previousTransactionHash = transactionInput.getPreviousOutputTransactionHash(); { // Avoid indexing Coinbase Inputs... final TransactionOutputIdentifier previousTransactionOutputIdentifier = TransactionOutputIdentifier.fromTransactionInput(transactionInput); if (Util.areEqual(TransactionOutputIdentifier.COINBASE, previousTransactionOutputIdentifier)) { continue; } } final TransactionId previousTransactionId = context.getTransactionId(previousTransactionHash); final Transaction previousTransaction = context.getTransaction(previousTransactionId); if (previousTransaction == null) { Logger.debug("Cannot index input; Transaction does not exist: " + previousTransactionHash); continue; } final TransactionOutputId transactionOutputId = new TransactionOutputId(previousTransactionId, previousTransactionOutputIndex); final InputIndexData inputIndexData = new InputIndexData(); inputIndexData.transactionId = transactionId; inputIndexData.inputIndex = inputIndex; inputIndexData.transactionOutputId = transactionOutputId; inputIndexDataList.add(inputIndexData); } return inputIndexDataList; } protected Map<TransactionOutputIdentifier, OutputIndexData> _indexTransactionOutputs(final AtomicTransactionOutputIndexerContext context, final TransactionId transactionId, final Transaction transaction) throws ContextException { final HashMap<TransactionOutputIdentifier, OutputIndexData> outputIndexData = new HashMap<TransactionOutputIdentifier, OutputIndexData>(); final Sha256Hash transactionHash = transaction.getHash(); final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final int transactionOutputCount = transactionOutputs.getCount(); final LockingScript slpLockingScript; { final TransactionOutput transactionOutput = transactionOutputs.get(0); slpLockingScript = transactionOutput.getLockingScript(); } for (int outputIndex = 0; outputIndex < transactionOutputCount; ++outputIndex) { final TransactionOutput transactionOutput = transactionOutputs.get(outputIndex); final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, outputIndex); if (! outputIndexData.containsKey(transactionOutputIdentifier)) { final Address address; { final LockingScript lockingScript = transactionOutput.getLockingScript(); final ScriptType scriptType = _scriptPatternMatcher.getScriptType(lockingScript); address = _scriptPatternMatcher.extractAddress(scriptType, lockingScript); } final OutputIndexData indexData = new OutputIndexData(); indexData.transactionId = transactionId; indexData.outputIndex = outputIndex; indexData.amount = transactionOutput.getAmount(); indexData.scriptType = ScriptType.UNKNOWN; indexData.address = address; indexData.slpTransactionId = null; outputIndexData.put(transactionOutputIdentifier, indexData); } } final ScriptType scriptType = _scriptPatternMatcher.getScriptType(slpLockingScript); if (! ScriptType.isSlpScriptType(scriptType)) { return outputIndexData; } boolean slpTransactionIsValid; { // Validate SLP Transaction... // NOTE: Inflating the whole transaction is mildly costly, but typically this only happens once per SLP transaction, which is required anyway. final SlpScript slpScript = _slpScriptInflater.fromLockingScript(slpLockingScript); slpTransactionIsValid = ( (slpScript != null) && (transactionOutputCount >= slpScript.getMinimumTransactionOutputCount()) ); if (slpTransactionIsValid) { ScriptType outputScriptType = ScriptType.CUSTOM_SCRIPT; final TransactionId slpTokenTransactionId = _getSlpTokenTransactionId(transactionId, slpScript); switch (slpScript.getType()) { case GENESIS: { final SlpGenesisScript slpGenesisScript = (SlpGenesisScript) slpScript; final Integer generatorOutputIndex = slpGenesisScript.getBatonOutputIndex(); if ( (generatorOutputIndex != null) && (generatorOutputIndex >= transactionOutputCount)) { slpTransactionIsValid = false; } else { outputScriptType = ScriptType.SLP_GENESIS_SCRIPT; { // Mark the Receiving Output as an SLP Output... final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, SlpGenesisScript.RECEIVER_TRANSACTION_OUTPUT_INDEX); final OutputIndexData indexData = outputIndexData.get(transactionOutputIdentifier); indexData.slpTransactionId = slpTokenTransactionId; } if (generatorOutputIndex != null) { // Mark the Mint Baton Output as an SLP Output... final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, generatorOutputIndex); final OutputIndexData indexData = outputIndexData.get(transactionOutputIdentifier); indexData.slpTransactionId = slpTokenTransactionId; } } } break; case MINT: { final SlpMintScript slpMintScript = (SlpMintScript) slpScript; final Integer generatorOutputIndex = slpMintScript.getBatonOutputIndex(); if ( (generatorOutputIndex != null) && (generatorOutputIndex >= transactionOutputCount)) { slpTransactionIsValid = false; } else { outputScriptType = ScriptType.SLP_MINT_SCRIPT; { // Mark the Receiving Output as an SLP Output... final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, SlpMintScript.RECEIVER_TRANSACTION_OUTPUT_INDEX); final OutputIndexData indexData = outputIndexData.get(transactionOutputIdentifier); indexData.slpTransactionId = slpTokenTransactionId; } if (generatorOutputIndex != null) { // Mark the Mint Baton Output as an SLP Output... final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, generatorOutputIndex); final OutputIndexData indexData = outputIndexData.get(transactionOutputIdentifier); indexData.slpTransactionId = slpTokenTransactionId; } } } break; case SEND: { final SlpSendScript slpSendScript = (SlpSendScript) slpScript; for (int outputIndex = 0; outputIndex < transactionOutputCount; ++outputIndex) { final Long slpAmount = Util.coalesce(slpSendScript.getAmount(outputIndex)); if (slpAmount > 0L) { outputScriptType = ScriptType.SLP_SEND_SCRIPT; final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, outputIndex); final OutputIndexData indexData = outputIndexData.get(transactionOutputIdentifier); indexData.slpTransactionId = slpTokenTransactionId; } } } break; case COMMIT: { outputScriptType = ScriptType.SLP_COMMIT_SCRIPT; } break; } { // Update the OutputIndexData for the first TransactionOutput... final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, 0); final OutputIndexData indexData = outputIndexData.get(transactionOutputIdentifier); indexData.scriptType = outputScriptType; if (slpTransactionIsValid) { indexData.slpTransactionId = slpTokenTransactionId; } } } } return outputIndexData; } public BlockchainIndexer(final TransactionOutputIndexerContext context, final Integer threadCount) { _context = context; _threadCount = threadCount; } protected TransactionId _indexTransaction(final TransactionId nullableTransactionId, final Transaction nullableTransaction, final AtomicTransactionOutputIndexerContext context) throws ContextException { final TransactionId transactionId; final Transaction transaction; { if (nullableTransaction != null) { transaction = nullableTransaction; if (nullableTransactionId != null) { transactionId = nullableTransactionId; } else { final Sha256Hash transactionHash = transaction.getHash(); transactionId = context.getTransactionId(transactionHash); } } else if (nullableTransactionId != null) { transactionId = nullableTransactionId; transaction = context.getTransaction(transactionId); } else { return null; } } if (transaction == null) { Logger.debug("Unable to inflate Transaction for address processing: " + transactionId); return null; } final Map<TransactionOutputIdentifier, OutputIndexData> outputIndexData = _indexTransactionOutputs(context, transactionId, transaction); for (final OutputIndexData indexData : outputIndexData.values()) { context.indexTransactionOutput(indexData.transactionId, indexData.outputIndex, indexData.amount, indexData.scriptType, indexData.address, indexData.slpTransactionId); } final List<InputIndexData> inputIndexDataList = _indexTransactionInputs(context, transactionId, transaction); for (final InputIndexData inputIndexData : inputIndexDataList) { context.indexTransactionInput(inputIndexData.transactionId, inputIndexData.inputIndex, inputIndexData.transactionOutputId); } return transactionId; } @Override protected void _onStart() { Logger.trace("BlockchainIndexer Starting."); } @Override protected Boolean _run() { final NanoTimer nanoTimer = new NanoTimer(); nanoTimer.start(); final boolean shouldExecuteAsynchronously = (_threadCount > 0); final int maxBatchCount = (shouldExecuteAsynchronously ? (BATCH_SIZE * _threadCount) : BATCH_SIZE); final MutableList<TransactionId> transactionIdQueue = new MutableList<TransactionId>(maxBatchCount); try (final AtomicTransactionOutputIndexerContext context = _context.newTransactionOutputIndexerContext()) { final List<TransactionId> queuedTransactionIds = context.getUnprocessedTransactions(maxBatchCount); transactionIdQueue.addAll(queuedTransactionIds); } catch (final Exception exception) { Logger.warn(exception); return false; } if (transactionIdQueue.isEmpty()) { Logger.trace("BlockchainIndexer has nothing to do."); return false; } final BatchRunner<TransactionId> batchRunner = new BatchRunner<TransactionId>(BATCH_SIZE, shouldExecuteAsynchronously); try { batchRunner.run(transactionIdQueue, new BatchRunner.Batch<TransactionId>() { @Override public void run(final List<TransactionId> transactionIds) throws Exception { try (final AtomicTransactionOutputIndexerContext context = _context.newTransactionOutputIndexerContext()) { context.startDatabaseTransaction(); for (final TransactionId transactionId : transactionIds) { _indexTransaction(transactionId, null, context); } context.dequeueTransactionsForProcessing(transactionIds); context.commitDatabaseTransaction(); } } }); } catch (final Exception exception) { Logger.debug(exception); return false; } nanoTimer.stop(); final double msElapsed = nanoTimer.getMillisecondsElapsed(); final int actualBatchCount = transactionIdQueue.getCount(); final long tps = (long) ((actualBatchCount * 1000L) / (msElapsed > 0D ? msElapsed : 0.01)); Logger.info("Indexed " + actualBatchCount + " transactions in " + msElapsed + "ms. (" + tps + "tps)"); return true; } @Override protected void _onSleep() { Logger.trace("BlockchainIndexer Sleeping."); final Runnable onSleepCallback = _onSleepCallback; if (onSleepCallback != null) { onSleepCallback.run(); } } public void setOnSleepCallback(final Runnable onSleepCallback) { _onSleepCallback = onSleepCallback; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/handler/SpvUnconfirmedTransactionsHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.handler; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.FullNodeTransactionDatabaseManager; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; public class SpvUnconfirmedTransactionsHandler { protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; public SpvUnconfirmedTransactionsHandler(final FullNodeDatabaseManagerFactory databaseManagerFactory) { _databaseManagerFactory = databaseManagerFactory; } public void broadcastUnconfirmedTransactions(final BitcoinNode bitcoinNode) { try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final FullNodeTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); final MutableList<Sha256Hash> matchedTransactionHashes = new MutableList<Sha256Hash>(); final List<TransactionId> transactionIds = transactionDatabaseManager.getUnconfirmedTransactionIds(); for (final TransactionId transactionId : transactionIds) { final Transaction transaction = transactionDatabaseManager.getTransaction(transactionId); final boolean matchesFilter = bitcoinNode.matchesFilter(transaction); if (matchesFilter) { matchedTransactionHashes.add(transaction.getHash()); } } if (! matchedTransactionHashes.isEmpty()) { bitcoinNode.transmitTransactionHashes(matchedTransactionHashes); } } catch (final DatabaseException exception) { Logger.debug(exception); } } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeStaticMedianBlockTimeContext.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.context.MedianBlockTimeContext; public class FakeStaticMedianBlockTimeContext implements MedianBlockTimeContext { public static final MedianBlockTimeContext MAX_MEDIAN_BLOCK_TIME = new FakeStaticMedianBlockTimeContext(MedianBlockTime.MAX_VALUE); protected final MedianBlockTime _medianBlockTime; public FakeStaticMedianBlockTimeContext(final MedianBlockTime medianBlockTime) { _medianBlockTime = medianBlockTime; } @Override public MedianBlockTime getMedianBlockTime(final Long blockHeight) { return _medianBlockTime; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/callback/Callback.java<|end_filename|> package com.softwareverde.bitcoin.callback; public interface Callback<T> { void onResult(T result); } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/rpc/StratumJsonRpcConnection.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.rpc; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.json.Json; import com.softwareverde.logging.Logger; import com.softwareverde.network.socket.JsonProtocolMessage; import com.softwareverde.network.socket.JsonSocket; public class StratumJsonRpcConnection implements AutoCloseable { public static final Long RPC_DURATION_TIMEOUT_MS = 30000L; protected final JsonSocket _jsonSocket; protected final Object _newMessageNotifier = new Object(); protected final Runnable _onNewMessageCallback = new Runnable() { @Override public void run() { synchronized (_newMessageNotifier) { _newMessageNotifier.notifyAll(); } } }; protected Boolean _isUpgradedToHook = false; protected Json _executeJsonRequest(final Json rpcRequestJson) { if (_isUpgradedToHook) { throw new RuntimeException("Attempted to invoke Json request to hook-upgraded socket."); } _jsonSocket.write(new JsonProtocolMessage(rpcRequestJson)); _jsonSocket.beginListening(); JsonProtocolMessage jsonProtocolMessage; synchronized (_newMessageNotifier) { jsonProtocolMessage = _jsonSocket.popMessage(); if (jsonProtocolMessage == null) { try { _newMessageNotifier.wait(RPC_DURATION_TIMEOUT_MS); } catch (final InterruptedException exception) { } jsonProtocolMessage = _jsonSocket.popMessage(); } } return (jsonProtocolMessage != null ? jsonProtocolMessage.getMessage() : null); } public StratumJsonRpcConnection(final String hostname, final Integer port, final ThreadPool threadPool) { java.net.Socket socket = null; try { socket = new java.net.Socket(hostname, port); } catch (final Exception exception) { Logger.warn(exception); } _jsonSocket = ((socket != null) ? new JsonSocket(socket, threadPool) : null); if (_jsonSocket != null) { _jsonSocket.setMessageReceivedCallback(_onNewMessageCallback); } } public StratumJsonRpcConnection(final java.net.Socket socket, final ThreadPool threadPool) { _jsonSocket = ((socket != null) ? new JsonSocket(socket, threadPool) : null); if (_jsonSocket != null) { _jsonSocket.setMessageReceivedCallback(_onNewMessageCallback); } } public Json getPrototypeBlock(final Boolean returnRawData) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("rawFormat", (returnRawData ? 1 : 0)); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "PROTOTYPE_BLOCK"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public JsonSocket getJsonSocket() { return _jsonSocket; } @Override public void close() { _jsonSocket.close(); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/util/TestUtilTests.java<|end_filename|> package com.softwareverde.bitcoin.test.util; import org.junit.Assert; import org.junit.Test; public class TestUtilTests { @Test public void mask_should_succeed_on_exact_match() { // Setup final String maskString = "0000"; final String string = "0000"; // Action TestUtil.assertMatchesMaskedHexString(maskString, string); } @Test public void mask_should_allow_spaces() { // Setup final String maskString = "0000 0000"; final String string = "00000000"; // Action TestUtil.assertMatchesMaskedHexString(maskString, string); } @Test public void mask_should_allow_masked_values() { // Setup final String maskString = "0000 0X0X 0000"; final String string = "000001010000"; // Action TestUtil.assertMatchesMaskedHexString(maskString, string); } @Test public void mask_should_fail_when_not_matching() { // Setup final String maskString = "0000 0X0X 0000"; final String string = "000011110000"; Boolean exceptionThrown = false; // Action try { TestUtil.assertMatchesMaskedHexString(maskString, string); } catch (final AssertionError assertionError) { exceptionThrown = true; } // Assert Assert.assertTrue(exceptionThrown); } @Test public void mask_should_fail_when_lengths_do_not_match() { // Setup final String maskString = "0000 1111 0000"; final String string = "00001111"; Boolean exceptionThrown = false; // Action try { TestUtil.assertMatchesMaskedHexString(maskString, string); } catch (final AssertionError assertionError) { exceptionThrown = true; } // Assert Assert.assertTrue(exceptionThrown); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/runner/context/ImmutableTransactionContext.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.runner.context; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.constable.util.ConstUtil; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.constable.Const; import com.softwareverde.json.Json; public class ImmutableTransactionContext implements TransactionContext, Const { protected Long _blockHeight; protected MedianBlockTime _medianBlockTime; protected Transaction _transaction; protected Integer _transactionInputIndex; protected TransactionInput _transactionInput; protected TransactionOutput _transactionOutput; protected Script _currentScript; protected Integer _currentScriptIndex; protected Integer _scriptLastCodeSeparatorIndex; protected Integer _signatureOperationCount; public ImmutableTransactionContext(final TransactionContext transactionContext) { _blockHeight = transactionContext.getBlockHeight(); _medianBlockTime = ConstUtil.asConstOrNull(transactionContext.getMedianBlockTime()); _transaction = ConstUtil.asConstOrNull(transactionContext.getTransaction()); _transactionInputIndex = transactionContext.getTransactionInputIndex(); _transactionInput = ConstUtil.asConstOrNull(transactionContext.getTransactionInput()); _transactionOutput = ConstUtil.asConstOrNull(transactionContext.getTransactionOutput()); final Script currentScript = transactionContext.getCurrentScript(); _currentScript = (currentScript != null ? ConstUtil.asConstOrNull(currentScript) : null); _currentScriptIndex = transactionContext.getScriptIndex(); _scriptLastCodeSeparatorIndex = transactionContext.getScriptLastCodeSeparatorIndex(); _signatureOperationCount = transactionContext.getSignatureOperationCount(); } @Override public Long getBlockHeight() { return _blockHeight; } @Override public MedianBlockTime getMedianBlockTime() { return _medianBlockTime; } @Override public TransactionInput getTransactionInput() { return _transactionInput; } @Override public TransactionOutput getTransactionOutput() { return _transactionOutput; } @Override public Transaction getTransaction() { return _transaction; } @Override public Integer getTransactionInputIndex() { return _transactionInputIndex; } @Override public Script getCurrentScript() { return _currentScript; } @Override public Integer getScriptIndex() { return _currentScriptIndex; } @Override public Integer getScriptLastCodeSeparatorIndex() { return _scriptLastCodeSeparatorIndex; } @Override public Integer getSignatureOperationCount() { return _signatureOperationCount; } @Override public ImmutableTransactionContext asConst() { return this; } @Override public Json toJson() { final ContextDeflater contextDeflater = new ContextDeflater(); return contextDeflater.toJson(this); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/lazy/LazyMutableUnspentTransactionOutputSet.java<|end_filename|> package com.softwareverde.bitcoin.context.lazy; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.context.core.MutableUnspentTransactionOutputSet; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; import java.util.LinkedList; public class LazyMutableUnspentTransactionOutputSet extends MutableUnspentTransactionOutputSet { protected static class LazyLoadTask { enum TaskType { LOAD, UPDATE } final Block block; final TaskType taskType; final Long blockHeight; public LazyLoadTask(final TaskType taskType, final Block block, final Long blockHeight) { this.taskType = taskType; this.block = block; this.blockHeight = blockHeight; } } protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; protected final LinkedList<LazyLoadTask> _lazyLoadTasks = new LinkedList<LazyLoadTask>(); /** * Empties the LazyTasks, if there any. * Requires synchronization on _lazyLoadTasks. * If a task fails, the function aborts and _lazyLoadTasks is not emptied. */ protected void _loadOutputsForBlocks() { try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { while (! _lazyLoadTasks.isEmpty()) { // NOTE: Constant time for LinkedList... final LazyLoadTask lazyLoadTask = _lazyLoadTasks.peekFirst(); final Block block = lazyLoadTask.block; final LazyLoadTask.TaskType taskType = lazyLoadTask.taskType; final Long blockHeight; if (lazyLoadTask.blockHeight != null) { blockHeight = lazyLoadTask.blockHeight; } else { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final Sha256Hash previousBlockHash = block.getPreviousBlockHash(); final BlockId previousBlockId = blockHeaderDatabaseManager.getBlockHeaderId(previousBlockHash); final Long previousBlockHeight = blockHeaderDatabaseManager.getBlockHeight(previousBlockId); if (previousBlockHeight == null) { Logger.debug("Unable to lazily load blockHeight for Block: " + block.getHash()); return; } blockHeight = (previousBlockHeight + 1L); } if (taskType == LazyLoadTask.TaskType.LOAD) { final Boolean outputsLoadedSuccessfully = super.loadOutputsForBlock(databaseManager, block, blockHeight); if (! outputsLoadedSuccessfully) { Logger.debug("Unable to lazily load outputs for Block: " + block.getHash()); return; } } else { super.update(block, blockHeight); } _lazyLoadTasks.removeFirst(); } } catch (final DatabaseException exception) { Logger.debug(exception); } } public LazyMutableUnspentTransactionOutputSet() { this(null); } public LazyMutableUnspentTransactionOutputSet(final FullNodeDatabaseManagerFactory databaseManagerFactory) { _databaseManagerFactory = databaseManagerFactory; } @Override public synchronized Boolean loadOutputsForBlock(final FullNodeDatabaseManager databaseManager, final Block block, final Long blockHeight) { synchronized (_lazyLoadTasks) { _lazyLoadTasks.addLast(new LazyLoadTask(LazyLoadTask.TaskType.LOAD, block, blockHeight)); } return true; } @Override public TransactionOutput getTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { synchronized (_lazyLoadTasks) { if (! _lazyLoadTasks.isEmpty()) { _loadOutputsForBlocks(); } if (! _lazyLoadTasks.isEmpty()) { return null; } // If a task failed, then return null. } return super.getTransactionOutput(transactionOutputIdentifier); } @Override public synchronized void update(final Block block, final Long blockHeight) { synchronized (_lazyLoadTasks) { _lazyLoadTasks.addLast(new LazyLoadTask(LazyLoadTask.TaskType.UPDATE, block, blockHeight)); } } @Override public synchronized void clear() { _lazyLoadTasks.clear(); super.clear(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/inflater/MerkleTreeInflaters.java<|end_filename|> package com.softwareverde.bitcoin.inflater; import com.softwareverde.bitcoin.block.merkleroot.PartialMerkleTreeDeflater; import com.softwareverde.bitcoin.block.merkleroot.PartialMerkleTreeInflater; public interface MerkleTreeInflaters extends Inflater { PartialMerkleTreeInflater getPartialMerkleTreeInflater(); PartialMerkleTreeDeflater getPartialMerkleTreeDeflater(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/message/client/AuthorizeMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.message.client; import com.softwareverde.bitcoin.server.stratum.message.RequestMessage; public class AuthorizeMessage extends RequestMessage { public AuthorizeMessage() { super(ClientCommand.AUTHORIZE.getValue()); } public void setCredentials(final String username, final String password) { _parameters.add(username); _parameters.add(password); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/MedianHeadBlockTimeContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; public interface MedianHeadBlockTimeContext { MedianBlockTime getHeadMedianBlockTime(); } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/account/PayoutAddressApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.miner.pool.AccountId; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.bitcoin.server.module.stratum.database.AccountDatabaseManager; import com.softwareverde.database.DatabaseException; import com.softwareverde.http.HttpMethod; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.logging.Logger; import com.softwareverde.servlet.AuthenticatedServlet; public class PayoutAddressApi extends AuthenticatedServlet { protected final DatabaseConnectionFactory _databaseConnectionFactory; public PayoutAddressApi(final StratumProperties stratumProperties, final DatabaseConnectionFactory databaseConnectionFactory) { super(stratumProperties); _databaseConnectionFactory = databaseConnectionFactory; } @Override protected Response _onAuthenticatedRequest(final AccountId accountId, final Request request) { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); if (request.getMethod() == HttpMethod.GET) { // GET PAYOUT ADDRESS // Requires GET: // Requires POST: try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { final AccountDatabaseManager accountDatabaseManager = new AccountDatabaseManager(databaseConnection); final Address address = accountDatabaseManager.getPayoutAddress(accountId); final StratumApiResult apiResult = new StratumApiResult(true, null); apiResult.put("address", (address != null ? address.toBase58CheckEncoded() : null)); return new JsonResponse(Response.Codes.OK, apiResult); } catch (final DatabaseException exception) { Logger.warn(exception); return new JsonResponse(Response.Codes.SERVER_ERROR, new StratumApiResult(false, "An internal error occurred.")); } } else if (request.getMethod() == HttpMethod.POST) { // SET PAYOUT ADDRESS // Requires GET: // Requires POST: address final AddressInflater addressInflater = new AddressInflater(); final String addressString = postParameters.get("address"); final Address address; if (! addressString.isEmpty()) { address = addressInflater.fromBase58Check(addressString); if (address == null) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid address.")); } } else { address = null; } try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { final AccountDatabaseManager accountDatabaseManager = new AccountDatabaseManager(databaseConnection); accountDatabaseManager.setPayoutAddress(accountId, address); return new JsonResponse(Response.Codes.OK, new StratumApiResult(true, null)); } catch (final DatabaseException exception) { Logger.warn(exception); return new JsonResponse(Response.Codes.SERVER_ERROR, new StratumApiResult(false, "An internal error occurred.")); } } else { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid method.")); } } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/IndexedInput.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.server.module.node.database.indexer.TransactionOutputId; import com.softwareverde.bitcoin.transaction.TransactionId; public class IndexedInput { public final TransactionId transactionId; public final Integer inputIndex; public final TransactionOutputId transactionOutputId; public IndexedInput(final TransactionId transactionId, final Integer inputIndex, final TransactionOutputId transactionOutputId) { this.transactionId = transactionId; this.inputIndex = inputIndex; this.transactionOutputId = transactionOutputId; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/pool/DatabaseConnectionPool.java<|end_filename|> package com.softwareverde.bitcoin.server.database.pool; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; public interface DatabaseConnectionPool extends DatabaseConnectionFactory, AutoCloseable { /** * Returns the number of connections that have not yet been returned to the pool. * Returns null if the operation is unsupported. */ default Integer getInUseConnectionCount() { return null; } /** * Returns the number of connections that have been created but have not yet been closed. * This number does not necessarily account for pooled connections that have died. * Returns null if the operation is unsupported. */ default Integer getAliveConnectionCount() { return null; } /** * Returns the desired maximum number of connections this pool will create. * This value can be surpassed if a thread waits for a connection longer than deadlockTimeout (ms). * Returns null if the operation is unsupported. */ default Integer getMaxConnectionCount() { return null; } /** * Returns the number of connections currently waiting and available within the pool. * This number does not account for pooled connections that have died. * This number should be equal to ::getAliveConnectionsCount + ::getInUseConnectionsCount * Returns null if the operation is unsupported. */ default Integer getCurrentPoolSize() { return null; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/core/PendingBlockLoaderContext.java<|end_filename|> package com.softwareverde.bitcoin.context.core; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.sync.blockloader.PendingBlockLoader; import com.softwareverde.concurrent.pool.ThreadPool; public class PendingBlockLoaderContext implements PendingBlockLoader.Context { protected final BlockInflaters _blockInflaters; protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; protected final ThreadPool _threadPool; public PendingBlockLoaderContext(final BlockInflaters blockInflaters, final FullNodeDatabaseManagerFactory databaseManagerFactory, final ThreadPool threadPool) { _blockInflaters = blockInflaters; _databaseManagerFactory = databaseManagerFactory; _threadPool = threadPool; } @Override public FullNodeDatabaseManagerFactory getDatabaseManagerFactory() { return _databaseManagerFactory; } @Override public ThreadPool getThreadPool() { return _threadPool; } @Override public BlockInflater getBlockInflater() { return _blockInflaters.getBlockInflater(); } @Override public BlockDeflater getBlockDeflater() { return _blockInflaters.getBlockDeflater(); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeBlockHeaderValidatorContext.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.block.validator.BlockHeaderValidator; import com.softwareverde.network.time.VolatileNetworkTime; public class FakeBlockHeaderValidatorContext extends FakeDifficultyCalculatorContext implements BlockHeaderValidator.Context { protected final VolatileNetworkTime _networkTime; public FakeBlockHeaderValidatorContext(final VolatileNetworkTime networkTime) { _networkTime = networkTime; } @Override public VolatileNetworkTime getNetworkTime() { return _networkTime; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/script/stack/ValueTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.stack; import com.softwareverde.bitcoin.test.util.TestUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.util.HexUtil; import org.junit.Assert; import org.junit.Test; public class ValueTests { @Test public void should_interpret_4_bytes_as_little_endian_integer() { // Setup final byte[] bytes = HexUtil.hexStringToByteArray("010000"); final int expectedValue = 1; final Value value = Value.fromBytes(bytes); // Action final int receivedValue = value.asInteger(); // Assert Assert.assertEquals(expectedValue, receivedValue); } @Test public void should_interpret_4_bytes_as_signed_little_endian_integer() { // Setup final byte[] bytes = HexUtil.hexStringToByteArray("010080"); final int expectedValue = -1; final Value value = Value.fromBytes(bytes); // Action final int receivedValue = value.asInteger(); // Assert Assert.assertEquals(expectedValue, receivedValue); } @Test public void should_interpret_1_bytes_as_signed_little_endian_integer() { // Setup final byte[] bytes = HexUtil.hexStringToByteArray("81"); final int expectedValue = -1; final Value value = Value.fromBytes(bytes); // Action final int receivedValue = value.asInteger(); // Assert Assert.assertEquals(expectedValue, receivedValue); } @Test public void should_interpret_2_bytes_as_signed_little_endian_integer() { // Setup final byte[] bytes = HexUtil.hexStringToByteArray("0180"); final int expectedValue = -1; final Value value = Value.fromBytes(bytes); // Action final int receivedValue = value.asInteger(); // Assert Assert.assertEquals(expectedValue, receivedValue); } @Test public void should_interpret_2_bytes_as_little_endian_integer() { // Setup final byte[] bytes = HexUtil.hexStringToByteArray("0100"); final int expectedValue = 1; final Value value = Value.fromBytes(bytes); // Action final int receivedValue = value.asInteger(); // Assert Assert.assertEquals(expectedValue, receivedValue); } @Test public void should_interpret_5_bytes_as_little_endian_integer() { // Setup final byte[] bytes = HexUtil.hexStringToByteArray("0100000000"); final int expectedValue = 1; final Value value = Value.fromBytes(bytes); // Action final int receivedValue = value.asInteger(); // Assert Assert.assertEquals(expectedValue, receivedValue); } @Test public void should_interpret_8_bytes_as_little_endian_long() { // Setup final byte[] bytes = HexUtil.hexStringToByteArray("0100000000000000"); final long expectedValue = 1; final Value value = Value.fromBytes(bytes); // Action final long receivedValue = value.asLong(); // Assert Assert.assertEquals(expectedValue, receivedValue); } @Test public void should_interpret_8_bytes_as_max_value_little_endian_long() { // Setup final byte[] bytes = HexUtil.hexStringToByteArray("FFFFFFFFFFFFFF7F"); final long expectedValue = Long.MAX_VALUE; final Value value = Value.fromBytes(bytes); // Action final long receivedValue = value.asLong(); // Assert Assert.assertEquals(expectedValue, receivedValue); } @Test public void should_interpret_1_byte_as_signed_little_endian_long() { // Setup final byte[] bytes = HexUtil.hexStringToByteArray("81"); final long expectedValue = -1L; final Value value = Value.fromBytes(bytes); // Action final long receivedValue = value.asLong(); // Assert Assert.assertEquals(expectedValue, receivedValue); } @Test public void should_interpret_8_bytes_as_signed_little_endian_long() { // Setup final byte[] bytes = HexUtil.hexStringToByteArray("FFFFFFFFFFFFFFFF"); final long expectedValue = Long.MIN_VALUE + 1; // The Bitcoin integer encoding allows for negative zero, therefore, the min range is one less. final Value value = Value.fromBytes(bytes); // Action final long receivedValue = value.asLong(); // Assert Assert.assertEquals(expectedValue, receivedValue); } @Test public void should_interpret_negative_zero_as_false() { // Setup final byte[] bytes = HexUtil.hexStringToByteArray("80"); final boolean expectedValue = false; final Value value = Value.fromBytes(bytes); // Action final boolean receivedValue = value.asBoolean(); // Assert Assert.assertEquals(expectedValue, receivedValue); } @Test public void should_maintain_integer_interpretation() { // Setup final Integer expectedIntegerValue = 7; final Value value = Value.fromInteger(expectedIntegerValue.longValue()); // Action final Integer integerValue = value.asInteger(); // Assert Assert.assertEquals(expectedIntegerValue, integerValue); } @Test public void should_maintain_boolean_interpretation() { // Setup final Boolean expectedValue = true; final Value value = Value.fromBoolean(expectedValue); // Action final Boolean booleanValue = value.asBoolean(); // Assert Assert.assertEquals(expectedValue, booleanValue); } @Test public void should_convert_boolean_to_integer() { // Setup final Integer expectedIntegerValue = 1; final Value value = Value.fromBoolean(true); // Action final Integer integerValue = value.asInteger(); // Assert Assert.assertEquals(expectedIntegerValue, integerValue); } @Test public void should_convert_values_to_mpi_encoding() { { final long value = 1L; final byte[] bytes = Value._longToBytes(value); final Value mpiBytes = Value.minimallyEncodeBytes(MutableByteArray.wrap(bytes)); TestUtil.assertEqual(HexUtil.hexStringToByteArray("01"), bytes); Assert.assertEquals(value, Value.fromBytes(bytes).asLong().longValue()); Assert.assertEquals(Value.fromBytes(bytes), mpiBytes); } { final long value = 2L; final byte[] bytes = Value._longToBytes(value); final Value mpiBytes = Value.minimallyEncodeBytes(MutableByteArray.wrap(bytes)); TestUtil.assertEqual(HexUtil.hexStringToByteArray("02"), bytes); Assert.assertEquals(value, Value.fromBytes(bytes).asLong().longValue()); Assert.assertEquals(Value.fromBytes(bytes), mpiBytes); } { final long value = 15L; final byte[] bytes = Value._longToBytes(value); final Value mpiBytes = Value.minimallyEncodeBytes(MutableByteArray.wrap(bytes)); TestUtil.assertEqual(HexUtil.hexStringToByteArray("0F"), bytes); Assert.assertEquals(value, Value.fromBytes(bytes).asLong().longValue()); Assert.assertEquals(Value.fromBytes(bytes), mpiBytes); } { final long value = 16L; final byte[] bytes = Value._longToBytes(value); final Value mpiBytes = Value.minimallyEncodeBytes(MutableByteArray.wrap(bytes)); TestUtil.assertEqual(HexUtil.hexStringToByteArray("10"), bytes); Assert.assertEquals(value, Value.fromBytes(bytes).asLong().longValue()); Assert.assertEquals(Value.fromBytes(bytes), mpiBytes); } { final long value = 0x0100L; final byte[] bytes = Value._longToBytes(value); final Value mpiBytes = Value.minimallyEncodeBytes(MutableByteArray.wrap(bytes)); TestUtil.assertEqual(HexUtil.hexStringToByteArray("0001"), bytes); Assert.assertEquals(value, Value.fromBytes(bytes).asLong().longValue()); Assert.assertEquals(Value.fromBytes(bytes), mpiBytes); } { final long value = 0xFF; final byte[] bytes = Value._longToBytes(value); final Value mpiBytes = Value.minimallyEncodeBytes(MutableByteArray.wrap(bytes)); TestUtil.assertEqual(HexUtil.hexStringToByteArray("FF00"), bytes); Assert.assertEquals(value, Value.fromBytes(bytes).asLong().longValue()); Assert.assertEquals(Value.fromBytes(bytes), mpiBytes); } { final long value = 0xFF00; final byte[] bytes = Value._longToBytes(value); final Value mpiBytes = Value.minimallyEncodeBytes(MutableByteArray.wrap(bytes)); TestUtil.assertEqual(HexUtil.hexStringToByteArray("00FF00"), bytes); Assert.assertEquals(value, Value.fromBytes(bytes).asLong().longValue()); Assert.assertEquals(Value.fromBytes(bytes), mpiBytes); } { final long value = -0xFF00; final byte[] bytes = Value._longToBytes(value); final Value mpiBytes = Value.minimallyEncodeBytes(MutableByteArray.wrap(bytes)); TestUtil.assertEqual(HexUtil.hexStringToByteArray("00FF80"), bytes); Assert.assertEquals(value, Value.fromBytes(bytes).asLong().longValue()); Assert.assertEquals(Value.fromBytes(bytes), mpiBytes); } { final long value = -943534368L; final byte[] bytes = Value._longToBytes(value); final Value mpiBytes = Value.minimallyEncodeBytes(MutableByteArray.wrap(bytes)); TestUtil.assertEqual(HexUtil.hexStringToByteArray("20313DB8"), bytes); Assert.assertEquals(value, Value.fromBytes(bytes).asLong().longValue()); Assert.assertEquals(Value.fromBytes(bytes), mpiBytes); } { final long value = Integer.MAX_VALUE; final byte[] bytes = Value._longToBytes(value); final Value mpiBytes = Value.minimallyEncodeBytes(MutableByteArray.wrap(bytes)); TestUtil.assertEqual(HexUtil.hexStringToByteArray("FFFFFF7F"), bytes); Assert.assertEquals(value, Value.fromBytes(bytes).asLong().longValue()); Assert.assertEquals(Value.fromBytes(bytes), mpiBytes); } { final long value = Integer.MIN_VALUE; final byte[] bytes = Value._longToBytes(value); final Value mpiBytes = Value.minimallyEncodeBytes(MutableByteArray.wrap(bytes)); TestUtil.assertEqual(HexUtil.hexStringToByteArray("00000080"), bytes); Assert.assertEquals(value, Value.fromBytes(bytes).asLong().longValue()); Assert.assertEquals(Value.fromBytes(bytes), mpiBytes); } } @Test public void should_minimally_encode_value_that_is_not_minimally_encoded() { // Setup final ByteArray notMinimallyEncodedByteArray = ByteArray.fromHexString("ABCDEF4280"); final ByteArray expectedEncoding = ByteArray.fromHexString("ABCDEFC2"); // Action final ByteArray encodedValue = Value.minimallyEncodeBytes(notMinimallyEncodedByteArray); // Assert Assert.assertEquals(expectedEncoding, encodedValue); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/SystemTimeContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.util.type.time.SystemTime; public interface SystemTimeContext { SystemTime getSystemTime(); } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/script/runner/ScriptRunnerTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.runner; import com.softwareverde.bitcoin.chain.time.MutableMedianBlockTime; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.ScriptInflater; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.locking.MutableLockingScript; import com.softwareverde.bitcoin.transaction.script.runner.context.MutableTransactionContext; import com.softwareverde.bitcoin.transaction.script.unlocking.MutableUnlockingScript; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.util.HexUtil; import org.junit.Assert; import org.junit.Test; public class ScriptRunnerTests { @Test public void should_execute_checksig_transaction() { // Setup final TransactionInflater transactionInflater = new TransactionInflater(); final TransactionDeflater transactionDeflater = new TransactionDeflater(); final Transaction transactionBeingSpent = transactionInflater.fromBytes(HexUtil.hexStringToByteArray("01000000010000000000000000000000000000000000000000000000000000000000000000FFFFFFFF0704FFFF001D0134FFFFFFFF0100F2052A0100000043410411DB93E1DCDB8A016B49840F8C53BC1EB68A382E97B1482ECAD7B148A6909A5CB2E0EADDFB84CCF9744464F82E160BFA9B8B64F9D4C03F999B8643F656B412A3AC00000000")); final Transaction transaction0 = transactionInflater.fromBytes(HexUtil.hexStringToByteArray( // Transaction 1 "01000000" + // Transaction Version "01" + // Transaction-Input Count // Transaction 1, Transaction-Input 1 "0000000000000000000000000000000000000000000000000000000000000000" + // Previous Transaction Hash "FFFFFFFF" + // Previous Transaction Output Index "07" + // Script Byte Count "04FFFF001D0102" + // Locking Script "FFFFFFFF" + // Sequence Number "01" + // Transaction-Output Count "00F2052A01000000" + // Amount "43" + // Script Byte Count "4104D46C4968BDE02899D2AA0963367C7A6CE34EEC332B32E42E5F3407E052D64AC625DA6F0718E7B302140434BD725706957C092DB53805B821A85B23A7AC61725BAC" + // Script "00000000" // Locktime )); final String transactionBytesString01 = "01000000" + // Transaction Version "01" + // Transaction Input Count "C997A5E56E104102FA209C6A852DD90660A20B2D9C352423EDCE25857FCD3704" + // Previous Transaction Hash "00000000" + // Previous Transaction Output Index "48" + // Script Byte Count "47304402204E45E16932B8AF514961A1D3A1A25FDF3F4F7732E9D624C6C61548AB5FB8CD410220181522EC8ECA07DE4860A4ACDD12909D831CC56CBBAC4622082221A8768D1D0901" + // Script "FFFFFFFF" + // Sequence Number "02" + // Transaction-Output Count "00CA9A3B00000000" + // Amount "43" + // Script Byte Count "4104AE1A62FE09C5F51B13905F07F06B99A2F7159B2225F374CD378D71302FA28414E7AAB37397F554A7DF5F142C21C1B7303B8A0626F1BADED5C72A704F7E6CD84CAC" + "00286BEE00000000" + // Amount "43" + // Script Byte Count "410411DB93E1DCDB8A016B49840F8C53BC1EB68A382E97B1482ECAD7B148A6909A5CB2E0EADDFB84CCF9744464F82E160BFA9B8B64F9D4C03F999B8643F656B412A3AC" + // Script "00000000" // Locktime ; final Transaction transaction1 = transactionInflater.fromBytes(HexUtil.hexStringToByteArray(transactionBytesString01)); Assert.assertEquals(transactionBytesString01, HexUtil.toHexString(transactionDeflater.toBytes(transaction1).getBytes())); final MutableTransactionContext context = new MutableTransactionContext(); final ScriptRunner scriptRunner = new ScriptRunner(); final TransactionInput transactionInput = transaction1.getTransactionInputs().get(0); final TransactionOutput transactionOutput = transactionBeingSpent.getTransactionOutputs().get(0); context.setTransaction(transaction1); context.setTransactionInputIndex(0); context.setTransactionInput(transactionInput); context.setTransactionOutputBeingSpent(transactionOutput); context.setBlockHeight(0L); final LockingScript lockingScript = transactionOutput.getLockingScript(); final UnlockingScript unlockingScript = transactionInput.getUnlockingScript(); // Action final Boolean inputIsUnlocked = scriptRunner.runScript(lockingScript, unlockingScript, context); // Assert Assert.assertTrue(inputIsUnlocked); } @Test public void should_execute_checksig_transaction01() { // Setup final TransactionInflater transactionInflater = new TransactionInflater(); final TransactionDeflater transactionDeflater = new TransactionDeflater(); final ScriptRunner scriptRunner = new ScriptRunner(); final Transaction transactionBeingSpent = transactionInflater.fromBytes(HexUtil.hexStringToByteArray( "01000000015AEFC06AF14A9216350A1F549971E0C8381D69B00B492CA20663CAEB5F191825010000006B4830450220210947BCC472D558BED1A36A573BC3C5E11914BE685E868639A46B330AE1879B022100964512E526759EE915A3178F43520CF53D2C38E18A229062EEAB8E2D544A91990121021B36AF5FEDC577DFBF74D75060B20305F1D9127A3C7A7373EF91BF684F6A0491FFFFFFFF0246FBBB84000000001976A914F6A9D96485D1D45D28E38662F617BA39A6B151BB88AC00093D00000000001976A914D948D7A14685B7B5B528034137AA4C590F84F62988AC00000000" )); final String transactionHexString = "0100000001BF9705FAE2004CC9072D7C6D73BC8F38A0A7C67DACEED5FC42E0D20AC8D898C0000000006B483045022100CB0093D91F09644065AC05424DE3DE709C90A9BC963945EE149EAA1CF7B13DA802200EFE508E68A5E2F9C3CBD851B66EB597803ACCDC2F45F07BFD5488DA476727FE0121039500311F6688A8C16A570853AC22230F4B1E0A551D8846550FE4AE56F9799E80FFFFFFFF0200E1F505000000001976A914C23E891A29D290DDB454EBF3456EEAEC56412AB988AC36F3C57E000000001976A914DB89750F929FBD94A8018767A49EF6FC6AC7E46888AC00000000"; final Transaction transaction = transactionInflater.fromBytes(HexUtil.hexStringToByteArray(transactionHexString)); Assert.assertEquals(transactionHexString, HexUtil.toHexString(transactionDeflater.toBytes(transaction).getBytes())); final MutableTransactionContext context = new MutableTransactionContext(); context.setTransaction(transaction); final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); for (int inputIndex=0; inputIndex<transactionInputs.getCount(); ++inputIndex) { final TransactionInput transactionInput = transactionInputs.get(inputIndex); final TransactionOutput transactionOutputBeingSpent = transactionBeingSpent.getTransactionOutputs().get(0); context.setTransactionInputIndex(inputIndex); context.setTransactionInput(transactionInput); context.setTransactionOutputBeingSpent(transactionOutputBeingSpent); context.setBlockHeight(0L); final LockingScript lockingScript = transactionOutputBeingSpent.getLockingScript(); final UnlockingScript unlockingScript = transactionInput.getUnlockingScript(); // Action final Boolean inputIsUnlocked = scriptRunner.runScript(lockingScript, unlockingScript, context); // Assert Assert.assertTrue(inputIsUnlocked); } } @Test public void should_allow_segwit_recovery_after_20190515HF() { // Setup final ScriptRunner scriptRunner = new ScriptRunner(); final MutableTransactionContext context = new MutableTransactionContext(); context.setBlockHeight(590000L); final String[] lockingScriptStrings = new String[7]; final String[] unlockingScriptStrings = new String[7]; // Recovering v0 P2SH-P2WPKH: lockingScriptStrings[0] = "A91417743BEB429C55C942D2EC703B98C4D57C2DF5C687"; unlockingScriptStrings[0] = "16001491B24BF9F5288532960AC687ABB035127B1D28A5"; // Recovering v0 P2SH-P2WSH: lockingScriptStrings[1] = "A91417A6BE2F8FE8E94F033E53D17BEEFDA0F3AC440987"; unlockingScriptStrings[1] = "2200205A0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"; // Max allowed version, v16: lockingScriptStrings[2] = "A9149B0C7017004D3818B7C833DDB3CB5547A22034D087"; unlockingScriptStrings[2] = "2260205A0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"; // Max allowed length, 42 bytes: lockingScriptStrings[3] = "A914DF7B93F88E83471B479FB219AE90E5B633D6B75087"; unlockingScriptStrings[3] = "2A00285A0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627"; // Min allowed length, 4 bytes: lockingScriptStrings[4] = "A91486123D8E050333A605E434ECF73128D83815B36F87"; unlockingScriptStrings[4] = "0400025A01"; // Valid in spite of a false boolean value being left on stack, 0: lockingScriptStrings[5] = "A9140E01BCFE7C6F3FD2FD8F8109229936974468473387"; unlockingScriptStrings[5] = "0400020000"; // Valid in spite of a false boolean value being left on stack, minus 0: lockingScriptStrings[6] = "A91410DDC638CB26615F867DAD80EFACCED9E73766BC87"; unlockingScriptStrings[6] = "0400020080"; for (int i = 0; i < lockingScriptStrings.length; ++i) { final String lockingScriptString = lockingScriptStrings[i]; final String unlockingScriptString = unlockingScriptStrings[i]; final LockingScript lockingScript = new MutableLockingScript(ByteArray.fromHexString(lockingScriptString)); final UnlockingScript unlockingScript = new MutableUnlockingScript(ByteArray.fromHexString(unlockingScriptString)); // Action final Boolean outputIsUnlocked = scriptRunner.runScript(lockingScript, unlockingScript, context); // Assert Assert.assertTrue(outputIsUnlocked); } } @Test public void should_not_allow_invalid_segwit_recovery_after_20190515HF() { // Setup final ScriptRunner scriptRunner = new ScriptRunner(); final MutableTransactionContext context = new MutableTransactionContext(); context.setBlockHeight(590000L); final String[] lockingScriptStrings = new String[11]; final String[] unlockingScriptStrings = new String[11]; // Non-P2SH output: lockingScriptStrings[0] = "81"; unlockingScriptStrings[0] = "16001491B24BF9F5288532960AC687ABB035127B1D28A5"; // Redeem script hash does not match P2SH output: lockingScriptStrings[1] = "A91417A6BE2F8FE8E94F033E53D17BEEFDA0F3AC440987"; unlockingScriptStrings[1] = "16001491B24BF9F5288532960AC687ABB035127B1D28A5"; // scriptSig pushes two items onto the stack: lockingScriptStrings[2] = "A91417743BEB429C55C942D2EC703B98C4D57C2DF5C687"; unlockingScriptStrings[2] = "0016001491B24BF9F5288532960AC687ABB035127B1D28A5"; // Invalid witness program, non-minimal push in version field: lockingScriptStrings[3] = "A9140718743E67C1EF4911E0421F206C5FF81755718E87"; unlockingScriptStrings[3] = "1701001491B24BF9F5288532960AC687ABB035127B1D28A5"; // Invalid witness program, non-minimal push in program field: lockingScriptStrings[4] = "A914D3EC673296C7FD7E1A9E53BFC36F414DE303E90587"; unlockingScriptStrings[4] = "05004C0245AA"; // Invalid witness program, too short, 3 bytes: lockingScriptStrings[5] = "A91440B6941895022D458DE8F4BBFE27F3AAA4FB9A7487"; unlockingScriptStrings[5] = "0300015A"; // Invalid witness program, too long, 43 bytes: lockingScriptStrings[6] = "A91413AA4FCFD630508E0794DCA320CAC172C5790AEA87"; unlockingScriptStrings[6] = "2B00295A0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728"; // Invalid witness program, version -1: lockingScriptStrings[7] = "A91497AA1E96E49CA6D744D7344F649DD9F94BCC35EB87"; unlockingScriptStrings[7] = "224F205A0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"; // Invalid witness program, version 17: lockingScriptStrings[8] = "A9144B5321BEB1C09F593FF3C02BE4AF21C7F949E10187"; unlockingScriptStrings[8] = "230111205A0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"; // Invalid witness program, OP_RESERVED in version field: lockingScriptStrings[9] = "A914BE02794CEEDE051DA41B420E88A86FFF2802AF0687"; unlockingScriptStrings[9] = "2250205A0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"; // Invalid witness program, more than 2 stack items: lockingScriptStrings[10] = "A9148EB812176C9E71732584123DD06D3246E659B19987"; unlockingScriptStrings[10] = "2300205A0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F51"; for (int i = 0; i < lockingScriptStrings.length; ++i) { final String lockingScriptString = lockingScriptStrings[i]; final String unlockingScriptString = unlockingScriptStrings[i]; final LockingScript lockingScript = new MutableLockingScript(ByteArray.fromHexString(lockingScriptString)); final UnlockingScript unlockingScript = new MutableUnlockingScript(ByteArray.fromHexString(unlockingScriptString)); // Action final Boolean outputIsUnlocked = scriptRunner.runScript(lockingScript, unlockingScript, context); // Assert Assert.assertFalse(outputIsUnlocked); } } @Test public void should_validate_large_value_for_decode_number() { // Setup // "0x10 0x0102030405060708090A0B0C0D0E0F10 DUP CAT DUP CAT DUP CAT DUP CAT DUP CAT 0x08 0x0102030405060708 CAT 520" // "NUM2BIN 0x10 0x0102030405060708090A0B0C0D0E0F10 DUP CAT DUP CAT DUP CAT DUP CAT DUP CAT 0x08 0x0102030405060708 CAT EQUAL" final ScriptInflater scriptInflater = new ScriptInflater(); final UnlockingScript unlockingScript = UnlockingScript.castFrom(scriptInflater.fromBytes(ByteArray.fromHexString("100102030405060708090A0B0C0D0E0F10767E767E767E767E767E0801020304050607087E020802"))); final LockingScript lockingScript = LockingScript.castFrom(scriptInflater.fromBytes(ByteArray.fromHexString("80100102030405060708090A0B0C0D0E0F10767E767E767E767E767E0801020304050607087E87"))); final MutableMedianBlockTime medianBlockTime = new MutableMedianBlockTime(); final MutableTransactionContext context = new MutableTransactionContext(); context.setBlockHeight(0L); context.setMedianBlockTime(medianBlockTime); final ScriptRunner scriptRunner = new ScriptRunner(); // Action final Boolean isValid = scriptRunner.runScript(lockingScript, unlockingScript, context); // Assert Assert.assertTrue(isValid); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/SlpScriptType.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.util.Util; public enum SlpScriptType { GENESIS ("47454E45534953"), SEND ("53454E44"), MINT ("4D494E54"), COMMIT ("434F4D4D4954"); public static final ByteArray LOKAD_ID = ByteArray.fromHexString("534C5000"); public static final ByteArray TOKEN_TYPE = ByteArray.fromHexString("01"); public static SlpScriptType fromBytes(final ByteArray byteArray) { for (final SlpScriptType slpScriptType : SlpScriptType.values()) { if (Util.areEqual(slpScriptType.getBytes(), byteArray)) { return slpScriptType; } } return null; } protected final ByteArray _value; SlpScriptType(final String value) { _value = ByteArray.fromHexString(value); } public ByteArray getBytes() { return _value; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/SlpScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp; public interface SlpScript { SlpScriptType getType(); Integer getMinimumTransactionOutputCount(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/configuration/CheckpointConfiguration.java<|end_filename|> package com.softwareverde.bitcoin.server.configuration; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.Util; import java.util.HashMap; public class CheckpointConfiguration { protected final HashMap<Long, Sha256Hash> _checkpoints = new HashMap<Long, Sha256Hash>(); public CheckpointConfiguration() { _checkpoints.put(11111L, Sha256Hash.fromHexString("0000000069E244F73D78E8FD29BA2FD2ED618BD6FA2EE92559F542FDB26E7C1D")); _checkpoints.put(33333L, Sha256Hash.fromHexString("000000002DD5588A74784EAA7AB0507A18AD16A236E7B1CE69F00D7DDFB5D0A6")); _checkpoints.put(74000L, Sha256Hash.fromHexString("0000000000573993A3C9E41CE34471C079DCF5F52A0E824A81E7F953B8661A20")); _checkpoints.put(105000L, Sha256Hash.fromHexString("00000000000291CE28027FAEA320C8D2B054B2E0FE44A773F3EEFB151D6BDC97")); _checkpoints.put(134444L, Sha256Hash.fromHexString("00000000000005B12FFD4CD315CD34FFD4A594F430AC814C91184A0D42D2B0FE")); _checkpoints.put(168000L, Sha256Hash.fromHexString("000000000000099E61EA72015E79632F216FE6CB33D7899ACB35B75C8303B763")); _checkpoints.put(193000L, Sha256Hash.fromHexString("000000000000059F452A5F7340DE6682A977387C17010FF6E6C3BD83CA8B1317")); _checkpoints.put(210000L, Sha256Hash.fromHexString("000000000000048B95347E83192F69CF0366076336C639F9B7228E9BA171342E")); _checkpoints.put(216116L, Sha256Hash.fromHexString("00000000000001B4F4B433E81EE46494AF945CF96014816A4E2370F11B23DF4E")); _checkpoints.put(225430L, Sha256Hash.fromHexString("00000000000001C108384350F74090433E7FCF79A606B8E797F065B130575932")); _checkpoints.put(250000L, Sha256Hash.fromHexString("000000000000003887DF1F29024B06FC2200B55F8AF8F35453D7BE294DF2D214")); _checkpoints.put(279000L, Sha256Hash.fromHexString("0000000000000001AE8C72A0B0C301F67E3AFCA10E819EFA9041E458E9BD7E40")); _checkpoints.put(295000L, Sha256Hash.fromHexString("00000000000000004D9B4EF50F0F9D686FD69DB2E03AF35A100370C64632A983")); _checkpoints.put(478558L, Sha256Hash.fromHexString("0000000000000000011865AF4122FE3B144E2CBEEA86142E8FF2FB4107352D43")); _checkpoints.put(504031L, Sha256Hash.fromHexString("0000000000000000011EBF65B60D0A3DE80B8175BE709D653B4C1A1BEEB6AB9C")); _checkpoints.put(530359L, Sha256Hash.fromHexString("0000000000000000011ADA8BD08F46074F44A8F155396F43E38ACF9501C49103")); _checkpoints.put(556767L, Sha256Hash.fromHexString("0000000000000000004626FF6E3B936941D341C5932ECE4357EECCAC44E6D56C")); _checkpoints.put(582680L, Sha256Hash.fromHexString("000000000000000001B4B8E36AEC7D4F9671A47872CB9A74DC16CA398C7DCC18")); _checkpoints.put(609136L, Sha256Hash.fromHexString("000000000000000000B48BB207FAAC5AC655C313E41AC909322EAA694F5BC5B1")); _checkpoints.put(635259L, Sha256Hash.fromHexString("00000000000000000033DFEF1FC2D6A5D5520B078C55193A9BF498C5B27530F7")); } public Boolean violatesCheckpoint(final Long blockHeight, final Sha256Hash blockHash) { final Sha256Hash requiredBlockHash = _checkpoints.get(blockHeight); if (requiredBlockHash == null) { return false; } // Not a checkpoint block... return (! Util.areEqual(requiredBlockHash, blockHash)); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/node/pong/BitcoinPongMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.node.pong; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.util.bytearray.ByteArrayReader; import com.softwareverde.util.bytearray.Endian; public class BitcoinPongMessageInflater extends BitcoinProtocolMessageInflater { @Override public BitcoinPongMessage fromBytes(final byte[] bytes) { final BitcoinPongMessage pingMessage = new BitcoinPongMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.PONG); if (protocolMessageHeader == null) { return null; } pingMessage._nonce = byteArrayReader.readLong(8, Endian.LITTLE); if (byteArrayReader.didOverflow()) { return null; } return pingMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/opcode/NothingOperation.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode; import com.softwareverde.bitcoin.transaction.script.runner.ControlState; import com.softwareverde.bitcoin.transaction.script.runner.context.MutableTransactionContext; import com.softwareverde.bitcoin.transaction.script.stack.Stack; import com.softwareverde.logging.Logger; import com.softwareverde.util.bytearray.ByteArrayReader; public class NothingOperation extends SubTypedOperation { public static final Type TYPE = Type.OP_NOTHING; protected static NothingOperation fromBytes(final ByteArrayReader byteArrayReader) { if (! byteArrayReader.hasBytes()) { return null; } final byte opcodeByte = byteArrayReader.readByte(); final Type type = Type.getType(opcodeByte); if (type != TYPE) { return null; } final Opcode opcode = TYPE.getSubtype(opcodeByte); if (opcode == null) { return null; } return new NothingOperation(opcodeByte, opcode); } protected NothingOperation(final byte value, final Opcode opcode) { super(value, TYPE, opcode); } @Override public Boolean applyTo(final Stack stack, final ControlState controlState, final MutableTransactionContext context) { if (! _opcode.isEnabled()) { Logger.debug("NOTICE: Opcode is disabled: " + _opcode); return false; } return true; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/main/SystemMemoryStatus.java<|end_filename|> package com.softwareverde.bitcoin.server.main; import com.softwareverde.bitcoin.server.memory.MemoryStatus; import com.softwareverde.logging.Logger; import com.sun.management.OperatingSystemMXBean; import java.lang.management.ManagementFactory; public class SystemMemoryStatus implements MemoryStatus { protected final OperatingSystemMXBean _operatingSystem; protected Long _calculateUsedMemory() { // In Bytes... if (_operatingSystem == null) { return 0L; } return (_operatingSystem.getTotalPhysicalMemorySize() - _operatingSystem.getFreePhysicalMemorySize()); } protected Long _calculateMaxMemory() { // In Bytes... if (_operatingSystem == null) { return 0L; } return _operatingSystem.getTotalPhysicalMemorySize(); } public SystemMemoryStatus() { final java.lang.management.OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); _operatingSystem = ( (operatingSystemMXBean instanceof OperatingSystemMXBean) ? (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean() : null ); } @Override public Long getByteCountAvailable() { return (_calculateMaxMemory() - _calculateUsedMemory()); } @Override public Long getByteCountUsed() { return _calculateUsedMemory(); } /** * Returns a value between 0 and 1 representing the percentage of memory used within the JVM. */ @Override public Float getMemoryUsedPercent() { final Long maxMemory = _calculateMaxMemory(); final Long usedMemory = _calculateUsedMemory(); if (usedMemory == 0L) { return 1.0F; } return (usedMemory.floatValue() / maxMemory.floatValue()); } @Override public void logCurrentMemoryUsage() { Logger.info("Current System Memory Usage : " + _operatingSystem.getFreePhysicalMemorySize() + " bytes | MAX=" + _calculateMaxMemory()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/runner/ScriptRunner.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.runner; import com.softwareverde.bitcoin.bip.Bip16; import com.softwareverde.bitcoin.bip.HF20181115; import com.softwareverde.bitcoin.bip.HF20190515; import com.softwareverde.bitcoin.transaction.script.ImmutableScript; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.bitcoin.transaction.script.ScriptPatternMatcher; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.opcode.Operation; import com.softwareverde.bitcoin.transaction.script.runner.context.MutableTransactionContext; import com.softwareverde.bitcoin.transaction.script.runner.context.TransactionContext; import com.softwareverde.bitcoin.transaction.script.stack.Stack; import com.softwareverde.bitcoin.transaction.script.stack.Value; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.constable.list.List; import com.softwareverde.logging.Logger; /** * NOTE: It seems that all values within Bitcoin Core scripts are stored as little-endian. * To remain consistent with the rest of this library, all values are converted from little-endian * to big-endian for all internal (in-memory) purposes, and then reverted to little-endian when stored. * * NOTE: All Operation Math and Values appear to be injected into the script as 4-byte integers. */ public class ScriptRunner { public static final Integer MAX_SCRIPT_BYTE_COUNT = 10000; protected static final Boolean BITCOIN_ABC_QUIRK_ENABLED = true; public ScriptRunner() { } public Boolean runScript(final LockingScript lockingScript, final UnlockingScript unlockingScript, final TransactionContext transactionContext) { final MutableTransactionContext mutableContext = new MutableTransactionContext(transactionContext); final ControlState controlState = new ControlState(); if (lockingScript.getByteCount() > MAX_SCRIPT_BYTE_COUNT) { return false; } if (unlockingScript.getByteCount() > MAX_SCRIPT_BYTE_COUNT) { return false; } final Stack traditionalStack; final Stack payToScriptHashStack; { // Normal Script-Validation... traditionalStack = new Stack(); traditionalStack.setMaxItemCount(1000); try { final List<Operation> unlockingScriptOperations = unlockingScript.getOperations(); if (unlockingScriptOperations == null) { return false; } if (HF20181115.isEnabled(transactionContext.getBlockHeight())) { final Boolean unlockingScriptContainsNonPushOperations = unlockingScript.containsNonPushOperations(); if (unlockingScriptContainsNonPushOperations) { return false; } // Only push operations are allowed in the unlocking script. (BIP 62) } mutableContext.setCurrentScript(unlockingScript); for (final Operation operation : unlockingScriptOperations) { mutableContext.incrementCurrentScriptIndex(); if (operation.failIfPresent()) { return false; } final Boolean shouldExecute = operation.shouldExecute(traditionalStack, controlState, mutableContext); if (! shouldExecute) { continue; } final Boolean wasSuccessful = operation.applyTo(traditionalStack, controlState, mutableContext); if (! wasSuccessful) { return false; } } if (controlState.isInCodeBlock()) { return false; } // IF/ELSE blocks cannot span scripts. traditionalStack.clearAltStack(); // Clear the alt stack for the unlocking script, and for the payToScriptHash script... payToScriptHashStack = new Stack(traditionalStack); final List<Operation> lockingScriptOperations = lockingScript.getOperations(); if (lockingScriptOperations == null) { return false; } mutableContext.setCurrentScript(lockingScript); for (final Operation operation : lockingScriptOperations) { mutableContext.incrementCurrentScriptIndex(); if (operation.failIfPresent()) { return false; } final Boolean shouldExecute = operation.shouldExecute(traditionalStack, controlState, mutableContext); if (! shouldExecute) { continue; } final Boolean wasSuccessful = operation.applyTo(traditionalStack, controlState, mutableContext); if (! wasSuccessful) { return false; } } } catch (final Exception exception) { Logger.warn(exception); return false; } { // Validate Stack... if (traditionalStack.didOverflow()) { return false; } if (traditionalStack.isEmpty()) { return false; } final Value topStackValue = traditionalStack.pop(); if (! topStackValue.asBoolean()) { return false; } } } final boolean shouldRunPayToScriptHashScript; { // Pay-To-Script-Hash Validation final Boolean payToScriptHashValidationRulesAreEnabled = Bip16.isEnabled(mutableContext.getBlockHeight()); final Boolean scriptIsPayToScriptHash = (lockingScript.getScriptType() == ScriptType.PAY_TO_SCRIPT_HASH); if (BITCOIN_ABC_QUIRK_ENABLED) { // NOTE: Bitcoin ABC's 0.19 behavior does not run P2SH Scripts that match the Segwit format... final ScriptPatternMatcher scriptPatternMatcher = new ScriptPatternMatcher(); final Boolean unlockingScriptIsSegregatedWitnessProgram = scriptPatternMatcher.matchesSegregatedWitnessProgram(unlockingScript); shouldRunPayToScriptHashScript = ( payToScriptHashValidationRulesAreEnabled && scriptIsPayToScriptHash && (! unlockingScriptIsSegregatedWitnessProgram) ); } else { shouldRunPayToScriptHashScript = ( payToScriptHashValidationRulesAreEnabled && scriptIsPayToScriptHash ); } if (shouldRunPayToScriptHashScript) { final Boolean unlockingScriptContainsNonPushOperations = unlockingScript.containsNonPushOperations(); if (unlockingScriptContainsNonPushOperations) { return false; } try { final Value redeemScriptValue = payToScriptHashStack.pop(); if (payToScriptHashStack.didOverflow()) { return false; } final Script redeemScript = new ImmutableScript(redeemScriptValue); mutableContext.setCurrentScript(redeemScript); final List<Operation> redeemScriptOperations = redeemScript.getOperations(); if (redeemScriptOperations == null) { return false; } for (final Operation operation : redeemScriptOperations) { mutableContext.incrementCurrentScriptIndex(); if (operation.failIfPresent()) { return false; } final Boolean shouldExecute = operation.shouldExecute(payToScriptHashStack, controlState, mutableContext); if (! shouldExecute) { continue; } final Boolean wasSuccessful = operation.applyTo(payToScriptHashStack, controlState, mutableContext); if (! wasSuccessful) { return false; } } } catch (final Exception exception) { Logger.warn(exception); return false; } { // Validate P2SH Stack... if (payToScriptHashStack.isEmpty()) { return false; } final Value topStackValue = payToScriptHashStack.pop(); if (! topStackValue.asBoolean()) { return false; } } } } if (controlState.isInCodeBlock()) { return false; } // All CodeBlocks must be closed before the end of the script... // Dirty stacks are considered invalid after HF20181115 in order to reduce malleability... if (HF20181115.isEnabled(transactionContext.getBlockHeight())) { final Stack stack = (shouldRunPayToScriptHashScript ? payToScriptHashStack : traditionalStack); if (! stack.isEmpty()) { if (HF20190515.isEnabled(transactionContext.getMedianBlockTime())) { final ScriptPatternMatcher scriptPatternMatcher = new ScriptPatternMatcher(); final Boolean unlockingScriptIsSegregatedWitnessProgram = scriptPatternMatcher.matchesSegregatedWitnessProgram(unlockingScript); if (! (shouldRunPayToScriptHashScript && unlockingScriptIsSegregatedWitnessProgram)) { return false; } } else { return false; } } } return true; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/database/FakeMedianBlockTimeWithBlocks.java<|end_filename|> package com.softwareverde.bitcoin.test.fake.database; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.chain.time.ImmutableMedianBlockTime; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.chain.time.MedianBlockTimeWithBlocks; import com.softwareverde.bitcoin.chain.time.MutableMedianBlockTimeTests; public class FakeMedianBlockTimeWithBlocks implements MedianBlockTimeWithBlocks { @Override public MedianBlockTime subset(final Integer blockCount) { return MedianBlockTime.MAX_VALUE; } @Override public BlockHeader getBlockHeader(final Integer indexFromTip) { return new MutableMedianBlockTimeTests.FakeBlockHeader(Long.MAX_VALUE); } @Override public ImmutableMedianBlockTime asConst() { return MedianBlockTime.MAX_VALUE; } @Override public Long getCurrentTimeInSeconds() { return Long.MAX_VALUE; } @Override public Long getCurrentTimeInMilliSeconds() { return Long.MAX_VALUE; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/chain/BlockchainDatabaseManagerTests2.java<|end_filename|> package com.softwareverde.bitcoin.chain; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockHasher; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.server.module.node.database.block.BlockRelationship; import com.softwareverde.bitcoin.server.module.node.database.block.fullnode.FullNodeBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.test.BlockData; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.util.HexUtil; import com.softwareverde.util.Util; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.Random; // NOTE: These tests were back-ported from DocChain... public class BlockchainDatabaseManagerTests2 extends IntegrationTest { @Override @Before public void before() throws Exception { super.before(); final BlockInflater blockInflater = new BlockInflater(); try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final FullNodeBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final Block genesisBlock = blockInflater.fromBytes(HexUtil.hexStringToByteArray(BlockData.MainChain.GENESIS_BLOCK)); if (! Util.areEqual(BlockHeader.GENESIS_BLOCK_HASH, genesisBlock.getHash())) { throw new RuntimeException("Error inflating Genesis Block."); } synchronized (BlockHeaderDatabaseManager.MUTEX) { blockDatabaseManager.insertBlock(genesisBlock); } } } @After public void after() throws Exception { super.after(); } private Sha256Hash _insertTestBlocks(final Sha256Hash startingHash, final int blockCount) throws DatabaseException { try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final FullNodeBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final Random random = new Random(); Sha256Hash hash = ((startingHash == null) ? BlockHeader.GENESIS_BLOCK_HASH : startingHash); final BlockHasher blockHasher = new BlockHasher(); final BlockInflater blockInflater = new BlockInflater(); final Block genesisBlock = blockInflater.fromBytes(HexUtil.hexStringToByteArray(BlockData.MainChain.GENESIS_BLOCK)); for (int i = 0; i < blockCount; i++) { final byte[] nonceBytes = new byte[4]; random.nextBytes(nonceBytes); final MutableBlock block = new MutableBlock(); block.setPreviousBlockHash(hash); block.setVersion(1L); block.setTimestamp((long) i+100); block.setNonce(ByteUtil.bytesToLong(nonceBytes)); block.setDifficulty(Difficulty.BASE_DIFFICULTY); block.addTransaction(genesisBlock.getCoinbaseTransaction()); synchronized (BlockHeaderDatabaseManager.MUTEX) { blockDatabaseManager.insertBlock(block); } hash = blockHasher.calculateBlockHash(block); } // return final hash return hash; } } private Sha256Hash _insertTestBlocks(final int blockCount) throws DatabaseException { return _insertTestBlocks(null, blockCount); } @Test public void should_return_timestamp_of_14th_ancestor_relative_to_current_block_with_16_blocks_on_one_chain() throws DatabaseException { // Setup final Sha256Hash headHash = _insertTestBlocks(16); // Action long timestamp = -1; try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockId headHashId = blockHeaderDatabaseManager.getBlockHeaderId(headHash); final BlockId ancestorBlockId = blockHeaderDatabaseManager.getAncestorBlockId(headHashId, 15); final BlockHeader ancestorBlockHeader = blockHeaderDatabaseManager.getBlockHeader(ancestorBlockId); timestamp = ancestorBlockHeader.getTimestamp(); } // Test Assert.assertEquals(timestamp, 100); // (100 + 0) (since the 16th ancestor will be the first block and the block timestamp is in milliseconds) } @Test public void should_return_timestamp_of_current_block_for_0th_ancestor_with_16_blocks_on_one_chain() throws DatabaseException { // Setup final Sha256Hash headHash = _insertTestBlocks(16); // Action long timestamp = -1; try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockId headHashId = blockHeaderDatabaseManager.getBlockHeaderId(headHash); final BlockId ancestorBlockId = blockHeaderDatabaseManager.getAncestorBlockId(headHashId, 0); final BlockHeader ancestorBlockHeader = blockHeaderDatabaseManager.getBlockHeader(ancestorBlockId); timestamp = ancestorBlockHeader.getTimestamp(); } // Test Assert.assertEquals(timestamp, 115); // (100 + 15) (since the 0th ancestor will be the 16th/final block and the block timestamp is in milliseconds) } @Test public void should_return_timestamp_of_100th_ancestor_with_200_blocks_on_one_chain() throws DatabaseException { // Setup final Sha256Hash headHash = _insertTestBlocks(200); // Action long timestamp = -1; try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockId headHashId = blockHeaderDatabaseManager.getBlockHeaderId(headHash); final BlockId ancestorBlockId = blockHeaderDatabaseManager.getAncestorBlockId(headHashId, 100); final BlockHeader ancestorBlockHeader = blockHeaderDatabaseManager.getBlockHeader(ancestorBlockId); timestamp = ancestorBlockHeader.getTimestamp(); } // Test Assert.assertEquals(timestamp, 199); // (100 + 99) (since the 100th ancestor will be the 99th block and the block timestamp is in milliseconds) } @Test public void should_create_fork() throws DatabaseException { // Setup final Sha256Hash forkStartHash = _insertTestBlocks(10); final Sha256Hash fork1Hash = _insertTestBlocks(forkStartHash, 4); final Sha256Hash fork2Hash = _insertTestBlocks(forkStartHash, 3); // Action try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockId fork1Id = blockHeaderDatabaseManager.getBlockHeaderId(fork1Hash); final BlockchainSegmentId fork1SegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(fork1Id); final BlockId fork2Id = blockHeaderDatabaseManager.getBlockHeaderId(fork2Hash); final BlockchainSegmentId fork2SegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(fork2Id); final BlockId forkStartId = blockHeaderDatabaseManager.getBlockHeaderId(forkStartHash); final BlockchainSegmentId forkStartSegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(forkStartId); // final BlockchainSegment forkStartBlockchainSegment = blockchainDatabaseManager.getBlockchainSegment(forkStartSegmentId); // final BlockchainSegment fork1BlockchainSegment = blockchainDatabaseManager.getBlockchainSegment(fork1SegmentId); // final BlockchainSegment fork2BlockchainSegment = blockchainDatabaseManager.getBlockchainSegment(fork2SegmentId); // Test Assert.assertNotEquals(fork1SegmentId, fork2SegmentId); // Assert.assertEquals(10, forkStartBlockchainSegment.getBlockHeight().longValue()); // Assert.assertEquals(4, fork1BlockchainSegment.getBlockHeight().longValue()); // Assert.assertEquals(3, fork2BlockchainSegment.getBlockHeight().longValue()); } } @Test public void should_correctly_report_connected_and_unconnected_blockchain_segments() throws DatabaseException { // Setup final Sha256Hash forkStartHash1 = _insertTestBlocks(10); final Sha256Hash fork1Hash = _insertTestBlocks(forkStartHash1, 10); final Sha256Hash fork2Hash = _insertTestBlocks(forkStartHash1, 10); final Sha256Hash forkStartHash2 = _insertTestBlocks(fork2Hash, 10); final Sha256Hash fork3Hash = _insertTestBlocks(forkStartHash2, 10); final Sha256Hash fork4Hash = _insertTestBlocks(forkStartHash2, 10); // Action try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockchainDatabaseManager blockchainDatabaseManager = databaseManager.getBlockchainDatabaseManager(); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockId forkStartId1 = blockHeaderDatabaseManager.getBlockHeaderId(forkStartHash1); final BlockchainSegmentId forkStart1SegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(forkStartId1); final BlockId fork1Id = blockHeaderDatabaseManager.getBlockHeaderId(fork1Hash); final BlockchainSegmentId fork1SegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(fork1Id); final BlockId fork2Id = blockHeaderDatabaseManager.getBlockHeaderId(fork2Hash); final BlockchainSegmentId fork2SegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(fork2Id); final BlockId forkStartId2 = blockHeaderDatabaseManager.getBlockHeaderId(forkStartHash2); final BlockchainSegmentId forkStart2SegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(forkStartId2); final BlockId fork3Id = blockHeaderDatabaseManager.getBlockHeaderId(fork3Hash); final BlockchainSegmentId fork3SegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(fork3Id); final BlockId fork4Id = blockHeaderDatabaseManager.getBlockHeaderId(fork4Hash); final BlockchainSegmentId fork4SegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(fork4Id); // Test // all are connected to fork start 1 Assert.assertTrue(blockchainDatabaseManager.areBlockchainSegmentsConnected(forkStart1SegmentId, fork1SegmentId, BlockRelationship.ANY)); Assert.assertTrue(blockchainDatabaseManager.areBlockchainSegmentsConnected(forkStart1SegmentId, fork2SegmentId, BlockRelationship.ANY)); Assert.assertTrue(blockchainDatabaseManager.areBlockchainSegmentsConnected(forkStart1SegmentId, fork3SegmentId, BlockRelationship.ANY)); Assert.assertTrue(blockchainDatabaseManager.areBlockchainSegmentsConnected(forkStart1SegmentId, fork4SegmentId, BlockRelationship.ANY)); // fork 1 and fork 2 are not connected to each other Assert.assertFalse(blockchainDatabaseManager.areBlockchainSegmentsConnected(fork1SegmentId, fork2SegmentId, BlockRelationship.ANY)); // fork 3 and fork 4 are connected to fork start 2 and fork 2 Assert.assertTrue(blockchainDatabaseManager.areBlockchainSegmentsConnected(forkStart2SegmentId, fork3SegmentId, BlockRelationship.ANY)); Assert.assertTrue(blockchainDatabaseManager.areBlockchainSegmentsConnected(forkStart2SegmentId, fork4SegmentId, BlockRelationship.ANY)); Assert.assertTrue(blockchainDatabaseManager.areBlockchainSegmentsConnected(fork2SegmentId, fork3SegmentId, BlockRelationship.ANY)); Assert.assertTrue(blockchainDatabaseManager.areBlockchainSegmentsConnected(fork2SegmentId, fork4SegmentId, BlockRelationship.ANY)); // fork 3 and fork 4 are not connected to each other, nor fork 1 Assert.assertFalse(blockchainDatabaseManager.areBlockchainSegmentsConnected(fork3SegmentId, fork4SegmentId, BlockRelationship.ANY)); Assert.assertFalse(blockchainDatabaseManager.areBlockchainSegmentsConnected(fork1SegmentId, fork3SegmentId, BlockRelationship.ANY)); Assert.assertFalse(blockchainDatabaseManager.areBlockchainSegmentsConnected(fork1SegmentId, fork4SegmentId, BlockRelationship.ANY)); } } } <|start_filename|>src/main/java/com/softwareverde/network/p2p/message/type/NodeIpAddressMessage.java<|end_filename|> package com.softwareverde.network.p2p.message.type; import com.softwareverde.constable.list.List; import com.softwareverde.network.p2p.message.ProtocolMessage; import com.softwareverde.network.p2p.node.address.NodeIpAddress; public interface NodeIpAddressMessage extends ProtocolMessage { List<NodeIpAddress> getNodeIpAddresses(); void addAddress(NodeIpAddress nodeIpAddress); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/miner/pool/WorkerId.java<|end_filename|> package com.softwareverde.bitcoin.miner.pool; import com.softwareverde.util.type.identifier.Identifier; public class WorkerId extends Identifier { public static WorkerId wrap(final Long value) { if (value == null) { return null; } return new WorkerId(value); } protected WorkerId(final Long value) { super(value); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/node/fullnode/FullNodeBitcoinNodeDatabaseManagerCore.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.node.fullnode; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.query.BatchedInsertQuery; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.bitcoin.server.database.query.ValueExtractor; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.BlockRelationship; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.node.BitcoinNodeDatabaseManagerCore; import com.softwareverde.bitcoin.server.module.node.manager.FilterType; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.row.Row; import com.softwareverde.network.ip.Ip; import com.softwareverde.network.p2p.node.NodeId; import com.softwareverde.util.Util; import java.util.HashSet; public class FullNodeBitcoinNodeDatabaseManagerCore extends BitcoinNodeDatabaseManagerCore implements FullNodeBitcoinNodeDatabaseManager { public FullNodeBitcoinNodeDatabaseManagerCore(final DatabaseManager databaseManager) { super(databaseManager); } @Override public Boolean updateBlockInventory(final BitcoinNode node, final Long blockHeight, final Sha256Hash blockHash) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final Ip ip = node.getIp(); final Integer port = node.getPort(); final NodeId nodeId = _getNodeId(ip, port); if (nodeId == null) { return false; } java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id, head_block_height, head_block_hash FROM nodes WHERE id = ?") .setParameter(nodeId) ); if (rows.isEmpty()) { return false; } final Row row = rows.get(0); final Long headBlockHeight = row.getLong("head_block_height"); final Sha256Hash headBlockHash = Sha256Hash.wrap(row.getBytes("head_block_hash")); if (headBlockHeight > blockHeight) { return false; } if (Util.areEqual(headBlockHeight, blockHeight)) { if (Util.areEqual(headBlockHash, blockHash)) { return false; } } databaseConnection.executeSql( new Query("UPDATE nodes SET head_block_height = ?, head_block_hash = ? WHERE id = ?") .setParameter(blockHeight) .setParameter(blockHash) .setParameter(nodeId) ); return true; } @Override public void updateTransactionInventory(final BitcoinNode node, final List<Sha256Hash> transactionHashes) throws DatabaseException { if (transactionHashes.isEmpty()) { return; } final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final Ip ip = node.getIp(); final Integer port = node.getPort(); final NodeId nodeId = _getNodeId(ip, port); if (nodeId == null) { return; } final BatchedInsertQuery batchedInsertQuery = new BatchedInsertQuery("INSERT IGNORE INTO node_transactions_inventory (node_id, hash) VALUES (?, ?)"); for (final Sha256Hash transactionHash : transactionHashes) { batchedInsertQuery.setParameter(nodeId); batchedInsertQuery.setParameter(transactionHash); } databaseConnection.executeSql(batchedInsertQuery); } @Override public List<NodeId> filterNodesViaTransactionInventory(final List<NodeId> nodeIds, final Sha256Hash transactionHash, final FilterType filterType) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT node_id FROM node_transactions_inventory WHERE hash = ? AND node_id IN (?)") .setParameter(transactionHash) .setInClauseParameters(nodeIds, ValueExtractor.IDENTIFIER) ); final HashSet<NodeId> filteredNodes = new HashSet<NodeId>(rows.size()); if (filterType == FilterType.KEEP_NODES_WITHOUT_INVENTORY) { for (final NodeId nodeId : nodeIds) { filteredNodes.add(nodeId); } } for (final Row row : rows) { final NodeId nodeWithTransaction = NodeId.wrap(row.getLong("node_id")); if (filterType == FilterType.KEEP_NODES_WITHOUT_INVENTORY) { filteredNodes.remove(nodeWithTransaction); } else { filteredNodes.add(nodeWithTransaction); } } return new ImmutableList<NodeId>(filteredNodes); } @Override public List<NodeId> filterNodesViaBlockInventory(final List<NodeId> nodeIds, final Sha256Hash blockHash, final FilterType filterType) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id, head_block_height, head_block_hash FROM nodes WHERE id IN (?)") .setInClauseParameters(nodeIds, ValueExtractor.IDENTIFIER) ); // TODO: Check for blockchain node feature... final HashSet<NodeId> filteredNodes = new HashSet<NodeId>(rows.size()); final BlockchainDatabaseManager blockchainDatabaseManager = _databaseManager.getBlockchainDatabaseManager(); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = _databaseManager.getBlockHeaderDatabaseManager(); final BlockId blockId = blockHeaderDatabaseManager.getBlockHeaderId(blockHash); final Long blockHeight = blockHeaderDatabaseManager.getBlockHeight(blockId); final BlockchainSegmentId blockchainSegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(blockId); for (final Row row : rows) { final NodeId nodeId = NodeId.wrap(row.getLong("id")); final Long nodeBlockHeight = row.getLong("head_block_height"); final Sha256Hash nodeBlockHash = Sha256Hash.wrap(row.getBytes("head_block_hash")); final BlockId nodeBlockId = blockHeaderDatabaseManager.getBlockHeaderId(nodeBlockHash); final BlockchainSegmentId nodeBlockchainSegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(nodeBlockId); final Boolean nodeIsOnSameBlockchain = (blockchainDatabaseManager.areBlockchainSegmentsConnected(blockchainSegmentId, nodeBlockchainSegmentId, BlockRelationship.ANY)); final boolean nodeHasBlock = ((nodeBlockHeight >= blockHeight) && nodeIsOnSameBlockchain); // TODO: Nodes that diverged after the desired blockHeight could still serve the block... if (filterType == FilterType.KEEP_NODES_WITH_INVENTORY) { if (nodeHasBlock) { filteredNodes.add(nodeId); } } else if (filterType == FilterType.KEEP_NODES_WITHOUT_INVENTORY) { if (! nodeHasBlock) { filteredNodes.add(nodeId); } } } return new ImmutableList<NodeId>(filteredNodes); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/core/BlockchainBuilderContext.java<|end_filename|> package com.softwareverde.bitcoin.context.core; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.manager.BitcoinNodeManager; import com.softwareverde.bitcoin.server.module.node.sync.BlockchainBuilder; import com.softwareverde.concurrent.pool.ThreadPool; public class BlockchainBuilderContext implements BlockchainBuilder.Context { protected final BlockInflaters _blockInflaters; protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; protected final BitcoinNodeManager _nodeManager; protected final ThreadPool _threadPool; public BlockchainBuilderContext(final BlockInflaters blockInflaters, final FullNodeDatabaseManagerFactory databaseManagerFactory, final BitcoinNodeManager bitcoinNodeManager, final ThreadPool threadPool) { _blockInflaters = blockInflaters; _databaseManagerFactory = databaseManagerFactory; _nodeManager = bitcoinNodeManager; _threadPool = threadPool; } @Override public FullNodeDatabaseManagerFactory getDatabaseManagerFactory() { return _databaseManagerFactory; } @Override public BitcoinNodeManager getBitcoinNodeManager() { return _nodeManager; } @Override public ThreadPool getThreadPool() { return _threadPool; } @Override public BlockInflater getBlockInflater() { return _blockInflaters.getBlockInflater(); } @Override public BlockDeflater getBlockDeflater() { return _blockInflaters.getBlockDeflater(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/ReadUncommittedRawConnectionConfigurer.java<|end_filename|> package com.softwareverde.bitcoin.server.database; import com.softwareverde.database.DatabaseException; import java.sql.Connection; import java.sql.SQLException; public class ReadUncommittedRawConnectionConfigurer implements ReadUncommittedDatabaseConnectionConfigurer { @Override public void setReadUncommittedTransactionIsolationLevel(final DatabaseConnection databaseConnection) throws DatabaseException { // databaseConnection.executeSql("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED", null); try { final Connection rawConnection = databaseConnection.getRawConnection(); rawConnection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); } catch (final SQLException exception) { throw new DatabaseException(exception); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/task/StratumUtil.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.task; public class StratumUtil { protected static String _createByteString(final char a, final char b) { return String.valueOf(a) + b; } public static String swabHexString(final String input) { // 00 01 02 03 | 04 05 06 07 -> 03 02 01 00 | 07 06 05 04 final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < (input.length() / 8); ++i) { final int index = (i * 8); final String byteString0 = _createByteString(input.charAt(index + 0), input.charAt(index + 1)); final String byteString1 = _createByteString(input.charAt(index + 2), input.charAt(index + 3)); final String byteString2 = _createByteString(input.charAt(index + 4), input.charAt(index + 5)); final String byteString3 = _createByteString(input.charAt(index + 6), input.charAt(index + 7)); stringBuilder.append(byteString3); stringBuilder.append(byteString2); stringBuilder.append(byteString1); stringBuilder.append(byteString0); } return stringBuilder.toString(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/configuration/StratumProperties.java<|end_filename|> package com.softwareverde.bitcoin.server.configuration; public class StratumProperties { public static final Integer PORT = 3333; public static final Integer RPC_PORT = 3334; public static final Integer HTTP_PORT = 8082; public static final Integer TLS_PORT = 4482; protected Integer _port; protected Integer _rpcPort; protected String _bitcoinRpcUrl; protected Integer _bitcoinRpcPort; protected Integer _httpPort; protected String _rootDirectory; protected Integer _tlsPort; protected String _tlsKeyFile; protected String _tlsCertificateFile; protected String _cookiesDirectory; public Integer getPort() { return _port; } public Integer getRpcPort() { return _rpcPort; } public String getBitcoinRpcUrl() { return _bitcoinRpcUrl; } public Integer getBitcoinRpcPort() { return _bitcoinRpcPort; } public Integer getHttpPort() { return _httpPort; } public String getRootDirectory() { return _rootDirectory; } public Integer getTlsPort() { return _tlsPort; } public String getTlsKeyFile() { return _tlsKeyFile; } public String getTlsCertificateFile() { return _tlsCertificateFile; } public String getCookiesDirectory() { return _cookiesDirectory; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/response/block/header/BlockHeadersMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response.block.header; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.block.header.BlockHeaderWithTransactionCountInflater; import com.softwareverde.bitcoin.inflater.ExtendedBlockHeaderInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.server.message.type.request.header.RequestBlockHeadersMessage; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.logging.Logger; public class BlockHeadersMessageInflater extends BitcoinProtocolMessageInflater { protected final ExtendedBlockHeaderInflaters _blockHeaderInflaters; public BlockHeadersMessageInflater(final ExtendedBlockHeaderInflaters blockHeaderInflaters) { _blockHeaderInflaters = blockHeaderInflaters; } @Override public BlockHeadersMessage fromBytes(final byte[] bytes) { final BlockHeadersMessage blockHeadersResponseMessage = new BlockHeadersMessage(_blockHeaderInflaters); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.BLOCK_HEADERS); if (protocolMessageHeader == null) { return null; } final Integer blockHeaderCount = byteArrayReader.readVariableSizedInteger().intValue(); if (blockHeaderCount > RequestBlockHeadersMessage.MAX_BLOCK_HEADER_HASH_COUNT) { Logger.debug("Block Header Count Exceeded: " + blockHeaderCount); return null; } final Integer bytesRequired = ( blockHeaderCount * (BlockHeaderInflater.BLOCK_HEADER_BYTE_COUNT + 1) ); if (byteArrayReader.remainingByteCount() < bytesRequired) { return null; } final BlockHeaderWithTransactionCountInflater blockHeaderInflater = _blockHeaderInflaters.getBlockHeaderWithTransactionCountInflater(); // NOTE: The BlockHeaders message always appends a zero variable-sized-integer to represent the TransactionCount. for (int i = 0; i < blockHeaderCount; ++i) { final BlockHeader blockHeader = blockHeaderInflater.fromBytes(byteArrayReader); if (blockHeader == null) { return null; } blockHeadersResponseMessage._blockHeaders.add(blockHeader); } if (byteArrayReader.didOverflow()) { return null; } return blockHeadersResponseMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/inflater/ExtendedBlockHeaderInflaters.java<|end_filename|> package com.softwareverde.bitcoin.inflater; import com.softwareverde.bitcoin.block.header.BlockHeaderWithTransactionCountInflater; public interface ExtendedBlockHeaderInflaters extends BlockHeaderInflaters { BlockHeaderWithTransactionCountInflater getBlockHeaderWithTransactionCountInflater(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/signature/hashtype/Mode.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.signature.hashtype; // NOTE: Arbitrary (non-standard) HashType Modes are permitted. // https://bitcoin.stackexchange.com/questions/38971/op-checksig-signature-hash-type-0 public enum Mode { SIGNATURE_HASH_ALL((byte) 0x01), SIGNATURE_HASH_NONE((byte) 0x02), SIGNATURE_HASH_SINGLE((byte) 0x03); public static final byte USED_BITS_MASK = (byte) 0x03; // Bitmask containing the range of bits used to determine the Mode. public static Mode fromByte(final byte value) { final byte valueMask = 0x0F; switch (value & valueMask) { case 0x01: { return SIGNATURE_HASH_ALL; } case 0x02: { return SIGNATURE_HASH_NONE; } case 0x03: { return SIGNATURE_HASH_SINGLE; } default: { return null; } } } private final byte _value; Mode(final byte value) { _value = value; } public byte getValue() { return _value; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/chain/time/MutableMedianBlockTimeTests.java<|end_filename|> package com.softwareverde.bitcoin.chain.time; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.MutableBlockHeader; import org.junit.Assert; import org.junit.Test; public class MutableMedianBlockTimeTests { public static class FakeBlockHeader extends MutableBlockHeader { private final Long _timestamp; public FakeBlockHeader(final Long timestamp) { _timestamp = timestamp; } @Override public Long getTimestamp() { return _timestamp; } } @Test public void should_create_valid_subset_from_the_most_recent_blocks() { // Setup final MutableMedianBlockTime medianBlockTime = new MutableMedianBlockTime(); for (int i = 0; i < 12; ++i) { medianBlockTime.addBlock(new FakeBlockHeader((long) i)); } // Action final MedianBlockTime subsetMedianBlockTime = medianBlockTime.subset(1); // Assert Assert.assertEquals(11L, subsetMedianBlockTime.getCurrentTimeInSeconds().longValue()); } @Test public void should_create_valid_subset_from_the_most_recent_blocks_2() { // Setup final MutableMedianBlockTime medianBlockTime = new MutableMedianBlockTime(); for (int i = 0; i < 11; ++i) { medianBlockTime.addBlock(new FakeBlockHeader((long) i)); } // Action final MedianBlockTime subsetMedianBlockTime = medianBlockTime.subset(5); // Assert Assert.assertEquals(8L, subsetMedianBlockTime.getCurrentTimeInSeconds().longValue()); } @Test public void should_create_valid_subset_from_the_most_recent_blocks_3() { // Setup final MutableMedianBlockTime medianBlockTime = new MutableMedianBlockTime(); for (int i = 0; i < 11; ++i) { medianBlockTime.addBlock(new FakeBlockHeader(11L - i)); } // Action final MedianBlockTime subsetMedianBlockTime = medianBlockTime.subset(5); // Assert Assert.assertEquals(3L, subsetMedianBlockTime.getCurrentTimeInSeconds().longValue()); } @Test public void getBlockHeader_should_return_the_most_recent_block_for_index_0() { // Setup final MutableMedianBlockTime medianBlockTime = new MutableMedianBlockTime(); for (int i = 0; i < 11; ++i) { medianBlockTime.addBlock(new FakeBlockHeader((long) i)); } // Action final BlockHeader blockHeader = medianBlockTime.getBlockHeader(0); // Assert Assert.assertEquals(10L, blockHeader.getTimestamp().longValue()); } @Test public void getBlockHeader_should_return_the_most_recent_block_for_index_11() { // Setup final MutableMedianBlockTime medianBlockTime = new MutableMedianBlockTime(); for (int i = 0; i < 11; ++i) { medianBlockTime.addBlock(new FakeBlockHeader((long) i)); } // Action final BlockHeader blockHeader = medianBlockTime.getBlockHeader(10); // Assert Assert.assertEquals(0L, blockHeader.getTimestamp().longValue()); } @Test public void should_create_valid_subset_from_the_most_recent_blocks_when_more_blocks_have_been_added_than_max_capacity() { // Setup final MutableMedianBlockTime medianBlockTime = new MutableMedianBlockTime(); for (int i = 0; i < 100; ++i) { medianBlockTime.addBlock(new FakeBlockHeader((long) i)); } // Action final Long medianBlockTimeInSeconds = medianBlockTime.getCurrentTimeInSeconds(); // Assert // 99 98 97 96 95 | 94 | 93 92 91 90 89 Assert.assertEquals(94L, medianBlockTimeInSeconds.longValue()); } } <|start_filename|>src/test/java/com/softwareverde/test/database/MysqlTestDatabase.java<|end_filename|> package com.softwareverde.test.database; import com.softwareverde.bitcoin.server.database.pool.DatabaseConnectionPool; import com.softwareverde.bitcoin.server.database.pool.hikari.HikariDatabaseConnectionPool; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.mysql.MysqlDatabase; import com.softwareverde.database.mysql.MysqlDatabaseConnection; import com.softwareverde.database.mysql.MysqlDatabaseConnectionFactory; import com.softwareverde.database.mysql.embedded.vorburger.DB; import com.softwareverde.database.mysql.embedded.vorburger.DBConfiguration; import com.softwareverde.database.mysql.embedded.vorburger.DatabaseConfigurationBuilder; import com.softwareverde.database.properties.DatabaseCredentials; import com.softwareverde.database.properties.DatabaseProperties; import com.softwareverde.database.properties.MutableDatabaseProperties; public class MysqlTestDatabase extends MysqlDatabase { protected final DB _databaseInstance; protected final MysqlDatabaseConnectionFactory _databaseConnectionFactory; protected final DatabaseCredentials _credentials; protected final String _host; protected final Integer _port; protected final String _rootUsername = "root"; protected final String _rootPassword = ""; protected final String _databaseSchema = "bitcoin_test"; protected DatabaseProperties _getDatabaseProperties() { final MutableDatabaseProperties databaseProperties = new MutableDatabaseProperties(); databaseProperties.setHostname(_host); databaseProperties.setPort(_port); databaseProperties.setSchema(_schema); databaseProperties.setPassword(_password); databaseProperties.setUsername(_username); return databaseProperties; } public MysqlTestDatabase() { super(null, null, null, null); final DBConfiguration dbConfiguration; { final DatabaseConfigurationBuilder configBuilder = DatabaseConfigurationBuilder.newBuilder(); dbConfiguration = configBuilder.build(); _host = "localhost"; _port = configBuilder.getPort(); _databaseConnectionFactory = new MysqlDatabaseConnectionFactory(_host, _port, _databaseSchema, _rootUsername, _rootPassword); } { try { _databaseInstance = DB.newEmbeddedDB(dbConfiguration); _databaseInstance.start(); _databaseInstance.createDB(_databaseSchema); } catch (final Exception exception) { throw new RuntimeException(exception); } } _credentials = new DatabaseCredentials(_rootUsername, _rootPassword); } @Override public MysqlDatabaseConnection newConnection() throws DatabaseException { try { return _databaseConnectionFactory.newConnection(); } catch (final Exception exception) { throw new DatabaseException("Unable to connect to database.", exception); } } public void reset() throws DatabaseException { _databaseInstance.run("DROP DATABASE "+ _databaseSchema, _rootUsername, _rootPassword); _databaseInstance.createDB(_databaseSchema); } public DB getDatabaseInstance() { return _databaseInstance; } public DatabaseCredentials getCredentials() { return _credentials; } public MysqlDatabaseConnectionFactory getDatabaseConnectionFactory() { return _databaseConnectionFactory; } public DatabaseConnectionPool getDatabaseConnectionPool() { return new HikariDatabaseConnectionPool(_getDatabaseProperties()); } public DatabaseProperties getDatabaseProperties() { return _getDatabaseProperties(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/node/pong/BitcoinPongMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.node.pong; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.network.p2p.message.type.PongMessage; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class BitcoinPongMessage extends BitcoinProtocolMessage implements PongMessage { protected Long _nonce; public BitcoinPongMessage() { super(MessageType.PONG); _nonce = (long) (Math.random() * Long.MAX_VALUE); } public void setNonce(final Long nonce) { _nonce = nonce; } @Override public Long getNonce() { return _nonce; } @Override protected ByteArray _getPayload() { final byte[] nonce = new byte[8]; ByteUtil.setBytes(nonce, ByteUtil.longToBytes(_nonce)); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(nonce, Endian.LITTLE); return byteArrayBuilder; } @Override protected Integer _getPayloadByteCount() { return 8; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/database/FakeDatabaseConnection.java<|end_filename|> package com.softwareverde.bitcoin.test.fake.database; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.row.Row; import java.sql.Connection; public interface FakeDatabaseConnection extends DatabaseConnection { @Override default Integer getRowsAffectedCount() { throw new UnsupportedOperationException(); } @Override default void executeDdl(String query) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default void executeDdl(com.softwareverde.database.query.Query query) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default Long executeSql(String query, String[] parameters) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default Long executeSql(com.softwareverde.database.query.Query query) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default java.util.List<Row> query(String query, String[] parameters) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default java.util.List<Row> query(com.softwareverde.database.query.Query query) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default void close() throws DatabaseException { } @Override default Connection getRawConnection() { throw new UnsupportedOperationException(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/fullnode/FullNodeDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.fullnode; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.inflater.MasterInflater; import com.softwareverde.bitcoin.server.configuration.CheckpointConfiguration; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.fullnode.FullNodeBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.fullnode.FullNodeBlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.pending.fullnode.FullNodePendingBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManagerCore; import com.softwareverde.bitcoin.server.module.node.database.indexer.BlockchainIndexerDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.indexer.BlockchainIndexerDatabaseManagerCore; import com.softwareverde.bitcoin.server.module.node.database.node.fullnode.FullNodeBitcoinNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.node.fullnode.FullNodeBitcoinNodeDatabaseManagerCore; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.FullNodeTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.FullNodeTransactionDatabaseManagerCore; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.input.UnconfirmedTransactionInputDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.output.UnconfirmedTransactionOutputDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.UnspentTransactionOutputDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.UnspentTransactionOutputJvmManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.pending.PendingTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.slp.SlpTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.slp.SlpTransactionDatabaseManagerCore; import com.softwareverde.bitcoin.server.module.node.store.PendingBlockStore; import com.softwareverde.database.DatabaseException; public class FullNodeDatabaseManager implements DatabaseManager { protected final DatabaseConnection _databaseConnection; protected final Integer _maxQueryBatchSize; protected final PendingBlockStore _blockStore; protected final MasterInflater _masterInflater; protected final Long _maxUtxoCount; protected final Float _utxoPurgePercent; protected final CheckpointConfiguration _checkpointConfiguration; protected FullNodeBitcoinNodeDatabaseManager _nodeDatabaseManager; protected BlockchainDatabaseManagerCore _blockchainDatabaseManager; protected FullNodeBlockDatabaseManager _blockDatabaseManager; protected FullNodeBlockHeaderDatabaseManager _blockHeaderDatabaseManager; protected FullNodePendingBlockDatabaseManager _pendingBlockDatabaseManager; protected BlockchainIndexerDatabaseManager _blockchainIndexerDatabaseManager; protected FullNodeTransactionDatabaseManager _transactionDatabaseManager; protected UnconfirmedTransactionInputDatabaseManager _unconfirmedTransactionInputDatabaseManager; protected UnconfirmedTransactionOutputDatabaseManager _unconfirmedTransactionOutputDatabaseManager; protected PendingTransactionDatabaseManager _pendingTransactionDatabaseManager; protected SlpTransactionDatabaseManager _slpTransactionDatabaseManager; protected UnspentTransactionOutputDatabaseManager _unspentTransactionOutputDatabaseManager; public FullNodeDatabaseManager(final DatabaseConnection databaseConnection, final Integer maxQueryBatchSize, final PendingBlockStore blockStore, final MasterInflater masterInflater, final CheckpointConfiguration checkpointConfiguration) { this(databaseConnection, maxQueryBatchSize, blockStore, masterInflater, checkpointConfiguration, UnspentTransactionOutputDatabaseManager.DEFAULT_MAX_UTXO_CACHE_COUNT, UnspentTransactionOutputDatabaseManager.DEFAULT_PURGE_PERCENT); } public FullNodeDatabaseManager(final DatabaseConnection databaseConnection, final Integer maxQueryBatchSize, final PendingBlockStore blockStore, final MasterInflater masterInflater, final CheckpointConfiguration checkpointConfiguration, final Long maxUtxoCount, final Float utxoPurgePercent) { _databaseConnection = databaseConnection; _maxQueryBatchSize = maxQueryBatchSize; _blockStore = blockStore; _masterInflater = masterInflater; _maxUtxoCount = maxUtxoCount; _utxoPurgePercent = utxoPurgePercent; _checkpointConfiguration = checkpointConfiguration; } @Override public DatabaseConnection getDatabaseConnection() { return _databaseConnection; } @Override public FullNodeBitcoinNodeDatabaseManager getNodeDatabaseManager() { if (_nodeDatabaseManager == null) { _nodeDatabaseManager = new FullNodeBitcoinNodeDatabaseManagerCore(this); } return _nodeDatabaseManager; } @Override public BlockchainDatabaseManagerCore getBlockchainDatabaseManager() { if (_blockchainDatabaseManager == null) { _blockchainDatabaseManager = new BlockchainDatabaseManagerCore(this); } return _blockchainDatabaseManager; } @Override public FullNodeBlockDatabaseManager getBlockDatabaseManager() { if (_blockDatabaseManager == null) { _blockDatabaseManager = new FullNodeBlockDatabaseManager(this, _blockStore); } return _blockDatabaseManager; } @Override public FullNodeBlockHeaderDatabaseManager getBlockHeaderDatabaseManager() { if (_blockHeaderDatabaseManager == null) { _blockHeaderDatabaseManager = new FullNodeBlockHeaderDatabaseManager(this, _checkpointConfiguration); } return _blockHeaderDatabaseManager; } public FullNodePendingBlockDatabaseManager getPendingBlockDatabaseManager() { if (_pendingBlockDatabaseManager == null) { _pendingBlockDatabaseManager = new FullNodePendingBlockDatabaseManager(this, _blockStore); } return _pendingBlockDatabaseManager; } @Override public FullNodeTransactionDatabaseManager getTransactionDatabaseManager() { if (_transactionDatabaseManager == null) { _transactionDatabaseManager = new FullNodeTransactionDatabaseManagerCore(this, _blockStore, _masterInflater); } return _transactionDatabaseManager; } @Override public Integer getMaxQueryBatchSize() { return _maxQueryBatchSize; } public BlockchainIndexerDatabaseManager getBlockchainIndexerDatabaseManager() { if (_blockchainIndexerDatabaseManager == null) { final AddressInflater addressInflater = _masterInflater.getAddressInflater(); _blockchainIndexerDatabaseManager = new BlockchainIndexerDatabaseManagerCore(addressInflater, this); } return _blockchainIndexerDatabaseManager; } public UnconfirmedTransactionInputDatabaseManager getUnconfirmedTransactionInputDatabaseManager() { if (_unconfirmedTransactionInputDatabaseManager == null) { _unconfirmedTransactionInputDatabaseManager = new UnconfirmedTransactionInputDatabaseManager(this); } return _unconfirmedTransactionInputDatabaseManager; } public UnconfirmedTransactionOutputDatabaseManager getUnconfirmedTransactionOutputDatabaseManager() { if (_unconfirmedTransactionOutputDatabaseManager == null) { _unconfirmedTransactionOutputDatabaseManager = new UnconfirmedTransactionOutputDatabaseManager(this); } return _unconfirmedTransactionOutputDatabaseManager; } public PendingTransactionDatabaseManager getPendingTransactionDatabaseManager() { if (_pendingTransactionDatabaseManager == null) { _pendingTransactionDatabaseManager = new PendingTransactionDatabaseManager(this); } return _pendingTransactionDatabaseManager; } public SlpTransactionDatabaseManager getSlpTransactionDatabaseManager() { if (_slpTransactionDatabaseManager == null) { _slpTransactionDatabaseManager = new SlpTransactionDatabaseManagerCore(this); } return _slpTransactionDatabaseManager; } public UnspentTransactionOutputDatabaseManager getUnspentTransactionOutputDatabaseManager() { if (_unspentTransactionOutputDatabaseManager == null) { _unspentTransactionOutputDatabaseManager = new UnspentTransactionOutputJvmManager(_maxUtxoCount, _utxoPurgePercent, this, _blockStore, _masterInflater); } return _unspentTransactionOutputDatabaseManager; } @Override public void close() throws DatabaseException { _databaseConnection.close(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/response/block/merkle/MerkleBlockMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response.block.merkle; import com.softwareverde.bitcoin.block.MerkleBlock; import com.softwareverde.bitcoin.block.header.BlockHeaderDeflater; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.block.header.BlockHeaderWithTransactionCount; import com.softwareverde.bitcoin.block.merkleroot.PartialMerkleTree; import com.softwareverde.bitcoin.block.merkleroot.PartialMerkleTreeDeflater; import com.softwareverde.bitcoin.inflater.BlockHeaderInflaters; import com.softwareverde.bitcoin.inflater.MerkleTreeInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.util.bytearray.ByteArrayBuilder; public class MerkleBlockMessage extends BitcoinProtocolMessage { protected final BlockHeaderInflaters _blockHeaderInflaters; protected final MerkleTreeInflaters _merkleTreeInflaters; protected BlockHeaderWithTransactionCount _blockHeader; protected PartialMerkleTree _partialMerkleTree; public MerkleBlockMessage(final BlockHeaderInflaters blockHeaderInflaters, final MerkleTreeInflaters merkleTreeInflaters) { super(MessageType.MERKLE_BLOCK); _blockHeaderInflaters = blockHeaderInflaters; _merkleTreeInflaters = merkleTreeInflaters; } public BlockHeaderWithTransactionCount getBlockHeader() { return _blockHeader; } public PartialMerkleTree getPartialMerkleTree() { return _partialMerkleTree; } public MerkleBlock getMerkleBlock() { if ( (_blockHeader == null) || (_partialMerkleTree == null) ) { return null; } return new MerkleBlock(_blockHeader, _partialMerkleTree); } public void setBlockHeader(final BlockHeaderWithTransactionCount blockHeader) { _blockHeader = blockHeader; } public void setPartialMerkleTree(final PartialMerkleTree partialMerkleTree) { _partialMerkleTree = partialMerkleTree; } @Override protected ByteArray _getPayload() { final BlockHeaderDeflater blockHeaderDeflater = _blockHeaderInflaters.getBlockHeaderDeflater(); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(blockHeaderDeflater.toBytes(_blockHeader)); // NOTE: TransactionCount is handled by the PartialMerkleTreeDeflater... // byteArrayBuilder.appendBytes(ByteUtil.integerToBytes(_blockHeader.getTransactionCount()), Endian.LITTLE); final PartialMerkleTreeDeflater partialMerkleTreeDeflater = _merkleTreeInflaters.getPartialMerkleTreeDeflater(); final ByteArray partialMerkleTreeBytes = partialMerkleTreeDeflater.toBytes(_partialMerkleTree); byteArrayBuilder.appendBytes(partialMerkleTreeBytes); return byteArrayBuilder; } @Override protected Integer _getPayloadByteCount() { final PartialMerkleTreeDeflater partialMerkleTreeDeflater = _merkleTreeInflaters.getPartialMerkleTreeDeflater(); final Integer partialMerkleTreeByteCount = partialMerkleTreeDeflater.getByteCount(_partialMerkleTree); return (BlockHeaderInflater.BLOCK_HEADER_BYTE_COUNT + partialMerkleTreeByteCount); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/send/SlpSendScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp.send; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.transaction.script.slp.SlpScript; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptType; import com.softwareverde.constable.Constable; public interface SlpSendScript extends SlpScript, Constable<ImmutableSlpSendScript> { Integer MAX_OUTPUT_COUNT = 20; SlpTokenId getTokenId(); Long getAmount(Integer transactionOutputIndex); Long getTotalAmount(); } abstract class SlpSendScriptCore implements SlpSendScript { protected SlpTokenId _tokenId; protected final Long[] _amounts = new Long[MAX_OUTPUT_COUNT]; public SlpSendScriptCore() { } public SlpSendScriptCore(final SlpSendScript slpSendScript) { _tokenId = slpSendScript.getTokenId().asConst(); for (int i = 0; i < MAX_OUTPUT_COUNT; ++i) { _amounts[i] = slpSendScript.getAmount(i); } } @Override public SlpScriptType getType() { return SlpScriptType.SEND; } @Override public Integer getMinimumTransactionOutputCount() { int tokenOutputCount = 0; for (int i = 0; i < MAX_OUTPUT_COUNT; ++i) { final Long amount = _amounts[i]; if (amount == null) { break; } tokenOutputCount += 1; } return (tokenOutputCount + 1); // Requires the number of outputs specified in the SpendScript and one for the Script itself. } @Override public SlpTokenId getTokenId() { return _tokenId; } @Override public Long getAmount(final Integer transactionOutputIndex) { if (transactionOutputIndex >= MAX_OUTPUT_COUNT) { return null; } if (transactionOutputIndex < 0) { throw new IndexOutOfBoundsException(); } if (transactionOutputIndex == 0) { return null; } return _amounts[transactionOutputIndex]; } @Override public Long getTotalAmount() { long totalAmount = 0L; for (int i = 0; i < MAX_OUTPUT_COUNT; ++i) { final Long amount = _amounts[i]; if (amount == null) { continue; } totalAmount += amount; } return totalAmount; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/account/CreateAccountApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account; import com.softwareverde.bitcoin.miner.pool.AccountId; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiEndpoint; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.bitcoin.server.module.stratum.database.AccountDatabaseManager; import com.softwareverde.database.DatabaseException; import com.softwareverde.http.HttpMethod; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.json.Json; import com.softwareverde.logging.Logger; import com.softwareverde.servlet.session.Session; public class CreateAccountApi extends StratumApiEndpoint { public static final Integer MIN_PASSWORD_LENGTH = 8; protected final DatabaseConnectionFactory _databaseConnectionFactory; public CreateAccountApi(final StratumProperties stratumProperties, final DatabaseConnectionFactory databaseConnectionFactory) { super(stratumProperties); _databaseConnectionFactory = databaseConnectionFactory; } @Override protected Response _onRequest(final Request request) { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); if (request.getMethod() != HttpMethod.POST) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid method.")); } { // CREATE ACCOUNT // Requires GET: // Requires POST: email, password final String email = postParameters.get("email").trim(); if (email.isEmpty()) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid email address.")); } final String password = postParameters.get("password"); if (password.length() < MIN_PASSWORD_LENGTH) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid password length.")); } try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { final AccountDatabaseManager accountDatabaseManager = new AccountDatabaseManager(databaseConnection); { // Check for existing account... final AccountId accountId = accountDatabaseManager.getAccountId(email); if (accountId != null) { return new JsonResponse(Response.Codes.OK, new StratumApiResult(false, "An account with that email address already exists.")); } } final AccountId accountId = accountDatabaseManager.createAccount(email, password); if (accountId == null) { return new JsonResponse(Response.Codes.SERVER_ERROR, new StratumApiResult(false, "Unable to create account.")); } final Response response = new JsonResponse(Response.Codes.OK, new StratumApiResult(true, null)); final Session session = _sessionManager.createSession(request, response); final Json sessionData = session.getMutableData(); sessionData.put("accountId", accountId); _sessionManager.saveSession(session); return response; } catch (final DatabaseException exception) { Logger.warn(exception); return new JsonResponse(Response.Codes.SERVER_ERROR, new StratumApiResult(false, "An internal error occurred.")); } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/BitcoinBinaryPacketFormat.java<|end_filename|> package com.softwareverde.bitcoin.server.message; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeaderInflater; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.network.socket.BinaryPacketFormat; public class BitcoinBinaryPacketFormat extends BinaryPacketFormat { public BitcoinBinaryPacketFormat(final ByteArray magicNumber, final BitcoinProtocolMessageHeaderInflater protocolMessageHeaderInflater, final BitcoinProtocolMessageFactory protocolMessageFactory) { super(magicNumber, protocolMessageHeaderInflater, protocolMessageFactory); } @Override public BitcoinProtocolMessageHeaderInflater getProtocolMessageHeaderInflater() { return (BitcoinProtocolMessageHeaderInflater) _protocolMessageHeaderInflater; } @Override public BitcoinProtocolMessageFactory getProtocolMessageFactory() { return (BitcoinProtocolMessageFactory) _protocolMessageFactory; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/core/TransactionProcessorContext.java<|end_filename|> package com.softwareverde.bitcoin.context.core; import com.softwareverde.bitcoin.context.TransactionValidatorFactory; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.sync.transaction.TransactionProcessor; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.validator.BlockOutputs; import com.softwareverde.bitcoin.transaction.validator.TransactionValidator; import com.softwareverde.network.time.VolatileNetworkTime; import com.softwareverde.util.type.time.SystemTime; public class TransactionProcessorContext implements TransactionProcessor.Context { protected final TransactionInflaters _transactionInflaters; protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; protected final VolatileNetworkTime _networkTime; protected final SystemTime _systemTime; protected final TransactionValidatorFactory _transactionValidatorFactory; public TransactionProcessorContext(final TransactionInflaters transactionInflaters, final FullNodeDatabaseManagerFactory databaseManagerFactory, final VolatileNetworkTime networkTime, final SystemTime systemTime, final TransactionValidatorFactory transactionValidatorFactory) { _transactionInflaters = transactionInflaters; _databaseManagerFactory = databaseManagerFactory; _networkTime = networkTime; _systemTime = systemTime; _transactionValidatorFactory = transactionValidatorFactory; } @Override public FullNodeDatabaseManagerFactory getDatabaseManagerFactory() { return _databaseManagerFactory; } @Override public VolatileNetworkTime getNetworkTime() { return _networkTime; } @Override public SystemTime getSystemTime() { return _systemTime; } @Override public TransactionValidator getTransactionValidator(final BlockOutputs blockOutputs, final TransactionValidator.Context transactionValidatorContext) { return _transactionValidatorFactory.getTransactionValidator(blockOutputs, transactionValidatorContext); } @Override public TransactionInflater getTransactionInflater() { return _transactionInflaters.getTransactionInflater(); } @Override public TransactionDeflater getTransactionDeflater() { return _transactionInflaters.getTransactionDeflater(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/NetworkTimeContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.network.time.VolatileNetworkTime; public interface NetworkTimeContext { VolatileNetworkTime getNetworkTime(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/task/StratumMineBlockTaskBuilder.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.task; public interface StratumMineBlockTaskBuilder { StratumMineBlockTask buildMineBlockTask(); } <|start_filename|>src/test/java/com/softwareverde/test/time/FakeSystemTime.java<|end_filename|> package com.softwareverde.test.time; import com.softwareverde.util.type.time.SystemTime; public class FakeSystemTime extends SystemTime { protected Long _timeMs = 0L; @Override public Long getCurrentTimeInSeconds() { return (_timeMs / 1_000L); } @Override public Long getCurrentTimeInMilliSeconds() { return _timeMs; } public void advanceTimeInMilliseconds(final Long milliseconds) { _timeMs += milliseconds; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/chain/time/ImmutableMedianBlockTime.java<|end_filename|> package com.softwareverde.bitcoin.chain.time; import com.softwareverde.constable.Const; public class ImmutableMedianBlockTime extends MedianBlockTimeCore implements MedianBlockTime, Const { public static ImmutableMedianBlockTime fromSeconds(final Long medianBlockTimeInSeconds) { return new ImmutableMedianBlockTime(medianBlockTimeInSeconds * 1000L); } public static ImmutableMedianBlockTime fromMilliseconds(final Long medianBlockTimeInMilliseconds) { return new ImmutableMedianBlockTime(medianBlockTimeInMilliseconds); } protected final Long _medianBlockTimeInMilliseconds; protected ImmutableMedianBlockTime(final Long medianBlockTimeInMilliseconds) { _medianBlockTimeInMilliseconds = medianBlockTimeInMilliseconds; } public ImmutableMedianBlockTime(final MedianBlockTime medianBlockTime) { _medianBlockTimeInMilliseconds = medianBlockTime.getCurrentTimeInMilliSeconds(); } @Override public Long getCurrentTimeInSeconds() { return (_medianBlockTimeInMilliseconds / 1000L); } @Override public Long getCurrentTimeInMilliSeconds() { return _medianBlockTimeInMilliseconds; } @Override public ImmutableMedianBlockTime asConst() { return this; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/database/node/BitcoinNodeDatabaseManagerTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.node; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.bitcoin.server.message.type.node.feature.LocalNodeFeatures; import com.softwareverde.bitcoin.server.message.type.node.feature.NodeFeatures; import com.softwareverde.bitcoin.server.message.type.version.synchronize.BitcoinSynchronizeVersionMessageInflater; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManagerFactory; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.concurrent.pool.MainThreadPool; import com.softwareverde.database.row.Row; import com.softwareverde.logging.Logger; import com.softwareverde.util.HexUtil; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class BitcoinNodeDatabaseManagerTests extends IntegrationTest { @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } public void _storeAndAssertNodeFeatures(final DatabaseManagerFactory databaseManagerFactory) throws Exception { // Setup final MainThreadPool mainThreadPool = new MainThreadPool(0, 1000L); final BitcoinNode bitcoinNode = new BitcoinNode("127.0.0.1", 8333, mainThreadPool, new LocalNodeFeatures() { @Override public NodeFeatures getNodeFeatures() { final NodeFeatures nodeFeatures = new NodeFeatures(); nodeFeatures.enableFeature(NodeFeatures.Feature.BITCOIN_CASH_ENABLED); return nodeFeatures; } }) {{ _synchronizeVersionMessage = (new BitcoinSynchronizeVersionMessageInflater(_masterInflater)).fromBytes(HexUtil.hexStringToByteArray("E3E1F3E876657273696F6E00000000006B0000006ACB57267F110100B50100000000000035F9AB5F00000000000000000000000000000000000000000000FFFF43954527F9F3000000000000000000000000000000000000FFFF00000000000000A8D9B1778B1A14152F426974636F696E2056657264653A312E342E302F5B160A0001")); }}; // Action try (final DatabaseManager databaseManager = databaseManagerFactory.newDatabaseManager()) { final BitcoinNodeDatabaseManager nodeDatabaseManager = databaseManager.getNodeDatabaseManager(); nodeDatabaseManager.storeNode(bitcoinNode); nodeDatabaseManager.updateLastHandshake(bitcoinNode); nodeDatabaseManager.updateNodeFeatures(bitcoinNode); nodeDatabaseManager.updateUserAgent(bitcoinNode); } catch (final Exception exception) { Logger.debug(exception); } final NodeFeatures storedFeatures = new NodeFeatures(); try (final DatabaseManager databaseManager = databaseManagerFactory.newDatabaseManager()) { final DatabaseConnection databaseConnection = databaseManager.getDatabaseConnection(); for (final Row row : databaseConnection.query(new Query("SELECT * FROM node_features"))) { final NodeFeatures.Feature nodeFeature = NodeFeatures.Feature.fromString(row.getString("feature")); if (nodeFeature != null) { storedFeatures.enableFeature(nodeFeature); } } } // Assert Assert.assertTrue(storedFeatures.isFeatureEnabled(NodeFeatures.Feature.BITCOIN_CASH_ENABLED)); Assert.assertTrue(storedFeatures.isFeatureEnabled(NodeFeatures.Feature.BLOCKCHAIN_ENABLED)); Assert.assertTrue(storedFeatures.isFeatureEnabled(NodeFeatures.Feature.BLOCKCHAIN_INDEX_ENABLED)); Assert.assertTrue(storedFeatures.isFeatureEnabled(NodeFeatures.Feature.BLOOM_CONNECTIONS_ENABLED)); Assert.assertTrue(storedFeatures.isFeatureEnabled(NodeFeatures.Feature.SLP_INDEX_ENABLED)); Assert.assertTrue(storedFeatures.isFeatureEnabled(NodeFeatures.Feature.XTHIN_PROTOCOL_ENABLED)); } @Test public void should_store_node_features_full_node() throws Exception { _storeAndAssertNodeFeatures(_fullNodeDatabaseManagerFactory); } @Test public void should_store_node_features_spv_node() throws Exception { _storeAndAssertNodeFeatures(_spvDatabaseManagerFactory); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/TransactionDeflater.java<|end_filename|> package com.softwareverde.bitcoin.transaction; import com.softwareverde.bitcoin.bytearray.FragmentedBytes; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.input.TransactionInputDeflater; import com.softwareverde.bitcoin.transaction.locktime.LockTime; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.TransactionOutputDeflater; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.json.Json; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class TransactionDeflater { protected void _toFragmentedBytes(final Transaction transaction, final ByteArrayBuilder headBytesBuilder, final ByteArrayBuilder tailBytesBuilder) { final byte[] versionBytes = new byte[4]; ByteUtil.setBytes(versionBytes, ByteUtil.integerToBytes(transaction.getVersion())); final byte[] lockTimeBytes = new byte[4]; final LockTime lockTime = transaction.getLockTime(); ByteUtil.setBytes(MutableByteArray.wrap(lockTimeBytes), lockTime.getBytes()); headBytesBuilder.appendBytes(versionBytes, Endian.LITTLE); final TransactionInputDeflater transactionInputDeflater = new TransactionInputDeflater(); final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); headBytesBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(transactionInputs.getCount()), Endian.BIG); int transactionInputIndex = 0; for (final TransactionInput transactionInput : transactionInputs) { if (transactionInputIndex == 0) { final FragmentedBytes fragmentedTransactionInputBytes = transactionInputDeflater.fragmentTransactionInput(transactionInput); headBytesBuilder.appendBytes(fragmentedTransactionInputBytes.headBytes, Endian.BIG); tailBytesBuilder.appendBytes(fragmentedTransactionInputBytes.tailBytes, Endian.BIG); } else { tailBytesBuilder.appendBytes(transactionInputDeflater.toBytes(transactionInput), Endian.BIG); } transactionInputIndex += 1; } final TransactionOutputDeflater transactionOutputDeflater = new TransactionOutputDeflater(); final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); tailBytesBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(transactionOutputs.getCount()), Endian.BIG); for (final TransactionOutput transactionOutput : transactionOutputs) { tailBytesBuilder.appendBytes(transactionOutputDeflater.toBytes(transactionOutput), Endian.BIG); } tailBytesBuilder.appendBytes(lockTimeBytes, Endian.LITTLE); } protected byte[] _toBytes(final Transaction transaction) { final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); _toFragmentedBytes(transaction, byteArrayBuilder, byteArrayBuilder); return byteArrayBuilder.build(); } public ByteArrayBuilder toByteArrayBuilder(final Transaction transaction) { final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); _toFragmentedBytes(transaction, byteArrayBuilder, byteArrayBuilder); return byteArrayBuilder; } public ByteArray toBytes(final Transaction transaction) { return MutableByteArray.wrap(_toBytes(transaction)); } public Integer getByteCount(final Transaction transaction) { final Integer versionByteCount = 4; final Integer transactionInputsByteCount; { final TransactionInputDeflater transactionInputDeflater = new TransactionInputDeflater(); Integer byteCount = 0; final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); byteCount += ByteUtil.variableLengthIntegerToBytes(transactionInputs.getCount()).length; for (final TransactionInput transactionInput : transactionInputs) { byteCount += transactionInputDeflater.getByteCount(transactionInput); } transactionInputsByteCount = byteCount; } final Integer transactionOutputsByteCount; { final TransactionOutputDeflater transactionOutputDeflater = new TransactionOutputDeflater(); Integer byteCount = 0; final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); byteCount += ByteUtil.variableLengthIntegerToBytes(transactionOutputs.getCount()).length; for (final TransactionOutput transactionOutput : transactionOutputs) { byteCount += transactionOutputDeflater.getByteCount(transactionOutput); } transactionOutputsByteCount = byteCount; } final Integer lockTimeByteCount = 4; return (versionByteCount + transactionInputsByteCount + transactionOutputsByteCount + lockTimeByteCount); } public FragmentedBytes fragmentTransaction(final Transaction transaction) { final ByteArrayBuilder headBytesBuilder = new ByteArrayBuilder(); final ByteArrayBuilder tailBytesBuilder = new ByteArrayBuilder(); _toFragmentedBytes(transaction, headBytesBuilder, tailBytesBuilder); return new FragmentedBytes(headBytesBuilder.build(), tailBytesBuilder.build()); } public Json toJson(final Transaction transaction) { final Json json = new Json(); json.put("version", transaction.getVersion()); json.put("hash", transaction.getHash()); final Json inputsJson = new Json(); for (final TransactionInput transactionInput : transaction.getTransactionInputs()) { inputsJson.add(transactionInput); } json.put("inputs", inputsJson); final Json outputsJson = new Json(); for (final TransactionOutput transactionOutput : transaction.getTransactionOutputs()) { outputsJson.add(transactionOutput); } json.put("outputs", outputsJson); json.put("lockTime", transaction.getLockTime()); // json.put("bytes", HexUtil.toHexString(_toBytes(transaction))); return json; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/ScriptBuilder.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.opcode.ComparisonOperation; import com.softwareverde.bitcoin.transaction.script.opcode.CryptographicOperation; import com.softwareverde.bitcoin.transaction.script.opcode.Opcode; import com.softwareverde.bitcoin.transaction.script.opcode.Operation; import com.softwareverde.bitcoin.transaction.script.opcode.PushOperation; import com.softwareverde.bitcoin.transaction.script.signature.ScriptSignature; import com.softwareverde.bitcoin.transaction.script.stack.Value; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.secp256k1.key.PublicKey; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.StringUtil; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class ScriptBuilder { protected static LockingScript _createPayToAddressScript(final Address address) { // TODO: Refactor to use ScriptBuilder (i.e. implement ScriptBuilder.pushOperation())... final byte[] addressBytes = address.getBytes(); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendByte(Opcode.COPY_1ST.getValue()); byteArrayBuilder.appendByte(Opcode.SHA_256_THEN_RIPEMD_160.getValue()); byteArrayBuilder.appendByte((byte) addressBytes.length); byteArrayBuilder.appendBytes(addressBytes, Endian.BIG); byteArrayBuilder.appendByte(Opcode.IS_EQUAL_THEN_VERIFY.getValue()); byteArrayBuilder.appendByte(Opcode.CHECK_SIGNATURE.getValue()); final ScriptInflater scriptInflater = new ScriptInflater(); return LockingScript.castFrom(scriptInflater.fromBytes(byteArrayBuilder.build())); } // NOTE: Also known as payToPublicKeyHash (or P2PKH)... public static LockingScript payToAddress(final String base58Address) { final AddressInflater addressInflater = new AddressInflater(); return _createPayToAddressScript(addressInflater.fromBase58Check(base58Address)); } public static LockingScript payToAddress(final Address base58Address) { return _createPayToAddressScript(base58Address); } public static UnlockingScript unlockPayToAddress(final ScriptSignature signature, final PublicKey publicKey) { final ScriptBuilder scriptBuilder = new ScriptBuilder(); scriptBuilder.pushSignature(signature); scriptBuilder.pushBytes(publicKey); return scriptBuilder.buildUnlockingScript(); } public static LockingScript payToScriptHash(final Script payToScript) { final ScriptBuilder scriptBuilder = new ScriptBuilder(); scriptBuilder.pushOperation(CryptographicOperation.SHA_256_THEN_RIPEMD_160); scriptBuilder.pushOperation(PushOperation.pushBytes(HashUtil.ripemd160(HashUtil.sha256(payToScript.getBytes())))); scriptBuilder.pushOperation(ComparisonOperation.IS_EQUAL); return scriptBuilder.buildLockingScript(); } protected void _pushBytes(final ByteArray bytes) { final Integer dataByteCount = bytes.getByteCount(); if (dataByteCount == 0) { // Nothing. } else if (dataByteCount <= Opcode.PUSH_DATA.getMaxValue()) { _byteArrayBuilder.appendByte((byte) (dataByteCount.intValue())); _byteArrayBuilder.appendBytes(bytes, Endian.BIG); } else if (dataByteCount <= 0xFFL) { _byteArrayBuilder.appendByte(Opcode.PUSH_DATA_BYTE.getValue()); _byteArrayBuilder.appendByte((byte) (dataByteCount.intValue())); _byteArrayBuilder.appendBytes(bytes, Endian.BIG); } else if (dataByteCount <= 0xFFFFL) { _byteArrayBuilder.appendByte(Opcode.PUSH_DATA_SHORT.getValue()); final byte[] dataDataByteCountBytes = ByteUtil.integerToBytes(dataByteCount); _byteArrayBuilder.appendBytes(new byte[] { dataDataByteCountBytes[3], dataDataByteCountBytes[4] }, Endian.LITTLE); _byteArrayBuilder.appendBytes(bytes, Endian.BIG); } else { _byteArrayBuilder.appendByte(Opcode.PUSH_DATA_INTEGER.getValue()); _byteArrayBuilder.appendBytes(ByteUtil.integerToBytes(dataByteCount), Endian.LITTLE); _byteArrayBuilder.appendBytes(bytes, Endian.BIG); } } protected final ByteArrayBuilder _byteArrayBuilder = new ByteArrayBuilder(); public ScriptBuilder pushString(final String stringData) { final Integer stringDataByteCount = stringData.length(); if (stringDataByteCount == 0) { // Nothing. } else if (stringDataByteCount <= Opcode.PUSH_DATA.getMaxValue()) { _byteArrayBuilder.appendByte((byte) (stringDataByteCount.intValue())); _byteArrayBuilder.appendBytes(StringUtil.stringToBytes(stringData), Endian.BIG); } else if (stringDataByteCount <= 0xFFL) { _byteArrayBuilder.appendByte(Opcode.PUSH_DATA_BYTE.getValue()); _byteArrayBuilder.appendByte((byte) (stringDataByteCount.intValue())); _byteArrayBuilder.appendBytes(StringUtil.stringToBytes(stringData), Endian.BIG); } else if (stringDataByteCount <= 0xFFFFL) { _byteArrayBuilder.appendByte(Opcode.PUSH_DATA_SHORT.getValue()); final byte[] stringDataByteCountBytes = ByteUtil.integerToBytes(stringDataByteCount); _byteArrayBuilder.appendBytes(new byte[] { stringDataByteCountBytes[3], stringDataByteCountBytes[4] }, Endian.LITTLE); _byteArrayBuilder.appendBytes(StringUtil.stringToBytes(stringData), Endian.BIG); } else { _byteArrayBuilder.appendByte(Opcode.PUSH_DATA_INTEGER.getValue()); _byteArrayBuilder.appendBytes(ByteUtil.integerToBytes(stringDataByteCount), Endian.LITTLE); _byteArrayBuilder.appendBytes(StringUtil.stringToBytes(stringData), Endian.BIG); } return this; } /** * Pushes the provided value on the stack as a number. The number is encoded as the shortest possible encoding. */ public ScriptBuilder pushInteger(final Long longValue) { final Value value = Value.fromInteger(longValue); _pushBytes(MutableByteArray.wrap(value.getBytes())); return this; } public ScriptBuilder pushBytes(final ByteArray bytes) { _pushBytes(bytes); return this; } public ScriptBuilder pushSignature(final ScriptSignature scriptSignature) { final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(scriptSignature.getSignature().encode()); byteArrayBuilder.appendByte(scriptSignature.getHashType().toByte()); _pushBytes(MutableByteArray.wrap(byteArrayBuilder.build())); return this; } public ScriptBuilder pushOperation(final Operation operation) { _byteArrayBuilder.appendBytes(operation.getBytes()); return this; } public Script build() { final ScriptInflater scriptInflater = new ScriptInflater(); return scriptInflater.fromBytes(_byteArrayBuilder.build()); } public UnlockingScript buildUnlockingScript() { final ScriptInflater scriptInflater = new ScriptInflater(); return UnlockingScript.castFrom(scriptInflater.fromBytes(_byteArrayBuilder.build())); } public LockingScript buildLockingScript() { final ScriptInflater scriptInflater = new ScriptInflater(); return LockingScript.castFrom(scriptInflater.fromBytes(_byteArrayBuilder.build())); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeSynchronizationStatus.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.server.State; import com.softwareverde.bitcoin.server.SynchronizationStatus; public class FakeSynchronizationStatus implements SynchronizationStatus { protected State _state = State.ONLINE; protected Long _currentBlockHeight = Long.MAX_VALUE; @Override public State getState() { return _state; } @Override public Boolean isBlockchainSynchronized() { return (_state == State.ONLINE); } @Override public Boolean isReadyForTransactions() { return (_state == State.ONLINE); } @Override public Boolean isShuttingDown() { return (_state == State.SHUTTING_DOWN); } @Override public Long getCurrentBlockHeight() { return _currentBlockHeight; } public void setState(final State state) { _state = state; } public void setCurrentBlockHeight(final Long currentBlockHeight) { _currentBlockHeight = currentBlockHeight; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/util/IoUtil.java<|end_filename|> package com.softwareverde.bitcoin.util; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.logging.Logger; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class IoUtil extends com.softwareverde.util.IoUtil { protected IoUtil() { } /** * Skips byteCount bytes within inputStream. * The number of bytes skipped is returned. If no bytes were skipped, then 0 is returned. * If byteCount is less than 1, 0 is returned. * This method is similar to InputStream::skip except that this function will not return until EOF is reached or byteCount bytes has been skipped. */ public static Long skipBytes(final Long byteCount, final InputStream inputStream) { if (byteCount < 1) { return 0L; } int numberOfTimesSkipReturnedZero = 0; long skippedByteCount = 0L; while (skippedByteCount < byteCount) { final long skipReturnValue; try { skipReturnValue = inputStream.skip(byteCount - skippedByteCount); } catch (final IOException exception) { break; } skippedByteCount += skipReturnValue; if (skipReturnValue == 0) { numberOfTimesSkipReturnedZero += 1; } else { numberOfTimesSkipReturnedZero = 0; } // InputStream::skip can sometimes return zero for "valid" reasons, but does not report EOF... // If skip returns zero 32 times (arbitrarily chosen), EOF is assumed... if (numberOfTimesSkipReturnedZero > 32) { break; } } return skippedByteCount; } public static Boolean fileExists(final String path) { final File file = new File(path); return file.exists(); } public static Boolean isEmpty(final String path) { final File file = new File(path); if (! file.exists()) { return true; } if (! file.isFile()) { return true; } return (file.length() < 1); } public static Boolean putFileContents(final String filename, final ByteArray bytes) { final File file = new File(filename); return IoUtil.putFileContents(file, bytes); } public static Boolean putFileContents(final File file, final ByteArray bytes) { final int pageSize = (16 * 1024); int bytesWritten = 0; int bytesRemaining = bytes.getByteCount(); try (final OutputStream outputStream = new FileOutputStream(file)) { while (bytesRemaining > 0) { final byte[] buffer = bytes.getBytes(bytesWritten, Math.min(pageSize, bytesRemaining)); outputStream.write(buffer); bytesWritten += buffer.length; bytesRemaining -= buffer.length; } outputStream.flush(); return true; } catch (final Exception exception) { Logger.warn("Unable to write file contents.", exception); return false; } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/request/header/RequestBlockHeadersMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.request.header; import com.softwareverde.bitcoin.server.main.BitcoinConstants; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class RequestBlockHeadersMessage extends BitcoinProtocolMessage { public static Integer MAX_BLOCK_HEADER_HASH_COUNT = 2000; // NOTE: This value is a "not-to-exceed"... protected Integer _version; protected final MutableList<Sha256Hash> _blockHashes = new MutableList<Sha256Hash>(); protected final MutableSha256Hash _stopBeforeBlockHash = new MutableSha256Hash(); public RequestBlockHeadersMessage() { super(MessageType.REQUEST_BLOCK_HEADERS); _version = BitcoinConstants.getProtocolVersion(); } public Integer getVersion() { return _version; } public void addBlockHash(final Sha256Hash blockHash) { if (_blockHashes.getCount() >= MAX_BLOCK_HEADER_HASH_COUNT) { return; } if (blockHash == null) { return; } _blockHashes.add(blockHash); } public void clearBlockHashes() { _blockHashes.clear(); } public List<Sha256Hash> getBlockHashes() { return _blockHashes; } public Sha256Hash getStopBeforeBlockHash() { return _stopBeforeBlockHash; } public void setStopBeforeBlockHash(final Sha256Hash blockHash) { if (blockHash == null) { _stopBeforeBlockHash.setBytes(Sha256Hash.EMPTY_HASH); return; } _stopBeforeBlockHash.setBytes(blockHash); } @Override protected ByteArray _getPayload() { final int blockHeaderCount = _blockHashes.getCount(); final int blockHashByteCount = Sha256Hash.BYTE_COUNT; final byte[] versionBytes = ByteUtil.integerToBytes(_version); final byte[] blockHeaderCountBytes = ByteUtil.variableLengthIntegerToBytes(blockHeaderCount); final byte[] blockHashesBytes = new byte[blockHashByteCount * blockHeaderCount]; for (int i = 0; i < blockHeaderCount; ++i) { final Sha256Hash blockHash = _blockHashes.get(i); final int startIndex = (blockHashByteCount * i); final ByteArray littleEndianBlockHash = blockHash.toReversedEndian(); ByteUtil.setBytes(blockHashesBytes, littleEndianBlockHash.getBytes(), startIndex); } final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(versionBytes, Endian.LITTLE); byteArrayBuilder.appendBytes(blockHeaderCountBytes, Endian.BIG); byteArrayBuilder.appendBytes(blockHashesBytes, Endian.BIG); byteArrayBuilder.appendBytes(_stopBeforeBlockHash, Endian.LITTLE); return byteArrayBuilder; } @Override protected Integer _getPayloadByteCount() { final int blockHeaderCount = _blockHashes.getCount(); final byte[] blockHeaderCountBytes = ByteUtil.variableLengthIntegerToBytes(blockHeaderCount); return (4 + blockHeaderCountBytes.length + (Sha256Hash.BYTE_COUNT * (blockHeaderCount + 1))); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/fullnode/utxo/jvm/UtxoKey.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.jvm; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.ByteArrayCore; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import java.util.Comparator; public class UtxoKey implements Comparable<UtxoKey> { public static final Comparator<UtxoKey> COMPARATOR = new Comparator<UtxoKey>() { @Override public int compare(final UtxoKey utxo0, final UtxoKey utxo1) { if (utxo0.transactionHash != utxo1.transactionHash) { for (int i = 0; i < Sha256Hash.BYTE_COUNT; ++i) { final byte b0 = utxo0.transactionHash[i]; final byte b1 = utxo1.transactionHash[i]; final int compare = Byte.compare(b0, b1); if (compare != 0) { return compare; } } } return Integer.compare(utxo0.outputIndex, utxo1.outputIndex); } }; public final byte[] transactionHash; public final int outputIndex; public UtxoKey(final TransactionOutputIdentifier transactionOutputIdentifier) { this( transactionOutputIdentifier.getTransactionHash().getBytes(), transactionOutputIdentifier.getOutputIndex() ); } public UtxoKey(final byte[] transactionHash, final int outputIndex) { this.transactionHash = transactionHash; this.outputIndex = outputIndex; } @Override public boolean equals(final Object obj) { if (! (obj instanceof UtxoKey)) { return false; } return (COMPARATOR.compare(this, (UtxoKey) obj) == 0); } @Override public int compareTo(final UtxoKey utxo) { return COMPARATOR.compare(this, utxo); } @Override public int hashCode() { return ByteArrayCore.hashCode(ByteArray.wrap(this.transactionHash)) + Integer.hashCode(this.outputIndex); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/output/UnconfirmedTransactionOutputId.java<|end_filename|> package com.softwareverde.bitcoin.transaction.output; import com.softwareverde.util.type.identifier.Identifier; public class UnconfirmedTransactionOutputId extends Identifier { public static UnconfirmedTransactionOutputId wrap(final Long value) { if (value == null) { return null; } return new UnconfirmedTransactionOutputId(value); } protected UnconfirmedTransactionOutputId(final Long value) { super(value); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/sync/block/pending/PendingBlockId.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync.block.pending; import com.softwareverde.util.type.identifier.Identifier; public class PendingBlockId extends Identifier { public static PendingBlockId wrap(final Long value) { if (value == null) { return null; } return new PendingBlockId(value); } protected PendingBlockId(final Long value) { super(value); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/merkleroot/MerkleRoot.java<|end_filename|> package com.softwareverde.bitcoin.merkleroot; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface MerkleRoot extends Sha256Hash { static MerkleRoot fromHexString(final String hexString) { return ImmutableMerkleRoot.fromHexString(hexString); } static MerkleRoot copyOf(final byte[] bytes) { return ImmutableMerkleRoot.copyOf(bytes); } static MerkleRoot wrap(final byte[] bytes) { return MutableMerkleRoot.wrap(bytes); } @Override ImmutableMerkleRoot asConst(); } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/script/runner/ControlStateTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.runner; import org.junit.Assert; import org.junit.Test; public class ControlStateTests { @Test public void should_execute_initially() { // Setup final ControlState controlState = new ControlState(); // Action final Boolean shouldExecute = controlState.shouldExecute(); // Assert Assert.assertTrue(shouldExecute); } @Test public void should_execute_if_in_true_if() { /* IF TRUE // Should execute... ENDIF */ // Setup final ControlState controlState = new ControlState(); controlState.enteredIfBlock(true); // Action final Boolean shouldExecute = controlState.shouldExecute(); // Assert Assert.assertTrue(shouldExecute); } @Test public void should_not_execute_if_in_false_if() { /* IF FALSE // ... ENDIF */ // Setup final ControlState controlState = new ControlState(); controlState.enteredIfBlock(false); // Action final Boolean shouldExecute = controlState.shouldExecute(); // Assert Assert.assertFalse(shouldExecute); } @Test public void should_execute_if_in_else() { /* IF FALSE // ... ELSE // Should execute... ENDIF */ // Setup final ControlState controlState = new ControlState(); controlState.enteredIfBlock(false); controlState.enteredElseBlock(); // Action final Boolean shouldExecute = controlState.shouldExecute(); // Assert Assert.assertTrue(shouldExecute); } @Test public void should_not_execute_nested_else_when_outer_condition_is_false() { /* IF FALSE IF FALSE // ... ELSE // ... ENDIF ENDIF */ // Setup final ControlState controlState = new ControlState(); controlState.enteredIfBlock(false); controlState.enteredIfBlock(false); // NOTE: This value should not matter... Assert.assertNull(controlState._codeBlock.condition); controlState.enteredElseBlock(); // Action final Boolean shouldExecute = controlState.shouldExecute(); // Assert Assert.assertFalse(shouldExecute); } @Test public void should_execute_nested_if_when_outer_condition_is_true() { /* IF TRUE IF TRUE // Should execute... ENDIF ENDIF */ // Setup final ControlState controlState = new ControlState(); controlState.enteredIfBlock(true); controlState.enteredIfBlock(true); // Action final Boolean shouldExecute = controlState.shouldExecute(); // Assert Assert.assertTrue(shouldExecute); } @Test public void should_execute_nested_else_when_outer_condition_is_true() { /* IF TRUE IF FALSE // ... ELSE // Should execute... ENDIF ENDIF */ // Setup final ControlState controlState = new ControlState(); controlState.enteredIfBlock(true); controlState.enteredIfBlock(false); controlState.enteredElseBlock(); // Action final Boolean shouldExecute = controlState.shouldExecute(); // Assert Assert.assertTrue(shouldExecute); } @Test public void should_not_execute_doubly_nested_if_when_super_outer_condition_is_false() { /* IF FALSE IF FALSE IF FALSE // ... ENDIF ENDIF ENDIF */ // Setup final ControlState controlState = new ControlState(); controlState.enteredIfBlock(false); controlState.enteredIfBlock(false); // NOTE: This value should not matter... controlState.enteredIfBlock(false); // NOTE: This value should not matter... // Action final Boolean shouldExecute = controlState.shouldExecute(); // Assert Assert.assertFalse(shouldExecute); } @Test public void should_not_execute_doubly_nested_else_when_super_outer_condition_is_false() { /* IF FALSE IF FALSE IF FALSE // ... ELSE // ... ENDIF ENDIF ENDIF */ // Setup final ControlState controlState = new ControlState(); controlState.enteredIfBlock(false); controlState.enteredIfBlock(false); // NOTE: This value should not matter... controlState.enteredIfBlock(false); // NOTE: This value should not matter... controlState.enteredElseBlock(); // Action final Boolean shouldExecute = controlState.shouldExecute(); // Assert Assert.assertFalse(shouldExecute); } @Test public void should_execute_else_after_doubly_nested_if_super_outer_condition_is_false() { /* IF FALSE IF FALSE IF FALSE // ... ELSE // ... ENDIF ENDIF ELSE // Should execute... ENDIF */ // Setup final ControlState controlState = new ControlState(); controlState.enteredIfBlock(false); controlState.enteredIfBlock(false); // NOTE: This value should not matter... controlState.enteredIfBlock(false); // NOTE: This value should not matter... controlState.enteredElseBlock(); controlState.exitedCodeBlock(); controlState.exitedCodeBlock(); controlState.enteredElseBlock(); // Action final Boolean shouldExecute = controlState.shouldExecute(); // Assert Assert.assertTrue(shouldExecute); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/unlocking/UnlockingScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.unlocking; import com.softwareverde.bitcoin.transaction.script.Script; public interface UnlockingScript extends Script { UnlockingScript EMPTY_SCRIPT = new ImmutableUnlockingScript(); static UnlockingScript castFrom(final Script script) { return new ImmutableUnlockingScript(script); } @Override ImmutableUnlockingScript asConst(); } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/util/TestUtil.java<|end_filename|> package com.softwareverde.bitcoin.test.util; import com.softwareverde.database.query.parameter.TypedParameter; import com.softwareverde.database.row.Row; import com.softwareverde.util.HexUtil; import com.softwareverde.util.ReflectionUtil; import java.util.HashMap; import java.util.Map; public class TestUtil { private static void _fail(final String message) { throw new AssertionError(message); } /** * Throws an AssertionError if the string does not match the matching pattern provided by expectedMaskedString. * Mask Pattern: * 'X' denotes characters are masked but must be present */ public static void assertMatchesMaskedHexString(final String stringMask, final String string) { if (string == null) { _fail("Unexpected null value within value."); } final String uppercaseString = string.toUpperCase(); final int uppercaseStringLength = uppercaseString.length(); final String uppercaseStrippedStringMask = stringMask.replaceAll("\\s+", "").toUpperCase(); final int uppercaseStrippedStringMaskLength = uppercaseStrippedStringMask.length(); for (int i = 0; i < uppercaseStrippedStringMask.length(); ++i) { final char maskCharacter = uppercaseStrippedStringMask.charAt(i); if (i >= uppercaseStringLength) { _fail("Provided value does not match expected value. (Expected length: "+ (uppercaseStrippedStringMaskLength/2) +", found: "+ (uppercaseStringLength/2) +".)\n" + stringMask + "\n" + string); } if (maskCharacter == 'X') { continue; } final char stringCharacter = uppercaseString.charAt(i); if (maskCharacter != stringCharacter) { _fail("Provided value does not match expected value.\n" + stringMask + "\n" + string); } } } public static void assertMatchesMaskedHexString(final String stringMask, final byte[] data) { assertMatchesMaskedHexString(stringMask, HexUtil.toHexString(data)); } public static void assertEqual(final byte[] expectedBytes, final byte[] bytes) { assertMatchesMaskedHexString(HexUtil.toHexString(expectedBytes), HexUtil.toHexString(bytes)); } public static Map<String, Object>[] debugQuery(final java.util.List<Row> rows) { final Map<String, Object>[] debugRows = new Map[rows.size()]; int i = 0; for (final Row row : rows) { final Map<String, TypedParameter> values = ReflectionUtil.getValue(row, "_columnValues"); final HashMap<String, Object> debugValues = new HashMap<String, Object>(); for (final String columnName : row.getColumnNames()) { final TypedParameter typedParameter = values.get(columnName); debugValues.put(columnName, typedParameter.value); } debugRows[i] = debugValues; i += 1; } return debugRows; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/TransactionHasher.java<|end_filename|> package com.softwareverde.bitcoin.transaction; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.util.bytearray.ByteArrayBuilder; public class TransactionHasher { public Sha256Hash hashTransaction(final Transaction transaction) { final TransactionDeflater transactionDeflater = new TransactionDeflater(); final ByteArrayBuilder byteArrayBuilder = transactionDeflater.toByteArrayBuilder(transaction); final byte[] doubleSha256 = HashUtil.doubleSha256(byteArrayBuilder.build()); return MutableSha256Hash.wrap(ByteUtil.reverseEndian(doubleSha256)); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/sync/SlpTransactionProcessor.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.transaction.TransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.FullNodeTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.slp.SlpTransactionDatabaseManager; import com.softwareverde.bitcoin.slp.validator.SlpTransactionValidationCache; import com.softwareverde.bitcoin.slp.validator.SlpTransactionValidator; import com.softwareverde.bitcoin.slp.validator.TransactionAccumulator; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.concurrent.service.SleepyService; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; import com.softwareverde.util.Container; import com.softwareverde.util.timer.MilliTimer; import java.util.HashMap; import java.util.Map; public class SlpTransactionProcessor extends SleepyService { public static final Integer BATCH_SIZE = 4096; public static TransactionAccumulator createTransactionAccumulator(final FullNodeDatabaseManager databaseManager, final Container<Integer> nullableTransactionLookupCount) { final FullNodeTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); return new TransactionAccumulator() { @Override public Map<Sha256Hash, Transaction> getTransactions(final List<Sha256Hash> transactionHashes, final Boolean allowUnconfirmedTransactions) { try { final HashMap<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(transactionHashes.getCount()); final MilliTimer milliTimer = new MilliTimer(); milliTimer.start(); for (final Sha256Hash transactionHash : transactionHashes) { final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); if (transactionId == null) { continue; } if (! allowUnconfirmedTransactions) { final Boolean isUnconfirmedTransaction = transactionDatabaseManager.isUnconfirmedTransaction(transactionId); if (isUnconfirmedTransaction) { continue; } } final Transaction transaction = transactionDatabaseManager.getTransaction(transactionId); transactions.put(transactionHash, transaction); } milliTimer.stop(); if (nullableTransactionLookupCount != null) { nullableTransactionLookupCount.value += transactionHashes.getCount(); } Logger.trace("Loaded " + transactionHashes.getCount() + " in " + milliTimer.getMillisecondsElapsed() + "ms."); return transactions; } catch (final DatabaseException exception) { Logger.warn(exception); return null; } } }; } public static SlpTransactionValidationCache createSlpTransactionValidationCache(final FullNodeDatabaseManager databaseManager) { final TransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); final SlpTransactionDatabaseManager slpTransactionDatabaseManager = databaseManager.getSlpTransactionDatabaseManager(); return new SlpTransactionValidationCache() { @Override public Boolean isValid(final Sha256Hash transactionHash) { try { final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); if (transactionId == null) { return null; } final MilliTimer milliTimer = new MilliTimer(); milliTimer.start(); final Boolean result = slpTransactionDatabaseManager.getSlpTransactionValidationResult(transactionId); milliTimer.stop(); Logger.trace("Loaded Cached Validity: " + transactionHash + " in " + milliTimer.getMillisecondsElapsed() + "ms. (" + result + ")"); return result; } catch (final DatabaseException exception) { Logger.warn(exception); return null; } } @Override public void setIsValid(final Sha256Hash transactionHash, final Boolean isValid) { try { final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); if (transactionId == null) { return; } slpTransactionDatabaseManager.setSlpTransactionValidationResult(transactionId, isValid); } catch (final DatabaseException exception) { Logger.warn(exception); } } }; } protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; @Override protected void _onStart() { Logger.trace("SlpTransactionProcessor Starting."); } @Override protected Boolean _run() { Logger.trace("SlpTransactionProcessor Running."); try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final TransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); final SlpTransactionDatabaseManager slpTransactionDatabaseManager = databaseManager.getSlpTransactionDatabaseManager(); final Container<Integer> transactionLookupCount = new Container<Integer>(0); final TransactionAccumulator transactionAccumulator = SlpTransactionProcessor.createTransactionAccumulator(databaseManager, transactionLookupCount); final SlpTransactionValidationCache slpTransactionValidationCache = SlpTransactionProcessor.createSlpTransactionValidationCache(databaseManager); // 1. Iterate through blocks for SLP transactions. // 2. Validate any SLP transactions for that block's blockchain segment. // 3. Update those SLP transactions validation statuses via the slpTransactionDatabaseManager. // 4. Move on to the next block. final SlpTransactionValidator slpTransactionValidator = new SlpTransactionValidator(transactionAccumulator, slpTransactionValidationCache); final Map<BlockId, List<TransactionId>> pendingSlpTransactionIds = slpTransactionDatabaseManager.getConfirmedPendingValidationSlpTransactions(BATCH_SIZE); final List<TransactionId> unconfirmedPendingSlpTransactionIds; if (pendingSlpTransactionIds.isEmpty()) { // Only validate unconfirmed SLP Transactions if the history is up to date in order to reduce the validation depth. unconfirmedPendingSlpTransactionIds = slpTransactionDatabaseManager.getUnconfirmedPendingValidationSlpTransactions(BATCH_SIZE); if (unconfirmedPendingSlpTransactionIds.isEmpty()) { return false; } } else { unconfirmedPendingSlpTransactionIds = new MutableList<TransactionId>(0); } final MilliTimer milliTimer = new MilliTimer(); // Validate Confirmed SLP Transactions... for (final BlockId blockId : pendingSlpTransactionIds.keySet()) { final List<TransactionId> transactionIds = pendingSlpTransactionIds.get(blockId); for (final TransactionId transactionId : transactionIds) { transactionLookupCount.value = 0; milliTimer.start(); final Transaction transaction = transactionDatabaseManager.getTransaction(transactionId); final Boolean isValid = slpTransactionValidator.validateTransaction(transaction); slpTransactionDatabaseManager.setSlpTransactionValidationResult(transactionId, isValid); milliTimer.stop(); Logger.trace("Validated Slp Tx " + transaction.getHash() + " in " + milliTimer.getMillisecondsElapsed() + "ms. IsValid: " + isValid + " (lookUps=" + transactionLookupCount.value + ")"); } slpTransactionDatabaseManager.setLastSlpValidatedBlockId(blockId); } // Validate Unconfirmed SLP Transactions... for (final TransactionId transactionId : unconfirmedPendingSlpTransactionIds) { transactionLookupCount.value = 0; milliTimer.start(); final Transaction transaction = transactionDatabaseManager.getTransaction(transactionId); final Boolean isValid = slpTransactionValidator.validateTransaction(transaction); slpTransactionDatabaseManager.setSlpTransactionValidationResult(transactionId, isValid); milliTimer.stop(); Logger.trace("Validated Unconfirmed Slp Tx " + transaction.getHash() + " in " + milliTimer.getMillisecondsElapsed() + "ms. IsValid: " + isValid + " (lookUps=" + transactionLookupCount.value + ")"); } } catch (final Exception exception) { Logger.warn(exception); return false; } Logger.trace("SlpTransactionProcessor Stopping."); return true; } @Override protected void _onSleep() { Logger.trace("SlpTransactionProcessor Sleeping."); } public SlpTransactionProcessor(final FullNodeDatabaseManagerFactory databaseManagerFactory) { _databaseManagerFactory = databaseManagerFactory; } } <|start_filename|>explorer/www/css/list-blocks.css<|end_filename|> .block-header { border-bottom: solid 1px rgba(0, 0, 0, 0.1); display: block; font-size: 0; } .block-header > div:first-child { padding-left: 0.5em; } .block-header > div { display: inline-block; box-sizing: border-box; border: none; font-size: initial; line-height: 2em; } #main { margin-top: 1em; margin-left: 2em; margin-right: 2em; margin-bottom: 1em; } #main > div.block:not(.table-header):nth-child(even) { background-color: #FFFFFF; } .block-header .height { width: 5%; min-width: 5em; } .block-header .hash { min-width: 50%; } .block-header .time-diff { width: 12em; float: right; text-align: right; margin-right: 0.5em; } .block-header .byte-count, .block-header .transaction-count { width: 8em; float: right; margin-right: 1.5em; text-align: right; } .byte-count > span.value::after { content: ' kB'; font-size: 0.75em; color: #808080; } #main > div:not(.table-header) .block-header label { display: none; } #main .table-header label { font-weight: bold; line-height: 2em; } span.value:not(.fixed) { font-size: 0.9em; } .block-header .difficulty, .block-header .previous-block-hash, .block-header .merkle-root, .block-header .nonce, .block-header .reward, .block-header .timestamp { display: none; } @media only screen and (max-width: 1234px) { #main { margin-left: 0; margin-right: 0; } .block.table-header { display: none; } .block { margin-bottom: 1em; margin-left: 0.5em; margin-right: 0.5em; padding-top: 1em; padding-bottom: 1em; border-bottom: solid 1px #CCCCCC; } .block-header { padding-top: 0.5em; padding-bottom: 0.5em; border: none !important; } .block-header > div { display: block; float: none !important; text-align: left !important; width: 100% !important; box-sizing: border-box; line-height: 1em !important; margin-bottom: 0.25em; padding-left: 0.25em !important; } .block-header label { display: block !important; font-size: 0.8em; font-weight: bold; color: #AAAAAA; } .block-header .value { padding-left: 1em; } .block:nth-child(even) { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/sync/blockloader/BlockLoader.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync.blockloader; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.server.module.node.database.block.fullnode.FullNodeBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; import com.softwareverde.util.timer.MilliTimer; import java.util.HashMap; public class BlockLoader { protected final ThreadPool _threadPool; protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; protected final BlockchainSegmentId _blockchainSegmentId; protected final HashMap<Long, BlockFuture> _blockFutures; protected final Integer _maxQueueCount; protected final Long _maxBlockHeight; protected Long _nextBlockHeight; /** * Preloads the block, specified by the nextPendingBlockId, and the unspentOutputs it requires. * When complete, the pin is released. */ protected BlockFuture _asynchronouslyLoadNextBlock(final Long blockHeight) { final BlockFuture blockFuture = new BlockFuture(blockHeight); _threadPool.execute(new Runnable() { @Override public void run() { try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final FullNodeBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final MilliTimer milliTimer = new MilliTimer(); milliTimer.start(); // Expensive relative to the other actions during the UTXO loading... final BlockId blockId = blockHeaderDatabaseManager.getBlockIdAtHeight(_blockchainSegmentId, blockHeight); blockFuture._block = blockDatabaseManager.getBlock(blockId); milliTimer.stop(); Logger.trace("Preloaded block#" + blockHeight + " in: " + milliTimer.getMillisecondsElapsed() + "ms."); } catch (final DatabaseException exception) { Logger.debug(exception); } finally { blockFuture._pin.release(); } } }); return blockFuture; } public BlockLoader(final BlockchainSegmentId blockchainSegmentId, final Integer queueCount, final FullNodeDatabaseManagerFactory databaseManagerFactory, final ThreadPool threadPool) { _blockchainSegmentId = blockchainSegmentId; _threadPool = threadPool; _databaseManagerFactory = databaseManagerFactory; _blockFutures = new HashMap<Long, BlockFuture>(queueCount); _maxQueueCount = queueCount; _nextBlockHeight = 0L; Long maxBlockHeight = Long.MAX_VALUE; try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final FullNodeBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final BlockId headBlockId = blockDatabaseManager.getHeadBlockId(); maxBlockHeight = blockHeaderDatabaseManager.getBlockHeight(headBlockId); } catch (final DatabaseException exception) { Logger.debug(exception); } _maxBlockHeight = maxBlockHeight; } public synchronized PreloadedBlock getBlock(final Long blockHeight) { while ( (_blockFutures.size() < _maxQueueCount) && (_nextBlockHeight <= _maxBlockHeight) ) { _nextBlockHeight = Math.max(_nextBlockHeight, blockHeight); final BlockFuture blockFuture = _asynchronouslyLoadNextBlock(_nextBlockHeight); _blockFutures.put(_nextBlockHeight, blockFuture); _nextBlockHeight += 1L; } { // Check for already preloadedBlock... final BlockFuture blockFuture = _blockFutures.remove(blockHeight); if (blockFuture != null) { blockFuture.waitFor(); return blockFuture; } } // If the requested block is out of range of the queue then load it outside of the regular process... final BlockFuture blockFuture = _asynchronouslyLoadNextBlock(blockHeight); blockFuture.waitFor(); return blockFuture; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/validator/BlockValidator.java<|end_filename|> package com.softwareverde.bitcoin.block.validator; import com.softwareverde.bitcoin.bip.Bip34; import com.softwareverde.bitcoin.bip.HF20200515; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.block.header.difficulty.PrototypeDifficulty; import com.softwareverde.bitcoin.block.validator.thread.ParalleledTaskSpawner; import com.softwareverde.bitcoin.block.validator.thread.TaskHandler; import com.softwareverde.bitcoin.block.validator.thread.TaskHandlerFactory; import com.softwareverde.bitcoin.block.validator.thread.TotalExpenditureTaskHandler; import com.softwareverde.bitcoin.block.validator.thread.TransactionValidationTaskHandler; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.context.TransactionValidatorFactory; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.coinbase.CoinbaseTransaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.script.opcode.Operation; import com.softwareverde.bitcoin.transaction.script.opcode.PushOperation; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.bitcoin.transaction.validator.BlockOutputs; import com.softwareverde.bitcoin.transaction.validator.SpentOutputsTracker; import com.softwareverde.bitcoin.transaction.validator.TransactionValidationResult; import com.softwareverde.bitcoin.transaction.validator.TransactionValidator; import com.softwareverde.concurrent.pool.MainThreadPool; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableArrayListBuilder; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import com.softwareverde.util.Util; import com.softwareverde.util.timer.NanoTimer; import com.softwareverde.util.type.time.SystemTime; public class BlockValidator { public interface Context extends BlockHeaderValidator.Context, TransactionValidator.Context, TransactionValidatorFactory { } public static final Long DO_NOT_TRUST_BLOCKS = -1L; public static final Integer MIN_BYTES_PER_SIGNATURE_OPERATION = 141; protected final Context _context; protected final SystemTime _systemTime = new SystemTime(); protected Boolean _shouldLogValidBlocks = true; protected Integer _maxThreadCount = 4; protected Long _trustedBlockHeight = DO_NOT_TRUST_BLOCKS; protected BlockValidationResult _validateTransactions(final Block block, final Long blockHeight) { final Thread currentThread = Thread.currentThread(); { // Enforce max byte count... final Integer blockByteCount = block.getByteCount(); if (blockByteCount > BlockInflater.MAX_BYTE_COUNT) { return BlockValidationResult.invalid("Block exceeded maximum size."); } } final List<Transaction> transactions; { // Remove the coinbase transaction and create a lookup map for transaction outputs... final List<Transaction> fullTransactionList = block.getTransactions(); final int transactionCount = (fullTransactionList.getCount() - 1); final ImmutableArrayListBuilder<Transaction> listBuilder = new ImmutableArrayListBuilder<Transaction>(transactionCount); int transactionIndex = 0; for (final Transaction transaction : fullTransactionList) { if (transactionIndex > 0) { listBuilder.add(transaction); } transactionIndex += 1; } transactions = listBuilder.build(); } final BlockOutputs blockOutputs = BlockOutputs.fromBlock(block); final MainThreadPool threadPool = new MainThreadPool(_maxThreadCount, 1000L); threadPool.setThreadPriority(currentThread.getPriority()); final int threadCount; final boolean executeBothTasksAsynchronously; { final int transactionCount = transactions.getCount(); if (transactionCount > 512) { executeBothTasksAsynchronously = false; threadCount = Math.max(_maxThreadCount, 1); } else { executeBothTasksAsynchronously = true; threadCount = Math.max((_maxThreadCount / 2), 1); } } final SpentOutputsTracker spentOutputsTracker = new SpentOutputsTracker(blockOutputs.getOutputCount(), threadCount); final ParalleledTaskSpawner<Transaction, TotalExpenditureTaskHandler.ExpenditureResult> totalExpenditureValidationTaskSpawner = new ParalleledTaskSpawner<Transaction, TotalExpenditureTaskHandler.ExpenditureResult>("Expenditures", threadPool); totalExpenditureValidationTaskSpawner.setTaskHandlerFactory(new TaskHandlerFactory<Transaction, TotalExpenditureTaskHandler.ExpenditureResult>() { @Override public TaskHandler<Transaction, TotalExpenditureTaskHandler.ExpenditureResult> newInstance() { return new TotalExpenditureTaskHandler(_context, blockOutputs, spentOutputsTracker); } }); final TransactionValidator transactionValidator = _context.getTransactionValidator(blockOutputs, _context); final ParalleledTaskSpawner<Transaction, TransactionValidationTaskHandler.TransactionValidationTaskResult> transactionValidationTaskSpawner = new ParalleledTaskSpawner<Transaction, TransactionValidationTaskHandler.TransactionValidationTaskResult>("Validation", threadPool); transactionValidationTaskSpawner.setTaskHandlerFactory(new TaskHandlerFactory<Transaction, TransactionValidationTaskHandler.TransactionValidationTaskResult>() { @Override public TaskHandler<Transaction, TransactionValidationTaskHandler.TransactionValidationTaskResult> newInstance() { return new TransactionValidationTaskHandler(blockHeight, transactionValidator); } }); if (executeBothTasksAsynchronously) { transactionValidationTaskSpawner.executeTasks(transactions, threadCount); totalExpenditureValidationTaskSpawner.executeTasks(transactions, threadCount); } else { transactionValidationTaskSpawner.executeTasks(transactions, threadCount); transactionValidationTaskSpawner.waitForResults(); // Wait for the results synchronously when the threadCount is one... if (currentThread.isInterrupted()) { return BlockValidationResult.invalid("Validation aborted."); } // Bail out if an abort occurred during single-threaded invocation... totalExpenditureValidationTaskSpawner.executeTasks(transactions, threadCount); totalExpenditureValidationTaskSpawner.waitForResults(); // Wait for the results synchronously when the threadCount is one... if (currentThread.isInterrupted()) { return BlockValidationResult.invalid("Validation aborted."); } // Bail out if an abort occurred during single-threaded invocation... } { // Validate coinbase contains block height... if (Bip34.isEnabled(blockHeight)) { final Long blockVersion = block.getVersion(); if (blockVersion < 2L) { totalExpenditureValidationTaskSpawner.abort(); transactionValidationTaskSpawner.abort(); return BlockValidationResult.invalid("Invalid block version: " + blockVersion); } final CoinbaseTransaction coinbaseTransaction = block.getCoinbaseTransaction(); final UnlockingScript unlockingScript = coinbaseTransaction.getCoinbaseScript(); final List<Operation> operations = unlockingScript.getOperations(); final Operation operation = operations.get(0); if (operation.getType() != Operation.Type.OP_PUSH) { totalExpenditureValidationTaskSpawner.abort(); transactionValidationTaskSpawner.abort(); return BlockValidationResult.invalid("Block coinbase does not contain block height.", coinbaseTransaction); } final PushOperation pushOperation = (PushOperation) operation; final Long coinbaseBlockHeight = pushOperation.getValue().asLong(); if (blockHeight.longValue() != coinbaseBlockHeight.longValue()) { totalExpenditureValidationTaskSpawner.abort(); transactionValidationTaskSpawner.abort(); return BlockValidationResult.invalid("Invalid block height within coinbase.", coinbaseTransaction); } } } { // Validate coinbase input... final Transaction coinbaseTransaction = block.getCoinbaseTransaction(); final List<TransactionInput> transactionInputs = coinbaseTransaction.getTransactionInputs(); { // Validate transaction amount... if (transactionInputs.getCount() != 1) { totalExpenditureValidationTaskSpawner.abort(); transactionValidationTaskSpawner.abort(); return BlockValidationResult.invalid("Invalid coinbase transaction inputs. Count: " + transactionInputs.getCount() + "; " + "Block: " + block.getHash(), coinbaseTransaction); } } { // Validate previousOutputTransactionHash... final TransactionInput transactionInput = transactionInputs.get(0); final Sha256Hash previousTransactionOutputHash = transactionInput.getPreviousOutputTransactionHash(); final Integer previousTransactionOutputIndex = transactionInput.getPreviousOutputIndex(); final Boolean previousTransactionOutputHashIsValid = Util.areEqual(previousTransactionOutputHash, TransactionOutputIdentifier.COINBASE.getTransactionHash()); final Boolean previousTransactionOutputIndexIsValid = Util.areEqual(previousTransactionOutputIndex, TransactionOutputIdentifier.COINBASE.getOutputIndex()); if (! (previousTransactionOutputHashIsValid && previousTransactionOutputIndexIsValid)) { totalExpenditureValidationTaskSpawner.abort(); transactionValidationTaskSpawner.abort(); return BlockValidationResult.invalid("Invalid coinbase transaction input. " + previousTransactionOutputHash + ":" + previousTransactionOutputIndex + "; " + "Block: " + block.getHash(), coinbaseTransaction); } } } final List<TotalExpenditureTaskHandler.ExpenditureResult> expenditureResults = totalExpenditureValidationTaskSpawner.waitForResults(); if (currentThread.isInterrupted()) { // Bail out if an abort occurred... transactionValidationTaskSpawner.abort(); return BlockValidationResult.invalid("Validation aborted."); // Bail out if an abort occurred... } if (expenditureResults == null) { return BlockValidationResult.invalid("An internal error occurred during ExpenditureValidatorTask."); } final List<TransactionValidationTaskHandler.TransactionValidationTaskResult> transactionValidationTaskResults = transactionValidationTaskSpawner.waitForResults(); if (currentThread.isInterrupted()) { BlockValidationResult.invalid("Validation aborted."); } // Bail out if an abort occurred... if (transactionValidationTaskResults == null) { return BlockValidationResult.invalid("An internal error occurred during InputsValidatorTask."); } threadPool.stop(); final MutableList<Sha256Hash> invalidTransactions = new MutableList<Sha256Hash>(); final long totalTransactionFees; { long totalFees = 0L; for (final TotalExpenditureTaskHandler.ExpenditureResult expenditureResult : expenditureResults) { if (! expenditureResult.isValid) { invalidTransactions.addAll(expenditureResult.invalidTransactions); } else { totalFees += expenditureResult.totalFees; } } totalTransactionFees = totalFees; } if (! invalidTransactions.isEmpty()) { return BlockValidationResult.invalid("Invalid transactions expenditures.", invalidTransactions); } final StringBuilder errorMessage = new StringBuilder("Transactions failed to unlock inputs."); final int totalSignatureOperationCount; { int signatureOperationCount = 0; for (final TransactionValidationTaskHandler.TransactionValidationTaskResult transactionValidationTaskResult : transactionValidationTaskResults) { if (transactionValidationTaskResult.isValid()) { signatureOperationCount += transactionValidationTaskResult.getSignatureOperationCount(); } else { for (final Sha256Hash invalidTransactionHash : transactionValidationTaskResult.getInvalidTransactions()) { invalidTransactions.add(invalidTransactionHash); final TransactionValidationResult transactionValidationResult = transactionValidationTaskResult.getTransactionValidationResult(invalidTransactionHash); errorMessage.append("\n"); errorMessage.append(invalidTransactionHash); errorMessage.append(": "); errorMessage.append(transactionValidationResult.errorMessage); } } } totalSignatureOperationCount = signatureOperationCount; } if (! invalidTransactions.isEmpty()) { return BlockValidationResult.invalid(errorMessage.toString(), invalidTransactions); } final MedianBlockTime medianBlockTime = _context.getMedianBlockTime(blockHeight); if (HF20200515.isEnabled(medianBlockTime)) { // Enforce maximum Signature operation count... final int maximumSignatureOperationCount = (BlockHeaderInflater.BLOCK_HEADER_BYTE_COUNT / BlockValidator.MIN_BYTES_PER_SIGNATURE_OPERATION); if (totalSignatureOperationCount > maximumSignatureOperationCount) { return BlockValidationResult.invalid("Too many signature operations."); } } { // Validate coinbase amount... final Transaction coinbaseTransaction = block.getCoinbaseTransaction(); final Long maximumCreatedCoinsAmount = BlockHeader.calculateBlockReward(blockHeight); final long maximumCoinbaseValue = (maximumCreatedCoinsAmount + totalTransactionFees); final long coinbaseTransactionAmount; { long totalAmount = 0L; for (final TransactionOutput transactionOutput : coinbaseTransaction.getTransactionOutputs()) { totalAmount += transactionOutput.getAmount(); } coinbaseTransactionAmount = totalAmount; } final boolean coinbaseTransactionAmountIsValid = (coinbaseTransactionAmount <= maximumCoinbaseValue); if (! coinbaseTransactionAmountIsValid) { return BlockValidationResult.invalid("Invalid coinbase transaction amount. Amount: " + coinbaseTransactionAmount + "; " + "Block: "+ block.getHash(), coinbaseTransaction); } } return BlockValidationResult.valid(); } protected BlockValidationResult _validateBlock(final Block block, final Long blockHeight) { final BlockHeaderValidator blockHeaderValidator = new BlockHeaderValidator(_context); final BlockHeaderValidator.BlockHeaderValidationResult blockHeaderValidationResult = blockHeaderValidator.validateBlockHeader(block, blockHeight); if (! blockHeaderValidationResult.isValid) { return BlockValidationResult.invalid(blockHeaderValidationResult.errorMessage); } if (! block.isValid()) { return BlockValidationResult.invalid("Block header is invalid."); } { // Ensure the Coinbase Transaction is valid. final CoinbaseTransaction coinbaseTransaction = block.getCoinbaseTransaction(); final Boolean isValidCoinbase = Transaction.isCoinbaseTransaction(coinbaseTransaction); if (! isValidCoinbase) { return BlockValidationResult.invalid("Coinbase Transaction is invalid."); } } final boolean shouldValidateInputs = (blockHeight > _trustedBlockHeight); if (shouldValidateInputs) { final NanoTimer validateBlockTimer = new NanoTimer(); validateBlockTimer.start(); final BlockValidationResult transactionsValidationResult = _validateTransactions(block, blockHeight); if (! transactionsValidationResult.isValid) { return transactionsValidationResult; } validateBlockTimer.stop(); if (_shouldLogValidBlocks) { final List<Transaction> transactions = block.getTransactions(); Logger.info("Validated " + transactions.getCount() + " transactions in " + (validateBlockTimer.getMillisecondsElapsed()) + "ms (" + ((int) ((transactions.getCount() / validateBlockTimer.getMillisecondsElapsed()) * 1000)) + " tps). " + block.getHash()); } } else { Logger.debug("Trusting Block Height: " + blockHeight); } return BlockValidationResult.valid(); } public BlockValidator(final Context context) { _context = context; } /** * Sets the total number of threads that will be spawned for each call to BlockValidator::Validate. NOTE: This number should be divisible by 2. */ public void setMaxThreadCount(final Integer maxThreadCount) { _maxThreadCount = maxThreadCount; } public void setTrustedBlockHeight(final Long trustedBlockHeight) { _trustedBlockHeight = trustedBlockHeight; } public BlockValidationResult validateBlock(final Block block, final Long blockHeight) { return _validateBlock(block, blockHeight); } /** * Validates the provided block for mining. * PrototypeBlock's are valid blocks, with the sole exception of their hash is not required to be valid. */ public BlockValidationResult validatePrototypeBlock(final Block prototypeBlock, final Long blockHeight) { final MutableBlock mutableBlock = new MutableBlock(prototypeBlock); final Difficulty difficulty = prototypeBlock.getDifficulty(); final PrototypeDifficulty prototypeDifficulty = new PrototypeDifficulty(difficulty); mutableBlock.setDifficulty(prototypeDifficulty); return _validateBlock(mutableBlock, blockHeight); } public BlockValidationResult validateBlockTransactions(final Block block, final Long blockHeight) { return _validateBlock(block, blockHeight); } public void setShouldLogValidBlocks(final Boolean shouldLogValidBlocks) { _shouldLogValidBlocks = shouldLogValidBlocks; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/endpoint/BlockchainApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.endpoint; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.bitcoin.server.module.explorer.api.v1.get.GetBlockchainSegmentsHandler; import com.softwareverde.http.HttpMethod; import com.softwareverde.json.Json; public class BlockchainApi extends ExplorerApiEndpoint { public static class BlockchainResult extends ApiResult { private Json _blockchainJson = new Json(); public void setBlockchainMetadataJson(final Json blockchainJson) { _blockchainJson = blockchainJson; } @Override public Json toJson() { final Json json = super.toJson(); json.put("blockchainMetadata", _blockchainJson); return json; } } public BlockchainApi(final String apiPrePath, final Environment environment) { super(environment); _defineEndpoint((apiPrePath + "/blockchain"), HttpMethod.GET, new GetBlockchainSegmentsHandler()); } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/endpoint/ExplorerApiEndpoint.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.endpoint; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.http.server.servlet.routed.json.JsonApplicationServlet; public abstract class ExplorerApiEndpoint extends JsonApplicationServlet<Environment> { public ExplorerApiEndpoint(final Environment environment) { super(environment); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/NodeManagerContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.server.module.node.manager.BitcoinNodeManager; public interface NodeManagerContext { BitcoinNodeManager getBitcoinNodeManager(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/UnspentTransactionOutputContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface UnspentTransactionOutputContext { /** * Two sets of coinbase transactions share duplicate hashes. Before Bip34 it was trivially possible to create * transactions with duplicate hashes via mining coinbases with the same output address. Duplicate transactions * are now near-impossible to create. Consensus behavior dictates that historic duplicate transactions overwrite * one another, so only the latter transactions is actually spendable. */ List<Sha256Hash> ALLOWED_DUPLICATE_TRANSACTION_HASHES = new ImmutableList<Sha256Hash>( Sha256Hash.fromHexString("E3BF3D07D4B0375638D5F1DB5255FE07BA2C4CB067CD81B84EE974B6585FB468"), Sha256Hash.fromHexString("D5D27987D2A3DFC724E359870C6644B40E497BDC0589A033220FE15429D88599") ); TransactionOutput getTransactionOutput(TransactionOutputIdentifier transactionOutputIdentifier); Long getBlockHeight(TransactionOutputIdentifier transactionOutputIdentifier); Sha256Hash getBlockHash(TransactionOutputIdentifier transactionOutputIdentifier); Boolean isCoinbaseTransactionOutput(TransactionOutputIdentifier transactionOutputIdentifier); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/header/BlockHeader.java<|end_filename|> package com.softwareverde.bitcoin.block.header; import com.softwareverde.bitcoin.block.BlockHasher; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.block.merkleroot.Hashable; import com.softwareverde.bitcoin.constable.util.ConstUtil; import com.softwareverde.bitcoin.merkleroot.MerkleRoot; import com.softwareverde.bitcoin.merkleroot.MutableMerkleRoot; import com.softwareverde.bitcoin.server.main.BitcoinConstants; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.constable.Constable; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.json.Json; import com.softwareverde.json.Jsonable; import com.softwareverde.util.Util; public interface BlockHeader extends Hashable, Constable<ImmutableBlockHeader>, Jsonable { Long VERSION = BitcoinConstants.getBlockVersion(); Sha256Hash GENESIS_BLOCK_HASH = Sha256Hash.fromHexString(BitcoinConstants.getGenesisBlockHash()); static Long calculateBlockReward(final Long blockHeight) { return ((50 * Transaction.SATOSHIS_PER_BITCOIN) >> (blockHeight / 210000)); } Sha256Hash getPreviousBlockHash(); MerkleRoot getMerkleRoot(); Difficulty getDifficulty(); Long getVersion(); Long getTimestamp(); Long getNonce(); Boolean isValid(); @Override ImmutableBlockHeader asConst(); } abstract class BlockHeaderCore implements BlockHeader { protected static final BlockHasher DEFAULT_BLOCK_HASHER = new BlockHasher(); protected final BlockHasher _blockHasher; protected final BlockHeaderDeflater _blockHeaderDeflater; protected Long _version; protected Sha256Hash _previousBlockHash = Sha256Hash.EMPTY_HASH; protected MerkleRoot _merkleRoot = new MutableMerkleRoot(); protected Long _timestamp; protected Difficulty _difficulty; protected Long _nonce; protected BlockHeaderCore(final BlockHasher blockHasher) { _blockHeaderDeflater = blockHasher.getBlockHeaderDeflater(); _blockHasher = blockHasher; _version = VERSION; } public BlockHeaderCore() { _blockHasher = DEFAULT_BLOCK_HASHER; _blockHeaderDeflater = _blockHasher.getBlockHeaderDeflater(); _version = VERSION; } public BlockHeaderCore(final BlockHeader blockHeader) { _blockHasher = DEFAULT_BLOCK_HASHER; _blockHeaderDeflater = _blockHasher.getBlockHeaderDeflater(); _version = blockHeader.getVersion(); _previousBlockHash = (Sha256Hash) ConstUtil.asConstOrNull(blockHeader.getPreviousBlockHash()); _merkleRoot = (MerkleRoot) ConstUtil.asConstOrNull(blockHeader.getMerkleRoot()); _timestamp = blockHeader.getTimestamp(); _difficulty = ConstUtil.asConstOrNull(blockHeader.getDifficulty()); _nonce = blockHeader.getNonce(); } @Override public Long getVersion() { return _version; } @Override public Sha256Hash getPreviousBlockHash() { return _previousBlockHash; } @Override public MerkleRoot getMerkleRoot() { return _merkleRoot; } @Override public Long getTimestamp() { return _timestamp; } @Override public Difficulty getDifficulty() { return _difficulty; } @Override public Long getNonce() { return _nonce; } @Override public Sha256Hash getHash() { return _blockHasher.calculateBlockHash(this); } @Override public Boolean isValid() { final Sha256Hash calculatedHash = _blockHasher.calculateBlockHash(this); return (_difficulty.isSatisfiedBy(calculatedHash)); } @Override public ImmutableBlockHeader asConst() { return new ImmutableBlockHeader(this); } @Override public Json toJson() { return _blockHeaderDeflater.toJson(this); } @Override public int hashCode() { final ByteArray byteArray = _blockHeaderDeflater.toBytes(this); return byteArray.hashCode(); } @Override public boolean equals(final Object object) { if (! (object instanceof BlockHeader)) { return false; } return Util.areEqual(this.getHash(), ((BlockHeader) object).getHash()); } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/rpc/StratumRpcServer.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.rpc; import com.softwareverde.bitcoin.CoreInflater; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumDataHandler; import com.softwareverde.concurrent.pool.MainThreadPool; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.json.Json; import com.softwareverde.network.socket.JsonProtocolMessage; import com.softwareverde.network.socket.JsonSocket; import com.softwareverde.network.socket.JsonSocketServer; public class StratumRpcServer { protected static final String ERROR_MESSAGE_KEY = "errorMessage"; protected static final String WAS_SUCCESS_KEY = "wasSuccess"; protected final JsonSocketServer _jsonRpcSocketServer; protected final MainThreadPool _rpcThreadPool; protected final StratumDataHandler _stratumDataHandler; protected final BlockInflaters _blockInflaters; // Requires GET: [rawFormat=0] // Requires POST: protected void _getPrototypeBlock(final Json parameters, final Json response) { final StratumDataHandler stratumDataHandler = _stratumDataHandler; if (stratumDataHandler == null) { response.put(ERROR_MESSAGE_KEY, "Operation not supported."); return; } final Block prototypeBlock = stratumDataHandler.getPrototypeBlock(); final Boolean shouldReturnRawBlockData = parameters.getBoolean("rawFormat"); if (shouldReturnRawBlockData) { final BlockDeflater blockDeflater = _blockInflaters.getBlockDeflater(); final ByteArray blockData = blockDeflater.toBytes(prototypeBlock); response.put("block", blockData); } else { final Json blockJson = prototypeBlock.toJson(); response.put("block", blockJson); } response.put(WAS_SUCCESS_KEY, 1); } public StratumRpcServer(final StratumProperties stratumProperties, final StratumDataHandler stratumDataHandler, final MainThreadPool rpcThreadPool) { this( stratumProperties, stratumDataHandler, rpcThreadPool, new CoreInflater() ); } public StratumRpcServer(final StratumProperties stratumProperties, final StratumDataHandler stratumDataHandler, final MainThreadPool rpcThreadPool, final BlockInflaters blockInflaters) { _rpcThreadPool = rpcThreadPool; _stratumDataHandler = stratumDataHandler; _blockInflaters = blockInflaters; final Integer rpcPort = stratumProperties.getRpcPort(); if (rpcPort > 0) { final JsonSocketServer jsonRpcSocketServer = new JsonSocketServer(rpcPort, _rpcThreadPool); jsonRpcSocketServer.setSocketConnectedCallback(new JsonSocketServer.SocketConnectedCallback() { @Override public void run(final JsonSocket socketConnection) { socketConnection.setMessageReceivedCallback(new Runnable() { @Override public void run() { final JsonProtocolMessage protocolMessage = socketConnection.popMessage(); final Json message = protocolMessage.getMessage(); final String method = message.getString("method"); final String query = message.getString("query"); final Json response = new Json(); response.put(WAS_SUCCESS_KEY, 0); response.put(ERROR_MESSAGE_KEY, null); final Json parameters = message.get("parameters"); Boolean closeConnection = true; switch (method.toUpperCase()) { case "GET": { switch (query.toUpperCase()) { case "PROTOTYPE_BLOCK": { _getPrototypeBlock(parameters, response); } break; default: { response.put(ERROR_MESSAGE_KEY, "Invalid " + method + " query: " + query); } break; } } break; case "POST": { switch (query.toUpperCase()) { default: { response.put(ERROR_MESSAGE_KEY, "Invalid " + method + " query: " + query); } break; } } break; default: { response.put(ERROR_MESSAGE_KEY, "Invalid command: " + method.toUpperCase()); } break; } socketConnection.write(new JsonProtocolMessage(response)); if (closeConnection) { socketConnection.close(); } } }); socketConnection.beginListening(); } }); _jsonRpcSocketServer = jsonRpcSocketServer; } else { _jsonRpcSocketServer = null; } } public void start() { if (_jsonRpcSocketServer != null) { _jsonRpcSocketServer.start(); } } public void stop() { if (_jsonRpcSocketServer != null) { _jsonRpcSocketServer.stop(); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/send/ImmutableSlpSendScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp.send; import com.softwareverde.constable.Const; public class ImmutableSlpSendScript extends SlpSendScriptCore implements Const { public ImmutableSlpSendScript(final SlpSendScript slpSendScript) { super(slpSendScript); } @Override public ImmutableSlpSendScript asConst() { return this; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/configuration/BitcoinProperties.java<|end_filename|> package com.softwareverde.bitcoin.server.configuration; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.UnspentTransactionOutputDatabaseManager; import com.softwareverde.constable.list.List; import com.softwareverde.logging.LogLevel; public class BitcoinProperties { public static final String DATA_DIRECTORY_NAME = "network"; public static final Integer PORT = 8333; public static final Integer RPC_PORT = 8334; protected Integer _bitcoinPort; protected Integer _bitcoinRpcPort; protected List<SeedNodeProperties> _seedNodeProperties; protected List<String> _dnsSeeds; protected List<String> _userAgentBlacklist; protected List<SeedNodeProperties> _nodesWhitelist; protected Boolean _banFilterIsEnabled; protected Integer _minPeerCount; protected Integer _maxPeerCount; protected Integer _maxThreadCount; protected Long _trustedBlockHeight; protected Boolean _shouldSkipNetworking; protected Long _maxUtxoCacheByteCount; protected Long _utxoCommitFrequency; protected Float _utxoPurgePercent; protected Boolean _bootstrapIsEnabled; protected Boolean _shouldReIndexPendingBlocks; protected Boolean _indexingModeIsEnabled; protected Integer _maxMessagesPerSecond; protected String _dataDirectory; protected Boolean _shouldRelayInvalidSlpTransactions; protected Boolean _deletePendingBlocksIsEnabled; protected String _logDirectory; protected LogLevel _logLevel; public Integer getBitcoinPort() { return _bitcoinPort; } public Integer getBitcoinRpcPort() { return _bitcoinRpcPort; } public List<SeedNodeProperties> getSeedNodeProperties() { return _seedNodeProperties; } public List<String> getDnsSeeds() { return _dnsSeeds; } public List<String> getUserAgentBlacklist() { return _userAgentBlacklist; } public List<SeedNodeProperties> getNodeWhitelist() { return _nodesWhitelist; } public Boolean isBanFilterEnabled() { return _banFilterIsEnabled; } public Integer getMinPeerCount() { return _minPeerCount; } public Integer getMaxPeerCount() { return _maxPeerCount; } public Integer getMaxThreadCount() { return _maxThreadCount; } public Long getTrustedBlockHeight() { return _trustedBlockHeight; } public Boolean skipNetworking() { return _shouldSkipNetworking; } public Boolean isDeletePendingBlocksEnabled() { return _deletePendingBlocksIsEnabled; } public String getLogDirectory() { return _logDirectory; } public LogLevel getLogLevel() { return _logLevel; } public Long getMaxUtxoCacheByteCount() { return _maxUtxoCacheByteCount; } public Long getMaxCachedUtxoCount() { final Long maxUtxoCacheWithDoubleBufferByteCount = (_maxUtxoCacheByteCount / 2L); // Disk-writes are double-buffered, using up to double the size in the worst-case scenario. return (maxUtxoCacheWithDoubleBufferByteCount / UnspentTransactionOutputDatabaseManager.BYTES_PER_UTXO); } public Long getUtxoCacheCommitFrequency() { return _utxoCommitFrequency; } public Float getUtxoCachePurgePercent() { return _utxoPurgePercent; } public Boolean isIndexingModeEnabled() { return _indexingModeIsEnabled; } public Integer getMaxMessagesPerSecond() { return _maxMessagesPerSecond; } public Boolean isBootstrapEnabled() { return _bootstrapIsEnabled; } public Boolean shouldReIndexPendingBlocks() { return _shouldReIndexPendingBlocks; } // May be null if unset. public String getDataDirectory() { return _dataDirectory; } public Boolean isInvalidSlpTransactionRelayEnabled() { return _shouldRelayInvalidSlpTransactions; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/core/BlockDownloaderContext.java<|end_filename|> package com.softwareverde.bitcoin.context.core; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.server.SynchronizationStatus; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.manager.BitcoinNodeManager; import com.softwareverde.bitcoin.server.module.node.store.PendingBlockStore; import com.softwareverde.bitcoin.server.module.node.sync.block.BlockDownloader; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.network.time.VolatileNetworkTime; import com.softwareverde.util.type.time.SystemTime; public class BlockDownloaderContext extends BlockHeaderDownloaderContext implements BlockDownloader.Context { protected final BlockInflaters _blockInflaters; protected final PendingBlockStore _pendingBlockStore; protected final SynchronizationStatus _synchronizationStatus; public BlockDownloaderContext(final BitcoinNodeManager nodeManager, final BlockInflaters blockInflaters, final FullNodeDatabaseManagerFactory databaseManagerFactory, final VolatileNetworkTime networkTime, final PendingBlockStore pendingBlockStore, final SynchronizationStatus synchronizationStatus, final SystemTime systemTime, final ThreadPool threadPool) { super(nodeManager, databaseManagerFactory, networkTime, systemTime, threadPool); _blockInflaters = blockInflaters; _pendingBlockStore = pendingBlockStore; _synchronizationStatus = synchronizationStatus; } @Override public FullNodeDatabaseManagerFactory getDatabaseManagerFactory() { return (FullNodeDatabaseManagerFactory) _databaseManagerFactory; } @Override public PendingBlockStore getPendingBlockStore() { return _pendingBlockStore; } @Override public SynchronizationStatus getSynchronizationStatus() { return _synchronizationStatus; } @Override public BlockInflater getBlockInflater() { return _blockInflaters.getBlockInflater(); } @Override public BlockDeflater getBlockDeflater() { return _blockInflaters.getBlockDeflater(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/cache/Cache.java<|end_filename|> package com.softwareverde.bitcoin.server.database.cache; import com.softwareverde.constable.list.List; public interface Cache<KEY, VALUE> { List<KEY> getKeys(); VALUE get(KEY key); void set(KEY key, VALUE value); VALUE remove(KEY key); void invalidate(KEY key); void invalidate(); } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/wallet/api/endpoint/KeysApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.wallet.api.endpoint; public class KeysApi { } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/opcode/controlstate/CodeBlockType.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode.controlstate; public enum CodeBlockType { IF, ELSE } <|start_filename|>explorer/www/js/main.js<|end_filename|> var webSocket = null; $(document).ready(function() { const searchInput = $("#search"); const loadingImage = $("#search-loading-image"); const renderObject = function(object, objectType) { if ( (objectType == Constants.BLOCK) || (objectType == Constants.BLOCK_HEADER) ) { Ui.renderBlock(object); } else if (objectType == Constants.ADDRESS) { Ui.renderAddress(object); } else if (objectType == Constants.TRANSACTION) { Ui.renderTransaction(object); } else { Console.log("Unknown ObjectType: " + objectType); } }; searchInput.on("focus", function() { searchInput.select(); }); searchInput.on("keyup", function(event) { const value = searchInput.val(); searchInput.css("text-transform", (value.length == 64 ? "uppercase" : "none")); }); searchInput.on("keypress", function(event) { const value = searchInput.val(); if (value.length == 0) { return true; } const key = event.which; if (key != KeyCodes.ENTER) { return true; } loadingImage.css("visibility", "visible"); Api.search({ query: value }, function(data) { loadingImage.css("visibility", "hidden"); const wasSuccess = data.wasSuccess; const errorMessage = data.errorMessage; const objectType = data.objectType; const object = data.object; if (wasSuccess) { renderObject(object, objectType); } else { console.log(errorMessage); } }); searchInput.blur(); return false; }); const queryParams = new URLSearchParams(window.location.search); if (queryParams.has("search")) { searchInput.val(queryParams.get("search")); searchInput.trigger($.Event( "keypress", { which: KeyCodes.ENTER } )); } window.onpopstate = function(event) { const state = event.state; if (state && state.hash) { searchInput.val(state.hash); searchInput.trigger($.Event( "keypress", { which: KeyCodes.ENTER } )); } else { searchInput.val(""); const main = $("#main"); main.empty(); } }; if (window.location.protocol == "http:") { webSocket = new WebSocket("ws://" + window.location.host + "/api/v1/announcements"); } else { webSocket = new WebSocket("wss://" + window.location.host + "/api/v1/announcements"); } webSocket.onopen = function() { }; webSocket.onmessage = function(event) { const message = JSON.parse(event.data); const objectType = message.objectType; let container = null; let element = null; if ( (objectType == "TRANSACTION") || (objectType == "TRANSACTION_HASH") ) { const transaction = message.object; container = $("#main .recent-transactions"); element = Ui.inflateTransaction(transaction); element.off("click"); } else if (objectType == "BLOCK") { const blockHeader = message.object; container = $("#main .recent-blocks"); element = Ui.inflateBlock(blockHeader); const blockLink = $(".hash .value", element); blockLink.toggleClass("clickable", true); blockLink.on("click", Ui._makeNavigateToBlockEvent(blockHeader.hash)); element.off("click"); } if (container != null && element != null) { const childrenElements = container.children(); if (childrenElements.length > 9) { childrenElements.last().remove(); } container.prepend(element); HashResizer.update(container); } return false; }; webSocket.onclose = function() { console.log("WebSocket closed..."); }; const postTransactionInput = $("#post-transaction-input"); const postTransactionButton = $("#post-transaction-button"); postTransactionButton.on("click", function() { const transactionData = postTransactionInput.val(); Api.postTransaction({ transactionData: transactionData }, function(result) { if (result.wasSuccess) { postTransactionInput.val(""); } }); }); Ui.displayCashAddressFormat = (Cookies.get("cashAddressIsEnabled") != "false"); $("#cash-address-format-toggle").toggleClass("off", (Ui.displayCashAddressFormat ? false : true)); $("#cash-address-format-toggle").on("change", function(event, isToggledOn) { Ui.displayCashAddressFormat = isToggledOn; Cookies.set("cashAddressIsEnabled", (Ui.displayCashAddressFormat ? "true" : "false")); if ( (Ui.currentObject != null) && (Ui.currentObjectType != null) ) { const originalScrollOffset = window.scrollY; renderObject(Ui.currentObject, Ui.currentObjectType); window.setTimeout(function() { window.scrollTo({ top: originalScrollOffset }); }, 0); } }); }); <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/database/transaction/fullnode/utxo/BlockingQueueBatchRunnerTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo; import com.softwareverde.bitcoin.server.database.BatchRunner; import com.softwareverde.bitcoin.server.module.node.database.transaction.BlockingQueueBatchRunner; import com.softwareverde.bitcoin.test.UnitTest; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.ConcurrentLinkedDeque; public class BlockingQueueBatchRunnerTests extends UnitTest { @Test public void should_include_all_items_when_less_than_the_batch_size() throws Exception { // Setup final ConcurrentLinkedDeque<TransactionOutputIdentifier> executedItems = new ConcurrentLinkedDeque<TransactionOutputIdentifier>(); final BlockingQueueBatchRunner<TransactionOutputIdentifier> blockingQueueBatchRunner = BlockingQueueBatchRunner.newInstance(true, new BatchRunner.Batch<TransactionOutputIdentifier>() { @Override public void run(final List<TransactionOutputIdentifier> batchItems) throws Exception { for (final TransactionOutputIdentifier transactionOutputIdentifier : batchItems) { executedItems.add(transactionOutputIdentifier); } } } ); final Sha256Hash transactionHash = TransactionOutputIdentifier.COINBASE.getTransactionHash(); // Action blockingQueueBatchRunner.start(); final int batchSize = (1024 + 1); for (int i = 0; i < batchSize; ++i) { final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, i); blockingQueueBatchRunner.addItem(transactionOutputIdentifier); } blockingQueueBatchRunner.finish(); blockingQueueBatchRunner.join(); // Assert Assert.assertEquals(batchSize, executedItems.size()); for (int i = 0; i < batchSize; ++i) { final TransactionOutputIdentifier transactionOutputIdentifier = executedItems.removeFirst(); Assert.assertEquals(transactionHash, transactionOutputIdentifier.getTransactionHash()); Assert.assertEquals(Integer.valueOf(i), transactionOutputIdentifier.getOutputIndex()); } } @Test public void UtxoQueryBatchGroupedByBlockHeight_should_include_all_items_when_less_than_the_batch_size() throws Exception { // Setup final ConcurrentLinkedDeque<TransactionOutputIdentifier> executedItems = new ConcurrentLinkedDeque<TransactionOutputIdentifier>(); final BlockingQueueBatchRunner<TransactionOutputIdentifier> blockingQueueBatchRunner = BlockingQueueBatchRunner.newInstance(true, new BatchRunner.Batch<TransactionOutputIdentifier>() { @Override public void run(final List<TransactionOutputIdentifier> batchItems) throws Exception { for (final TransactionOutputIdentifier unspentTransactionOutput : batchItems) { executedItems.add(unspentTransactionOutput); } } } ); final Sha256Hash transactionHash = TransactionOutputIdentifier.COINBASE.getTransactionHash(); // Action blockingQueueBatchRunner.start(); final int batchSize = ((1024 * 3) + 1); for (int i = 0; i < batchSize; ++i) { final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, i); blockingQueueBatchRunner.addItem(transactionOutputIdentifier); } blockingQueueBatchRunner.finish(); blockingQueueBatchRunner.join(); // Assert Assert.assertEquals(batchSize, executedItems.size()); for (int i = 0; i < batchSize; ++i) { final TransactionOutputIdentifier transactionOutputIdentifier = executedItems.removeFirst(); Assert.assertEquals(transactionHash, transactionOutputIdentifier.getTransactionHash()); Assert.assertEquals(Integer.valueOf(i), transactionOutputIdentifier.getOutputIndex()); } } @Test public void UtxoQueryBatchGroupedByBlockHeight_should_run_both_entries_when_last_entry_has_unique_block_height() throws Exception { // Setup final ConcurrentLinkedDeque<TransactionOutputIdentifier> executedItems = new ConcurrentLinkedDeque<TransactionOutputIdentifier>(); final BlockingQueueBatchRunner<TransactionOutputIdentifier> blockingQueueBatchRunner = BlockingQueueBatchRunner.newInstance(true, new BatchRunner.Batch<TransactionOutputIdentifier>() { @Override public void run(final List<TransactionOutputIdentifier> batchItems) throws Exception { for (final TransactionOutputIdentifier unspentTransactionOutput : batchItems) { executedItems.add(unspentTransactionOutput); } } } ); // Action blockingQueueBatchRunner.start(); blockingQueueBatchRunner.addItem(new TransactionOutputIdentifier(Sha256Hash.fromHexString("0000000000000000000000000000000000000000000000000000000000000000"), 0)); blockingQueueBatchRunner.addItem(new TransactionOutputIdentifier(Sha256Hash.fromHexString("F4184FC596403B9D638783CF57ADFE4C75C605F6356FBC91338530E9831E9E16"), 1)); blockingQueueBatchRunner.addItem(new TransactionOutputIdentifier(Sha256Hash.fromHexString("0437CD7F8525CEED2324359C2D0BA26006D92D856A9C20FA0241106EE5A597C9"), 0)); blockingQueueBatchRunner.finish(); blockingQueueBatchRunner.join(); // Assert Assert.assertEquals(blockingQueueBatchRunner.getTotalItemCount(), Integer.valueOf(executedItems.size())); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/output/TransactionOutputDeflater.java<|end_filename|> package com.softwareverde.bitcoin.transaction.output; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.bitcoin.transaction.script.ScriptPatternMatcher; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.json.Json; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class TransactionOutputDeflater { protected ByteArray _toBytes(final TransactionOutput transactionOutput) { final byte[] valueBytes = new byte[8]; ByteUtil.setBytes(valueBytes, ByteUtil.longToBytes(transactionOutput.getAmount())); final ByteArray lockingScriptBytes = transactionOutput.getLockingScript().getBytes(); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(valueBytes, Endian.LITTLE); byteArrayBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(lockingScriptBytes.getByteCount()), Endian.BIG); byteArrayBuilder.appendBytes(lockingScriptBytes, Endian.BIG); return MutableByteArray.wrap(byteArrayBuilder.build()); } public Integer getByteCount(final TransactionOutput transactionOutput) { final Integer valueByteCount = 8; final Script lockingScript = transactionOutput.getLockingScript(); final Integer scriptByteCount; { Integer byteCount = 0; byteCount += ByteUtil.variableLengthIntegerToBytes(lockingScript.getByteCount()).length; byteCount += lockingScript.getByteCount(); scriptByteCount = byteCount; } return (valueByteCount + scriptByteCount); } public ByteArray toBytes(final TransactionOutput transactionOutput) { return _toBytes(transactionOutput); } public Json toJson(final TransactionOutput transactionOutput) { final ScriptPatternMatcher scriptPatternMatcher = new ScriptPatternMatcher(); final LockingScript lockingScript = transactionOutput.getLockingScript(); final ScriptType scriptType = scriptPatternMatcher.getScriptType(lockingScript); final Address address = scriptPatternMatcher.extractAddress(scriptType, lockingScript); final Json json = new Json(); json.put("amount", transactionOutput.getAmount()); json.put("index", transactionOutput.getIndex()); json.put("lockingScript", transactionOutput.getLockingScript()); json.put("type", scriptType); json.put("address", (address == null ? null : address.toBase58CheckEncoded())); // json.put("bytes", HexUtil.toHexString(_toBytes(transactionOutput))); return json; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/opcode/BitwiseOperation.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode; import com.softwareverde.bitcoin.transaction.script.runner.ControlState; import com.softwareverde.bitcoin.transaction.script.runner.context.MutableTransactionContext; import com.softwareverde.bitcoin.transaction.script.stack.Stack; import com.softwareverde.bitcoin.transaction.script.stack.Value; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.logging.Logger; import com.softwareverde.util.bytearray.ByteArrayReader; public class BitwiseOperation extends SubTypedOperation { public static final Type TYPE = Type.OP_BITWISE; protected static BitwiseOperation fromBytes(final ByteArrayReader byteArrayReader) { if (! byteArrayReader.hasBytes()) { return null; } final byte opcodeByte = byteArrayReader.readByte(); final Type type = Type.getType(opcodeByte); if (type != TYPE) { return null; } final Opcode opcode = TYPE.getSubtype(opcodeByte); if (opcode == null) { return null; } return new BitwiseOperation(opcodeByte, opcode); } protected BitwiseOperation(final Opcode opcode) { super(opcode.getValue(), TYPE, opcode); } protected BitwiseOperation(final byte value, final Opcode opcode) { super(value, TYPE, opcode); } @Override public Boolean applyTo(final Stack stack, final ControlState controlState, final MutableTransactionContext context) { if (! _opcode.isEnabled()) { Logger.debug("NOTICE: Opcode is disabled: " + _opcode); return false; } switch (_opcode) { case BITWISE_INVERT: { final Value value = stack.pop(); final MutableByteArray byteValue = MutableByteArray.wrap(value.getBytes()); final int byteCount = byteValue.getByteCount(); for (int i = 0; i < byteCount; ++i) { final byte b = byteValue.getByte(i); final byte newB = (byte) ~b; byteValue.setByte(i, newB); } stack.push(Value.fromBytes(byteValue.unwrap())); return (! stack.didOverflow()); } case BITWISE_AND: { // value0 value1 BITWISE_AND -> { value0 & value1 } // { 0x00 } { 0x01 } BITWISE_AND -> { 0x00 } final Value value1 = stack.pop(); final Value value0 = stack.pop(); final MutableByteArray byteValue0 = MutableByteArray.wrap(value0.getBytes()); final ByteArray byteValue1 = MutableByteArray.wrap(value1.getBytes()); if (byteValue0.getByteCount() != byteValue1.getByteCount()) { return false; } final int byteCount = byteValue0.getByteCount(); for (int i = 0; i < byteCount; ++i) { final byte b0 = byteValue0.getByte(i); final byte b1 = byteValue1.getByte(i); final byte newB = (byte) (b0 & b1); byteValue0.setByte(i, newB); } stack.push(Value.fromBytes(byteValue0.unwrap())); return (! stack.didOverflow()); } case BITWISE_OR: { // value0 value1 BITWISE_OR -> { value0 | value1 } // { 0x00 } { 0x01 } BITWISE_OR -> { 0x01 } final Value value1 = stack.pop(); final Value value0 = stack.pop(); final MutableByteArray byteValue0 = MutableByteArray.wrap(value0.getBytes()); final ByteArray byteValue1 = MutableByteArray.wrap(value1.getBytes()); if (byteValue0.getByteCount() != byteValue1.getByteCount()) { return false; } final int byteCount = byteValue0.getByteCount(); for (int i = 0; i < byteCount; ++i) { final byte b0 = byteValue0.getByte(i); final byte b1 = byteValue1.getByte(i); final byte newB = (byte) (b0 | b1); byteValue0.setByte(i, newB); } stack.push(Value.fromBytes(byteValue0.unwrap())); return (! stack.didOverflow()); } case BITWISE_XOR: { // value0 value1 BITWISE_XOR -> { value0 ^ value1 } // { 0x01 } { 0x01 } BITWISE_XOR -> { 0x00 } final Value value1 = stack.pop(); final Value value0 = stack.pop(); final MutableByteArray byteValue0 = MutableByteArray.wrap(value0.getBytes()); final ByteArray byteValue1 = MutableByteArray.wrap(value1.getBytes()); if (byteValue0.getByteCount() != byteValue1.getByteCount()) { return false; } final int byteCount = byteValue0.getByteCount(); for (int i = 0; i < byteCount; ++i) { final byte b0 = byteValue0.getByte(i); final byte b1 = byteValue1.getByte(i); final byte newB = (byte) (b0 ^ b1); byteValue0.setByte(i, newB); } stack.push(Value.fromBytes(byteValue0.unwrap())); return (! stack.didOverflow()); } case SHIFT_LEFT: { final Value bitShiftCountValue = stack.pop(); final MutableByteArray value = new MutableByteArray(stack.pop()); if (! bitShiftCountValue.isMinimallyEncodedInteger()) { return false; } final Integer bitShiftCount = bitShiftCountValue.asInteger(); if (bitShiftCount < 0) { return false; } final int byteCount = value.getByteCount(); final int bitCount = (byteCount * 8); if (bitShiftCount < bitCount) { for (int i = 0; i < bitCount; ++i) { final int writeIndex = i; final int readIndex = (writeIndex + bitShiftCount); final boolean newValue = ( (readIndex < bitCount) && value.getBit(readIndex) ); value.setBit(writeIndex, newValue); } stack.push(Value.fromBytes(value.unwrap())); } else { stack.push(Value.fromBytes(new byte[byteCount])); } return (! stack.didOverflow()); } case SHIFT_RIGHT: { final Value bitShiftCountValue = stack.pop(); final MutableByteArray value = new MutableByteArray(stack.pop()); if (! bitShiftCountValue.isMinimallyEncodedInteger()) { return false; } final Integer bitShiftCount = bitShiftCountValue.asInteger(); if (bitShiftCount < 0) { return false; } final int byteCount = value.getByteCount(); final int bitCount = (byteCount * 8); if (bitShiftCount < bitCount) { for (int i = 0; i < bitCount; ++i) { final int writeIndex = (bitCount - i - 1); final int readIndex = (writeIndex - bitShiftCount); final boolean newValue = ( (readIndex >= 0) && value.getBit(readIndex) ); value.setBit(writeIndex, newValue); } stack.push(Value.fromBytes(value.unwrap())); } else { stack.push(Value.fromBytes(new byte[byteCount])); } return (! stack.didOverflow()); } default: { return false; } } } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeDifficultyCalculatorContext.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.work.ChainWork; import com.softwareverde.bitcoin.block.validator.difficulty.AsertReferenceBlock; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.context.DifficultyCalculatorContext; import org.junit.Assert; import java.util.HashMap; public class FakeDifficultyCalculatorContext implements DifficultyCalculatorContext { protected final HashMap<Long, BlockHeader> _blockHeaders = new HashMap<Long, BlockHeader>(); protected final HashMap<Long, ChainWork> _chainWorks = new HashMap<Long, ChainWork>(); protected final HashMap<Long, MedianBlockTime> _medianBlockTimes = new HashMap<Long, MedianBlockTime>(); protected final AsertReferenceBlock _asertReferenceBlock; public FakeDifficultyCalculatorContext() { this(null); } public FakeDifficultyCalculatorContext(final AsertReferenceBlock asertReferenceBlock) { _asertReferenceBlock = asertReferenceBlock; } @Override public BlockHeader getBlockHeader(final Long blockHeight) { if (! _blockHeaders.containsKey(blockHeight)) { Assert.fail("Requesting unregistered BlockHeader for blockHeight: " + blockHeight); } return _blockHeaders.get(blockHeight); } @Override public ChainWork getChainWork(final Long blockHeight) { if (! _chainWorks.containsKey(blockHeight)) { Assert.fail("Requesting unregistered ChainWork for blockHeight: " + blockHeight); } return _chainWorks.get(blockHeight); } @Override public MedianBlockTime getMedianBlockTime(final Long blockHeight) { if (! _medianBlockTimes.containsKey(blockHeight)) { Assert.fail("Requesting unregistered MedianBlockTime for blockHeight: " + blockHeight); } return _medianBlockTimes.get(blockHeight); } public HashMap<Long, BlockHeader> getBlockHeaders() { return _blockHeaders; } public HashMap<Long, ChainWork> getChainWorks() { return _chainWorks; } public HashMap<Long, MedianBlockTime> getMedianBlockTimes() { return _medianBlockTimes; } @Override public AsertReferenceBlock getAsertReferenceBlock() { return _asertReferenceBlock; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/rpc/NodeJsonRpcConnection.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.rpc; import com.softwareverde.bitcoin.CoreInflater; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.inflater.MasterInflater; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.json.Json; import com.softwareverde.logging.Logger; import com.softwareverde.network.socket.JsonProtocolMessage; import com.softwareverde.network.socket.JsonSocket; import com.softwareverde.util.HexUtil; public class NodeJsonRpcConnection implements AutoCloseable { public interface AnnouncementHookCallback { void onNewBlockHeader(Json blockHeaderJson); void onNewTransaction(Json transactionJson); } public interface RawAnnouncementHookCallback { void onNewBlockHeader(BlockHeader blockHeader); void onNewTransaction(Transaction transaction, Long fee); } public static final Long RPC_DURATION_TIMEOUT_MS = 30000L; protected final MasterInflater _masterInflater; protected final JsonSocket _jsonSocket; protected final Object _newMessageNotifier = new Object(); protected final Runnable _onNewMessageCallback = new Runnable() { @Override public void run() { synchronized (_newMessageNotifier) { _newMessageNotifier.notifyAll(); } } }; protected Boolean _isUpgradedToHook = false; protected Boolean _announcementHookExpectsRawTransactionData = null; protected Json _executeJsonRequest(final Json rpcRequestJson) { if (_isUpgradedToHook) { throw new RuntimeException("Attempted to invoke Json request to a hook-upgraded socket."); } if (! _jsonSocket.isConnected()) { throw new RuntimeException("Attempted to invoke Json request to a closed socket."); } _jsonSocket.write(new JsonProtocolMessage(rpcRequestJson)); _jsonSocket.beginListening(); JsonProtocolMessage jsonProtocolMessage; synchronized (_newMessageNotifier) { jsonProtocolMessage = _jsonSocket.popMessage(); if (jsonProtocolMessage == null) { try { _newMessageNotifier.wait(RPC_DURATION_TIMEOUT_MS); } catch (final InterruptedException exception) { } jsonProtocolMessage = _jsonSocket.popMessage(); } } return (jsonProtocolMessage != null ? jsonProtocolMessage.getMessage() : null); } protected Json _createRegisterHookRpcJson(final Boolean returnRawData, final Boolean includeTransactionFees, final List<Address> addressFilter) { final Json eventTypesJson = new Json(true); eventTypesJson.add("NEW_BLOCK"); eventTypesJson.add("NEW_TRANSACTION"); final Json parametersJson = new Json(); parametersJson.put("events", eventTypesJson); parametersJson.put("rawFormat", (returnRawData ? 1 : 0)); parametersJson.put("includeTransactionFees", (includeTransactionFees ? 1 : 0)); if (addressFilter != null) { final Json addressFilterJson = new Json(true); for (final Address address : addressFilter) { final String addressString = address.toBase58CheckEncoded(); addressFilterJson.add(addressString); } parametersJson.put("addressFilter", addressFilterJson); } final Json registerHookRpcJson = new Json(); registerHookRpcJson.put("method", "POST"); registerHookRpcJson.put("query", "ADD_HOOK"); registerHookRpcJson.put("parameters", parametersJson); return registerHookRpcJson; } protected Json _getBlock(final Sha256Hash blockHash, final Boolean hexFormat) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("hash", blockHash); if (hexFormat != null) { rpcParametersJson.put("rawFormat", (hexFormat ? 1 : 0)); } final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCK"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } protected Json _getBlock(final Long blockHeight, final Boolean hexFormat) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("blockHeight", blockHeight); if (hexFormat != null) { rpcParametersJson.put("rawFormat", (hexFormat ? 1 : 0)); } final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCK"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } protected Json _getBlockHeader(final Sha256Hash blockHash, final Boolean hexFormat) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("hash", blockHash); if (hexFormat != null) { rpcParametersJson.put("rawFormat", (hexFormat ? 1 : 0)); } final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCK_HEADER"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } protected Json _getBlockHeader(final Long blockHeight, final Boolean hexFormat) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("blockHeight", blockHeight); if (hexFormat != null) { rpcParametersJson.put("rawFormat", (hexFormat ? 1 : 0)); } final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCK_HEADER"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } protected Json _getBlockTransactions(final Sha256Hash blockHash, final Integer pageSize, final Integer pageNumber) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("hash", blockHash); if (pageSize != null) { rpcParametersJson.put("pageSize", pageSize); } if (pageNumber != null) { rpcParametersJson.put("pageNumber", pageNumber); } final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCK_TRANSACTIONS"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } protected Json _getBlockTransactions(final Long blockHeight, final Integer pageSize, final Integer pageNumber) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("blockHeight", blockHeight); if (pageSize != null) { rpcParametersJson.put("pageSize", pageSize); } if (pageNumber != null) { rpcParametersJson.put("pageNumber", pageNumber); } final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCK_TRANSACTIONS"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } protected Json _getTransaction(final Sha256Hash transactionHash, final Boolean hexFormat) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("hash", transactionHash); if (hexFormat != null) { rpcParametersJson.put("rawFormat", (hexFormat ? 1 : 0)); } final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "TRANSACTION"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public NodeJsonRpcConnection(final String hostname, final Integer port, final ThreadPool threadPool) { this( hostname, port, threadPool, new CoreInflater() ); } public NodeJsonRpcConnection(final String hostname, final Integer port, final ThreadPool threadPool, final MasterInflater masterInflater) { _masterInflater = masterInflater; final java.net.Socket javaSocket; { java.net.Socket socket = null; try { socket = new java.net.Socket(hostname, port); } catch (final Exception exception) { Logger.debug(exception); } javaSocket = socket; } _jsonSocket = ((javaSocket != null) ? new JsonSocket(javaSocket, threadPool) : null); if (_jsonSocket != null) { _jsonSocket.setMessageReceivedCallback(_onNewMessageCallback); } } public NodeJsonRpcConnection(final java.net.Socket javaSocket, final ThreadPool threadPool) { this( javaSocket, threadPool, new CoreInflater() ); } public NodeJsonRpcConnection(final java.net.Socket socket, final ThreadPool threadPool, final MasterInflater masterInflater) { _masterInflater = masterInflater; _jsonSocket = ((socket != null) ? new JsonSocket(socket, threadPool) : null); if (_jsonSocket != null) { _jsonSocket.setMessageReceivedCallback(_onNewMessageCallback); } } public Json getBlockHeaders(final Long blockHeight, final Integer maxBlockCount, final Boolean returnRawFormat) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("blockHeight", blockHeight); rpcParametersJson.put("maxBlockCount", maxBlockCount); rpcParametersJson.put("rawFormat", (returnRawFormat ? 1 : 0)); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCK_HEADERS"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public Json getBlockHeaders(final Integer maxBlockCount, final Boolean returnRawFormat) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("maxBlockCount", maxBlockCount); rpcParametersJson.put("rawFormat", (returnRawFormat ? 1 : 0)); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCK_HEADERS"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public Json getDifficulty() { final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "DIFFICULTY"); return _executeJsonRequest(rpcRequestJson); } public Json getBlockReward() { final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCK_REWARD"); return _executeJsonRequest(rpcRequestJson); } public Json getUnconfirmedTransactions(final Boolean returnRawFormat) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("rawFormat", (returnRawFormat ? 1 : 0)); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "UNCONFIRMED_TRANSACTIONS"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public Json getBlockHeight() { final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCK_HEIGHT"); return _executeJsonRequest(rpcRequestJson); } public Json getBlockHeaderHeight(final Sha256Hash blockHash) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("hash", blockHash.toString()); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCK_HEIGHT"); return _executeJsonRequest(rpcRequestJson); } public Json getBlockchainMetadata() { final Json rpcRequestJson = new Json(); { rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "BLOCKCHAIN"); } return _executeJsonRequest(rpcRequestJson); } public Json getNodes() { final Json rpcRequestJson = new Json(); { rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "NODES"); } return _executeJsonRequest(rpcRequestJson); } public Json getAddressTransactions(final Address address) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("address", address.toBase58CheckEncoded()); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "ADDRESS"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public Json getBlock(final Sha256Hash blockHash) { return _getBlock(blockHash, null); } public Json getBlock(final Sha256Hash blockHash, final Boolean hexFormat) { return _getBlock(blockHash, hexFormat); } public Json getBlock(final Long blockHeight) { return _getBlock(blockHeight, null); } public Json getBlock(final Long blockHeight, final Boolean hexFormat) { return _getBlock(blockHeight, hexFormat); } public Json getBlockHeader(final Sha256Hash blockHash) { return _getBlockHeader(blockHash, null); } public Json getBlockHeader(final Sha256Hash blockHash, final Boolean hexFormat) { return _getBlockHeader(blockHash, hexFormat); } public Json getBlockHeader(final Long blockHeight) { return _getBlockHeader(blockHeight, null); } public Json getBlockHeader(final Long blockHeight, final Boolean hexFormat) { return _getBlockHeader(blockHeight, hexFormat); } public Json getBlockTransactions(final Sha256Hash blockHash, final Integer pageSize, final Integer pageNumber) { return _getBlockTransactions(blockHash, pageSize, pageNumber); } public Json getBlockTransactions(final Long blockHeight, final Integer pageSize, final Integer pageNumber) { return _getBlockTransactions(blockHeight, pageSize, pageNumber); } public Json getTransaction(final Sha256Hash transactionHash) { return _getTransaction(transactionHash, null); } public Json getTransaction(final Sha256Hash transactionHash, final Boolean hexFormat) { return _getTransaction(transactionHash, hexFormat); } public Json getStatus() { final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "STATUS"); return _executeJsonRequest(rpcRequestJson); } public Json getUtxoCacheStatus() { final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "UTXO_CACHE"); return _executeJsonRequest(rpcRequestJson); } public Json commitUtxoCache() { final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "POST"); rpcRequestJson.put("query", "COMMIT_UTXO_CACHE"); return _executeJsonRequest(rpcRequestJson); } /** * Subscribes to the Node for new Block/Transaction announcements. * The NodeJsonRpcConnection is consumed by this operation and cannot be used for additional API calls. * The underlying JsonSocket remains connected and must be closed when announcements are no longer desired. */ public Boolean upgradeToAnnouncementHook(final AnnouncementHookCallback announcementHookCallback) { return this.upgradeToAnnouncementHook(announcementHookCallback, null); } public Boolean upgradeToAnnouncementHook(final AnnouncementHookCallback announcementHookCallback, final List<Address> addressesFilter) { if (announcementHookCallback == null) { throw new NullPointerException("Attempted to create AnnouncementHook without a callback."); } final Json registerHookRpcJson = _createRegisterHookRpcJson(false, true, addressesFilter); final Json upgradeResponseJson = _executeJsonRequest(registerHookRpcJson); if (! upgradeResponseJson.getBoolean("wasSuccess")) { return false; } _jsonSocket.setMessageReceivedCallback(new Runnable() { @Override public void run() { final JsonProtocolMessage message = _jsonSocket.popMessage(); final Json json = message.getMessage(); final String objectType = json.getString("objectType"); final Json object = json.get("object"); switch (objectType) { case "BLOCK": { announcementHookCallback.onNewBlockHeader(object); } break; case "TRANSACTION": { announcementHookCallback.onNewTransaction(object); } break; default: { } break; } } }); _isUpgradedToHook = true; _announcementHookExpectsRawTransactionData = false; return true; } public Boolean replaceAnnouncementHookAddressFilter(final List<Address> addressesFilter) { if (! _isUpgradedToHook) { return false; } final boolean returnRawData = _announcementHookExpectsRawTransactionData; final Json rpcRequestJson = _createRegisterHookRpcJson(returnRawData, true, addressesFilter); rpcRequestJson.put("query", "UPDATE_HOOK"); _jsonSocket.write(new JsonProtocolMessage(rpcRequestJson)); return true; } public Boolean upgradeToAnnouncementHook(final RawAnnouncementHookCallback announcementHookCallback) { return this.upgradeToAnnouncementHook(announcementHookCallback, null); } public Boolean upgradeToAnnouncementHook(final RawAnnouncementHookCallback announcementHookCallback, final List<Address> addressesFilter) { if (announcementHookCallback == null) { throw new NullPointerException("Null AnnouncementHookCallback found."); } final Json registerHookRpcJson = _createRegisterHookRpcJson(true, true, addressesFilter); final Json upgradeResponseJson = _executeJsonRequest(registerHookRpcJson); if (! upgradeResponseJson.getBoolean("wasSuccess")) { return false; } _jsonSocket.setMessageReceivedCallback(new Runnable() { @Override public void run() { final JsonProtocolMessage message = _jsonSocket.popMessage(); final Json json = message.getMessage(); final String objectType = json.getString("objectType"); switch (objectType) { case "BLOCK": { final String objectData = json.getString("object"); final BlockHeaderInflater blockHeaderInflater = _masterInflater.getBlockHeaderInflater(); final BlockHeader blockHeader = blockHeaderInflater.fromBytes(HexUtil.hexStringToByteArray(objectData)); if (blockHeader == null) { Logger.warn("Error inflating block: " + objectData); return; } announcementHookCallback.onNewBlockHeader(blockHeader); } break; case "TRANSACTION": { final String objectData = json.getString("object"); final TransactionInflater transactionInflater = _masterInflater.getTransactionInflater(); final Transaction transaction = transactionInflater.fromBytes(HexUtil.hexStringToByteArray(objectData)); if (transaction == null) { Logger.warn("Error inflating transaction: " + objectData); return; } announcementHookCallback.onNewTransaction(transaction, null); } break; case "TRANSACTION_WITH_FEE": { final Json object = json.get("object"); final String transactionData = object.getString("transactionData"); final Long fee = object.getLong("transactionFee"); final TransactionInflater transactionInflater = _masterInflater.getTransactionInflater(); final Transaction transaction = transactionInflater.fromBytes(HexUtil.hexStringToByteArray(transactionData)); if (transaction == null) { Logger.warn("Error inflating transaction: " + transactionData); return; } announcementHookCallback.onNewTransaction(transaction, fee); } break; default: { } break; } } }); _isUpgradedToHook = true; _announcementHookExpectsRawTransactionData = true; return true; } public Json validatePrototypeBlock(final Block block) { final Json rpcParametersJson = new Json(); final BlockDeflater blockDeflater = _masterInflater.getBlockDeflater(); rpcParametersJson.put("blockData", blockDeflater.toBytes(block)); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "POST"); rpcRequestJson.put("query", "VALIDATE_PROTOTYPE_BLOCK"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public Json submitTransaction(final Transaction transaction) { final Json rpcParametersJson = new Json(); final TransactionDeflater transactionDeflater = _masterInflater.getTransactionDeflater(); rpcParametersJson.put("transactionData", transactionDeflater.toBytes(transaction)); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "POST"); rpcRequestJson.put("query", "TRANSACTION"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public Json submitBlock(final Block block) { final Json rpcParametersJson = new Json(); final BlockDeflater blockDeflater = _masterInflater.getBlockDeflater(); rpcParametersJson.put("blockData", blockDeflater.toBytes(block)); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "POST"); rpcRequestJson.put("query", "BLOCK"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public Json isSlpTransaction(final Sha256Hash transactionHash) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("hash", transactionHash); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "IS_SLP_TRANSACTION"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public Json isValidSlpTransaction(final Sha256Hash transactionHash) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("hash", transactionHash); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "IS_VALID_SLP_TRANSACTION"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public Json validateTransaction(final Transaction transaction, final Boolean enableSlpValidation) { final TransactionDeflater transactionDeflater = new TransactionDeflater(); final ByteArray transactionBytes = transactionDeflater.toBytes(transaction); final Json rpcParametersJson = new Json(); rpcParametersJson.put("transactionData", transactionBytes); rpcParametersJson.put("enableSlpValidation", (enableSlpValidation ? 1 : 0)); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "POST"); rpcRequestJson.put("query", "IS_VALID_SLP_TRANSACTION"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public Json getSlpTokenId(final Sha256Hash transactionHash) { final Json rpcParametersJson = new Json(); rpcParametersJson.put("hash", transactionHash); final Json rpcRequestJson = new Json(); rpcRequestJson.put("method", "GET"); rpcRequestJson.put("query", "SLP_TOKEN_ID"); rpcRequestJson.put("parameters", rpcParametersJson); return _executeJsonRequest(rpcRequestJson); } public JsonSocket getJsonSocket() { return _jsonSocket; } @Override public void close() { _jsonSocket.close(); } } <|start_filename|>src/main/java/org/bitcoin/NativeSecp256k1.java<|end_filename|> package org.bitcoin; import java.nio.ByteBuffer; public class NativeSecp256k1 { public static native void secp256k1_destroy_context(long context); public static native int secp256k1_ecdsa_verify(ByteBuffer byteBuff, long context, int sigLen, int pubLen); } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/database/FakeDatabaseManagerFactory.java<|end_filename|> package com.softwareverde.bitcoin.test.fake.database; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManagerFactory; import com.softwareverde.database.DatabaseException; public interface FakeDatabaseManagerFactory extends DatabaseManagerFactory { @Override default DatabaseManager newDatabaseManager() throws DatabaseException { throw new UnsupportedOperationException(); } @Override default DatabaseConnectionFactory getDatabaseConnectionFactory() { throw new UnsupportedOperationException(); } @Override default DatabaseManagerFactory newDatabaseManagerFactory(DatabaseConnectionFactory databaseConnectionFactory) { throw new UnsupportedOperationException(); } @Override default Integer getMaxQueryBatchSize() { throw new UnsupportedOperationException(); } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/StratumDataHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint; import com.softwareverde.bitcoin.block.Block; public interface StratumDataHandler { Block getPrototypeBlock(); Long getPrototypeBlockHeight(); Long getHashesPerSecond(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/ChainValidationModule.java<|end_filename|> package com.softwareverde.bitcoin.server.module; import com.softwareverde.bitcoin.CoreInflater; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.validator.BlockValidationResult; import com.softwareverde.bitcoin.block.validator.BlockValidator; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.context.TransactionValidatorFactory; import com.softwareverde.bitcoin.context.lazy.LazyBlockValidatorContext; import com.softwareverde.bitcoin.context.lazy.LazyMutableUnspentTransactionOutputSet; import com.softwareverde.bitcoin.inflater.BlockHeaderInflaters; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.inflater.MasterInflater; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.Environment; import com.softwareverde.bitcoin.server.configuration.BitcoinProperties; import com.softwareverde.bitcoin.server.configuration.CheckpointConfiguration; import com.softwareverde.bitcoin.server.database.Database; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.BlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.fullnode.FullNodeBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.store.PendingBlockStore; import com.softwareverde.bitcoin.server.module.node.store.PendingBlockStoreCore; import com.softwareverde.bitcoin.transaction.validator.BlockOutputs; import com.softwareverde.bitcoin.transaction.validator.TransactionValidator; import com.softwareverde.bitcoin.transaction.validator.TransactionValidatorCore; import com.softwareverde.bitcoin.util.BitcoinUtil; import com.softwareverde.bitcoin.util.StringUtil; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; import com.softwareverde.network.time.NetworkTime; import com.softwareverde.network.time.VolatileNetworkTime; import com.softwareverde.util.Util; import com.softwareverde.util.timer.MilliTimer; import com.softwareverde.util.type.time.SystemTime; public class ChainValidationModule { protected final BitcoinProperties _bitcoinProperties; protected final Environment _environment; protected final Sha256Hash _startingBlockHash; protected final PendingBlockStore _blockStore; protected final CheckpointConfiguration _checkpointConfiguration; public ChainValidationModule(final BitcoinProperties bitcoinProperties, final Environment environment, final String startingBlockHash) { _bitcoinProperties = bitcoinProperties; _environment = environment; final MasterInflater masterInflater = new CoreInflater(); _startingBlockHash = Util.coalesce(Sha256Hash.fromHexString(startingBlockHash), BlockHeader.GENESIS_BLOCK_HASH); { // Initialize the BlockCache... final String blockCacheDirectory = (bitcoinProperties.getDataDirectory() + "/" + BitcoinProperties.DATA_DIRECTORY_NAME + "/blocks"); final String pendingBlockCacheDirectory = (bitcoinProperties.getDataDirectory() + "/" + BitcoinProperties.DATA_DIRECTORY_NAME + "/pending-blocks"); final BlockHeaderInflaters blockHeaderInflaters = masterInflater; final BlockInflaters blockInflaters = masterInflater; _blockStore = new PendingBlockStoreCore(blockCacheDirectory, pendingBlockCacheDirectory, blockHeaderInflaters, blockInflaters) { @Override protected void _deletePendingBlockData(final String blockPath) { if (bitcoinProperties.isDeletePendingBlocksEnabled()) { super._deletePendingBlockData(blockPath); } } }; } _checkpointConfiguration = new CheckpointConfiguration(); } public void run() { final Thread mainThread = Thread.currentThread(); mainThread.setPriority(Thread.MAX_PRIORITY); final Database database = _environment.getDatabase(); // final MasterDatabaseManagerCache masterDatabaseManagerCache = _environment.getMasterDatabaseManagerCache(); final MasterInflater masterInflater = new CoreInflater(); final BlockchainSegmentId blockchainSegmentId; final DatabaseConnectionFactory databaseConnectionPool = _environment.getDatabaseConnectionFactory(); final FullNodeDatabaseManagerFactory databaseManagerFactory = new FullNodeDatabaseManagerFactory(databaseConnectionPool, database.getMaxQueryBatchSize(), _blockStore, masterInflater, _checkpointConfiguration); try (final DatabaseManager databaseManager = databaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final BlockId headBlockId = blockDatabaseManager.getHeadBlockId(); blockchainSegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(headBlockId); } catch (final DatabaseException exception) { Logger.debug(exception); throw new RuntimeException(exception); } Sha256Hash nextBlockHash = _startingBlockHash; try (final DatabaseConnection databaseConnection = database.newConnection();) { final FullNodeDatabaseManager databaseManager = new FullNodeDatabaseManager( databaseConnection, database.getMaxQueryBatchSize(), _blockStore, masterInflater, _checkpointConfiguration, _bitcoinProperties.getMaxCachedUtxoCount(), _bitcoinProperties.getUtxoCachePurgePercent() ); final BlockchainDatabaseManager blockchainDatabaseManager = databaseManager.getBlockchainDatabaseManager(); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final FullNodeBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final SystemTime systemTime = new SystemTime(); final VolatileNetworkTime networkTime = NetworkTime.fromSystemTime(systemTime); final BlockchainSegmentId headBlockchainSegmentId = blockchainDatabaseManager.getHeadBlockchainSegmentId(); final BlockId headBlockId = blockDatabaseManager.getHeadBlockId(); final Long maxBlockHeight = blockHeaderDatabaseManager.getBlockHeight(headBlockId); Long validatedTransactionCount = 0L; final Long startTime = System.currentTimeMillis(); while (true) { final Sha256Hash blockHash = nextBlockHash; final BlockId blockId = blockHeaderDatabaseManager.getBlockHeaderId(nextBlockHash); final Long blockHeight = blockHeaderDatabaseManager.getBlockHeight(blockId); final int percentComplete = (int) ((blockHeight * 100) / maxBlockHeight.floatValue()); if (blockHeight % (maxBlockHeight / 100) == 0) { final int secondsElapsed; final float blocksPerSecond; final float transactionsPerSecond; { final Long now = System.currentTimeMillis(); final int seconds = (int) ((now - startTime) / 1000L); final long blockCount = blockHeight; blocksPerSecond = (blockCount / (seconds + 1F)); secondsElapsed = seconds; transactionsPerSecond = (validatedTransactionCount / (seconds + 1F)); } Logger.info(percentComplete + "% complete. " + blockHeight + " of " + maxBlockHeight + " - " + blockHash + " ("+ String.format("%.2f", blocksPerSecond) +" bps) (" + String.format("%.2f", transactionsPerSecond) + " tps) ("+ StringUtil.formatNumberString(secondsElapsed) +" seconds)"); } final MilliTimer blockInflaterTimer = new MilliTimer(); blockInflaterTimer.start(); final boolean blockIsCached; final Block block; { Block cachedBlock = null; if (_blockStore != null) { cachedBlock = _blockStore.getBlock(blockHash, blockHeight); } if (cachedBlock != null) { block = cachedBlock; blockIsCached = true; } else { block = blockDatabaseManager.getBlock(blockId); blockIsCached = false; } } blockInflaterTimer.stop(); System.out.println("Block Inflation: " + block.getHash() + " " + blockInflaterTimer.getMillisecondsElapsed() + "ms"); validatedTransactionCount += blockDatabaseManager.getTransactionCount(blockId); final BlockValidator blockValidator; { final TransactionValidatorFactory transactionValidatorFactory = new TransactionValidatorFactory() { @Override public TransactionValidator getTransactionValidator(final BlockOutputs blockOutputs, final TransactionValidator.Context transactionValidatorContext) { return new TransactionValidatorCore(blockOutputs, transactionValidatorContext); } }; final TransactionInflaters transactionInflaters = masterInflater; final LazyMutableUnspentTransactionOutputSet unspentTransactionOutputSet = new LazyMutableUnspentTransactionOutputSet(databaseManagerFactory); final LazyBlockValidatorContext blockValidatorContext = new LazyBlockValidatorContext(transactionInflaters, blockchainSegmentId, unspentTransactionOutputSet, transactionValidatorFactory, databaseManager, networkTime); blockValidator = new BlockValidator(blockValidatorContext); blockValidator.setMaxThreadCount(_bitcoinProperties.getMaxThreadCount()); blockValidator.setShouldLogValidBlocks(true); blockValidator.setTrustedBlockHeight(BlockValidator.DO_NOT_TRUST_BLOCKS); } final BlockValidationResult blockValidationResult = blockValidator.validateBlock(block, blockHeight); if (! blockValidationResult.isValid) { Logger.error("Invalid block found: " + blockHash + "(" + blockValidationResult.errorMessage + ")"); break; } if ( (! blockIsCached) && (_blockStore != null) ) { _blockStore.storeBlock(block, blockHeight); } nextBlockHash = null; final BlockId nextBlockId = blockHeaderDatabaseManager.getChildBlockId(headBlockchainSegmentId, blockId); if (nextBlockId != null) { final Boolean nextBlockHasTransactions = blockDatabaseManager.hasTransactions(nextBlockId); if (nextBlockHasTransactions) { nextBlockHash = blockHeaderDatabaseManager.getBlockHash(nextBlockId); } } } } catch (final DatabaseException exception) { Logger.error("Last validated block: " + nextBlockHash, exception); BitcoinUtil.exitFailure(); } System.exit(0); } } <|start_filename|>src/main/java/com/softwareverde/database/mysql/connection/ReadUncommittedDatabaseConnectionFactory.java<|end_filename|> package com.softwareverde.database.mysql.connection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; public interface ReadUncommittedDatabaseConnectionFactory extends DatabaseConnectionFactory { } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/message/ResponseMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.message; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.json.Json; import com.softwareverde.json.Jsonable; public class ResponseMessage implements Jsonable { public static ResponseMessage parse(final String input) { final Json json = Json.parse(input); return ResponseMessage.parse(json); } public static ResponseMessage parse(final Json json) { if (json.isArray()) { return null; } if (! json.hasKey("result")) { return null; } final Integer id = json.getInteger("id"); final ResponseMessage responseMessage = new ResponseMessage(id); { final Boolean isBoolean = (! Json.isJson(json.getString("result"))); if (isBoolean) { responseMessage._result = (json.getBoolean("result") ? RESULT_TRUE : RESULT_FALSE); } else { responseMessage._result = json.get("result"); } } { final Json errors = json.get("error"); if (errors != null) { for (int i = 0; i < errors.length(); ++i) { final String error = errors.getString(i); responseMessage._error.add(error); } } } return responseMessage; } public final static Json RESULT_TRUE = new Json(); public final static Json RESULT_FALSE = new Json(); protected final Integer _id; protected Json _result = RESULT_FALSE; protected final MutableList<String> _error = new MutableList<String>(); public ResponseMessage(final Integer id) { _id = id; } public Integer getId() { return _id; } public void setResult(final Json result) { _result = result; } public void setError(final String error1, final String error2, final String error3) { _error.clear(); _error.add(error1); _error.add(error2); _error.add(error3); } @Override public Json toJson() { final Json message = new Json(false); message.put("id", _id); if (_result == RESULT_TRUE) { message.put("result", true); } else if (_result == RESULT_FALSE) { message.put("result", false); } else { message.put("result", _result); } if (_error.isEmpty()) { message.put("error", null); } else { final Json errors = new Json(true); for (final String error : _error) { errors.add(error); } message.put("error", errors); } return message; } @Override public String toString() { final Json json = this.toJson(); return json.toString(); } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/configuration/Configuration.java<|end_filename|> package com.softwareverde.bitcoin.server.configuration; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.UnspentTransactionOutputDatabaseManager; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.json.Json; import com.softwareverde.logging.LogLevel; import com.softwareverde.logging.Logger; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.Util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class Configuration { protected final Properties _properties; protected BitcoinProperties _bitcoinProperties; protected DatabaseProperties _bitcoinDatabaseProperties; protected ExplorerProperties _explorerProperties; protected StratumProperties _stratumProperties; protected DatabaseProperties _stratumDatabaseProperties; protected WalletProperties _walletProperties; protected ProxyProperties _proxyProperties; protected DatabaseProperties _loadDatabaseProperties(final String prefix) { final String propertyPrefix = (prefix == null ? "" : (prefix + ".")); final String rootPassword = _properties.getProperty(propertyPrefix + "database.rootPassword", "<PASSWORD>"); final String hostname = _properties.getProperty(propertyPrefix + "database.hostname", ""); final String username = _properties.getProperty(propertyPrefix + "database.username", "root"); final String password = _properties.getProperty(propertyPrefix + "database.password", ""); final String schema = (_properties.getProperty(propertyPrefix + "database.schema", "bitcoin")).replaceAll("[^A-Za-z0-9_]", ""); final Integer port = Util.parseInt(_properties.getProperty(propertyPrefix + "database.port", "8336")); final String dataDirectory = _properties.getProperty(propertyPrefix + "database.dataDirectory", "data"); final Boolean useEmbeddedDatabase = Util.parseBool(_properties.getProperty(propertyPrefix + "database.useEmbeddedDatabase", "1")); final Long maxMemoryByteCount = Util.parseLong(_properties.getProperty(propertyPrefix + "database.maxMemoryByteCount", String.valueOf(2L * ByteUtil.Unit.Binary.GIBIBYTES))); // According to https://www.percona.com/blog/2008/11/21/how-to-calculate-a-good-innodb-log-file-size/, and running the calculation on a trimming node syncing yr 2015, the GB/hr was about 6.5gb. // In lieu of this, the default value was decided to be set to 8GB to better accommodate slightly higher loads. final Long logFileByteCount = Util.parseLong(_properties.getProperty(propertyPrefix + "database.logFileByteCount", String.valueOf(512 * ByteUtil.Unit.Binary.MEBIBYTES))); final DatabaseProperties databaseProperties = new DatabaseProperties(); databaseProperties.setRootPassword(<PASSWORD>); databaseProperties.setHostname(hostname); databaseProperties.setUsername(username); databaseProperties.setPassword(password); databaseProperties.setSchema(schema); databaseProperties.setPort(port); databaseProperties.setDataDirectory(dataDirectory); databaseProperties._useEmbeddedDatabase = useEmbeddedDatabase; databaseProperties._maxMemoryByteCount = maxMemoryByteCount; databaseProperties._logFileByteCount = logFileByteCount; return databaseProperties; } protected List<SeedNodeProperties> _parseSeedNodeProperties(final String propertyName, final String defaultValue) { final Json seedNodesJson = Json.parse(_properties.getProperty(propertyName, defaultValue)); final int itemCount = seedNodesJson.length(); final MutableList<SeedNodeProperties> seedNodePropertiesArray = new MutableList<SeedNodeProperties>(itemCount); for (int i = 0; i < itemCount; ++i) { final String propertiesString = seedNodesJson.getString(i); final SeedNodeProperties seedNodeProperties; final int indexOfColon = propertiesString.indexOf(":"); if (indexOfColon < 0) { seedNodeProperties = new SeedNodeProperties(propertiesString, BitcoinProperties.PORT); } else { final String address = propertiesString.substring(0, indexOfColon); final Integer port = Util.parseInt(propertiesString.substring(indexOfColon + 1)); seedNodeProperties = new SeedNodeProperties(address, port); } seedNodePropertiesArray.add(seedNodeProperties); } return seedNodePropertiesArray; } protected void _loadBitcoinProperties() { _bitcoinProperties = new BitcoinProperties(); _bitcoinProperties._bitcoinPort = Util.parseInt(_properties.getProperty("bitcoin.port", BitcoinProperties.PORT.toString())); _bitcoinProperties._bitcoinRpcPort = Util.parseInt(_properties.getProperty("bitcoin.rpcPort", BitcoinProperties.RPC_PORT.toString())); { // Parse Seed Nodes... final List<SeedNodeProperties> seedNodeProperties = _parseSeedNodeProperties("bitcoin.seedNodes", "[\"btc.softwareverde.com\", \"bitcoinverde.org\"]"); _bitcoinProperties._seedNodeProperties = seedNodeProperties; } { // Parse Whitelisted Nodes... final String defaultSeedsString = "[\"seed.flowee.cash\", \"seed-bch.bitcoinforks.org\", \"btccash-seeder.bitcoinunlimited.info\", \"seed.bchd.cash\"]"; final Json seedNodesJson = Json.parse(_properties.getProperty("bitcoin.dnsSeeds", defaultSeedsString)); final int itemCount = seedNodesJson.length();; final MutableList<String> dnsSeeds = new MutableList<String>(itemCount); for (int i = 0; i < itemCount; ++i) { final String seedHost = seedNodesJson.getString(i); if (seedHost != null) { dnsSeeds.add(seedHost); } } _bitcoinProperties._dnsSeeds = dnsSeeds; } { // Parse Blacklisted User Agents... final String defaultBlacklist = "[\".*Bitcoin ABC.*\", \".*Bitcoin SV.*\"]"; final Json blacklistJson = Json.parse(_properties.getProperty("bitcoin.userAgentBlacklist", defaultBlacklist)); final int itemCount = blacklistJson.length();; final MutableList<String> patterns = new MutableList<String>(itemCount); for (int i = 0; i < itemCount; ++i) { final String pattern = blacklistJson.getString(i); patterns.add(pattern); } _bitcoinProperties._userAgentBlacklist = patterns; } { // Parse Whitelisted Nodes... final List<SeedNodeProperties> nodeWhitelist = _parseSeedNodeProperties("bitcoin.nodeWhitelist", "[]"); _bitcoinProperties._nodesWhitelist = nodeWhitelist; } _bitcoinProperties._banFilterIsEnabled = Util.parseBool(_properties.getProperty("bitcoin.enableBanFilter", "1")); _bitcoinProperties._minPeerCount = Util.parseInt(_properties.getProperty("bitcoin.minPeerCount", "8")); _bitcoinProperties._maxPeerCount = Util.parseInt(_properties.getProperty("bitcoin.maxPeerCount", "24")); _bitcoinProperties._maxThreadCount = Util.parseInt(_properties.getProperty("bitcoin.maxThreadCount", "4")); _bitcoinProperties._trustedBlockHeight = Util.parseLong(_properties.getProperty("bitcoin.trustedBlockHeight", "0")); _bitcoinProperties._shouldSkipNetworking = Util.parseBool(_properties.getProperty("bitcoin.skipNetworking", "0")); _bitcoinProperties._deletePendingBlocksIsEnabled = Util.parseBool(_properties.getProperty("bitcoin.deletePendingBlocks", "1")); _bitcoinProperties._maxUtxoCacheByteCount = Util.parseLong(_properties.getProperty("bitcoin.maxUtxoCacheByteCount", String.valueOf(UnspentTransactionOutputDatabaseManager.DEFAULT_MAX_UTXO_CACHE_COUNT * UnspentTransactionOutputDatabaseManager.BYTES_PER_UTXO))); _bitcoinProperties._utxoCommitFrequency = Util.parseLong(_properties.getProperty("bitcoin.utxoCommitFrequency", "50000")); _bitcoinProperties._logDirectory = _properties.getProperty("bitcoin.logDirectory", "logs"); _bitcoinProperties._logLevel = LogLevel.fromString(_properties.getProperty("bitcoin.logLevel", "INFO")); _bitcoinProperties._utxoPurgePercent = Util.parseFloat(_properties.getProperty("bitcoin.utxoPurgePercent", String.valueOf(UnspentTransactionOutputDatabaseManager.DEFAULT_PURGE_PERCENT))); if (_bitcoinProperties._utxoPurgePercent < 0F) { _bitcoinProperties._utxoPurgePercent = 0F; } else if (_bitcoinProperties._utxoPurgePercent > 1F) { _bitcoinProperties._utxoPurgePercent = 1F; } _bitcoinProperties._bootstrapIsEnabled = Util.parseBool(_properties.getProperty("bitcoin.enableBootstrap", "1")); { final String reIndexPendingBlocks = _properties.getProperty("bitcoin.reIndexPendingBlocks", null); _bitcoinProperties._shouldReIndexPendingBlocks = ((reIndexPendingBlocks != null) ? Util.parseBool(reIndexPendingBlocks) : null); } _bitcoinProperties._indexingModeIsEnabled = Util.parseBool(_properties.getProperty("bitcoin.indexBlocks", "1")); _bitcoinProperties._maxMessagesPerSecond = Util.parseInt(_properties.getProperty("bitcoin.maxMessagesPerSecondPerNode", "250")); _bitcoinProperties._dataDirectory = _properties.getProperty("bitcoin.dataDirectory", "data"); _bitcoinProperties._shouldRelayInvalidSlpTransactions = Util.parseBool(_properties.getProperty("bitcoin.relayInvalidSlpTransactions", "1")); } protected void _loadExplorerProperties() { final Integer port = Util.parseInt(_properties.getProperty("explorer.httpPort", ExplorerProperties.HTTP_PORT.toString())); final String rootDirectory = _properties.getProperty("explorer.rootDirectory", "explorer/www"); final String bitcoinRpcUrl = _properties.getProperty("explorer.bitcoinRpcUrl", ""); final Integer bitcoinRpcPort = Util.parseInt(_properties.getProperty("explorer.bitcoinRpcPort", BitcoinProperties.RPC_PORT.toString())); final String stratumRpcUrl = _properties.getProperty("explorer.stratumRpcUrl", ""); final Integer stratumRpcPort = Util.parseInt(_properties.getProperty("explorer.stratumRpcPort", StratumProperties.RPC_PORT.toString())); final Integer tlsPort = Util.parseInt(_properties.getProperty("explorer.tlsPort", ExplorerProperties.TLS_PORT.toString())); final String tlsKeyFile = _properties.getProperty("explorer.tlsKeyFile", ""); final String tlsCertificateFile = _properties.getProperty("explorer.tlsCertificateFile", ""); final ExplorerProperties explorerProperties = new ExplorerProperties(); explorerProperties._port = port; explorerProperties._rootDirectory = rootDirectory; explorerProperties._bitcoinRpcUrl = bitcoinRpcUrl; explorerProperties._bitcoinRpcPort = bitcoinRpcPort; explorerProperties._stratumRpcUrl = stratumRpcUrl; explorerProperties._stratumRpcPort = stratumRpcPort; explorerProperties._tlsPort = tlsPort; explorerProperties._tlsKeyFile = (tlsKeyFile.isEmpty() ? null : tlsKeyFile); explorerProperties._tlsCertificateFile = (tlsCertificateFile.isEmpty() ? null : tlsCertificateFile); _explorerProperties = explorerProperties; } protected void _loadStratumProperties() { final Integer port = Util.parseInt(_properties.getProperty("stratum.port", StratumProperties.PORT.toString())); final Integer rpcPort = Util.parseInt(_properties.getProperty("stratum.rpcPort", StratumProperties.RPC_PORT.toString())); final String bitcoinRpcUrl = _properties.getProperty("stratum.bitcoinRpcUrl", ""); final Integer bitcoinRpcPort = Util.parseInt(_properties.getProperty("stratum.bitcoinRpcPort", BitcoinProperties.RPC_PORT.toString())); final Integer httpPort = Util.parseInt(_properties.getProperty("stratum.httpPort", StratumProperties.HTTP_PORT.toString())); final Integer tlsPort = Util.parseInt(_properties.getProperty("stratum.tlsPort", StratumProperties.TLS_PORT.toString())); final String rootDirectory = _properties.getProperty("stratum.rootDirectory", "stratum/www"); final String tlsKeyFile = _properties.getProperty("stratum.tlsKeyFile", ""); final String tlsCertificateFile = _properties.getProperty("stratum.tlsCertificateFile", ""); final String cookiesDirectory = _properties.getProperty("stratum.cookiesDirectory", "tmp"); final StratumProperties stratumProperties = new StratumProperties(); stratumProperties._port = port; stratumProperties._rpcPort = rpcPort; stratumProperties._bitcoinRpcUrl = bitcoinRpcUrl; stratumProperties._bitcoinRpcPort = bitcoinRpcPort; stratumProperties._rootDirectory = rootDirectory; stratumProperties._httpPort = httpPort; stratumProperties._tlsPort = tlsPort; stratumProperties._tlsKeyFile = (tlsKeyFile.isEmpty() ? null : tlsKeyFile); stratumProperties._tlsCertificateFile = (tlsCertificateFile.isEmpty() ? null : tlsCertificateFile); stratumProperties._cookiesDirectory = cookiesDirectory; _stratumProperties = stratumProperties; } protected void _loadWalletProperties() { final Integer port = Util.parseInt(_properties.getProperty("wallet.port", WalletProperties.PORT.toString())); final String rootDirectory = _properties.getProperty("wallet.rootDirectory", "wallet/www"); final Integer tlsPort = Util.parseInt(_properties.getProperty("wallet.tlsPort", WalletProperties.TLS_PORT.toString())); final String tlsKeyFile = _properties.getProperty("wallet.tlsKeyFile", ""); final String tlsCertificateFile = _properties.getProperty("wallet.tlsCertificateFile", ""); final WalletProperties walletProperties = new WalletProperties(); walletProperties._port = port; walletProperties._rootDirectory = rootDirectory; walletProperties._tlsPort = tlsPort; walletProperties._tlsKeyFile = (tlsKeyFile.isEmpty() ? null : tlsKeyFile); walletProperties._tlsCertificateFile = (tlsCertificateFile.isEmpty() ? null : tlsCertificateFile); _walletProperties = walletProperties; } protected List<String> _getArrayStringProperty(final String propertyName, final String defaultValue) { final String arrayString = _properties.getProperty(propertyName, defaultValue).trim(); final MutableList<String> matches = new MutableList<String>(); final int startingIndex; final int length; if (arrayString.startsWith("[") && arrayString.endsWith("]")) { startingIndex = 1; length = (arrayString.length() - 1); } else { startingIndex = 0; length = arrayString.length(); } final StringBuilder stringBuilder = new StringBuilder(); for (int i = startingIndex; i < length; ++i) { final char c = arrayString.charAt(i); if (c == ',') { matches.add(stringBuilder.toString().trim()); stringBuilder.setLength(0); continue; } stringBuilder.append(c); } if (stringBuilder.length() > 0) { matches.add(stringBuilder.toString().trim()); } return matches; } protected void _loadProxyProperties() { final Integer httpPort = Util.parseInt(_properties.getProperty("proxy.httpPort", ProxyProperties.HTTP_PORT.toString())); final Integer tlsPort = Util.parseInt(_properties.getProperty("proxy.tlsPort", ProxyProperties.TLS_PORT.toString())); final Integer externalTlsPort = Util.parseInt(_properties.getProperty("proxy.externalTlsPort", tlsPort.toString())); final List<String> tlsKeyFiles = _getArrayStringProperty("proxy.tlsKeyFiles", "[]"); final List<String> tlsCertificateFiles = _getArrayStringProperty("proxy.tlsCertificateFiles", "[]"); final ProxyProperties proxyProperties = new ProxyProperties(); proxyProperties._httpPort = httpPort; proxyProperties._tlsPort = tlsPort; proxyProperties._externalTlsPort = externalTlsPort; proxyProperties._tlsKeyFiles = tlsKeyFiles; proxyProperties._tlsCertificateFiles = tlsCertificateFiles; _proxyProperties = proxyProperties; } public Configuration(final File configurationFile) { _properties = new Properties(); try (final FileInputStream fileInputStream = new FileInputStream(configurationFile)) { _properties.load(fileInputStream); } catch (final IOException exception) { Logger.warn("Unable to load properties."); } _bitcoinDatabaseProperties = _loadDatabaseProperties("bitcoin"); _stratumDatabaseProperties = _loadDatabaseProperties("stratum"); _loadBitcoinProperties(); _loadStratumProperties(); _loadExplorerProperties(); _loadWalletProperties(); _loadProxyProperties(); } public BitcoinProperties getBitcoinProperties() { return _bitcoinProperties; } public DatabaseProperties getBitcoinDatabaseProperties() { return _bitcoinDatabaseProperties; } public ExplorerProperties getExplorerProperties() { return _explorerProperties; } public StratumProperties getStratumProperties() { return _stratumProperties; } public DatabaseProperties getStratumDatabaseProperties() { return _stratumDatabaseProperties; } public WalletProperties getWalletProperties() { return _walletProperties; } public ProxyProperties getProxyProperties() { return _proxyProperties; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/account/worker/GetWorkersApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.worker; import com.softwareverde.bitcoin.miner.pool.AccountId; import com.softwareverde.bitcoin.miner.pool.WorkerId; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.bitcoin.server.module.stratum.database.AccountDatabaseManager; import com.softwareverde.constable.list.List; import com.softwareverde.database.DatabaseException; import com.softwareverde.http.HttpMethod; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.json.Json; import com.softwareverde.logging.Logger; import com.softwareverde.servlet.AuthenticatedServlet; public class GetWorkersApi extends AuthenticatedServlet { protected final DatabaseConnectionFactory _databaseConnectionFactory; public GetWorkersApi(final StratumProperties stratumProperties, final DatabaseConnectionFactory databaseConnectionFactory) { super(stratumProperties); _databaseConnectionFactory = databaseConnectionFactory; } @Override protected Response _onAuthenticatedRequest(final AccountId accountId, final Request request) { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); if (request.getMethod() != HttpMethod.GET) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid method.")); } { // GET WORKERS // Requires GET: // Requires POST: try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { final AccountDatabaseManager accountDatabaseManager = new AccountDatabaseManager(databaseConnection); final List<WorkerId> workerIds = accountDatabaseManager.getWorkerIds(accountId); final Json workersJson = new Json(true); for (final WorkerId workerId : workerIds) { final String workerUsername = accountDatabaseManager.getWorkerUsername(workerId); final Long workerSharesCount = accountDatabaseManager.getWorkerSharesCount(workerId); final Json workerJson = new Json(false); workerJson.put("id", workerId); workerJson.put("username", workerUsername); workerJson.put("sharesCount", workerSharesCount); workersJson.add(workerJson); } final StratumApiResult result = new StratumApiResult(true, null); result.put("workers", workersJson); return new JsonResponse(Response.Codes.OK, result); } catch (final DatabaseException exception) { Logger.warn(exception); return new JsonResponse(Response.Codes.SERVER_ERROR, new StratumApiResult(false, "An internal error occurred.")); } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/validator/difficulty/DifficultyCalculator.java<|end_filename|> package com.softwareverde.bitcoin.block.validator.difficulty; import com.softwareverde.bitcoin.bip.Buip55; import com.softwareverde.bitcoin.bip.HF20171113; import com.softwareverde.bitcoin.bip.HF20201115; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.block.header.difficulty.work.ChainWork; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.context.DifficultyCalculatorContext; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import com.softwareverde.util.DateUtil; import com.softwareverde.util.Util; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class DifficultyCalculator { protected static final Integer BLOCK_COUNT_PER_DIFFICULTY_ADJUSTMENT = 2016; protected static final BigInteger TWO_TO_THE_POWER_OF_256 = BigInteger.valueOf(2L).pow(256); protected final DifficultyCalculatorContext _context; protected final MedianBlockHeaderSelector _medianBlockHeaderSelector; protected final AsertDifficultyCalculator _asertDifficultyCalculator; protected DifficultyCalculator(final DifficultyCalculatorContext blockchainContext, final MedianBlockHeaderSelector medianBlockHeaderSelector, final AsertDifficultyCalculator asertDifficultyCalculator) { _context = blockchainContext; _medianBlockHeaderSelector = medianBlockHeaderSelector; _asertDifficultyCalculator = asertDifficultyCalculator; } public DifficultyCalculator(final DifficultyCalculatorContext blockchainContext) { this(blockchainContext, new MedianBlockHeaderSelector(), new AsertDifficultyCalculator()); } protected Difficulty _calculateNewBitcoinCoreTarget(final Long forBlockHeight) { // Calculate the new difficulty. https://bitcoin.stackexchange.com/questions/5838/how-is-difficulty-calculated final BlockHeader parentBlockHeader = _context.getBlockHeader(forBlockHeight - 1L); // 1. Get the block that is 2016 blocks behind the head block of this chain. final long blockHeightOfPreviousAdjustment = (forBlockHeight - BLOCK_COUNT_PER_DIFFICULTY_ADJUSTMENT); // NOTE: This is 2015 blocks worth of time (not 2016) because of a bug in Satoshi's implementation and is now part of the protocol definition. final BlockHeader lastAdjustedBlockHeader = _context.getBlockHeader(blockHeightOfPreviousAdjustment); if (lastAdjustedBlockHeader == null) { return null; } // 2. Get the current block timestamp. final long blockTimestamp = parentBlockHeader.getTimestamp(); final long previousBlockTimestamp = lastAdjustedBlockHeader.getTimestamp(); Logger.trace(DateUtil.Utc.timestampToDatetimeString(blockTimestamp * 1000L)); Logger.trace(DateUtil.Utc.timestampToDatetimeString(previousBlockTimestamp * 1000L)); // 3. Calculate the difference between the network-time and the time of the 2015th-parent block ("secondsElapsed"). (NOTE: 2015 instead of 2016 due to protocol bug.) final long secondsElapsed = (blockTimestamp - previousBlockTimestamp); Logger.trace("2016 blocks in " + secondsElapsed + " (" + (secondsElapsed / 60F / 60F / 24F) + " days)"); // 4. Calculate the desired two-weeks elapse-time ("secondsInTwoWeeks"). final long secondsInTwoWeeks = (2L * 7L * 24L * 60L * 60L); // <Week Count> * <Days / Week> * <Hours / Day> * <Minutes / Hour> * <Seconds / Minute> // 5. Calculate the difficulty adjustment via (secondsInTwoWeeks / secondsElapsed) ("difficultyAdjustment"). final double difficultyAdjustment = ( ((double) secondsInTwoWeeks) / ((double) secondsElapsed) ); Logger.trace("Adjustment: " + difficultyAdjustment); // 6. Bound difficultyAdjustment between [4, 0.25]. final double boundedDifficultyAdjustment = (Math.min(4D, Math.max(0.25D, difficultyAdjustment))); // 7. Multiply the difficulty by the bounded difficultyAdjustment. final Difficulty newDifficulty = (parentBlockHeader.getDifficulty().multiplyBy(1.0D / boundedDifficultyAdjustment)); // 8. The new difficulty cannot be less than the base difficulty. final Difficulty minimumDifficulty = Difficulty.BASE_DIFFICULTY; if (newDifficulty.isLessDifficultThan(minimumDifficulty)) { return minimumDifficulty; } return newDifficulty; } protected Difficulty _calculateBitcoinCashEmergencyDifficultyAdjustment(final Long forBlockHeight) { final long parentBlockHeight = (forBlockHeight - 1L); final BlockHeader previousBlockHeader = _context.getBlockHeader(parentBlockHeight); final MedianBlockTime medianBlockTime = _context.getMedianBlockTime(parentBlockHeight); final MedianBlockTime medianBlockTimeForSixthBlock = _context.getMedianBlockTime(parentBlockHeight - 6L); final long secondsInTwelveHours = 43200L; if ( (medianBlockTime == null) || (medianBlockTimeForSixthBlock == null) ) { Logger.debug("Unable to calculate difficulty for Block height: " + forBlockHeight); return null; } final long timeBetweenMedianBlockTimes = (medianBlockTime.getCurrentTimeInSeconds() - medianBlockTimeForSixthBlock.getCurrentTimeInSeconds()); if (timeBetweenMedianBlockTimes > secondsInTwelveHours) { final Difficulty newDifficulty = previousBlockHeader.getDifficulty().multiplyBy(1.25D); final Difficulty minimumDifficulty = Difficulty.BASE_DIFFICULTY; if (newDifficulty.isLessDifficultThan(minimumDifficulty)) { return minimumDifficulty; } Logger.debug("Emergency Difficulty Adjustment: BlockHeight: " + forBlockHeight + " Original Difficulty: " + previousBlockHeader.getDifficulty() + " New Difficulty: " + newDifficulty); return newDifficulty; } return previousBlockHeader.getDifficulty(); } protected Difficulty _calculateAserti32dBitcoinCashTarget(final Long blockHeight) { final BlockHeader previousBlockHeader = _context.getBlockHeader((blockHeight > 0) ? (blockHeight - 1L) : 0L); // The ASERT algorithm uses the parent block's timestamp, except for the genesis block itself (which should never happen). final Long previousBlockTimestamp = previousBlockHeader.getTimestamp(); final AsertReferenceBlock referenceBlock = _context.getAsertReferenceBlock(); return _asertDifficultyCalculator.computeAsertTarget(referenceBlock, previousBlockTimestamp, blockHeight); } protected Difficulty _calculateCw144BitcoinCashTarget(final Long forBlockHeight) { final BlockHeader[] firstBlockHeaders = new BlockHeader[3]; // The oldest BlockHeaders... final BlockHeader[] lastBlockHeaders = new BlockHeader[3]; // The newest BlockHeaders... final Map<Sha256Hash, Long> blockHeights = new HashMap<Sha256Hash, Long>(6); // Set the lastBlockHeaders to be the head blockId, its parent, and its grandparent... final long parentBlockHeight = (forBlockHeight - 1L); for (int i = 0; i < lastBlockHeaders.length; ++i) { final Long blockHeight = (parentBlockHeight - i); final BlockHeader blockHeader = _context.getBlockHeader(blockHeight); if (blockHeader == null) { return null; } final Sha256Hash blockHash = blockHeader.getHash(); blockHeights.put(blockHash, blockHeight); lastBlockHeaders[i] = blockHeader; } // Set the firstBlockHeaders to be the 144th, 145th, and 146th parent of the first block's parent... for (int i = 0; i < firstBlockHeaders.length; ++i) { final Long blockHeight = (parentBlockHeight - 144L - i); final BlockHeader blockHeader = _context.getBlockHeader(blockHeight); if (blockHeader == null) { return null; } final Sha256Hash blockHash = blockHeader.getHash(); blockHeights.put(blockHash, blockHeight); firstBlockHeaders[i] = blockHeader; } final BlockHeader firstBlockHeader = _medianBlockHeaderSelector.selectMedianBlockHeader(firstBlockHeaders); final Sha256Hash firstBlockHash = firstBlockHeader.getHash(); final Long firstBlockHeight = blockHeights.get(firstBlockHash); final BlockHeader lastBlockHeader = _medianBlockHeaderSelector.selectMedianBlockHeader(lastBlockHeaders); final Sha256Hash lastBlockHash = lastBlockHeader.getHash(); final Long lastBlockHeight = blockHeights.get(lastBlockHash); final long timeSpan; { final long minimumValue = (72L * 600L); final long maximumValue = (288L * 600L); final long difference = (lastBlockHeader.getTimestamp() - firstBlockHeader.getTimestamp()); if (difference < minimumValue) { timeSpan = minimumValue; } else { timeSpan = Math.min(difference, maximumValue); } } final ChainWork firstChainWork = _context.getChainWork(firstBlockHeight); // blockHeaderDatabaseManager.getChainWork(firstBlockId); final ChainWork lastChainWork = _context.getChainWork(lastBlockHeight); final BigInteger workPerformed; { final BigInteger firstChainWorkBigInteger = new BigInteger(firstChainWork.getBytes()); final BigInteger lastChainWorkBigInteger = new BigInteger(lastChainWork.getBytes()); workPerformed = lastChainWorkBigInteger.subtract(firstChainWorkBigInteger); } final BigInteger projectedWork; { projectedWork = workPerformed .multiply(BigInteger.valueOf(600L)) .divide(BigInteger.valueOf(timeSpan)); } final BigInteger targetWork; { targetWork = TWO_TO_THE_POWER_OF_256 .subtract(projectedWork) .divide(projectedWork); } final Difficulty newDifficulty = Difficulty.fromBigInteger(targetWork); final Difficulty minimumDifficulty = Difficulty.BASE_DIFFICULTY; if (newDifficulty.isLessDifficultThan(minimumDifficulty)) { return minimumDifficulty; } return newDifficulty; } public Difficulty calculateRequiredDifficulty(final Long blockHeight) { final Boolean isFirstBlock = (Util.areEqual(0L, blockHeight)); if (isFirstBlock) { return Difficulty.BASE_DIFFICULTY; } final MedianBlockTime medianBlockTime = _context.getMedianBlockTime(blockHeight); if (HF20201115.isEnabled(medianBlockTime)) { return _calculateAserti32dBitcoinCashTarget(blockHeight); } if (HF20171113.isEnabled(blockHeight)) { return _calculateCw144BitcoinCashTarget(blockHeight); } final boolean requiresDifficultyEvaluation = (blockHeight % BLOCK_COUNT_PER_DIFFICULTY_ADJUSTMENT == 0); if (requiresDifficultyEvaluation) { return _calculateNewBitcoinCoreTarget(blockHeight); } if (Buip55.isEnabled(blockHeight)) { return _calculateBitcoinCashEmergencyDifficultyAdjustment(blockHeight); } final Long previousBlockHeight = (blockHeight - 1L); final BlockHeader previousBlockHeader = _context.getBlockHeader(previousBlockHeight); return previousBlockHeader.getDifficulty(); } } <|start_filename|>src/main/java/com/softwareverde/network/time/NetworkTime.java<|end_filename|> package com.softwareverde.network.time; import com.softwareverde.constable.Constable; import com.softwareverde.util.type.time.SystemTime; import com.softwareverde.util.type.time.Time; public interface NetworkTime extends Time, Constable<ImmutableNetworkTime> { NetworkTime MAX_VALUE = new ImmutableNetworkTime(Long.MAX_VALUE); static NetworkTime fromSeconds(final Long medianNetworkTimeInSeconds) { return ImmutableNetworkTime.fromSeconds(medianNetworkTimeInSeconds); } static NetworkTime fromMilliseconds(final Long medianNetworkTimeInMilliseconds) { return ImmutableNetworkTime.fromMilliseconds(medianNetworkTimeInMilliseconds); } static MutableNetworkTime fromSystemTime(final SystemTime systemTime) { return MutableNetworkTime.fromSystemTime(systemTime); } @Override ImmutableNetworkTime asConst(); } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeReferenceBlockLoaderContext.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.constable.util.ConstUtil; import com.softwareverde.bitcoin.context.ContextException; import com.softwareverde.bitcoin.context.core.AsertReferenceBlockLoader; import com.softwareverde.logging.Logger; import com.softwareverde.util.Util; import java.util.HashMap; public class FakeReferenceBlockLoaderContext implements AsertReferenceBlockLoader.ReferenceBlockLoaderContext { protected final HashMap<BlockchainSegmentId, BlockId> _headBlockIds = new HashMap<BlockchainSegmentId, BlockId>(); protected final HashMap<BlockId, MedianBlockTime> _medianBlockTimes = new HashMap<BlockId, MedianBlockTime>(); protected final HashMap<BlockId, Long> _blockTimestamps = new HashMap<BlockId, Long>(); protected final HashMap<BlockId, Long> _blockHeights = new HashMap<BlockId, Long>(); protected final HashMap<BlockId, Difficulty> _difficulties = new HashMap<BlockId, Difficulty>(); protected Integer _lookupCount = 0; protected Integer _medianTimePastCalculationCount = 0; public void setBlockHeader(final BlockchainSegmentId blockchainSegmentId, final BlockId blockId, final Long blockHeight, final MedianBlockTime medianBlockTime, final Long blockTimestamp, final Difficulty difficulty) { final BlockId currentHeadBlockId = _headBlockIds.get(blockchainSegmentId); final Long currentHeadBlockHeight = ((currentHeadBlockId != null) ? _blockHeights.get(currentHeadBlockId) : null); if (Util.coalesce(currentHeadBlockHeight, Long.MIN_VALUE) < blockHeight) { _headBlockIds.put(blockchainSegmentId, blockId); } _medianBlockTimes.put(blockId, ConstUtil.asConstOrNull(medianBlockTime)); _blockHeights.put(blockId, blockHeight); _difficulties.put(blockId, difficulty); _blockTimestamps.put(blockId, blockTimestamp); } public Integer getLookupCount() { return _lookupCount; } public Integer getMedianTimePastCalculationCount() { return _medianTimePastCalculationCount; } @Override public BlockId getHeadBlockIdOfBlockchainSegment(final BlockchainSegmentId blockchainSegmentId) { final BlockId blockId = _headBlockIds.get(blockchainSegmentId); if (blockId == null) { Logger.debug("Requested unknown BlockId for BlockchainSegmentId: " + blockchainSegmentId); } return blockId; } @Override public MedianBlockTime getMedianBlockTime(final BlockId blockId) { _medianTimePastCalculationCount += 1; final MedianBlockTime medianBlockTime = _medianBlockTimes.get(blockId); if (medianBlockTime == null) { Logger.debug("Requested unknown MedianBlockTime for BlockId: " + blockId); } return medianBlockTime; } @Override public Long getBlockTimestamp(final BlockId blockId) throws ContextException { final Long blockTimestamp = _blockTimestamps.get(blockId); if (blockTimestamp == null) { Logger.debug("Requested unknown Timestamp for BlockId: " + blockId); } return blockTimestamp; } @Override public Long getBlockHeight(final BlockId blockId) { _lookupCount += 1; final Long blockHeight = _blockHeights.get(blockId); if (blockHeight == null) { Logger.debug("Requested unknown BlockHeight for BlockId: " + blockId); } return blockHeight; } @Override public BlockId getBlockIdAtHeight(final BlockchainSegmentId blockchainSegmentId, final Long blockHeight) { _lookupCount += 1; for (final BlockId blockId : _blockHeights.keySet()) { final Long blockIdBlockHeight = _blockHeights.get(blockId); if (Util.areEqual(blockHeight, blockIdBlockHeight)) { return blockId; } } Logger.debug("Requested unknown BlockId at Height: " + blockHeight); return null; } @Override public Difficulty getDifficulty(final BlockId blockId) { final Difficulty difficulty = _difficulties.get(blockId); if (difficulty == null) { Logger.debug("Requested unknown Difficulty for BlockId: " + blockId); } return difficulty; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/SynchronizationStatus.java<|end_filename|> package com.softwareverde.bitcoin.server; public interface SynchronizationStatus { State getState(); Boolean isBlockchainSynchronized(); Boolean isReadyForTransactions(); Boolean isShuttingDown(); Long getCurrentBlockHeight(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/BlockHeaderContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.block.header.BlockHeader; public interface BlockHeaderContext { BlockHeader getBlockHeader(Long blockHeight); } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/database/WorkerDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.database; import com.softwareverde.bitcoin.miner.pool.WorkerId; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.pbkdf2.Pbkdf2Key; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.mysql.MysqlDatabaseConnection; import com.softwareverde.database.row.Row; import com.softwareverde.util.Util; public class WorkerDatabaseManager { protected final MysqlDatabaseConnection _databaseConnection; public WorkerDatabaseManager(final MysqlDatabaseConnection databaseConnection) { _databaseConnection = databaseConnection; } public WorkerId getWorkerId(final String username) throws DatabaseException { final java.util.List<Row> rows = _databaseConnection.query( new Query("SELECT id FROM workers WHERE username = ?") .setParameter(username) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); return WorkerId.wrap(row.getLong("id")); } public WorkerId insertWorker(final String username, final String password) throws DatabaseException { final Pbkdf2Key pbkdf2Key = new Pbkdf2Key(password); final ByteArray keyByteArray = pbkdf2Key.getKey(); final ByteArray saltByteArray = pbkdf2Key.getSalt(); final Long workerId = _databaseConnection.executeSql( new Query("INSERT INTO workers (username, password, salt, iterations) VALUES (?, ?, ?, ?)") .setParameter(username) .setParameter(keyByteArray.toString()) .setParameter(saltByteArray.toString()) .setParameter(pbkdf2Key.getIterations()) ); return WorkerId.wrap(workerId); } public WorkerId authenticateWorker(final String username, final String password) throws DatabaseException { final java.util.List<Row> rows = _databaseConnection.query( new Query("SELECT id, password, salt, iterations FROM workers WHERE username = ?") .setParameter(username) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); final Long workerId = row.getLong("id"); final ByteArray passwordKey = ByteArray.fromHexString(row.getString("password")); final ByteArray salt = ByteArray.fromHexString(row.getString("salt")); final Integer iterations = row.getInteger("iterations"); final Integer keyBitCount = (passwordKey.getByteCount() * 8); final Pbkdf2Key providedPbkdf2Key = new Pbkdf2Key(password, iterations, salt, keyBitCount); final ByteArray providedKey = providedPbkdf2Key.getKey(); if (! Util.areEqual(passwordKey, providedKey)) { return null; } return WorkerId.wrap(workerId); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bloomfilter/UpdateBloomFilterMode.java<|end_filename|> package com.softwareverde.bitcoin.bloomfilter; public enum UpdateBloomFilterMode { READ_ONLY(0), // The filter is not adjusted when a match is found... UPDATE_ALL(1), // The filter is updated to include the TransactionOutput's TransactionOutputIdentifier when a match to any data element in the LockingScript is found. P2PK_P2MS(2); // The filter is updated to include the TransactionOutput TransactionOutputIdentifier only if a data element in the LockingScript is matched, and the script is either P2PK or MultiSig. public static UpdateBloomFilterMode valueOf(final byte value) { final int maskedValue = (0x03 & value); for (final UpdateBloomFilterMode filterMode : UpdateBloomFilterMode.values()) { if (maskedValue == filterMode.getValue()) { return filterMode; } } return null; } // https://github.com/bitcoinxt/bitcoinxt/pull/139/commits/b807723f2e577bca03e93476541d1ab31eb13907 // "Third bit of nFlags indicates filter wants to be updated with mempool ancestors for its entries." public static Boolean shouldUpdateFromMemoryPoolAncestors(final int value) { return ((value & 0x04) != 0x00); } protected byte _value; UpdateBloomFilterMode(final int value) { _value = (byte) value; } public byte getValue() { return _value; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/inflater/TransactionInflaters.java<|end_filename|> package com.softwareverde.bitcoin.inflater; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionInflater; public interface TransactionInflaters extends Inflater { TransactionInflater getTransactionInflater(); TransactionDeflater getTransactionDeflater(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/block/pending/inventory/UnknownBlockInventory.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.block.pending.inventory; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface UnknownBlockInventory { Sha256Hash getPreviousBlockHash(); Sha256Hash getFirstUnknownBlockHash(); Sha256Hash getLastUnknownBlockHash(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/validator/TransactionValidatorCore.java<|end_filename|> package com.softwareverde.bitcoin.transaction.validator; import com.softwareverde.bitcoin.bip.Bip113; import com.softwareverde.bitcoin.bip.Bip68; import com.softwareverde.bitcoin.bip.HF20181115; import com.softwareverde.bitcoin.bip.HF20200515; import com.softwareverde.bitcoin.block.validator.ValidationResult; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.input.TransactionInputDeflater; import com.softwareverde.bitcoin.transaction.locktime.LockTime; import com.softwareverde.bitcoin.transaction.locktime.LockTimeType; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumberType; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.TransactionOutputDeflater; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.runner.ScriptRunner; import com.softwareverde.bitcoin.transaction.script.runner.context.MutableTransactionContext; import com.softwareverde.bitcoin.transaction.script.runner.context.TransactionContext; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.json.Json; import com.softwareverde.network.time.NetworkTime; import com.softwareverde.util.Util; import java.util.HashSet; public class TransactionValidatorCore implements TransactionValidator { protected final Context _context; protected final BlockOutputs _blockOutputs; protected Long _getCoinbaseMaturity() { return TransactionValidator.COINBASE_MATURITY; } protected Integer _getMaximumSignatureOperations() { return TransactionValidator.MAX_SIGNATURE_OPERATIONS; } protected Json _createInvalidTransactionReport(final String errorMessage, final Transaction transaction, final TransactionContext transactionContext) { final TransactionDeflater transactionDeflater = new TransactionDeflater(); final TransactionInputDeflater transactionInputDeflater = new TransactionInputDeflater(); final TransactionOutputDeflater transactionOutputDeflater = new TransactionOutputDeflater(); final TransactionOutput outputToSpend = transactionContext.getTransactionOutput(); final TransactionInput transactionInput = transactionContext.getTransactionInput(); final LockingScript lockingScript = (outputToSpend != null ? outputToSpend.getLockingScript() : null); final UnlockingScript unlockingScript = (transactionInput != null ? transactionInput.getUnlockingScript() : null); final Integer transactionInputIndex = transactionContext.getTransactionInputIndex(); final MedianBlockTime medianBlockTime = transactionContext.getMedianBlockTime(); final NetworkTime networkTime = _context.getNetworkTime(); final Json json = new Json(false); json.put("errorMessage", errorMessage); json.put("transactionHash", transaction.getHash()); json.put("inputIndex", transactionInputIndex); json.put("transactionBytes", transactionDeflater.toBytes(transaction)); json.put("inputBytes", (transactionInput != null ? transactionInputDeflater.toBytes(transactionInput) : null)); // json.put("transactionOutputIndex", ); json.put("previousOutputBytes", ((outputToSpend != null) ? transactionOutputDeflater.toBytes(outputToSpend) : null)); json.put("blockHeight", transactionContext.getBlockHeight()); json.put("lockingScriptBytes", (lockingScript != null ? lockingScript.getBytes() : null)); json.put("unlockingScriptBytes", (unlockingScript != null ? unlockingScript.getBytes() : null)); json.put("medianBlockTime", (medianBlockTime != null ? medianBlockTime.getCurrentTimeInSeconds() : null)); json.put("networkTime", (networkTime != null ? networkTime.getCurrentTimeInSeconds() : null)); return json; } protected Boolean _shouldValidateLockTime(final Transaction transaction) { // If all TransactionInputs' SequenceNumbers are all final (0xFFFFFFFF) then lockTime is disregarded... for (final TransactionInput transactionInput : transaction.getTransactionInputs()) { final SequenceNumber sequenceNumber = transactionInput.getSequenceNumber(); if (! Util.areEqual(sequenceNumber, FINAL_SEQUENCE_NUMBER)) { return true; } } return false; } protected Boolean _validateTransactionLockTime(final TransactionContext transactionContext) { final Transaction transaction = transactionContext.getTransaction(); final Long blockHeight = transactionContext.getBlockHeight(); final LockTime transactionLockTime = transaction.getLockTime(); if (transactionLockTime.getType() == LockTimeType.BLOCK_HEIGHT) { if (blockHeight < transactionLockTime.getValue()) { return false; } } else { final Long currentNetworkTime; { if (Bip113.isEnabled(blockHeight)) { final MedianBlockTime medianBlockTime = transactionContext.getMedianBlockTime(); currentNetworkTime = medianBlockTime.getCurrentTimeInSeconds(); } else { final NetworkTime networkTime = _context.getNetworkTime(); currentNetworkTime = networkTime.getCurrentTimeInSeconds(); } } if (currentNetworkTime < transactionLockTime.getValue()) { return false; } } return true; } protected TransactionOutput _getUnspentTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { { final TransactionOutput transactionOutput = _context.getTransactionOutput(transactionOutputIdentifier); if (transactionOutput != null) { return transactionOutput; } } if (_blockOutputs != null) { final TransactionOutput transactionOutput = _blockOutputs.getTransactionOutput(transactionOutputIdentifier); if (transactionOutput != null) { return transactionOutput; } } return null; } /** * Returns the blockHeight of `transactionOutputIdentifier`, or `blockHeight` if the identifier is within the currently-validating block. * Therefore, for chained mempool Transactions, this function returns null. */ protected Long _getTransactionOutputBlockHeight(final TransactionOutputIdentifier transactionOutputIdentifier, final Long blockHeight) { { final Long transactionOutputBlockHeight = _context.getBlockHeight(transactionOutputIdentifier); if (transactionOutputBlockHeight != null) { return transactionOutputBlockHeight; } } if (_blockOutputs != null) { final TransactionOutput transactionOutput = _blockOutputs.getTransactionOutput(transactionOutputIdentifier); if (transactionOutput != null) { return blockHeight; } } return null; } /** * Returns the MedianBlockTime of the TransactionOutput specified by `transactionOutputIdentifier`. * NOTE: The MedianBlockTime used for the TransactionOutput is the parent of the block that mined it, as per BIP-68. * "The mining date of the output is equal to the median-time-past of the previous block which mined it." */ protected MedianBlockTime _getTransactionOutputMedianBlockTime(final TransactionOutputIdentifier transactionOutputIdentifier, final Long blockHeight) { { final Long transactionOutputBlockHeight = _context.getBlockHeight(transactionOutputIdentifier); final MedianBlockTime transactionOutputMedianBlockTime = _context.getMedianBlockTime(transactionOutputBlockHeight - 1L); if (transactionOutputMedianBlockTime != null) { return transactionOutputMedianBlockTime; } } if (_blockOutputs != null) { final TransactionOutput transactionOutput = _blockOutputs.getTransactionOutput(transactionOutputIdentifier); if (transactionOutput != null) { final MedianBlockTime transactionOutputMedianBlockTime = _context.getMedianBlockTime(blockHeight - 1L); return transactionOutputMedianBlockTime; } } return null; } protected Boolean _isTransactionOutputCoinbase(final TransactionOutputIdentifier transactionOutputIdentifier) { { final Boolean transactionOutputIsCoinbase = _context.isCoinbaseTransactionOutput(transactionOutputIdentifier); if (transactionOutputIsCoinbase != null) { return transactionOutputIsCoinbase; } } if (_blockOutputs != null) { final Boolean isCoinbaseTransactionOutput = _blockOutputs.isCoinbaseTransactionOutput(transactionOutputIdentifier); if (isCoinbaseTransactionOutput != null) { return isCoinbaseTransactionOutput; } } return null; } protected ValidationResult _validateSequenceNumbers(final Transaction transaction, final Long blockHeight) { for (final TransactionInput transactionInput : transaction.getTransactionInputs()) { final SequenceNumber sequenceNumber = transactionInput.getSequenceNumber(); if (sequenceNumber.isRelativeLockTimeDisabled()) { continue; } final TransactionOutputIdentifier previousTransactionOutputIdentifier = TransactionOutputIdentifier.fromTransactionInput(transactionInput); if (sequenceNumber.getType() == SequenceNumberType.SECONDS_ELAPSED) { final Long requiredSecondsElapsed = sequenceNumber.asSecondsElapsed(); final Long previousBlockHeight = (blockHeight - 1L); final MedianBlockTime medianBlockTime = _context.getMedianBlockTime(previousBlockHeight); final long secondsElapsed; { final MedianBlockTime medianBlockTimeOfOutputBeingSpent = _getTransactionOutputMedianBlockTime(previousTransactionOutputIdentifier, blockHeight); if (medianBlockTimeOfOutputBeingSpent != null) { secondsElapsed = (medianBlockTime.getCurrentTimeInSeconds() - medianBlockTimeOfOutputBeingSpent.getCurrentTimeInSeconds()); } else { secondsElapsed = 0L; // No time has elapsed for outputs spending unconfirmed transactions... } } final boolean sequenceNumberIsValid = (secondsElapsed >= requiredSecondsElapsed); if (! sequenceNumberIsValid) { return ValidationResult.invalid("Sequence Number (Elapsed) Invalid: " + secondsElapsed + " < " + requiredSecondsElapsed); } } else { final Long blockHeightContainingOutputBeingSpent = _getTransactionOutputBlockHeight(previousTransactionOutputIdentifier, blockHeight); final long blockCount = (blockHeight - Util.coalesce(blockHeightContainingOutputBeingSpent, blockHeight)); // Uses the current blockHeight if the previousTransactionOutput is also an unconfirmed Transaction. final Long requiredBlockCount = sequenceNumber.asBlockCount(); final boolean sequenceNumberIsValid = (blockCount >= requiredBlockCount); if (! sequenceNumberIsValid) { return ValidationResult.invalid("(BlockHeight) Sequence Number Invalid: " + blockCount + " >= " + requiredBlockCount); } } } return ValidationResult.valid(); } public TransactionValidatorCore(final Context context) { this(null, context); } public TransactionValidatorCore(final BlockOutputs blockOutputs, final Context context) { _context = context; _blockOutputs = blockOutputs; } @Override public TransactionValidationResult validateTransaction(final Long blockHeight, final Transaction transaction) { final Sha256Hash transactionHash = transaction.getHash(); final ScriptRunner scriptRunner = new ScriptRunner(); final Long previousBlockHeight = (blockHeight - 1L); final MedianBlockTime medianBlockTime = _context.getMedianBlockTime(previousBlockHeight); final MutableTransactionContext transactionContext = new MutableTransactionContext(); transactionContext.setBlockHeight(blockHeight); transactionContext.setMedianBlockTime(medianBlockTime); transactionContext.setTransaction(transaction); { // Enforce Transaction minimum byte count... if (HF20181115.isEnabled(blockHeight)) { final Integer transactionByteCount = transaction.getByteCount(); if (transactionByteCount < TransactionInflater.MIN_BYTE_COUNT) { final Json errorJson = _createInvalidTransactionReport("Invalid byte count." + transactionByteCount + " " + transactionHash, transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } } } { // Validate nLockTime... final Boolean shouldValidateLockTime = _shouldValidateLockTime(transaction); if (shouldValidateLockTime) { final Boolean lockTimeIsValid = _validateTransactionLockTime(transactionContext); if (! lockTimeIsValid) { final Json errorJson = _createInvalidTransactionReport("Invalid LockTime.", transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } } } if (Bip68.isEnabled(blockHeight)) { // Validate Relative SequenceNumber if (transaction.getVersion() >= 2L) { final ValidationResult sequenceNumbersValidationResult = _validateSequenceNumbers(transaction, blockHeight); if (! sequenceNumbersValidationResult.isValid) { final Json errorJson = _createInvalidTransactionReport(sequenceNumbersValidationResult.errorMessage, transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } } } final long totalTransactionInputValue; { long totalInputValue = 0L; final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); if (transactionInputs.isEmpty()) { final Json errorJson = _createInvalidTransactionReport("Transaction contained missing TransactionInputs.", transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } final int transactionInputCount = transactionInputs.getCount(); final HashSet<TransactionOutputIdentifier> spentOutputIdentifiers = new HashSet<TransactionOutputIdentifier>(transactionInputCount); for (int i = 0; i < transactionInputCount; ++i) { final TransactionInput transactionInput = transactionInputs.get(i); final TransactionOutputIdentifier transactionOutputIdentifierBeingSpent = TransactionOutputIdentifier.fromTransactionInput(transactionInput); final boolean previousOutputIsUniqueToTransaction = spentOutputIdentifiers.add(transactionOutputIdentifierBeingSpent); if (! previousOutputIsUniqueToTransaction) { // The transaction attempted to spend the same previous output twice... final Json errorJson = _createInvalidTransactionReport("Transaction spends duplicate previousOutput.", transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } { // Enforcing Coinbase Maturity... (If the input is a coinbase then the coinbase must be at least 100 blocks old.) final Boolean transactionOutputBeingSpentIsCoinbaseTransaction = _isTransactionOutputCoinbase(transactionOutputIdentifierBeingSpent); if (transactionOutputBeingSpentIsCoinbaseTransaction == null) { final Json errorJson = _createInvalidTransactionReport("Previous output does not exist.", transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } if (transactionOutputBeingSpentIsCoinbaseTransaction) { final Long blockHeightOfTransactionOutputBeingSpent = _getTransactionOutputBlockHeight(transactionOutputIdentifierBeingSpent, blockHeight); final long coinbaseMaturity = (blockHeight - blockHeightOfTransactionOutputBeingSpent); final Long requiredCoinbaseMaturity = _getCoinbaseMaturity(); if (coinbaseMaturity <= requiredCoinbaseMaturity) { final Json errorJson = _createInvalidTransactionReport("Attempted to spend coinbase before maturity.", transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } } } final TransactionOutput transactionOutputBeingSpent = _getUnspentTransactionOutput(transactionOutputIdentifierBeingSpent); if (transactionOutputBeingSpent == null) { final Json errorJson = _createInvalidTransactionReport("Transaction output does not exist.", transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } totalInputValue += transactionOutputBeingSpent.getAmount(); final LockingScript lockingScript = transactionOutputBeingSpent.getLockingScript(); final UnlockingScript unlockingScript = transactionInput.getUnlockingScript(); transactionContext.setTransactionInput(transactionInput); transactionContext.setTransactionOutputBeingSpent(transactionOutputBeingSpent); transactionContext.setTransactionInputIndex(i); final Boolean inputIsUnlocked = scriptRunner.runScript(lockingScript, unlockingScript, transactionContext); if (! inputIsUnlocked) { final Json errorJson = _createInvalidTransactionReport("Transaction failed to unlock inputs.", transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } } totalTransactionInputValue = totalInputValue; } { // Validate that the total input value is greater than or equal to the output value... final long totalTransactionOutputValue; { long totalOutputValue = 0L; final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); if (transactionOutputs.isEmpty()) { final Json errorJson = _createInvalidTransactionReport("Transaction contains no outputs.", transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } for (final TransactionOutput transactionOutput : transaction.getTransactionOutputs()) { final Long transactionOutputAmount = transactionOutput.getAmount(); if (transactionOutputAmount < 0L) { final Json errorJson = _createInvalidTransactionReport("TransactionOutput has negative amount.", transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } totalOutputValue += transactionOutputAmount; } totalTransactionOutputValue = totalOutputValue; } if (totalTransactionInputValue < totalTransactionOutputValue) { final Json errorJson = _createInvalidTransactionReport("Total TransactionInput value is less than the TransactionOutput value.", transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } } final Integer signatureOperationCount = transactionContext.getSignatureOperationCount(); if (HF20200515.isEnabled(medianBlockTime)) { // Enforce maximum Signature operations per Transaction... final Integer maximumSignatureOperationCount = _getMaximumSignatureOperations(); if (signatureOperationCount > maximumSignatureOperationCount) { final Json errorJson = _createInvalidTransactionReport("Transaction exceeds maximum signature operation count.", transaction, transactionContext); return TransactionValidationResult.invalid(errorJson); } } return TransactionValidationResult.valid(signatureOperationCount); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/handler/transaction/TransactionInventoryMessageHandlerFactory.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.handler.transaction; import com.softwareverde.bitcoin.server.SynchronizationStatus; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.manager.NodeInitializer; import com.softwareverde.bitcoin.server.node.BitcoinNode; public class TransactionInventoryMessageHandlerFactory implements NodeInitializer.TransactionsAnnouncementHandlerFactory { public static final TransactionInventoryMessageHandlerFactory IGNORE_NEW_TRANSACTIONS_HANDLER_FACTORY = new TransactionInventoryMessageHandlerFactory(null, null, null) { @Override public BitcoinNode.TransactionInventoryAnnouncementHandler createTransactionsAnnouncementHandler(final BitcoinNode bitcoinNode) { return TransactionInventoryAnnouncementHandler.IGNORE_NEW_TRANSACTIONS_HANDLER; } }; protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; protected final SynchronizationStatus _synchronizationStatus; protected final Runnable _newInventoryCallback; public TransactionInventoryMessageHandlerFactory(final FullNodeDatabaseManagerFactory databaseManagerFactory, final SynchronizationStatus synchronizationStatus, final Runnable newInventoryCallback) { _databaseManagerFactory = databaseManagerFactory; _synchronizationStatus = synchronizationStatus; _newInventoryCallback = newInventoryCallback; } @Override public BitcoinNode.TransactionInventoryAnnouncementHandler createTransactionsAnnouncementHandler(final BitcoinNode bitcoinNode) { return new TransactionInventoryAnnouncementHandler(bitcoinNode, _databaseManagerFactory, _synchronizationStatus, _newInventoryCallback); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/spv/SlpValidity.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.spv; public enum SlpValidity { VALID, INVALID, UNKNOWN } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeMedianBlockTimeContext.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.context.MedianBlockTimeContext; import java.util.HashMap; public class FakeMedianBlockTimeContext implements MedianBlockTimeContext { protected final HashMap<Long, MedianBlockTime> _medianBlockTimes = new HashMap<Long, MedianBlockTime>(); @Override public MedianBlockTime getMedianBlockTime(final Long blockHeight) { if (! _medianBlockTimes.containsKey(blockHeight)) { throw new RuntimeException("Requested undefined MedianBlockTime for BlockHeight: " + blockHeight); } return _medianBlockTimes.get(blockHeight); } public void setMedianBlockTime(final Long blockHeight, final MedianBlockTime medianBlockTime) { _medianBlockTimes.put(blockHeight, medianBlockTime); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/secp256k1/privatekey/PrivateKeyDeflater.java<|end_filename|> package com.softwareverde.bitcoin.secp256k1.privatekey; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.util.Base58Util; public class PrivateKeyDeflater { public static class WalletImportFormat extends PrivateKeyInflater.WalletImportFormat { } public String toWalletImportFormat(final PrivateKey privateKey, final Boolean asCompressed) { final MutableByteArray extendedKeyBytes = new MutableByteArray(asCompressed ? WalletImportFormat.COMPRESSED_EXTENDED_KEY_BYTE_COUNT : WalletImportFormat.UNCOMPRESSED_EXTENDED_KEY_BYTE_COUNT); extendedKeyBytes.setByte(0, WalletImportFormat.MAIN_NET_PREFIX); if (asCompressed) { final int compressedFlagByteIndex = (WalletImportFormat.NETWORK_PREFIX_BYTE_COUNT + PrivateKey.KEY_BYTE_COUNT); extendedKeyBytes.setByte(compressedFlagByteIndex, (byte) 0x01); } extendedKeyBytes.setBytes(WalletImportFormat.NETWORK_PREFIX_BYTE_COUNT, privateKey); final ByteArray fullChecksum = HashUtil.doubleSha256(extendedKeyBytes); final int byteCount = (asCompressed ? WalletImportFormat.COMPRESSED_BYTE_COUNT : WalletImportFormat.UNCOMPRESSED_BYTE_COUNT); final MutableByteArray wifKeyBytes = new MutableByteArray(byteCount); wifKeyBytes.setBytes(0, extendedKeyBytes); wifKeyBytes.setBytes(extendedKeyBytes.getByteCount(), fullChecksum.getBytes(0, WalletImportFormat.CHECKSUM_BYTE_COUNT)); return Base58Util.toBase58String(wifKeyBytes.unwrap()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/ReadUncommittedDatabaseConnectionFactoryWrapper.java<|end_filename|> package com.softwareverde.bitcoin.server.database; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.mysql.connection.ReadUncommittedDatabaseConnectionFactory; public class ReadUncommittedDatabaseConnectionFactoryWrapper implements DatabaseConnectionFactory, ReadUncommittedDatabaseConnectionFactory { protected final DatabaseConnectionFactory _core; protected final ReadUncommittedDatabaseConnectionConfigurer _readUncommittedDatabaseConnectionConfigurer; public ReadUncommittedDatabaseConnectionFactoryWrapper(final DatabaseConnectionFactory core) { _core = core; _readUncommittedDatabaseConnectionConfigurer = new ReadUncommittedRawConnectionConfigurer(); } public ReadUncommittedDatabaseConnectionFactoryWrapper(final DatabaseConnectionFactory core, final ReadUncommittedDatabaseConnectionConfigurer readUncommittedDatabaseConnectionConfigurer) { _core = core; _readUncommittedDatabaseConnectionConfigurer = readUncommittedDatabaseConnectionConfigurer; } @Override public DatabaseConnection newConnection() throws DatabaseException { final DatabaseConnection databaseConnection = _core.newConnection(); _readUncommittedDatabaseConnectionConfigurer.setReadUncommittedTransactionIsolationLevel(databaseConnection); return databaseConnection; } @Override public void close() throws DatabaseException { _core.close(); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/wallet/SeedPhraseGeneratorTests.java<|end_filename|> package com.softwareverde.bitcoin.wallet; import com.softwareverde.bitcoin.test.UnitTest; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.util.IoUtil; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; public class SeedPhraseGeneratorTests extends UnitTest { protected static SeedPhraseGenerator _seedPhraseGenerator; @BeforeClass public static void beforeClass() throws IOException { final String seedWords = IoUtil.getResource("/seed_words/seed_words_english.txt"); final ImmutableListBuilder<String> seedWordsBuilder = new ImmutableListBuilder<String>(2048); for (final String seedWord : seedWords.split("\n")) { seedWordsBuilder.add(seedWord.trim()); } Assert.assertEquals(2048, seedWordsBuilder.getCount()); _seedPhraseGenerator = new SeedPhraseGenerator(seedWordsBuilder.build()); } @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } /** * Used in cases where the sequence is not a valid Secp256k1 key. * * @param seedKey * @param expectedSeedPhrase */ private void _validateSeedPhrase(final String seedKey, final String expectedSeedPhrase) { // validate we can generate the correct seed key from the seed phrase final ByteArray extractedSeedKeyBytes = _seedPhraseGenerator.fromSeedPhrase(expectedSeedPhrase); if (extractedSeedKeyBytes == null) { throw new IllegalArgumentException(); } final String extractedSeedKey = extractedSeedKeyBytes.toString(); Assert.assertEquals(seedKey.toUpperCase(), extractedSeedKey.toUpperCase()); // validate we can generate the correct seed phrase from the seed key final ByteArray seedKeyBytes = ByteArray.fromHexString(seedKey); final String phrase = _seedPhraseGenerator.toSeedPhrase(seedKeyBytes); Assert.assertEquals(expectedSeedPhrase.toLowerCase(), phrase); } @Test public void should_create_seed_for_min_key() { _validateSeedPhrase( "0000000000000000000000000000000000000000000000000000000000000001", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon diesel" ); } @Test public void should_create_seed_for_max_key() { _validateSeedPhrase( "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo word priority hover one trouble parent target virus rug snack brass agree alpha" ); } @Test(expected = IllegalArgumentException.class) public void should_find_invalid_checksum() { _validateSeedPhrase( "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo word priority hover one trouble parent target virus rug snack brass agree zoo" ); } @Test public void should_create_seed_for_small_all_zeros_key() { _validateSeedPhrase( "00000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" ); } @Test public void should_create_seed_for_small_7Fs_key() { _validateSeedPhrase( "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank yellow" ); } @Test public void should_create_seed_for_small_80s_key() { _validateSeedPhrase( "80808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage above" ); } @Test public void should_create_seed_for_small_FFs_key() { _validateSeedPhrase( "ffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong" ); } @Test public void should_create_seed_for_medium_all_zeros_key() { _validateSeedPhrase( "000000000000000000000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent" ); } @Test public void should_create_seed_for_medium_7Fs_key() { _validateSeedPhrase( "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will" ); } @Test public void should_create_seed_for_medium_80s_key() { _validateSeedPhrase( "808080808080808080808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always" ); } @Test public void should_create_seed_for_medium_FFs_key() { _validateSeedPhrase( "ffffffffffffffffffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when" ); } @Test public void should_create_seed_for_long_all_zeros_key() { _validateSeedPhrase( "0000000000000000000000000000000000000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art" ); } @Test public void should_create_seed_for_long_7Fs_key() { _validateSeedPhrase( "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title" ); } @Test public void should_create_seed_for_long_80s_key() { _validateSeedPhrase( "8080808080808080808080808080808080808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless" ); } @Test public void should_create_seed_for_long_FFs_key() { _validateSeedPhrase( "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote" ); } @Test public void should_create_seed_for_short_random_key1() { _validateSeedPhrase( "9e885d952ad362caeb4efe34a8e91bd2", "ozone drill grab fiber curtain grace pudding thank cruise elder eight picnic" ); } @Test public void should_create_seed_for_medium_random_key2() { _validateSeedPhrase( "<KEY>", "gravity machine north sort system female filter attitude volume fold club stay feature office ecology stable narrow fog" ); } @Test public void should_create_seed_for_long_random_key3() { _validateSeedPhrase( "68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c", "hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay length" ); } @Test public void should_create_seed_for_short_random_key4() { _validateSeedPhrase( "c0ba5a8e914111210f2bd131f3d5e08d", "scheme spot photo card baby mountain device kick cradle pact join borrow" ); } @Test public void should_create_seed_for_medium_random_key5() { _validateSeedPhrase( "<KEY>", "horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave" ); } @Test public void should_create_seed_for_long_random_key6() { _validateSeedPhrase( "<KEY>", "panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol speed nation flash devote level hobby quick inner drive ghost inside" ); } @Test public void should_create_seed_for_short_random_key7() { _validateSeedPhrase( "23db8160a31d3e0dca3688ed941adbf3", "cat swing flag economy stadium alone churn speed unique patch report train" ); } @Test public void should_create_seed_for_medium_random_key8() { _validateSeedPhrase( "8197a4a47f0425faeaa69deebc05ca29c0a5b5cc76ceacc0", "light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart sustain crack supply proud access" ); } @Test public void should_create_seed_for_long_random_key9() { _validateSeedPhrase( "066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad", "all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform" ); } @Test public void should_create_seed_for_short_random_key10() { _validateSeedPhrase( "f30f8c1da665478f49b001d94c5fc452", "vessel ladder alter error federal sibling chat ability sun glass valve picture" ); } @Test public void should_create_seed_for_medium_random_key11() { _validateSeedPhrase( "<KEY>", "scissors invite lock maple supreme raw rapid void congress muscle digital elegant little brisk hair mango congress clump" ); } @Test public void should_create_seed_for_long_random_key12() { _validateSeedPhrase( "<KEY>", "void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold" ); } @Test public void should_create_seed_for_long_random_key12_case_insensitive() { _validateSeedPhrase( "<KEY>", "Void come effort suffer camp survey warrior Heavy shoOt primary clutch crush opEn amazing screen patrol group space point ten exist slush involve unfold" ); } @Test public void should_return_validation_errors_for_invalid_seed_words() { // Action final List<String> errors = _seedPhraseGenerator.validateSeedPhrase("abcd efgh ijkl mnop"); // Assert Assert.assertEquals(4, errors.getCount()); Assert.assertTrue(errors.get(0).contains("abcd")); } @Test public void should_return_validation_error_for_invalid_checksum() { // Action final List<String> errors = _seedPhraseGenerator.validateSeedPhrase("scissors invite lock maple supreme raw rapid void congress muscle digital elegant little brisk hair mango congress unfold"); // Assert Assert.assertEquals(1, errors.getCount()); Assert.assertTrue(errors.get(0).contains("checksum")); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/response/hash/InventoryItemInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response.hash; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.bytearray.ByteArrayReader; import com.softwareverde.util.bytearray.Endian; public class InventoryItemInflater { public static final Integer BYTE_COUNT = (4 + Sha256Hash.BYTE_COUNT); public InventoryItem fromBytes(final ByteArrayReader byteArrayReader) { final Integer inventoryTypeCode = byteArrayReader.readInteger(4, Endian.LITTLE); final Sha256Hash objectHash = MutableSha256Hash.wrap(byteArrayReader.readBytes(Sha256Hash.BYTE_COUNT, Endian.LITTLE)); if (byteArrayReader.didOverflow()) { return null; } final InventoryItemType dataType = InventoryItemType.fromValue(inventoryTypeCode); if (dataType == null) { return null; } return new InventoryItem(dataType, objectHash); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/header/AbstractBlockHeader.java<|end_filename|> package com.softwareverde.bitcoin.block.header; import com.softwareverde.bitcoin.block.BlockHasher; public class AbstractBlockHeader extends BlockHeaderCore { protected AbstractBlockHeader(final BlockHasher blockHasher) { super(blockHasher); } public AbstractBlockHeader() { } public AbstractBlockHeader(final BlockHeader blockHeader) { super(blockHeader); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/manager/banfilter/DisabledBanFilter.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager.banfilter; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.network.ip.Ip; import java.util.regex.Pattern; public class DisabledBanFilter implements BanFilter { @Override public Boolean isIpBanned(final Ip ip) { return false; } @Override public void banIp(final Ip ip) { // Nothing. } @Override public void unbanIp(final Ip ip) { // Nothing. } @Override public void addToWhitelist(final Ip ip) { // Nothing. } @Override public void removeIpFromWhitelist(final Ip ip) { // Nothing. } @Override public void addToUserAgentBlacklist(final Pattern pattern) { // Nothing. } @Override public void removePatternFromUserAgentBlacklist(final Pattern pattern) { // Nothing. } @Override public void onNodeConnected(final Ip ip) { // Nothing. } @Override public void onNodeHandshakeComplete(final BitcoinNode bitcoinNode) { // Nothing. } @Override public void onNodeDisconnected(final Ip ip) { // Nothing. } @Override public Boolean onInventoryReceived(final BitcoinNode bitcoinNode, final List<Sha256Hash> blockInventory) { return true; } @Override public Boolean onHeadersReceived(final BitcoinNode bitcoinNode, final List<BlockHeader> blockHeaders) { return true; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/StratumModule.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.miner.pool.WorkerId; import com.softwareverde.bitcoin.server.Environment; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.database.Database; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumDataHandler; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.AuthenticateApi; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.CreateAccountApi; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.PasswordApi; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.PayoutAddressApi; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.UnauthenticateApi; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.ValidateAuthenticationApi; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.worker.CreateWorkerApi; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.worker.DeleteWorkerApi; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.worker.GetWorkersApi; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.pool.PoolHashRateApi; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.pool.PoolPrototypeBlockApi; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.pool.PoolWorkerApi; import com.softwareverde.bitcoin.server.module.stratum.database.AccountDatabaseManager; import com.softwareverde.bitcoin.server.module.stratum.rpc.StratumRpcServer; import com.softwareverde.concurrent.pool.MainThreadPool; import com.softwareverde.database.DatabaseException; import com.softwareverde.http.server.HttpServer; import com.softwareverde.http.server.endpoint.Endpoint; import com.softwareverde.http.server.servlet.DirectoryServlet; import com.softwareverde.http.server.servlet.Servlet; import com.softwareverde.logging.Logger; import com.softwareverde.util.type.time.SystemTime; import java.io.File; public class StratumModule { protected final SystemTime _systemTime = new SystemTime(); protected final Environment _environment; protected final StratumProperties _stratumProperties; protected final StratumServer _stratumServer; protected final StratumRpcServer _stratumRpcServer; protected final HttpServer _apiServer = new HttpServer(); protected final MainThreadPool _stratumThreadPool = new MainThreadPool(256, 60000L); protected final MainThreadPool _rpcThreadPool = new MainThreadPool(256, 60000L); protected <T extends Servlet> void _assignEndpoint(final String path, final T servlet) { final Endpoint endpoint = new Endpoint(servlet); endpoint.setStrictPathEnabled(true); endpoint.setPath(path); _apiServer.addEndpoint(endpoint); } public StratumModule(final StratumProperties stratumProperties, final Environment environment) { _stratumProperties = stratumProperties; _environment = environment; final Database database = _environment.getDatabase(); final DatabaseConnectionFactory databaseConnectionFactory = database.newConnectionFactory(); _stratumServer = new StratumServer(_stratumProperties, _stratumThreadPool); _stratumServer.setWorkerShareCallback(new StratumServer.WorkerShareCallback() { @Override public void onNewWorkerShare(final String workerUsername, final Integer shareDifficulty) { try (final DatabaseConnection databaseConnection = databaseConnectionFactory.newConnection()) { final AccountDatabaseManager accountDatabaseManager = new AccountDatabaseManager(databaseConnection); final WorkerId workerId = accountDatabaseManager.getWorkerId(workerUsername); if (workerId == null) { Logger.debug("Unknown worker: " + workerUsername); } else { accountDatabaseManager.addWorkerShare(workerId, shareDifficulty); Logger.debug("Added worker share: " + workerUsername + " " + shareDifficulty); } } catch (final DatabaseException databaseException) { Logger.warn("Unable to add worker share: " + workerUsername + " " + shareDifficulty, databaseException); } } }); final String tlsKeyFile = stratumProperties.getTlsKeyFile(); final String tlsCertificateFile = stratumProperties.getTlsCertificateFile(); if ( (tlsKeyFile != null) && (tlsCertificateFile != null) ) { _apiServer.setTlsPort(stratumProperties.getTlsPort()); _apiServer.setCertificate(stratumProperties.getTlsCertificateFile(), stratumProperties.getTlsKeyFile()); _apiServer.enableEncryption(true); _apiServer.redirectToTls(false); } _apiServer.setPort(stratumProperties.getHttpPort()); final StratumDataHandler stratumDataHandler = new StratumDataHandler() { @Override public Block getPrototypeBlock() { return _stratumServer.getPrototypeBlock(); } @Override public Long getPrototypeBlockHeight() { return _stratumServer.getBlockHeight(); } @Override public Long getHashesPerSecond() { final Long hashesPerSecondMultiplier = (1L << 32); final Integer shareDifficulty = _stratumServer.getShareDifficulty(); final Long startTimeInSeconds = _stratumServer.getCurrentBlockStartTimeInSeconds(); final Long shareCount = _stratumServer.getShareCount(); final Long now = _systemTime.getCurrentTimeInSeconds(); final Long duration = (now - startTimeInSeconds); return (long) (shareDifficulty * hashesPerSecondMultiplier * (shareCount / duration.doubleValue())); } }; { // Api Endpoints _assignEndpoint("/api/v1/worker", new PoolWorkerApi(stratumProperties, stratumDataHandler)); _assignEndpoint("/api/v1/pool/prototype-block", new PoolPrototypeBlockApi(stratumProperties, stratumDataHandler)); _assignEndpoint("/api/v1/pool/hash-rate", new PoolHashRateApi(stratumProperties, stratumDataHandler)); _assignEndpoint("/api/v1/account/create", new CreateAccountApi(stratumProperties, databaseConnectionFactory)); _assignEndpoint("/api/v1/account/authenticate", new AuthenticateApi(stratumProperties, databaseConnectionFactory)); _assignEndpoint("/api/v1/account/validate", new ValidateAuthenticationApi(stratumProperties)); _assignEndpoint("/api/v1/account/unauthenticate", new UnauthenticateApi(stratumProperties, databaseConnectionFactory)); _assignEndpoint("/api/v1/account/address", new PayoutAddressApi(stratumProperties, databaseConnectionFactory)); _assignEndpoint("/api/v1/account/password", new PasswordApi(stratumProperties, databaseConnectionFactory)); _assignEndpoint("/api/v1/account/workers/create", new CreateWorkerApi(stratumProperties, databaseConnectionFactory)); _assignEndpoint("/api/v1/account/workers/delete", new DeleteWorkerApi(stratumProperties, databaseConnectionFactory)); _assignEndpoint("/api/v1/account/workers", new GetWorkersApi(stratumProperties, databaseConnectionFactory)); } { // Static Content final File servedDirectory = new File(stratumProperties.getRootDirectory() + "/"); final DirectoryServlet indexServlet = new DirectoryServlet(servedDirectory); indexServlet.setShouldServeDirectories(true); indexServlet.setIndexFile("index.html"); final Endpoint endpoint = new Endpoint(indexServlet); endpoint.setPath("/"); endpoint.setStrictPathEnabled(false); _apiServer.addEndpoint(endpoint); } _stratumRpcServer = new StratumRpcServer(stratumProperties, stratumDataHandler, _rpcThreadPool); } public void loop() { _stratumRpcServer.start(); _stratumServer.start(); _apiServer.start(); while (true) { try { Thread.sleep(60000L); } catch (final Exception exception) { break; } } _apiServer.stop(); _stratumServer.stop(); _stratumRpcServer.stop(); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/wallet/WalletTests.java<|end_filename|> package com.softwareverde.bitcoin.wallet; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.test.UnitTest; import com.softwareverde.bitcoin.transaction.MutableTransaction; import com.softwareverde.bitcoin.transaction.input.MutableTransactionInput; import com.softwareverde.bitcoin.transaction.output.MutableTransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.script.ScriptBuilder; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptBuilder; import com.softwareverde.bitcoin.transaction.script.slp.send.MutableSlpSendScript; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.util.Tuple; import org.junit.Assert; import org.junit.Test; public class WalletTests extends UnitTest { protected MutableList<Tuple<String, Long>> _setupTuples() { final MutableList<Tuple<String, Long>> sortedTuples = new MutableList<Tuple<String, Long>>(); sortedTuples.add(new Tuple<String, Long>("One", 1L)); sortedTuples.add(new Tuple<String, Long>("Two", 2L)); sortedTuples.add(new Tuple<String, Long>("Three", 3L)); sortedTuples.add(new Tuple<String, Long>("Four", 4L)); sortedTuples.add(new Tuple<String, Long>("Five", 5L)); sortedTuples.add(new Tuple<String, Long>("Six", 6L)); sortedTuples.add(new Tuple<String, Long>("Seven", 7L)); sortedTuples.add(new Tuple<String, Long>("Eight", 8L)); sortedTuples.add(new Tuple<String, Long>("Nine", 9L)); sortedTuples.add(new Tuple<String, Long>("Ten", 10L)); return sortedTuples; } @Test public void should_select_closest_tuple_from_list_0() { // Setup final MutableList<Tuple<String, Long>> sortedTuples = _setupTuples(); final Long desiredResult = 0L; // Action final Tuple<String, Long> selectedTuple = Wallet.removeClosestTupleAmount(sortedTuples, desiredResult); // Assert Assert.assertEquals(Long.valueOf(1L), selectedTuple.second); Assert.assertEquals(9, sortedTuples.getCount()); } @Test public void should_select_closest_tuple_from_list_6() { // Setup final MutableList<Tuple<String, Long>> sortedTuples = _setupTuples(); final Long desiredResult = 6L; // Action final Tuple<String, Long> selectedTuple = Wallet.removeClosestTupleAmount(sortedTuples, desiredResult); // Assert Assert.assertEquals(desiredResult, selectedTuple.second); Assert.assertEquals(9, sortedTuples.getCount()); } @Test public void should_select_closest_tuple_from_list_7() { // Setup final MutableList<Tuple<String, Long>> sortedTuples = _setupTuples(); final Long desiredResult = 7L; // Action final Tuple<String, Long> selectedTuple = Wallet.removeClosestTupleAmount(sortedTuples, desiredResult); // Assert Assert.assertEquals(desiredResult, selectedTuple.second); Assert.assertEquals(9, sortedTuples.getCount()); } @Test public void should_select_closest_tuple_from_list_8() { // Setup final MutableList<Tuple<String, Long>> sortedTuples = _setupTuples(); final Long desiredResult = 8L; // Action final Tuple<String, Long> selectedTuple = Wallet.removeClosestTupleAmount(sortedTuples, desiredResult); // Assert Assert.assertEquals(desiredResult, selectedTuple.second); Assert.assertEquals(9, sortedTuples.getCount()); } @Test public void should_select_closest_tuple_from_list_20() { // Setup final MutableList<Tuple<String, Long>> sortedTuples = _setupTuples(); final Long desiredResult = 20L; // Action final Tuple<String, Long> selectedTuple = Wallet.removeClosestTupleAmount(sortedTuples, desiredResult); // Assert Assert.assertEquals(Long.valueOf(10L), selectedTuple.second); Assert.assertEquals(9, sortedTuples.getCount()); } @Test public void should_select_two_closest_tuples_from_list() { // Setup final MutableList<Tuple<String, Long>> sortedTuples = _setupTuples(); // Action final Tuple<String, Long> selectedTuple0 = Wallet.removeClosestTupleAmount(sortedTuples, 5L); final Tuple<String, Long> selectedTuple1 = Wallet.removeClosestTupleAmount(sortedTuples, 5L); // Assert Assert.assertEquals(Long.valueOf(5L), selectedTuple0.second); Assert.assertEquals(Long.valueOf(6L), selectedTuple1.second); Assert.assertEquals(8, sortedTuples.getCount()); } /** * This test handles an edge-case in which the the code used to override fee payment with a single sufficiently * large output does so with the knowledge of the value that is being provided by the mandatory inputs but then * when the total amount is checked at the end it was not calculated correctly and as a result returned null despite * having actually found a workable set of outputs to spend. */ @Test public void should_use_output_funding_entire_transaction_even_if_mandatory_inputs_help() { // Setup final PrivateKey privateKey = PrivateKey.createNewKey(); final AddressInflater addressInflater = new AddressInflater(); final Address address = addressInflater.fromPrivateKey(privateKey, true); final SlpTokenId slpTokenId = SlpTokenId.wrap(HashUtil.sha256(new MutableByteArray(4))); final SlpScriptBuilder slpScriptBuilder = new SlpScriptBuilder(); final MutableSlpSendScript slpSendScript = new MutableSlpSendScript(); slpSendScript.setTokenId(slpTokenId); slpSendScript.setAmount(1, 50L); final LockingScript slpLockingScript = slpScriptBuilder.createSendScript(slpSendScript); final MutableTransactionOutput output0 = new MutableTransactionOutput(); output0.setLockingScript(slpLockingScript); output0.setIndex(0); output0.setAmount(0L); output0.setLockingScript(slpLockingScript); final MutableTransactionOutput output1 = new MutableTransactionOutput(); output1.setIndex(1); output1.setAmount(546L); output1.setLockingScript(ScriptBuilder.payToAddress(address)); final MutableTransactionOutput output2 = new MutableTransactionOutput(); output2.setIndex(2); output2.setAmount(1000L); output2.setLockingScript(ScriptBuilder.payToAddress(address)); final MutableTransaction transaction = new MutableTransaction(); transaction.addTransactionInput(new MutableTransactionInput()); transaction.addTransactionOutput(output0); transaction.addTransactionOutput(output1); transaction.addTransactionOutput(output2); final Wallet wallet = new Wallet(); wallet.addTransaction(transaction); wallet.addPrivateKey(privateKey); // Action final List<TransactionOutputIdentifier> transactionOutputList = wallet.getOutputsToSpend(3, 546L, slpTokenId, 10L); // Test Assert.assertNotNull(transactionOutputList); Assert.assertEquals(2, transactionOutputList.getCount()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/wallet/Wallet.java<|end_filename|> package com.softwareverde.bitcoin.wallet; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.server.module.node.database.transaction.spv.SlpValidity; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.slp.SlpUtil; import com.softwareverde.bitcoin.transaction.MutableTransaction; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.input.MutableTransactionInput; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.locktime.LockTime; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; import com.softwareverde.bitcoin.transaction.output.MutableTransactionOutput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.TransactionOutputDeflater; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.script.ScriptBuilder; import com.softwareverde.bitcoin.transaction.script.ScriptPatternMatcher; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.runner.ScriptRunner; import com.softwareverde.bitcoin.transaction.script.runner.context.MutableTransactionContext; import com.softwareverde.bitcoin.transaction.script.signature.hashtype.HashType; import com.softwareverde.bitcoin.transaction.script.signature.hashtype.Mode; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptBuilder; import com.softwareverde.bitcoin.transaction.script.slp.send.MutableSlpSendScript; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.bitcoin.transaction.signer.SignatureContext; import com.softwareverde.bitcoin.transaction.signer.TransactionSigner; import com.softwareverde.bitcoin.util.BitcoinUtil; import com.softwareverde.bitcoin.wallet.slp.ImmutableSlpToken; import com.softwareverde.bitcoin.wallet.slp.SlpPaymentAmount; import com.softwareverde.bitcoin.wallet.slp.SlpToken; import com.softwareverde.bitcoin.wallet.utxo.MutableSpendableTransactionOutput; import com.softwareverde.bitcoin.wallet.utxo.SpendableTransactionOutput; import com.softwareverde.bloomfilter.BloomFilter; import com.softwareverde.bloomfilter.MutableBloomFilter; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.cryptography.secp256k1.key.PublicKey; import com.softwareverde.logging.Logger; import com.softwareverde.util.Container; import com.softwareverde.util.Tuple; import com.softwareverde.util.Util; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; public class Wallet { protected static final Long BYTES_PER_TRANSACTION_INPUT = 148L; // P2PKH Inputs are either 147-148 bytes for compressed addresses, or 179-180 bytes for uncompressed addresses. protected static final Long BYTES_PER_UNCOMPRESSED_TRANSACTION_INPUT = 180L; protected static final Long BYTES_PER_TRANSACTION_OUTPUT = 34L; protected static final Long BYTES_PER_TRANSACTION_HEADER = 10L; // This value becomes inaccurate if either the number of inputs or the number out outputs exceeds 252 (The max value of a 1-byte variable length integer)... public static Long getDefaultDustThreshold() { return (long) ((BYTES_PER_TRANSACTION_OUTPUT + BYTES_PER_TRANSACTION_INPUT) * 3D); } protected static class SlpTokenTransactionConfiguration { public final MutableList<PaymentAmount> mutablePaymentAmounts = new MutableList<PaymentAmount>(); public final MutableList<TransactionOutputIdentifier> transactionOutputIdentifiersToSpend = new MutableList<TransactionOutputIdentifier>(); public final MutableSlpSendScript slpSendScript = new MutableSlpSendScript(); } protected static final Address DUMMY_ADDRESS = (new AddressInflater()).fromBytes(new MutableByteArray(Address.BYTE_COUNT)); protected final HashMap<Address, PublicKey> _publicKeys = new HashMap<Address, PublicKey>(); protected final HashMap<PublicKey, PrivateKey> _privateKeys = new HashMap<PublicKey, PrivateKey>(); protected final HashMap<Sha256Hash, Transaction> _transactions = new HashMap<Sha256Hash, Transaction>(); protected final HashSet<Sha256Hash> _confirmedTransactions = new HashSet<Sha256Hash>(); protected final HashSet<Sha256Hash> _notYetValidatedSlpTransactions = new HashSet<Sha256Hash>(); protected final HashSet<Sha256Hash> _invalidSlpTransactions = new HashSet<Sha256Hash>(); protected final HashSet<Sha256Hash> _validSlpTransactions = new HashSet<Sha256Hash>(); protected final HashMap<TransactionOutputIdentifier, Sha256Hash> _spentTransactionOutputs = new HashMap<TransactionOutputIdentifier, Sha256Hash>(); protected final HashMap<TransactionOutputIdentifier, MutableSpendableTransactionOutput> _transactionOutputs = new HashMap<TransactionOutputIdentifier, MutableSpendableTransactionOutput>(); protected final Map<TransactionOutputIdentifier, Sha256Hash> _externallySpentTransactionOutputs = new HashMap<>(); protected BloomFilter _cachedBloomFilter = null; protected final MedianBlockTime _medianBlockTime; protected Double _satoshisPerByteFee = 1D; protected static <T> Tuple<T, Long> removeClosestTupleAmount(final MutableList<Tuple<T, Long>> sortedAvailableAmounts, final Long desiredAmount) { int selectedIndex = -1; Tuple<T, Long> lastAmount = null; for (final Tuple<T, Long> tuple : sortedAvailableAmounts) { if (lastAmount == null) { lastAmount = tuple; selectedIndex += 1; continue; } final long previousDifference = Math.abs(lastAmount.second - desiredAmount); final long currentDifference = Math.abs(tuple.second - desiredAmount); if (previousDifference < currentDifference) { break; } lastAmount = tuple; selectedIndex += 1; } if (selectedIndex >= 0) { sortedAvailableAmounts.remove(selectedIndex); } return lastAmount; } protected void _debugWalletState() { Logger.debug("Wallet Transaction Hashes:"); for (final Sha256Hash transactionHash : _transactions.keySet()) { Logger.debug(transactionHash); } Logger.debug("Wallet Available Outputs:"); for (final TransactionOutputIdentifier transactionOutputIdentifier : _transactionOutputs.keySet()) { Logger.debug(transactionOutputIdentifier); } Logger.debug("Wallet Public Keys:"); for (final PublicKey publicKey : _privateKeys.keySet()) { Logger.debug(publicKey); } } protected SlpTokenId _getSlpTokenId(final TransactionOutputIdentifier transactionOutputIdentifier) { final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); final Transaction transaction = _transactions.get(transactionHash); if (transaction == null) { throw new RuntimeException("Unable to find TransactionOutput: " + transactionOutputIdentifier); } return SlpUtil.getTokenId(transaction); } protected Boolean _isSlpTokenOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); final Integer transactionOutputIndex = transactionOutputIdentifier.getOutputIndex(); final Transaction transaction = _transactions.get(transactionHash); if (transaction == null) { throw new RuntimeException("Unable to find TransactionOutput: " + transactionOutputIdentifier); } final boolean isPartOfValidSlpTransaction = _isSlpTransactionAndIsValid(transactionHash, true); return (isPartOfValidSlpTransaction && SlpUtil.isSlpTokenOutput(transaction, transactionOutputIndex)); } protected Boolean _outputContainsSpendableSlpTokens(final TransactionOutputIdentifier transactionOutputIdentifier) { final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); final Integer transactionOutputIndex = transactionOutputIdentifier.getOutputIndex(); final Transaction transaction = _transactions.get(transactionHash); if (transaction == null) { throw new RuntimeException("Unable to find TransactionOutput: " + transactionOutputIdentifier); } final boolean isPartOfValidSlpTransaction = _isSlpTransactionAndIsValid(transactionHash, true); return (isPartOfValidSlpTransaction && SlpUtil.outputContainsSpendableSlpTokens(transaction, transactionOutputIndex)); } protected List<SlpToken> _getSlpTokens(final SlpTokenId matchingSlpTokenId, final Boolean shouldIncludeNotYetValidatedTransactions) { final Collection<? extends SpendableTransactionOutput> spendableTransactionOutputs = _transactionOutputs.values(); final ImmutableListBuilder<SlpToken> slpTokens = new ImmutableListBuilder<SlpToken>(spendableTransactionOutputs.size()); for (final SpendableTransactionOutput spendableTransactionOutput : spendableTransactionOutputs) { final TransactionOutputIdentifier transactionOutputIdentifier = spendableTransactionOutput.getIdentifier(); final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); final Integer transactionOutputIndex = transactionOutputIdentifier.getOutputIndex(); final Transaction transaction = _transactions.get(transactionHash); if (transaction == null) { continue; } final boolean outputContainsTokens = SlpUtil.isSlpTokenOutput(transaction, transactionOutputIndex); if (! outputContainsTokens) { continue; } final SlpTokenId tokenId = SlpUtil.getTokenId(transaction); if (matchingSlpTokenId != null) { if (! Util.areEqual(matchingSlpTokenId, tokenId)) { continue; } } if (! _isSlpTransactionAndIsValid(transactionHash, shouldIncludeNotYetValidatedTransactions)) { continue; } final Long tokenAmount = SlpUtil.getOutputTokenAmount(transaction, transactionOutputIndex); final Boolean isBatonHolder = SlpUtil.isSlpTokenBatonHolder(transaction, transactionOutputIndex); final SlpToken slpToken = new ImmutableSlpToken(tokenId, tokenAmount, spendableTransactionOutput, isBatonHolder); slpTokens.add(slpToken); } return slpTokens.build(); } protected Long _getSlpTokenAmount(final TransactionOutputIdentifier transactionOutputIdentifier) { final Transaction transaction = _transactions.get(transactionOutputIdentifier.getTransactionHash()); if (transaction == null) { return null; } final Integer transactionOutputIndex = transactionOutputIdentifier.getOutputIndex(); return SlpUtil.getOutputTokenAmount(transaction, transactionOutputIndex); } protected Long _calculateDustThreshold(final Long transactionOutputByteCount, final Boolean addressIsCompressed) { // "Dust" is defined by XT/ABC as being an output that is less than 1/3 of the fees required to spend that output. // Non-spendable TransactionOutputs are exempt from this network rule. // For the common default _satoshisPerByteFee (1), the dust threshold is 546 satoshis. final long transactionInputByteCount = (addressIsCompressed ? BYTES_PER_TRANSACTION_INPUT : BYTES_PER_UNCOMPRESSED_TRANSACTION_INPUT); return (long) ((transactionOutputByteCount + transactionInputByteCount) * _satoshisPerByteFee * 3D); } /** * Returns the fee required to add the opReturnScript as a TransactionOutput, modified by _satoshisPerByteFee. * This calculation includes the entire TransactionOutput, not just its Script component. */ protected Long _calculateOpReturnScriptFee(final LockingScript opReturnScript) { final MutableTransactionOutput transactionOutput = new MutableTransactionOutput(); transactionOutput.setIndex(0); transactionOutput.setAmount(0L); transactionOutput.setLockingScript(opReturnScript); final TransactionOutputDeflater transactionOutputDeflater = new TransactionOutputDeflater(); final Integer outputByteCount = transactionOutputDeflater.getByteCount(transactionOutput); return (long) (outputByteCount * _satoshisPerByteFee); } protected void _addPrivateKey(final PrivateKey privateKey) { final PrivateKey constPrivateKey = privateKey.asConst(); final PublicKey publicKey = constPrivateKey.getPublicKey(); final PublicKey compressedPublicKey = publicKey.compress(); final PublicKey decompressedPublicKey = publicKey.decompress(); final AddressInflater addressInflater = new AddressInflater(); final Address decompressedAddress = addressInflater.fromPrivateKey(constPrivateKey, false); final Address compressedAddress = addressInflater.fromPrivateKey(constPrivateKey, true); _privateKeys.put(compressedPublicKey.asConst(), constPrivateKey); _privateKeys.put(decompressedPublicKey.asConst(), constPrivateKey); _publicKeys.put(compressedAddress, compressedPublicKey); _publicKeys.put(decompressedAddress, decompressedPublicKey); } protected Boolean _hasSpentInputs(final Transaction transaction) { for (final TransactionInput transactionInput : transaction.getTransactionInputs()) { final TransactionOutputIdentifier transactionOutputIdentifier = TransactionOutputIdentifier.fromTransactionInput(transactionInput); final boolean inputWasSpent = _spentTransactionOutputs.containsKey(transactionOutputIdentifier); if (inputWasSpent) { return true; } } return false; } protected void _addTransaction(final Transaction transaction, final Boolean isConfirmedTransaction) { final Transaction constTransaction = transaction.asConst(); final Sha256Hash transactionHash = constTransaction.getHash(); if ( (! isConfirmedTransaction) && _hasSpentInputs(transaction) ) { Logger.debug("Wallet is not adding already spent unconfirmed transaction: " + transactionHash); return; } _transactions.put(transactionHash, constTransaction); if (isConfirmedTransaction) { _confirmedTransactions.add(transactionHash); } // Mark outputs as spent, if any... for (final TransactionInput transactionInput : transaction.getTransactionInputs()) { final TransactionOutputIdentifier transactionOutputIdentifier = TransactionOutputIdentifier.fromTransactionInput(transactionInput); _spentTransactionOutputs.put(transactionOutputIdentifier, transactionHash); final MutableSpendableTransactionOutput spendableTransactionOutput = _transactionOutputs.get(transactionOutputIdentifier); if (spendableTransactionOutput == null) { continue; } spendableTransactionOutput.setIsSpent(true); } final ScriptPatternMatcher scriptPatternMatcher = new ScriptPatternMatcher(); final List<TransactionOutput> transactionOutputs = constTransaction.getTransactionOutputs(); for (int transactionOutputIndex = 0; transactionOutputIndex < transactionOutputs.getCount(); ++transactionOutputIndex) { final TransactionOutput transactionOutput = transactionOutputs.get(transactionOutputIndex); final LockingScript lockingScript = transactionOutput.getLockingScript(); final ScriptType scriptType = scriptPatternMatcher.getScriptType(lockingScript); if (scriptType == null) { continue; } final Address address = scriptPatternMatcher.extractAddress(scriptType, lockingScript); if (address == null) { continue; } if (_publicKeys.containsKey(address)) { final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, transactionOutputIndex); final boolean isSpent = _spentTransactionOutputs.containsKey(transactionOutputIdentifier); final MutableSpendableTransactionOutput spendableTransactionOutput = new MutableSpendableTransactionOutput(address, transactionOutputIdentifier, transactionOutput); spendableTransactionOutput.setIsSpent(isSpent); _transactionOutputs.put(transactionOutputIdentifier, spendableTransactionOutput); } } if (Transaction.isSlpTransaction(transaction)) { // check for validity and stop tracking its validity explicitly if it is valid if (! _validSlpTransactions.remove(transactionHash)) { // not known to be valid if (! _invalidSlpTransactions.contains(transactionHash)) { // not known to be invalid either, add as not yet validated _notYetValidatedSlpTransactions.add(transactionHash); } } } } protected void _reloadTransactions() { final MutableList<Transaction> transactions = new MutableList<Transaction>(_transactions.values()); final HashSet<Sha256Hash> confirmedTransactions = new HashSet<Sha256Hash>(_confirmedTransactions); final Map<TransactionOutputIdentifier, Sha256Hash> externallySpentTransactionOutputs = new HashMap<>(_externallySpentTransactionOutputs); _externallySpentTransactionOutputs.clear(); _spentTransactionOutputs.clear(); _transactionOutputs.clear(); _transactions.clear(); _confirmedTransactions.clear(); // intentionally not clearing SLP sets, since their state should remain valid across the reload for (final Transaction transaction : transactions) { final Sha256Hash transactionHash = transaction.getHash(); final boolean isConfirmedTransaction = confirmedTransactions.contains(transactionHash); // add any previously processed, valid SLP transactions (back) to the valid SLP transactions set if (Transaction.isSlpTransaction(transaction)) { if ( (! _notYetValidatedSlpTransactions.contains(transactionHash)) && (! _invalidSlpTransactions.contains(transactionHash)) ) { _validSlpTransactions.add(transactionHash); } } _addTransaction(transaction, isConfirmedTransaction); } // transfer explicitly spent outputs to new data set for (final TransactionOutputIdentifier transactionOutputIdentifier : externallySpentTransactionOutputs.keySet()) { if (_transactions.containsKey(transactionOutputIdentifier.getTransactionHash())) { _markTransactionOutputAsSpent(transactionOutputIdentifier); } } } /** * Return true if the transaction with the provided hash is known to be a valid SLP transaction or if <code>shouldTreatUnknownTransactionsAsValid</code> * is true and the transaction is known to be an SLP transaction but is not known to be valid or not. * * If the transaction is completely unknown, returns null. * * Otherwise, returns false. * @param transactionHash * @param shouldTreatUnknownTransactionsAsValid * @return */ protected Boolean _isSlpTransactionAndIsValid(final Sha256Hash transactionHash, final Boolean shouldTreatUnknownTransactionsAsValid) { // if we know a transaction is valid, return true whether we have it or not if (_validSlpTransactions.contains(transactionHash)) { return true; } // if the transaction is not known, we cannot make a decision if (! _transactions.containsKey(transactionHash)) { return null; } final Transaction transaction = _transactions.get(transactionHash); if (! Transaction.isSlpTransaction(transaction)) { return false; } if (_invalidSlpTransactions.contains(transactionHash)) { return false; } if (_notYetValidatedSlpTransactions.contains(transactionHash)) { return shouldTreatUnknownTransactionsAsValid; } // is an SLP transaction and is not invalid or unknown so it must be valid return true; } protected Long _getBalance(final PublicKey publicKey, final SlpTokenId slpTokenId, final Boolean shouldIncludeNotYetValidatedTransactions) { final ScriptPatternMatcher scriptPatternMatcher = new ScriptPatternMatcher(); final AddressInflater addressInflater = new AddressInflater(); final Address address = addressInflater.fromPublicKey(publicKey, false); final Address compressedAddress = addressInflater.fromPublicKey(publicKey, true); long amount = 0L; for (final SpendableTransactionOutput spendableTransactionOutput : _transactionOutputs.values()) { if (! spendableTransactionOutput.isSpent()) { final TransactionOutputIdentifier transactionOutputIdentifier = spendableTransactionOutput.getIdentifier(); final TransactionOutput transactionOutput = spendableTransactionOutput.getTransactionOutput(); final LockingScript lockingScript = transactionOutput.getLockingScript(); final ScriptType scriptType = scriptPatternMatcher.getScriptType(lockingScript); final Address outputAddress = scriptPatternMatcher.extractAddress(scriptType, lockingScript); if ( (! Util.areEqual(address, outputAddress)) && (! Util.areEqual(compressedAddress, outputAddress)) ) { continue; } if (slpTokenId == null) { // If the slpTokenId is null then only sum its BCH value. amount += transactionOutput.getAmount(); } else { // If the slpTokenId is provided but does not match the Transaction's SlpTokenId ignore the amount. // Otherwise, ensure retrieve its token balance. final SlpTokenId transactionTokenId = _getSlpTokenId(transactionOutputIdentifier); if (! Util.areEqual(slpTokenId, transactionTokenId)) { continue; } final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); if (! _isSlpTransactionAndIsValid(transactionHash, shouldIncludeNotYetValidatedTransactions)) { continue; } final Long slpTokenAmount = _getSlpTokenAmount(transactionOutputIdentifier); amount += slpTokenAmount; } } } return amount; } protected Long _getSlpTokenBalance(final SlpTokenId tokenId, final Boolean shouldIncludeNotYetValidatedTransactions) { long amount = 0L; for (final SpendableTransactionOutput spendableTransactionOutput : _transactionOutputs.values()) { if (! spendableTransactionOutput.isSpent()) { final TransactionOutputIdentifier transactionOutputIdentifier = spendableTransactionOutput.getIdentifier(); final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); final Integer transactionOutputIndex = transactionOutputIdentifier.getOutputIndex(); if (_isSlpTransactionAndIsValid(transactionHash, shouldIncludeNotYetValidatedTransactions)) { final Transaction transaction = _transactions.get(transactionHash); if (transaction == null) { return null; } final boolean outputContainsTokens = SlpUtil.isSlpTokenOutput(transaction, transactionOutputIndex); if (! outputContainsTokens) { continue; } final SlpTokenId transactionTokenId = SlpUtil.getTokenId(transaction); if (! Util.areEqual(tokenId, transactionTokenId)) { continue; } amount += SlpUtil.getOutputTokenAmount(transaction, transactionOutputIndex); } } } return amount; } protected Container<Long> _createNewFeeContainer(final Integer newOutputCount, final LockingScript opReturnScript) { final Container<Long> feesContainer = new Container<Long>(0L); feesContainer.value += (long) (BYTES_PER_TRANSACTION_HEADER * _satoshisPerByteFee); final long feeToSpendOneOutput = (long) (BYTES_PER_TRANSACTION_OUTPUT * _satoshisPerByteFee); feesContainer.value += (feeToSpendOneOutput * newOutputCount); if (opReturnScript != null) { feesContainer.value += _calculateOpReturnScriptFee(opReturnScript); } return feesContainer; } protected List<SpendableTransactionOutput> _getOutputsToSpend(final Long minimumUtxoAmount, final Container<Long> feesToSpendOutputs, final List<TransactionOutputIdentifier> mandatoryTransactionOutputsToSpend) { final Long originalFeesToSpendOutputs = feesToSpendOutputs.value; final long feeToSpendOneOutput = (long) (BYTES_PER_TRANSACTION_INPUT * _satoshisPerByteFee); final long feeToSpendOneUncompressedOutput = (long) (BYTES_PER_UNCOMPRESSED_TRANSACTION_INPUT * _satoshisPerByteFee); long selectedUtxoAmount = 0L; final MutableList<SpendableTransactionOutput> transactionOutputsToSpend = new MutableList<SpendableTransactionOutput>(); final MutableList<SpendableTransactionOutput> unspentTransactionOutputs = new MutableList<SpendableTransactionOutput>(_transactionOutputs.size()); for (final SpendableTransactionOutput spendableTransactionOutput : _transactionOutputs.values()) { final TransactionOutputIdentifier transactionOutputIdentifier = spendableTransactionOutput.getIdentifier(); // If this TransactionOutput is one that must be included in this transaction, // then add it to transactionOutputsToSpend, its amount to selectedUtxoAmount, // increase the total fees required for this transaction, and exclude the Utxo // from the possible spendableTransactionOutputs to prevent it from being added twice. if ( (mandatoryTransactionOutputsToSpend != null) && (mandatoryTransactionOutputsToSpend.contains(transactionOutputIdentifier)) ) { final Address address = spendableTransactionOutput.getAddress(); final TransactionOutput transactionOutput = spendableTransactionOutput.getTransactionOutput(); selectedUtxoAmount += transactionOutput.getAmount(); feesToSpendOutputs.value += (address.isCompressed() ? feeToSpendOneOutput : feeToSpendOneUncompressedOutput); transactionOutputsToSpend.add(spendableTransactionOutput); continue; } // Avoid spending tokens as regular BCH... if (_isSlpTokenOutput(transactionOutputIdentifier)) { continue; } if (! spendableTransactionOutput.isSpent()) { unspentTransactionOutputs.add(spendableTransactionOutput); } } unspentTransactionOutputs.sort(SpendableTransactionOutput.AMOUNT_ASCENDING_COMPARATOR); final long mandatoryOutputsFundingAmount = selectedUtxoAmount; for (final SpendableTransactionOutput spendableTransactionOutput : unspentTransactionOutputs) { if (selectedUtxoAmount >= (minimumUtxoAmount + feesToSpendOutputs.value)) { break; } final Address address = spendableTransactionOutput.getAddress(); final Long feeToSpendThisOutput = (address.isCompressed() ? feeToSpendOneOutput : feeToSpendOneUncompressedOutput); final TransactionOutput transactionOutput = spendableTransactionOutput.getTransactionOutput(); final Long transactionOutputAmount = transactionOutput.getAmount(); if (transactionOutputAmount < feeToSpendThisOutput) { continue; } // Exclude spending dust... // If the next UnspentTransactionOutput covers the whole transaction cost by itself, then use only that output instead... if (transactionOutputAmount >= (minimumUtxoAmount + feeToSpendThisOutput + originalFeesToSpendOutputs)) { // Remove any non-mandatory outputs, then add the output covering the cost... final Iterator<SpendableTransactionOutput> mutableIterator = transactionOutputsToSpend.mutableIterator(); while (mutableIterator.hasNext()) { final SpendableTransactionOutput selectedTransactionOutput = mutableIterator.next(); final TransactionOutputIdentifier transactionOutputIdentifier = selectedTransactionOutput.getIdentifier(); if ( (mandatoryTransactionOutputsToSpend == null) || (! mandatoryTransactionOutputsToSpend.contains(transactionOutputIdentifier)) ) { mutableIterator.remove(); // Subtract the fee for spending this output... final Address addressBeingRemoved = selectedTransactionOutput.getAddress(); final Long feeToSpendRemovedOutput = (addressBeingRemoved.isCompressed() ? feeToSpendOneOutput : feeToSpendOneUncompressedOutput); feesToSpendOutputs.value -= feeToSpendRemovedOutput; } } feesToSpendOutputs.value += feeToSpendThisOutput; selectedUtxoAmount = transactionOutputAmount + mandatoryOutputsFundingAmount; transactionOutputsToSpend.add(spendableTransactionOutput); break; } feesToSpendOutputs.value += feeToSpendThisOutput; selectedUtxoAmount += transactionOutputAmount; transactionOutputsToSpend.add(spendableTransactionOutput); } if (selectedUtxoAmount < (minimumUtxoAmount + feesToSpendOutputs.value)) { Logger.info("Insufficient funds to fund transaction."); if (Logger.isDebugEnabled()) { _debugWalletState(); } feesToSpendOutputs.value = originalFeesToSpendOutputs; // Reset the feesToSpendOutputs container... return null; } return transactionOutputsToSpend; } protected List<TransactionOutputIdentifier> _getOutputsToSpend(final Integer newTransactionOutputCount, final Long desiredSpendAmount, final SlpTokenId slpTokenId, final Long desiredSlpSpendAmount, final List<TransactionOutputIdentifier> requiredTransactionOutputsToSpend, final Boolean shouldIncludeNotYetValidatedTransactions) { final MutableList<SlpPaymentAmount> slpPaymentAmounts = new MutableList<SlpPaymentAmount>(newTransactionOutputCount); { // Create fake SlpPaymentAmounts that sum exactly to the requested amounts, and contain exactly newTransactionOutputCount items... if (newTransactionOutputCount > 0) { final Long fakeDesiredSpendAmount = (desiredSpendAmount - (newTransactionOutputCount - 1)); final Long fakeDesiredSlpSpendAmount = (desiredSlpSpendAmount - (newTransactionOutputCount - 1)); slpPaymentAmounts.add(new SlpPaymentAmount(DUMMY_ADDRESS, fakeDesiredSpendAmount, fakeDesiredSlpSpendAmount)); } for (int i = 1; i < newTransactionOutputCount; ++i) { slpPaymentAmounts.add(new SlpPaymentAmount(DUMMY_ADDRESS, 1L, 1L)); } } final SlpTokenTransactionConfiguration slpTokenTransactionConfiguration = _createSlpTokenTransactionConfiguration(slpTokenId, slpPaymentAmounts, DUMMY_ADDRESS, requiredTransactionOutputsToSpend, shouldIncludeNotYetValidatedTransactions); if (slpTokenTransactionConfiguration == null) { return null; } final SlpScriptBuilder slpScriptBuilder = new SlpScriptBuilder(); final LockingScript slpTokenScript = slpScriptBuilder.createSendScript(slpTokenTransactionConfiguration.slpSendScript); return _getOutputsToSpend(newTransactionOutputCount, desiredSpendAmount, slpTokenScript, slpTokenTransactionConfiguration.transactionOutputIdentifiersToSpend); } protected List<TransactionOutputIdentifier> _getOutputsToSpend(final Integer newTransactionOutputCount, final Long desiredSpendAmount, final LockingScript opReturnScript, final List<TransactionOutputIdentifier> requiredTransactionOutputIdentifiersToSpend) { final Container<Long> feesContainer = _createNewFeeContainer(newTransactionOutputCount, opReturnScript); final List<SpendableTransactionOutput> spendableTransactionOutputs = _getOutputsToSpend(desiredSpendAmount, feesContainer, requiredTransactionOutputIdentifiersToSpend); if (spendableTransactionOutputs == null) { return null; } final MutableList<TransactionOutputIdentifier> transactionOutputs = new MutableList<TransactionOutputIdentifier>(spendableTransactionOutputs.getCount()); for (final SpendableTransactionOutput spendableTransactionOutput : spendableTransactionOutputs) { transactionOutputs.add(spendableTransactionOutput.getIdentifier()); } return transactionOutputs; } protected SlpTokenTransactionConfiguration _createSlpTokenTransactionConfiguration(final SlpTokenId slpTokenId, final List<SlpPaymentAmount> paymentAmounts, final Address changeAddress, final List<TransactionOutputIdentifier> requiredTransactionOutputIdentifiersToSpend, final Boolean shouldIncludeNotYetValidatedTransactions) { final SlpTokenTransactionConfiguration configuration = new SlpTokenTransactionConfiguration(); final long requiredTokenAmount; { // Calculate the total token amount and build the SlpSendScript used to create the SLP LockingScript... long totalAmount = 0L; configuration.slpSendScript.setTokenId(slpTokenId); for (int i = 0; i < paymentAmounts.getCount(); ++i) { final SlpPaymentAmount slpPaymentAmount = paymentAmounts.get(i); final int transactionOutputId = (i + 1); configuration.slpSendScript.setAmount(transactionOutputId, slpPaymentAmount.tokenAmount); totalAmount += slpPaymentAmount.tokenAmount; } requiredTokenAmount = totalAmount; } final long preselectedTokenAmount; { // Calculate the total SLP Token amount selected by the required TransactionOutputs... long totalAmount = 0L; for (final TransactionOutputIdentifier transactionOutputIdentifier : requiredTransactionOutputIdentifiersToSpend) { final SlpTokenId outputTokenId = _getSlpTokenId(transactionOutputIdentifier); final Boolean isValidSlpTransaction = _isSlpTransactionAndIsValid(transactionOutputIdentifier.getTransactionHash(), shouldIncludeNotYetValidatedTransactions); if (isValidSlpTransaction == null) { Logger.error("Unable to add required output " + transactionOutputIdentifier.getTransactionHash() + ":" + transactionOutputIdentifier.getOutputIndex() + " as the transaction is not available."); return null; } final Boolean isSlpOutput = _isSlpTokenOutput(transactionOutputIdentifier); if (isValidSlpTransaction && isSlpOutput) { if (! Util.areEqual(slpTokenId, outputTokenId)) { Logger.warn("Required output " + transactionOutputIdentifier.getTransactionHash() + ":" + transactionOutputIdentifier.getOutputIndex() + " has a different token type (" + outputTokenId + ") than the transaction being created (" + slpTokenId + "). These tokens will be burned."); } final Long transactionOutputTokenAmount = _getSlpTokenAmount(transactionOutputIdentifier); totalAmount += transactionOutputTokenAmount; } configuration.transactionOutputIdentifiersToSpend.add(transactionOutputIdentifier); } preselectedTokenAmount = totalAmount; } for (final PaymentAmount paymentAmount : paymentAmounts) { configuration.mutablePaymentAmounts.add(paymentAmount); } // Add additional inputs to fulfill the requested payment amount(s)... long selectedTokenAmount = preselectedTokenAmount; if (selectedTokenAmount < requiredTokenAmount) { final MutableList<Tuple<TransactionOutputIdentifier, Long>> availableTokenAmounts = new MutableList<Tuple<TransactionOutputIdentifier, Long>>(); for (final TransactionOutputIdentifier transactionOutputIdentifier : _transactionOutputs.keySet()) { final SpendableTransactionOutput spendableTransactionOutput = _transactionOutputs.get(transactionOutputIdentifier); if (spendableTransactionOutput.isSpent()) { continue; } if (requiredTransactionOutputIdentifiersToSpend.contains(transactionOutputIdentifier)) { continue; } if (! _isSlpTokenOutput(transactionOutputIdentifier)) { continue; } final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); if (! _isSlpTransactionAndIsValid(transactionHash, shouldIncludeNotYetValidatedTransactions)) { continue; } final SlpTokenId outputTokenId = _getSlpTokenId(transactionOutputIdentifier); if (! Util.areEqual(slpTokenId, outputTokenId)) { continue; } final Long tokenAmount = _getSlpTokenAmount(transactionOutputIdentifier); if (tokenAmount == null) { continue; } if (tokenAmount < 1L) { continue; } final Tuple<TransactionOutputIdentifier, Long> tokenAmountTuple = new Tuple<TransactionOutputIdentifier, Long>(); tokenAmountTuple.first = transactionOutputIdentifier; tokenAmountTuple.second = tokenAmount; availableTokenAmounts.add(tokenAmountTuple); } availableTokenAmounts.sort(new Comparator<Tuple<TransactionOutputIdentifier, Long>>() { @Override public int compare(final Tuple<TransactionOutputIdentifier, Long> tuple0, final Tuple<TransactionOutputIdentifier, Long> tuple1) { final Long amount0 = tuple0.second; final Long amount1 = tuple1.second; return amount0.compareTo(amount1); } }); while (selectedTokenAmount < requiredTokenAmount) { final long missingAmount = (requiredTokenAmount - selectedTokenAmount); final Tuple<TransactionOutputIdentifier, Long> closestAmountTuple = Wallet.removeClosestTupleAmount(availableTokenAmounts, missingAmount); if (closestAmountTuple == null) { Logger.info("Insufficient tokens to fulfill payment amount. Required: " + requiredTokenAmount + " Available: " + selectedTokenAmount); return null; } if (closestAmountTuple.second >= (requiredTokenAmount - preselectedTokenAmount)) { // If the next output covers the whole transaction, only use itself and the required outputs... configuration.transactionOutputIdentifiersToSpend.clear(); configuration.transactionOutputIdentifiersToSpend.addAll(requiredTransactionOutputIdentifiersToSpend); configuration.transactionOutputIdentifiersToSpend.add(closestAmountTuple.first); selectedTokenAmount = (preselectedTokenAmount + closestAmountTuple.second); break; } selectedTokenAmount += closestAmountTuple.second; configuration.transactionOutputIdentifiersToSpend.add(closestAmountTuple.first); } } // Direct excess tokens to the changeAddress... final long changeAmount = (selectedTokenAmount - requiredTokenAmount); if (changeAmount > 0L) { final int changeOutputIndex; { Integer index = null; // If the changeAddress is already specified, reuse its output's index... for (int i = 0; i < paymentAmounts.getCount(); ++i) { final PaymentAmount paymentAmount = paymentAmounts.get(i); if (Util.areEqual(changeAddress, paymentAmount.address)) { index = i; break; } } if (index != null) { changeOutputIndex = index; } else { // Add the change address as an output... final Long bchAmount = _calculateDustThreshold(BYTES_PER_TRANSACTION_OUTPUT, changeAddress.isCompressed()); final SlpPaymentAmount changePaymentAmount = new SlpPaymentAmount(changeAddress, bchAmount, changeAmount); configuration.mutablePaymentAmounts.add(changePaymentAmount); changeOutputIndex = (configuration.mutablePaymentAmounts.getCount() - 1); } } configuration.slpSendScript.setAmount((changeOutputIndex + 1), changeAmount); // The index is increased by one to account for the SlpScript TransactionOutput... } return configuration; } protected Transaction _createSignedTransaction(final List<PaymentAmount> paymentAmounts, final List<SpendableTransactionOutput> transactionOutputsToSpend, final LockingScript opReturnScript) { if ( paymentAmounts.isEmpty() && (opReturnScript == null) ) { return null; } if (transactionOutputsToSpend == null) { return null; } final MutableTransaction transaction = new MutableTransaction(); transaction.setVersion(Transaction.VERSION); transaction.setLockTime(LockTime.MIN_TIMESTAMP); for (int i = 0; i < transactionOutputsToSpend.getCount(); ++i) { final SpendableTransactionOutput spendableTransactionOutput = transactionOutputsToSpend.get(i); final TransactionOutputIdentifier transactionOutputIdentifier = spendableTransactionOutput.getIdentifier(); final Transaction transactionBeingSpent = _transactions.get(transactionOutputIdentifier.getTransactionHash()); final Integer transactionOutputBeingSpentIndex = transactionOutputIdentifier.getOutputIndex(); { // Transaction Input... final MutableTransactionInput transactionInput = new MutableTransactionInput(); transactionInput.setSequenceNumber(SequenceNumber.MAX_SEQUENCE_NUMBER); transactionInput.setPreviousOutputTransactionHash(transactionBeingSpent.getHash()); transactionInput.setPreviousOutputIndex(transactionOutputBeingSpentIndex); transactionInput.setUnlockingScript(UnlockingScript.EMPTY_SCRIPT); transaction.addTransactionInput(transactionInput); } } int transactionOutputIndex = 0; if (opReturnScript != null) { { // OpReturn TransactionOutput... final MutableTransactionOutput transactionOutput = new MutableTransactionOutput(); transactionOutput.setIndex(0); transactionOutput.setAmount(0L); transactionOutput.setLockingScript(opReturnScript); transaction.addTransactionOutput(transactionOutput); } transactionOutputIndex += 1; } for (int i = 0; i < paymentAmounts.getCount(); ++i) { final PaymentAmount paymentAmount = paymentAmounts.get(i); { // TransactionOutput... final MutableTransactionOutput transactionOutput = new MutableTransactionOutput(); transactionOutput.setIndex(transactionOutputIndex); transactionOutput.setAmount(paymentAmount.amount); transactionOutput.setLockingScript(ScriptBuilder.payToAddress(paymentAmount.address)); transaction.addTransactionOutput(transactionOutput); } transactionOutputIndex += 1; } final TransactionSigner transactionSigner = new TransactionSigner(); final ScriptPatternMatcher scriptPatternMatcher = new ScriptPatternMatcher(); final Transaction signedTransaction; { Transaction transactionBeingSigned = transaction; final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); for (int i = 0; i < transactionInputs.getCount(); ++i) { final SpendableTransactionOutput spendableTransactionOutput = transactionOutputsToSpend.get(i); final TransactionOutput transactionOutputBeingSpent = spendableTransactionOutput.getTransactionOutput(); final PrivateKey privateKey; final Boolean useCompressedPublicKey; { final LockingScript lockingScript = transactionOutputBeingSpent.getLockingScript(); final ScriptType scriptType = scriptPatternMatcher.getScriptType(lockingScript); final Address addressBeingSpent = scriptPatternMatcher.extractAddress(scriptType, lockingScript); final PublicKey publicKey = _publicKeys.get(addressBeingSpent); privateKey = _privateKeys.get(publicKey); useCompressedPublicKey = publicKey.isCompressed(); } final SignatureContext signatureContext = new SignatureContext(transactionBeingSigned, new HashType(Mode.SIGNATURE_HASH_ALL, true, true)); signatureContext.setInputIndexBeingSigned(i); signatureContext.setShouldSignInputScript(i, true, transactionOutputBeingSpent); transactionBeingSigned = transactionSigner.signTransaction(signatureContext, privateKey, useCompressedPublicKey); } signedTransaction = transactionBeingSigned; } final ScriptRunner scriptRunner = new ScriptRunner(); final List<TransactionInput> signedTransactionInputs = signedTransaction.getTransactionInputs(); for (int i = 0; i < signedTransactionInputs.getCount(); ++i) { final TransactionInput signedTransactionInput = signedTransactionInputs.get(i); final TransactionOutput transactionOutputBeingSpent; { final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(signedTransactionInput.getPreviousOutputTransactionHash(), signedTransactionInput.getPreviousOutputIndex()); final SpendableTransactionOutput spendableTransactionOutput = _transactionOutputs.get(transactionOutputIdentifier); transactionOutputBeingSpent = spendableTransactionOutput.getTransactionOutput(); } final MutableTransactionContext context = MutableTransactionContext.getContextForVerification(signedTransaction, i, transactionOutputBeingSpent, _medianBlockTime); final Boolean outputIsUnlocked = scriptRunner.runScript(transactionOutputBeingSpent.getLockingScript(), signedTransactionInput.getUnlockingScript(), context); if (! outputIsUnlocked) { Logger.warn("Error signing transaction."); return null; } } return signedTransaction; } protected Transaction _createSignedTransaction(final List<PaymentAmount> paymentAmounts, final Address changeAddress, final List<TransactionOutputIdentifier> mandatoryOutputs, final LockingScript opReturnScript) { long totalPaymentAmount = 0L; for (final PaymentAmount paymentAmount : paymentAmounts) { totalPaymentAmount += paymentAmount.amount; } final int newOutputCount = (paymentAmounts.getCount() + (changeAddress != null ? 1 : 0)); final Container<Long> feesContainer = _createNewFeeContainer(newOutputCount, opReturnScript); final List<SpendableTransactionOutput> transactionOutputsToSpend = _getOutputsToSpend(totalPaymentAmount, feesContainer, mandatoryOutputs); if (transactionOutputsToSpend == null) { return null; } long totalAmountSelected = 0L; for (final SpendableTransactionOutput spendableTransactionOutput : transactionOutputsToSpend) { final TransactionOutput transactionOutput = spendableTransactionOutput.getTransactionOutput(); totalAmountSelected += transactionOutput.getAmount(); } final boolean shouldIncludeChangeOutput; final MutableList<PaymentAmount> paymentAmountsWithChange = new MutableList<PaymentAmount>(paymentAmounts.getCount() + 1); { paymentAmountsWithChange.addAll(paymentAmounts); final Long changeAmount = (totalAmountSelected - totalPaymentAmount - feesContainer.value); if (changeAddress != null) { final Long dustThreshold = _calculateDustThreshold(BYTES_PER_TRANSACTION_OUTPUT, changeAddress.isCompressed()); shouldIncludeChangeOutput = (changeAmount >= dustThreshold); } else { shouldIncludeChangeOutput = false; } if (shouldIncludeChangeOutput) { // Check paymentAmountsWithChange for an existing output using the change address... Integer changePaymentAmountIndex = null; for (int i = 0; i < paymentAmountsWithChange.getCount(); ++i) { final PaymentAmount paymentAmount = paymentAmountsWithChange.get(i); if (Util.areEqual(changeAddress, paymentAmount.address)) { changePaymentAmountIndex = i; break; } } if (changePaymentAmountIndex == null) { // The changeAddress was not listed as a PaymentAmount, so create a new one for the change... paymentAmountsWithChange.add(new PaymentAmount(changeAddress, changeAmount)); } else { // The changeAddress already existed as a PaymentAmount; copy it with the additional change, and maintain the SLP Amount if provided... final PaymentAmount paymentAmount = paymentAmountsWithChange.get(changePaymentAmountIndex); final PaymentAmount newPaymentAmount; if (paymentAmount instanceof SlpPaymentAmount) { newPaymentAmount = new SlpPaymentAmount(paymentAmount.address, (paymentAmount.amount + changeAmount), ((SlpPaymentAmount) paymentAmount).tokenAmount); } else { newPaymentAmount = new PaymentAmount(paymentAmount.address, (paymentAmount.amount + changeAmount)); } paymentAmountsWithChange.set(changePaymentAmountIndex, newPaymentAmount); } } } Logger.info("Creating Transaction. Spending " + transactionOutputsToSpend.getCount() + " UTXOs. Creating " + paymentAmountsWithChange.getCount() + " UTXOs. Sending " + totalPaymentAmount + ". Spending " + feesContainer.value + " in fees. " + (shouldIncludeChangeOutput ? ((totalAmountSelected - totalPaymentAmount - feesContainer.value) + " in change.") : "")); final Transaction signedTransaction = _createSignedTransaction(paymentAmountsWithChange, transactionOutputsToSpend, opReturnScript); if (signedTransaction == null) { return null; } final TransactionDeflater transactionDeflater = new TransactionDeflater(); Logger.debug(signedTransaction.getHash()); Logger.debug(transactionDeflater.toBytes(signedTransaction)); final Integer transactionByteCount = signedTransaction.getByteCount(); if (feesContainer.value < (transactionByteCount * _satoshisPerByteFee)) { Logger.info("Failed to create a transaction with sufficient fee..."); return null; } Logger.debug("Transaction Bytes Count: " + transactionByteCount + " (" + (feesContainer.value / transactionByteCount.floatValue()) + " sats/byte)"); return signedTransaction; } protected Transaction _createSlpTokenTransaction(final SlpTokenId slpTokenId, final List<SlpPaymentAmount> paymentAmounts, final Address changeAddress, final List<TransactionOutputIdentifier> requiredTransactionOutputIdentifiersToSpend, final Boolean shouldIncludeNotYetValidatedTransactions) { final SlpTokenTransactionConfiguration slpTokenTransactionConfiguration = _createSlpTokenTransactionConfiguration(slpTokenId, paymentAmounts, changeAddress, requiredTransactionOutputIdentifiersToSpend, shouldIncludeNotYetValidatedTransactions); if (slpTokenTransactionConfiguration == null) { return null; } final SlpScriptBuilder slpScriptBuilder = new SlpScriptBuilder(); final LockingScript slpTokenScript = slpScriptBuilder.createSendScript(slpTokenTransactionConfiguration.slpSendScript); return _createSignedTransaction(slpTokenTransactionConfiguration.mutablePaymentAmounts, changeAddress, slpTokenTransactionConfiguration.transactionOutputIdentifiersToSpend, slpTokenScript); } protected MutableBloomFilter _generateBloomFilter() { final AddressInflater addressInflater = new AddressInflater(); final Collection<PrivateKey> privateKeys = _privateKeys.values(); final long itemCount; { final int privateKeyCount = privateKeys.size(); final int estimatedItemCount = (privateKeyCount * 4); itemCount = (int) (Math.pow(2, (BitcoinUtil.log2(estimatedItemCount) + 1))); } final MutableBloomFilter bloomFilter = MutableBloomFilter.newInstance(Math.max(itemCount, 1024), 0.0001D); for (final PrivateKey privateKey : privateKeys) { final PublicKey publicKey = privateKey.getPublicKey(); // Add sending matchers... bloomFilter.addItem(publicKey.decompress()); bloomFilter.addItem(publicKey.compress()); // Add receiving matchers... bloomFilter.addItem(addressInflater.fromPrivateKey(privateKey, false)); bloomFilter.addItem(addressInflater.fromPrivateKey(privateKey, true)); } return bloomFilter; } public Wallet() { _medianBlockTime = null; // Only necessary for instances near impending hard forks... } public Wallet(final MedianBlockTime medianBlockTime) { _medianBlockTime = medianBlockTime; } public void setSatoshisPerByteFee(final Double satoshisPerByte) { _satoshisPerByteFee = satoshisPerByte; } public Long getDustThreshold(final Boolean addressIsCompressed) { return _calculateDustThreshold(BYTES_PER_TRANSACTION_OUTPUT, addressIsCompressed); } public synchronized void addPrivateKey(final PrivateKey privateKey) { _addPrivateKey(privateKey); _cachedBloomFilter = null; // Invalidate the cached BloomFilter... _reloadTransactions(); } public synchronized void addPrivateKeys(final List<PrivateKey> privateKeys) { for (final PrivateKey privateKey : privateKeys) { _addPrivateKey(privateKey); } _cachedBloomFilter = null; // Invalidate the cached BloomFilter... _reloadTransactions(); } public synchronized void addTransaction(final Transaction transaction) { _addTransaction(transaction, true); } public synchronized void addTransaction(final Transaction transaction, final List<Integer> validOutputIndexes) { _addTransaction(transaction, true); _markTransactionOutputsAsSpent(transaction, validOutputIndexes); } public synchronized void addUnconfirmedTransaction(final Transaction transaction) { _addTransaction(transaction, false); } public synchronized void addUnconfirmedTransaction(final Transaction transaction, final List<Integer> validOutputIndexes) { _addTransaction(transaction, false); _markTransactionOutputsAsSpent(transaction, validOutputIndexes); } public synchronized void markTransactionOutputAsSpent(final Sha256Hash transactionHash, final Integer transactionOutputIndex) { final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, transactionOutputIndex); _markTransactionOutputAsSpent(transactionOutputIdentifier); } protected void _markTransactionOutputsAsSpent(final Transaction transaction, final List<Integer> validOutputIndexes) { for (final TransactionOutput transactionOutput : transaction.getTransactionOutputs()) { if (! validOutputIndexes.contains(transactionOutput.getIndex())) { final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transaction.getHash(), transactionOutput.getIndex()); _markTransactionOutputAsSpent(transactionOutputIdentifier); } } } protected void _markTransactionOutputAsSpent(final TransactionOutputIdentifier transactionOutputIdentifier) { final MutableSpendableTransactionOutput transactionOutput = _transactionOutputs.get(transactionOutputIdentifier); if (transactionOutput != null) { transactionOutput.setIsSpent(true); } final Sha256Hash sentinelHash = Sha256Hash.EMPTY_HASH; _spentTransactionOutputs.put(transactionOutputIdentifier, sentinelHash); _externallySpentTransactionOutputs.put(transactionOutputIdentifier, sentinelHash); } public synchronized List<TransactionOutputIdentifier> getOutputsToSpend(final Integer newTransactionOutputCount, final Long desiredSpendAmount) { final List<TransactionOutputIdentifier> requiredTransactionOutputsToSpend = new MutableList<TransactionOutputIdentifier>(0); return _getOutputsToSpend(newTransactionOutputCount, desiredSpendAmount, null, requiredTransactionOutputsToSpend); } public synchronized List<TransactionOutputIdentifier> getOutputsToSpend(final Integer newTransactionOutputCount, final Long desiredSpendAmount, final List<TransactionOutputIdentifier> requiredTransactionOutputsToSpend) { return _getOutputsToSpend(newTransactionOutputCount, desiredSpendAmount, null, requiredTransactionOutputsToSpend); } public synchronized List<TransactionOutputIdentifier> getOutputsToSpend(final Integer newTransactionOutputCount, final Long desiredSpendAmount, final LockingScript opReturnScript) { final List<TransactionOutputIdentifier> requiredTransactionOutputsToSpend = new MutableList<TransactionOutputIdentifier>(0); return _getOutputsToSpend(newTransactionOutputCount, desiredSpendAmount, opReturnScript, requiredTransactionOutputsToSpend); } public synchronized List<TransactionOutputIdentifier> getOutputsToSpend(final Integer newTransactionOutputCount, final Long desiredSpendAmount, final SlpTokenId slpTokenId, final Long desiredSlpSpendAmount) { final List<TransactionOutputIdentifier> requiredTransactionOutputsToSpend = new MutableList<TransactionOutputIdentifier>(0); return _getOutputsToSpend(newTransactionOutputCount, desiredSpendAmount, slpTokenId, desiredSlpSpendAmount, requiredTransactionOutputsToSpend, true); } public synchronized List<TransactionOutputIdentifier> getOutputsToSpend(final Integer newTransactionOutputCount, final Long desiredSpendAmount, final SlpTokenId slpTokenId, final Long desiredSlpSpendAmount, final Boolean shouldIncludeNotYetValidatedTransactions) { final List<TransactionOutputIdentifier> requiredTransactionOutputsToSpend = new MutableList<TransactionOutputIdentifier>(0); return _getOutputsToSpend(newTransactionOutputCount, desiredSpendAmount, slpTokenId, desiredSlpSpendAmount, requiredTransactionOutputsToSpend, shouldIncludeNotYetValidatedTransactions); } public synchronized List<TransactionOutputIdentifier> getOutputsToSpend(final Integer newTransactionOutputCount, final Long desiredSpendAmount, final SlpTokenId slpTokenId, final Long desiredSlpSpendAmount, final List<TransactionOutputIdentifier> requiredTransactionOutputsToSpend) { return _getOutputsToSpend(newTransactionOutputCount, desiredSpendAmount, slpTokenId, desiredSlpSpendAmount, requiredTransactionOutputsToSpend, true); } public synchronized List<TransactionOutputIdentifier> getOutputsToSpend(final Integer newTransactionOutputCount, final Long desiredSpendAmount, final SlpTokenId slpTokenId, final Long desiredSlpSpendAmount, final List<TransactionOutputIdentifier> requiredTransactionOutputsToSpend, final Boolean shouldIncludeNotYetValidatedTransactions) { return _getOutputsToSpend(newTransactionOutputCount, desiredSpendAmount, slpTokenId, desiredSlpSpendAmount, requiredTransactionOutputsToSpend, shouldIncludeNotYetValidatedTransactions); } public Long calculateFees(final Integer newOutputCount, final Integer outputsBeingSpentCount) { final Container<Long> feeContainer = _createNewFeeContainer(newOutputCount, null); feeContainer.value += (long) ((BYTES_PER_TRANSACTION_INPUT * _satoshisPerByteFee) * outputsBeingSpentCount); return feeContainer.value; } public Long calculateFees(final Integer newOutputCount, final Integer outputsBeingSpentCount, final LockingScript opReturnScript) { final Container<Long> feeContainer = _createNewFeeContainer(newOutputCount, opReturnScript); feeContainer.value += (long) ((BYTES_PER_TRANSACTION_INPUT * _satoshisPerByteFee) * outputsBeingSpentCount); return feeContainer.value; } public synchronized Transaction createTransaction(final List<PaymentAmount> paymentAmounts, final Address changeAddress) { final List<TransactionOutputIdentifier> mandatoryTransactionOutputsToSpend = new MutableList<TransactionOutputIdentifier>(0); return _createSignedTransaction(paymentAmounts, changeAddress, mandatoryTransactionOutputsToSpend, null); } public synchronized Transaction createTransaction(final List<PaymentAmount> paymentAmounts, final Address changeAddress, final LockingScript opReturnScript) { final List<TransactionOutputIdentifier> mandatoryTransactionOutputsToSpend = new MutableList<TransactionOutputIdentifier>(0); return _createSignedTransaction(paymentAmounts, changeAddress, mandatoryTransactionOutputsToSpend, opReturnScript); } public synchronized Transaction createTransaction(final List<PaymentAmount> paymentAmounts, final Address changeAddress, final List<TransactionOutputIdentifier> transactionOutputIdentifiersToSpend) { return _createSignedTransaction(paymentAmounts, changeAddress, transactionOutputIdentifiersToSpend, null); } public synchronized Transaction createTransaction(final List<PaymentAmount> paymentAmounts, final Address changeAddress, final List<TransactionOutputIdentifier> transactionOutputIdentifiersToSpend, final LockingScript opReturnScript) { return _createSignedTransaction(paymentAmounts, changeAddress, transactionOutputIdentifiersToSpend, opReturnScript); } public synchronized Transaction createSlpTokenTransaction(final SlpTokenId slpTokenId, final List<SlpPaymentAmount> paymentAmounts, final Address changeAddress) { return _createSlpTokenTransaction(slpTokenId, paymentAmounts, changeAddress, new MutableList<TransactionOutputIdentifier>(0), true); } public synchronized Transaction createSlpTokenTransaction(final SlpTokenId slpTokenId, final List<SlpPaymentAmount> paymentAmounts, final Address changeAddress, final List<TransactionOutputIdentifier> requiredTransactionOutputIdentifiersToSpend) { return _createSlpTokenTransaction(slpTokenId, paymentAmounts, changeAddress, requiredTransactionOutputIdentifiersToSpend, true); } public synchronized Transaction createSlpTokenTransaction(final SlpTokenId slpTokenId, final List<SlpPaymentAmount> paymentAmounts, final Address changeAddress, final List<TransactionOutputIdentifier> requiredTransactionOutputIdentifiersToSpend, final Boolean shouldIncludeNotYetValidatedTransactions) { return _createSlpTokenTransaction(slpTokenId, paymentAmounts, changeAddress, requiredTransactionOutputIdentifiersToSpend, shouldIncludeNotYetValidatedTransactions); } public synchronized MutableBloomFilter generateBloomFilter() { return _generateBloomFilter(); } public synchronized BloomFilter getBloomFilter() { if (_cachedBloomFilter == null) { _cachedBloomFilter = _generateBloomFilter(); } return _cachedBloomFilter; } public synchronized Boolean hasTransaction(final Sha256Hash transactionHash) { return _transactions.containsKey(transactionHash); } /** * <p>Get a list of the transactions contained within this wallet object.</p> * * @return A new list populated with the transactions contained within the wallet. */ public List<Transaction> getTransactions() { return new MutableList<>(_transactions.values()); } public synchronized Transaction getTransaction(final Sha256Hash transactionHash) { final Transaction transaction = _transactions.get(transactionHash); return transaction; } public synchronized SpendableTransactionOutput getTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { return _transactionOutputs.get(transactionOutputIdentifier); } public synchronized List<SpendableTransactionOutput> getTransactionOutputs() { final Collection<? extends SpendableTransactionOutput> spendableTransactionOutputs = _transactionOutputs.values(); final ImmutableListBuilder<SpendableTransactionOutput> transactionOutputs = new ImmutableListBuilder<SpendableTransactionOutput>(spendableTransactionOutputs.size()); for (final SpendableTransactionOutput spendableTransactionOutput : spendableTransactionOutputs) { transactionOutputs.add(spendableTransactionOutput); } return transactionOutputs.build(); } public synchronized List<SpendableTransactionOutput> getNonSlpTokenTransactionOutputs() { final Collection<? extends SpendableTransactionOutput> spendableTransactionOutputs = _transactionOutputs.values(); final ImmutableListBuilder<SpendableTransactionOutput> transactionOutputs = new ImmutableListBuilder<SpendableTransactionOutput>(spendableTransactionOutputs.size()); for (final SpendableTransactionOutput spendableTransactionOutput : spendableTransactionOutputs) { final TransactionOutputIdentifier transactionOutputIdentifier = spendableTransactionOutput.getIdentifier(); if (! _isSlpTokenOutput(transactionOutputIdentifier)) { transactionOutputs.add(spendableTransactionOutput); } } return transactionOutputs.build(); } public synchronized List<SpendableTransactionOutput> getTransactionOutputsAndSpendableTokens(final SlpTokenId tokenId, final Boolean shouldIncludeNotYetValidatedTransactions) { final Collection<? extends SpendableTransactionOutput> spendableTransactionOutputs = _transactionOutputs.values(); final ImmutableListBuilder<SpendableTransactionOutput> transactionOutputs = new ImmutableListBuilder<SpendableTransactionOutput>(spendableTransactionOutputs.size()); for (final SpendableTransactionOutput spendableTransactionOutput : spendableTransactionOutputs) { final TransactionOutputIdentifier transactionOutputIdentifier = spendableTransactionOutput.getIdentifier(); final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); if ( (! _isSlpTokenOutput(transactionOutputIdentifier)) || (! _isSlpTransactionAndIsValid(transactionHash, shouldIncludeNotYetValidatedTransactions)) ) { transactionOutputs.add(spendableTransactionOutput); } else if (_outputContainsSpendableSlpTokens(transactionOutputIdentifier)) { if (Util.areEqual(tokenId, _getSlpTokenId(transactionOutputIdentifier))) { transactionOutputs.add(spendableTransactionOutput); } } } return transactionOutputs.build(); } public synchronized List<SlpToken> getSlpTokens() { return _getSlpTokens(null, true); } public synchronized List<SlpToken> getSlpTokens(final Boolean shouldIncludeNotYetValidatedTransactions) { return _getSlpTokens(null, shouldIncludeNotYetValidatedTransactions); } public synchronized List<SlpToken> getSlpTokens(final SlpTokenId slpTokenId) { return _getSlpTokens(slpTokenId, true); } public synchronized List<SlpToken> getSlpTokens(final SlpTokenId slpTokenId, final Boolean shouldIncludeNotYetValidatedTransactions) { return _getSlpTokens(slpTokenId, shouldIncludeNotYetValidatedTransactions); } public synchronized Long getBalance() { long amount = 0L; for (final SpendableTransactionOutput spendableTransactionOutput : _transactionOutputs.values()) { if (! spendableTransactionOutput.isSpent()) { final TransactionOutput transactionOutput = spendableTransactionOutput.getTransactionOutput(); amount += transactionOutput.getAmount(); } } return amount; } public synchronized Long getBalance(final PublicKey publicKey) { final ScriptPatternMatcher scriptPatternMatcher = new ScriptPatternMatcher(); final AddressInflater addressInflater = new AddressInflater(); final Address address = addressInflater.fromPublicKey(publicKey, false); final Address compressedAddress = addressInflater.fromPublicKey(publicKey, true); long amount = 0L; for (final SpendableTransactionOutput spendableTransactionOutput : _transactionOutputs.values()) { if (! spendableTransactionOutput.isSpent()) { final TransactionOutput transactionOutput = spendableTransactionOutput.getTransactionOutput(); final LockingScript lockingScript = transactionOutput.getLockingScript(); final ScriptType scriptType = scriptPatternMatcher.getScriptType(lockingScript); final Address outputAddress = scriptPatternMatcher.extractAddress(scriptType, lockingScript); if ( Util.areEqual(address, outputAddress) || Util.areEqual(compressedAddress, outputAddress) ) { amount += transactionOutput.getAmount(); } } } return amount; } public synchronized Long getBalance(final PublicKey publicKey, final SlpTokenId slpTokenId) { return _getBalance(publicKey, slpTokenId, true); } public synchronized Long getBalance(final PublicKey publicKey, final SlpTokenId slpTokenId, final Boolean shouldIncludeNotYetValidatedTransactions) { return _getBalance(publicKey, slpTokenId, shouldIncludeNotYetValidatedTransactions); } public synchronized Long getSlpTokenBalance(final SlpTokenId tokenId) { return _getSlpTokenBalance(tokenId, true); } public synchronized Long getSlpTokenBalance(final SlpTokenId tokenId, final Boolean shouldIncludeNotYetValidatedTransactions) { return _getSlpTokenBalance(tokenId, shouldIncludeNotYetValidatedTransactions); } public synchronized Long getInvalidSlpTokenBalance(final SlpTokenId tokenId) { long amount = 0L; for (final SpendableTransactionOutput spendableTransactionOutput : _transactionOutputs.values()) { if (! spendableTransactionOutput.isSpent()) { final TransactionOutputIdentifier transactionOutputIdentifier = spendableTransactionOutput.getIdentifier(); final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); final Integer transactionOutputIndex = transactionOutputIdentifier.getOutputIndex(); // only include invalid transactions if (_invalidSlpTransactions.contains(transactionHash)) { final Transaction transaction = _transactions.get(transactionHash); if (transaction == null) { return null; } final boolean outputContainsTokens = SlpUtil.isSlpTokenOutput(transaction, transactionOutputIndex); if (! outputContainsTokens) { continue; } final SlpTokenId transactionTokenId = SlpUtil.getTokenId(transaction); if (! Util.areEqual(tokenId, transactionTokenId)) { continue; } amount += SlpUtil.getOutputTokenAmount(transaction, transactionOutputIndex); } } } return amount; } public synchronized void markSlpTransactionAsValid(final Sha256Hash transactionHash) { if (_transactions.containsKey(transactionHash)) { _notYetValidatedSlpTransactions.remove(transactionHash); _validSlpTransactions.remove(transactionHash); } else { _validSlpTransactions.add(transactionHash); } // cannot be invalid now _invalidSlpTransactions.remove(transactionHash); Logger.debug(SlpValidity.VALID + " SLP transaction: " + transactionHash); } public synchronized void markSlpTransactionAsInvalid(final Sha256Hash transactionHash) { _notYetValidatedSlpTransactions.remove(transactionHash); _invalidSlpTransactions.add(transactionHash); // cannot be valid now _validSlpTransactions.remove(transactionHash); Logger.debug(SlpValidity.INVALID + " SLP transaction: " + transactionHash); } public synchronized void clearSlpValidity() { // mark explicitly tracked validity as unknown _notYetValidatedSlpTransactions.addAll(_validSlpTransactions); _notYetValidatedSlpTransactions.addAll(_invalidSlpTransactions); _validSlpTransactions.clear(); _invalidSlpTransactions.clear(); // mark implicitly tracked validity as unknown for (final Sha256Hash transactionHash : _transactions.keySet()) { final Transaction transaction = _transactions.get(transactionHash); if (Transaction.isSlpTransaction(transaction)) { _notYetValidatedSlpTransactions.add(transactionHash); } } } public synchronized Long getSlpTokenAmount(final SlpTokenId slpTokenId, final TransactionOutputIdentifier transactionOutputIdentifier) { final SlpTokenId outputSlpTokenId = _getSlpTokenId(transactionOutputIdentifier); if (! Util.areEqual(slpTokenId, outputSlpTokenId)) { return 0L; } return _getSlpTokenAmount(transactionOutputIdentifier); } public synchronized List<SlpTokenId> getSlpTokenIds() { final HashSet<SlpTokenId> tokenIdsSet = new HashSet<SlpTokenId>(); for (final SpendableTransactionOutput spendableTransactionOutput : _transactionOutputs.values()) { if (! spendableTransactionOutput.isSpent()) { final TransactionOutputIdentifier transactionOutputIdentifier = spendableTransactionOutput.getIdentifier(); final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); final Integer transactionOutputIndex = transactionOutputIdentifier.getOutputIndex(); final Transaction transaction = _transactions.get(transactionHash); if (transaction == null) { return null; } final boolean outputContainsTokens = SlpUtil.isSlpTokenOutput(transaction, transactionOutputIndex); if (! outputContainsTokens) { continue; } final SlpTokenId tokenId = SlpUtil.getTokenId(transaction); if (tokenId == null) { continue; } tokenIdsSet.add(tokenId); } } final MutableList<SlpTokenId> tokenIds = new MutableList<SlpTokenId>(); tokenIds.addAll(tokenIdsSet); tokenIds.sort(SlpTokenId.COMPARATOR); return tokenIds; } public synchronized Boolean hasPrivateKeys() { return (! _privateKeys.isEmpty()); } public synchronized Address getReceivingAddress() { final AddressInflater addressInflater = new AddressInflater(); for (final PublicKey publicKey : _privateKeys.keySet()) { return addressInflater.fromPublicKey(publicKey, true); } return null; } public synchronized List<PublicKey> getPublicKeys() { return new ImmutableList<PublicKey>(_privateKeys.keySet()); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/database/transaction/fullnode/utxo/UnspentTransactionOutputDatabaseManagerTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.row.Row; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.List; public class UnspentTransactionOutputDatabaseManagerTests extends IntegrationTest { @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } protected static final Long MAX_UTXO_COUNT = 32L; protected Long _getUtxoCountInMemory() throws DatabaseException { return (long) UnspentTransactionOutputJvmManager.UTXO_SET.size(); } protected Long _getUtxoCountOnDisk(final DatabaseConnection databaseConnection) throws DatabaseException { final List<Row> rows = databaseConnection.query(new Query("SELECT COUNT(*) AS count FROM committed_unspent_transaction_outputs")); final Row row = rows.get(0); return row.getLong("count"); } @Test public void should_purge_utxo_set_by_half_once_full() throws Exception { // Setup final FullNodeDatabaseManager fullNodeDatabaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager(); final float purgePercent = 0.50F; final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = new UnspentTransactionOutputJvmManager(MAX_UTXO_COUNT, purgePercent, fullNodeDatabaseManager, _blockStore, _masterInflater); long blockHeight = 1L; for (int i = 0; i < MAX_UTXO_COUNT; ) { final int utxoCountPerBlock = ((i * 2) + 1); final MutableList<TransactionOutputIdentifier> transactionOutputIdentifiers = new MutableList<TransactionOutputIdentifier>(utxoCountPerBlock); for (int j = 0; j < utxoCountPerBlock; ++j) { if (i >= MAX_UTXO_COUNT) { break; } final Sha256Hash transactionHash = Sha256Hash.wrap(HashUtil.sha256(ByteUtil.integerToBytes(i))); final Integer outputIndex = (j % 4); transactionOutputIdentifiers.add(new TransactionOutputIdentifier(transactionHash, outputIndex)); i += 1; } unspentTransactionOutputDatabaseManager.insertUnspentTransactionOutputs(transactionOutputIdentifiers, blockHeight); unspentTransactionOutputDatabaseManager.setUncommittedUnspentTransactionOutputBlockHeight(blockHeight); blockHeight += 1L; } { // Sanity-check the UTXO count... final Long utxoCount = _getUtxoCountInMemory(); Assert.assertEquals(MAX_UTXO_COUNT, utxoCount); } // Action unspentTransactionOutputDatabaseManager.commitUnspentTransactionOutputs(_fullNodeDatabaseManagerFactory, true); // Assert final long utxoCountInMemory = _getUtxoCountInMemory(); Assert.assertEquals((long) (MAX_UTXO_COUNT * (1.0F - purgePercent)), utxoCountInMemory); try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { Assert.assertEquals(MAX_UTXO_COUNT, _getUtxoCountOnDisk(databaseConnection)); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/MutableTransaction.java<|end_filename|> package com.softwareverde.bitcoin.transaction; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.transaction.coinbase.MutableCoinbaseTransaction; import com.softwareverde.bitcoin.transaction.input.MutableTransactionInput; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.locktime.ImmutableLockTime; import com.softwareverde.bitcoin.transaction.locktime.LockTime; import com.softwareverde.bitcoin.transaction.output.MutableTransactionOutput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bloomfilter.BloomFilter; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.constable.util.ConstUtil; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.json.Json; import com.softwareverde.util.Util; public class MutableTransaction implements Transaction { /** * NOTE: Math with Satoshis * The maximum number of satoshis is 210,000,000,000,000, which is less than the value a Java Long can hold. * Therefore, using BigInteger is not be necessary any non-multiplicative transaction calculation. */ protected static final TransactionHasher DEFAULT_TRANSACTION_HASHER = new TransactionHasher(); protected static final TransactionDeflater DEFAULT_TRANSACTION_DEFLATER = new TransactionDeflater(); protected static final AddressInflater DEFAULT_ADDRESS_INFLATER = new AddressInflater(); protected final TransactionHasher _transactionHasher; protected final TransactionDeflater _transactionDeflater; protected final AddressInflater _addressInflater; protected Long _version = Transaction.VERSION; protected final MutableList<TransactionInput> _transactionInputs = new MutableList<TransactionInput>(); protected final MutableList<TransactionOutput> _transactionOutputs = new MutableList<TransactionOutput>(); protected LockTime _lockTime = new ImmutableLockTime(); protected Integer _cachedByteCount = null; protected Sha256Hash _cachedHash = null; protected Integer _cachedHashCode = null; protected void _invalidateCachedProperties() { _cachedByteCount = null; _cachedHash = null; _cachedHashCode = null; } protected Integer _calculateByteCount() { return _transactionDeflater.getByteCount(this); } protected void cacheByteCount(final Integer byteCount) { _cachedByteCount = byteCount; } protected MutableTransaction(final TransactionHasher transactionHasher, final TransactionDeflater transactionDeflater, final AddressInflater addressInflater) { _transactionHasher = transactionHasher; _transactionDeflater = transactionDeflater; _addressInflater = addressInflater; } public MutableTransaction() { _transactionHasher = DEFAULT_TRANSACTION_HASHER; _transactionDeflater = DEFAULT_TRANSACTION_DEFLATER; _addressInflater = DEFAULT_ADDRESS_INFLATER; } public MutableTransaction(final Transaction transaction) { _transactionHasher = DEFAULT_TRANSACTION_HASHER; _transactionDeflater = DEFAULT_TRANSACTION_DEFLATER; _addressInflater = DEFAULT_ADDRESS_INFLATER; _version = transaction.getVersion(); for (final TransactionInput transactionInput : transaction.getTransactionInputs()) { _transactionInputs.add(new MutableTransactionInput(transactionInput)); } for (final TransactionOutput transactionOutput : transaction.getTransactionOutputs()) { _transactionOutputs.add(new MutableTransactionOutput(transactionOutput)); } _lockTime = transaction.getLockTime().asConst(); } @Override public Sha256Hash getHash() { final Sha256Hash cachedHash = _cachedHash; if (cachedHash != null) { return cachedHash; } final Sha256Hash hash = _transactionHasher.hashTransaction(this); _cachedHash = hash; return hash; } @Override public Long getVersion() { return _version; } public void setVersion(final Long version) { _version = version; _invalidateCachedProperties(); } @Override public final List<TransactionInput> getTransactionInputs() { return ConstUtil.downcastList(_transactionInputs); } public void addTransactionInput(final TransactionInput transactionInput) { _transactionInputs.add(transactionInput.asConst()); _invalidateCachedProperties(); } public void clearTransactionInputs() { _transactionInputs.clear(); _invalidateCachedProperties(); } public void setTransactionInput(final Integer index, final TransactionInput transactionInput) { _transactionInputs.set(index, transactionInput.asConst()); _invalidateCachedProperties(); } @Override public final List<TransactionOutput> getTransactionOutputs() { return _transactionOutputs; } public void addTransactionOutput(final TransactionOutput transactionOutput) { _transactionOutputs.add(transactionOutput.asConst()); _invalidateCachedProperties(); } public void clearTransactionOutputs() { _transactionOutputs.clear(); _invalidateCachedProperties(); } public void setTransactionOutput(final Integer index, final TransactionOutput transactionOutput) { _transactionOutputs.set(index, transactionOutput.asConst()); _invalidateCachedProperties(); } @Override public LockTime getLockTime() { return _lockTime; } public void setLockTime(final LockTime lockTime) { _lockTime = lockTime; _invalidateCachedProperties(); } @Override public Long getTotalOutputValue() { long totalValue = 0L; for (final TransactionOutput transactionOutput : _transactionOutputs) { totalValue += transactionOutput.getAmount(); } return totalValue; } @Override public Boolean matches(final BloomFilter bloomFilter) { final TransactionBloomFilterMatcher transactionBloomFilterMatcher = new TransactionBloomFilterMatcher(bloomFilter, _addressInflater); return transactionBloomFilterMatcher.shouldInclude(this); } @Override public MutableCoinbaseTransaction asCoinbase() { if (! Transaction.isCoinbaseTransaction(this)) { return null; } return new MutableCoinbaseTransaction(this); } @Override public Integer getByteCount() { final Integer cachedByteCount = _cachedByteCount; if (cachedByteCount != null) { return cachedByteCount; } final Integer byteCount = _calculateByteCount(); _cachedByteCount = byteCount; return byteCount; } @Override public ImmutableTransaction asConst() { return new ImmutableTransaction(this); } @Override public Json toJson() { return _transactionDeflater.toJson(this); } @Override public int hashCode() { final Integer cachedHashCode = _cachedHashCode; if (cachedHashCode != null) { return cachedHashCode; } final int hashCode = _transactionHasher.hashTransaction(this).hashCode(); _cachedHashCode = hashCode; return hashCode; } @Override public boolean equals(final Object object) { if (! (object instanceof Transaction)) { return false; } return Util.areEqual(this.getHash(), ((Transaction) object).getHash()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/SignatureModule.java<|end_filename|> package com.softwareverde.bitcoin.server.module; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.secp256k1.signature.BitcoinMessageSignature; import com.softwareverde.bitcoin.util.BitcoinUtil; import com.softwareverde.bitcoin.wallet.SeedPhraseGenerator; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.logging.Logger; import com.softwareverde.util.IoUtil; import com.softwareverde.util.StringUtil; public class SignatureModule { protected static SeedPhraseGenerator getSeedPhraseGenerator() { final String seedWords = IoUtil.getResource("/seed_words/seed_words_english.txt"); final ImmutableListBuilder<String> seedWordsBuilder = new ImmutableListBuilder<String>(2048); for (final String seedWord : seedWords.split("\n")) { seedWordsBuilder.add(seedWord.trim()); } if (seedWordsBuilder.getCount() != 2048) { Logger.error("Unable to load seed phrase word list."); return null; } return new SeedPhraseGenerator(seedWordsBuilder.build()); } protected static PrivateKey parsePrivateKeyFromFileContents(final String keyFileContents) { final PrivateKey privateKeyViaHexString = PrivateKey.fromHexString(keyFileContents); if (privateKeyViaHexString != null) { return privateKeyViaHexString; } final SeedPhraseGenerator seedPhraseGenerator = SignatureModule.getSeedPhraseGenerator(); if (seedPhraseGenerator == null) { return null; } final Boolean isSeedPhrase = seedPhraseGenerator.isSeedPhraseValid(keyFileContents); if (! isSeedPhrase) { return null; } final ByteArray privateKeyBytes = seedPhraseGenerator.fromSeedPhrase(keyFileContents); return PrivateKey.fromBytes(privateKeyBytes); } public static void executeSign(final String keyFileName, final String message, final Boolean useCompressedAddress) { final String keyFileContents; { final byte[] bytes = IoUtil.getFileContents(keyFileName); if (bytes == null) { Logger.error("Unable to read key file '" + keyFileName + "'."); return; } keyFileContents = StringUtil.bytesToString(bytes).trim(); if (keyFileContents.isEmpty()) { Logger.error("Empty key file."); return; } } final PrivateKey privateKey = SignatureModule.parsePrivateKeyFromFileContents(keyFileContents); if (privateKey == null) { Logger.error("Unrecognized key format."); return; } final BitcoinMessageSignature signature = BitcoinUtil.signBitcoinMessage(privateKey, message, useCompressedAddress); if (signature == null) { Logger.error("Unable to sign message."); return; } final AddressInflater addressInflater = new AddressInflater(); System.out.println("Address: " + addressInflater.fromPrivateKey(privateKey, useCompressedAddress)); System.out.println("Signature: " + signature.toBase64()); System.out.println("Message: " + message); } public static void executeVerify(final String addressStringBase58Check, final String signatureStringBase64, final String message) { final AddressInflater addressInflater = new AddressInflater(); final BitcoinMessageSignature signature = BitcoinMessageSignature.fromBase64(signatureStringBase64); if (signature == null) { Logger.error("Invalid signature."); return; } final Address address = addressInflater.fromBase58Check(addressStringBase58Check); if (address == null) { Logger.error("Invalid address."); return; } final Boolean signatureIsValid = BitcoinUtil.verifyBitcoinMessage(message, address, signature); System.out.println("Address: " + address.toBase58CheckEncoded()); System.out.println("Signature: " + signature.toBase64()); System.out.println("Message: " + message); System.out.println("------------"); System.out.println("Is Valid: " + (signatureIsValid ? "1" : "0")); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/header/difficulty/work/Work.java<|end_filename|> package com.softwareverde.bitcoin.block.header.difficulty.work; import com.softwareverde.constable.bytearray.ByteArray; public interface Work extends ByteArray { } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/ScriptTypeId.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script; import com.softwareverde.util.type.identifier.Identifier; public class ScriptTypeId extends Identifier { public static ScriptTypeId wrap(final Long value) { if (value == null) { return null; } return new ScriptTypeId(value); } protected ScriptTypeId(final Long value) { super(value); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/thin/block/ExtraThinBlockMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.thin.block; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.inflater.BlockHeaderInflaters; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.util.bytearray.Endian; public class ExtraThinBlockMessageInflater extends BitcoinProtocolMessageInflater { protected final BlockHeaderInflaters _blockHeaderInflaters; protected final TransactionInflaters _transactionInflaters; public ExtraThinBlockMessageInflater(final BlockHeaderInflaters blockHeaderInflaters, final TransactionInflaters transactionInflaters) { _blockHeaderInflaters = blockHeaderInflaters; _transactionInflaters = transactionInflaters; } @Override public ExtraThinBlockMessage fromBytes(final byte[] bytes) { final ExtraThinBlockMessage extraThinBlockMessage = new ExtraThinBlockMessage(_blockHeaderInflaters, _transactionInflaters); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.EXTRA_THIN_BLOCK); if (protocolMessageHeader == null) { return null; } final BlockHeaderInflater blockHeaderInflater = _blockHeaderInflaters.getBlockHeaderInflater(); final BlockHeader blockHeader = blockHeaderInflater.fromBytes(byteArrayReader); extraThinBlockMessage.setBlockHeader(blockHeader); final int transactionCount = byteArrayReader.readVariableSizedInteger().intValue(); if (transactionCount > BlockInflater.MAX_TRANSACTION_COUNT) { return null; } final ImmutableListBuilder<ByteArray> transactionShortHashesListBuilder = new ImmutableListBuilder<ByteArray>(transactionCount); for (int i = 0; i < transactionCount; ++i) { final ByteArray transactionShortHash = MutableByteArray.wrap(byteArrayReader.readBytes(4, Endian.LITTLE)); transactionShortHashesListBuilder.add(transactionShortHash); } extraThinBlockMessage.setTransactionHashes(transactionShortHashesListBuilder.build()); final int missingTransactionCount = byteArrayReader.readVariableSizedInteger().intValue(); if (missingTransactionCount > transactionCount) { return null; } final TransactionInflater transactionInflater = _transactionInflaters.getTransactionInflater(); final ImmutableListBuilder<Transaction> missingTransactionsListBuilder = new ImmutableListBuilder<Transaction>(missingTransactionCount); for (int i = 0; i < missingTransactionCount; ++i) { final Transaction transaction = transactionInflater.fromBytes(byteArrayReader); if (transaction == null) { return null; } missingTransactionsListBuilder.add(transaction); } extraThinBlockMessage.setMissingTransactions(missingTransactionsListBuilder.build()); if (byteArrayReader.didOverflow()) { return null; } return extraThinBlockMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/sync/DisabledBlockchainIndexer.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync; public class DisabledBlockchainIndexer extends BlockchainIndexer { public DisabledBlockchainIndexer() { super(null, 0); } @Override protected void _onStart() { } @Override protected Boolean _run() { return false; } @Override protected void _onSleep() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/DifficultyCalculatorContext.java<|end_filename|> package com.softwareverde.bitcoin.context; public interface DifficultyCalculatorContext extends BlockHeaderContext, ChainWorkContext, MedianBlockTimeContext, AsertReferenceBlockContext { } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/locktime/ImmutableSequenceNumber.java<|end_filename|> package com.softwareverde.bitcoin.transaction.locktime; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.Const; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.json.Json; public class ImmutableSequenceNumber implements SequenceNumber, Const { protected final Long _value; protected Long _getMaskedValue() { return (_value & 0x0000FFFF); } protected SequenceNumberType _getType() { final Boolean isTimeSpan = ( (_value & (1 << 22)) != 0x00); return (isTimeSpan ? SequenceNumberType.SECONDS_ELAPSED : SequenceNumberType.BLOCK_COUNT); } public ImmutableSequenceNumber(final Long value) { _value = value; } public ImmutableSequenceNumber(final SequenceNumber sequenceNumber) { _value = sequenceNumber.getValue(); } @Override public Long getValue() { return _value; } @Override public SequenceNumberType getType() { return _getType(); } @Override public Long getMaskedValue() { return _getMaskedValue(); } @Override public Long asSecondsElapsed() { final Long maskedValue = _getMaskedValue(); return (maskedValue * SECONDS_PER_SEQUENCE_NUMBER); } @Override public Long asBlockCount() { return _getMaskedValue(); } @Override public Boolean isRelativeLockTimeDisabled() { return ((_value & 0x80000000L) != 0L); } @Override public ByteArray getBytes() { // 4 Bytes... return MutableByteArray.wrap(ByteUtil.integerToBytes(_value)); } @Override public ImmutableSequenceNumber asConst() { return this; } @Override public Json toJson() { final SequenceNumberType type = _getType(); final Json json = new Json(); json.put("type", type); json.put("isDisabled", (this.isRelativeLockTimeDisabled() ? 1 : 0)); json.put("value", (type == SequenceNumberType.SECONDS_ELAPSED ? this.asSecondsElapsed() : this.asBlockCount())); json.put("bytes", this.getBytes()); return json; } @Override public boolean equals(final Object object) { if (object == null) { return false; } if (! (object instanceof SequenceNumber)) { return false; } final SequenceNumber sequenceNumber = (SequenceNumber) object; return _value.equals(sequenceNumber.getValue()); } @Override public int hashCode() { return _value.hashCode(); } @Override public String toString() { return _value.toString(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/inflater/ProtocolMessageInflaters.java<|end_filename|> package com.softwareverde.bitcoin.inflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeaderInflater; import com.softwareverde.bitcoin.server.message.type.node.address.NodeIpAddressInflater; public interface ProtocolMessageInflaters { BitcoinProtocolMessageHeaderInflater getBitcoinProtocolMessageHeaderInflater(); NodeIpAddressInflater getNodeIpAddressInflater(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/compact/EnableCompactBlocksMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.compact; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.util.bytearray.Endian; public class EnableCompactBlocksMessageInflater extends BitcoinProtocolMessageInflater { @Override public EnableCompactBlocksMessage fromBytes(final byte[] bytes) { final EnableCompactBlocksMessage enableCompactBlocksMessage = new EnableCompactBlocksMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.ENABLE_COMPACT_BLOCKS); if (protocolMessageHeader == null) { return null; } final Boolean isEnabled = (byteArrayReader.readInteger(4, Endian.LITTLE) > 0); final Integer version = byteArrayReader.readInteger(4, Endian.LITTLE); enableCompactBlocksMessage.setIsEnabled(isEnabled); enableCompactBlocksMessage.setVersion(version); if (byteArrayReader.didOverflow()) { return null; } return enableCompactBlocksMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/validator/BlockOutputs.java<|end_filename|> package com.softwareverde.bitcoin.transaction.validator; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.Util; import java.util.HashMap; import java.util.Map; public class BlockOutputs { protected final Sha256Hash _coinbaseTransactionHash; protected final Map<TransactionOutputIdentifier, TransactionOutput> _transactionOutputs; public static BlockOutputs fromBlock(final Block block) { final List<Transaction> transactions = block.getTransactions(); final HashMap<TransactionOutputIdentifier, TransactionOutput> transactionOutputMap = new HashMap<TransactionOutputIdentifier, TransactionOutput>(transactions.getCount()); final Transaction coinbaseTransaction = block.getCoinbaseTransaction(); final Sha256Hash coinbaseTransactionHash = coinbaseTransaction.getHash(); for (final Transaction transaction : transactions) { final Sha256Hash transactionHash = transaction.getHash(); final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); int outputIndex = 0; for (final TransactionOutput transactionOutput : transactionOutputs) { final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, outputIndex); transactionOutputMap.put(transactionOutputIdentifier, transactionOutput); outputIndex += 1; } } return new BlockOutputs(coinbaseTransactionHash, transactionOutputMap); } protected BlockOutputs(final Sha256Hash coinbaseTransactionHash, final Map<TransactionOutputIdentifier, TransactionOutput> transactionOutputs) { _coinbaseTransactionHash = coinbaseTransactionHash; _transactionOutputs = transactionOutputs; } public BlockOutputs() { _coinbaseTransactionHash = null; _transactionOutputs = new HashMap<TransactionOutputIdentifier, TransactionOutput>(0); } public TransactionOutput getTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { return _transactionOutputs.get(transactionOutputIdentifier); } public Boolean isCoinbaseTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); return Util.areEqual(_coinbaseTransactionHash, transactionHash); } public Integer getOutputCount() { return _transactionOutputs.size(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/miner/pool/AccountId.java<|end_filename|> package com.softwareverde.bitcoin.miner.pool; import com.softwareverde.util.type.identifier.Identifier; public class AccountId extends Identifier { public static AccountId wrap(final Long value) { if (value == null) { return null; } if (value < 1L) { return null; } return new AccountId(value); } protected AccountId(final Long value) { super(value); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/message/type/query/response/block/BlockMessageInflaterTests.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response.block; import com.softwareverde.bitcoin.CoreInflater; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.test.util.TestUtil; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.constable.list.List; import com.softwareverde.util.HexUtil; import org.junit.Assert; import org.junit.Test; public class BlockMessageInflaterTests { @Test public void should_inflate_genesis_block_message_from_byte_array() { // Setup // E3E1 F3E8 626C 6F63 6B00 0000 0000 0000 1D01 0000 F71A 2403 final byte[] genesisBlockMessageBytes = HexUtil.hexStringToByteArray("E3E1F3E8626C6F636B000000000000001D010000F71A24030100000000000000000000000000000000000000000000000000000000000000000000003BA3EDFD7A7B12B27AC72C3E67768F617FC81BC3888A51323A9FB8AA4B1E5E4A29AB5F49FFFF001D1DAC2B7C0101000000010000000000000000000000000000000000000000000000000000000000000000FFFFFFFF4D04FFFF001D0104455468652054696D65732030332F4A616E2F32303039204368616E63656C6C6F72206F6E206272696E6B206F66207365636F6E64206261696C6F757420666F722062616E6B73FFFFFFFF0100F2052A01000000434104678AFDB0FE5548271967F1A67130B7105CD6A828E03909A67962E0EA1F61DEB649F6BC3F4CEF38C4F35504E51EC112DE5C384DF7BA0B8D578A4C702B6BF11D5FAC00000000"); final CoreInflater coreInflater = new CoreInflater(); final BlockMessageInflater blockMessageInflater = new BlockMessageInflater(coreInflater); // Action final BlockMessage blockMessage = blockMessageInflater.fromBytes(genesisBlockMessageBytes); // Assert final Block block = blockMessage.getBlock(); Assert.assertNotNull(block); TestUtil.assertEqual(HexUtil.hexStringToByteArray("000000000019D6689C085AE165831E934FF763AE46A2A6C172B3F1B60A8CE26F"), block.getHash().getBytes()); Assert.assertTrue(block.getDifficulty().isSatisfiedBy(block.getHash())); Assert.assertEquals(1, block.getVersion().intValue()); TestUtil.assertEqual(new byte[]{ }, block.getPreviousBlockHash().getBytes()); TestUtil.assertEqual(HexUtil.hexStringToByteArray("4A5E1E4BAAB89F3A32518A88C31BC87F618F76673E2CC77AB2127B7AFDEDA33B"), block.getMerkleRoot().getBytes()); Assert.assertEquals(1231006505L, block.getTimestamp().longValue()); Assert.assertEquals(1.0, Math.round(block.getDifficulty().getDifficultyRatio().doubleValue() * 100.0) / 100.0, 0.0001); Assert.assertEquals(2083236893L, block.getNonce().longValue()); final List<Transaction> transactions = block.getTransactions(); Assert.assertEquals(1, transactions.getCount()); final Transaction transaction = transactions.get(0); Assert.assertEquals(1, transaction.getVersion().intValue()); Assert.assertEquals(0L, transaction.getLockTime().getValue().longValue()); final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); Assert.assertEquals(1, transactionInputs.getCount()); final TransactionInput transactionInput = transactionInputs.get(0); TestUtil.assertEqual(HexUtil.hexStringToByteArray("0000000000000000000000000000000000000000000000000000000000000000"), transactionInput.getPreviousOutputTransactionHash().getBytes()); Assert.assertEquals(0xFFFFFFFF, transactionInput.getPreviousOutputIndex().intValue()); TestUtil.assertEqual(HexUtil.hexStringToByteArray("04FFFF001D0104455468652054696D65732030332F4A616E2F32303039204368616E63656C6C6F72206F6E206272696E6B206F66207365636F6E64206261696C6F757420666F722062616E6B73"), transactionInput.getUnlockingScript().getBytes().getBytes()); Assert.assertEquals(0xFFFFFFFF, transactionInput.getSequenceNumber().getValue().intValue()); final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); Assert.assertEquals(1, transactionOutputs.getCount()); final TransactionOutput transactionOutput = transactionOutputs.get(0); Assert.assertEquals(5000000000L, transactionOutput.getAmount().longValue()); TestUtil.assertEqual(HexUtil.hexStringToByteArray("4104678AFDB0FE5548271967F1A67130B7105CD6A828E03909A67962E0EA1F61DEB649F6BC3F4CEF38C4F35504E51EC112DE5C384DF7BA0B8D578A4C702B6BF11D5FAC"), transactionOutput.getLockingScript().getBytes().getBytes()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/fullnode/utxo/jvm/UnspentTransactionOutput.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.jvm; import java.util.Comparator; public class UnspentTransactionOutput { public static final Comparator<UnspentTransactionOutput> COMPARATOR = new Comparator<UnspentTransactionOutput>() { @Override public int compare(final UnspentTransactionOutput o1, final UnspentTransactionOutput o2) { return o1._utxoKey.compareTo(o2._utxoKey); } }; protected final UtxoKey _utxoKey; protected final UtxoValue _utxoValue; public UnspentTransactionOutput(final UtxoKey utxoKey, final UtxoValue utxoValue) { _utxoKey = utxoKey; _utxoValue = utxoValue; } public byte[] getTransactionHash() { return _utxoKey.transactionHash; } public int getOutputIndex() { return _utxoKey.outputIndex; } public long getBlockHeight() { return _utxoValue.blockHeight; } } <|start_filename|>src/test/java/com/softwareverde/security/pbkdf2/Pbkdf2KeyTests.java<|end_filename|> package com.softwareverde.security.pbkdf2; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.pbkdf2.Pbkdf2Key; import org.junit.Assert; import org.junit.Test; public class Pbkdf2KeyTests { @Test public void should_create_unique_key_for_passwords_greater_than_default_bit_count() { // Setup final String password0 = "<PASSWORD> false come shell air define poverty session have atom quiz debate crucial size glimpse smoke around radio inner drop snack"; final String password1 = "<PASSWORD> come shell air define poverty session have atom quiz debate crucial size glimpse smoke around radio inner drop horse"; final ByteArray reusedSalt = Pbkdf2Key.generateRandomSalt(); // The salt is reused only to ensure the entire password is used... // Action final Pbkdf2Key pbkdf2Key0 = new Pbkdf2Key(password0, Pbkdf2Key.DEFAULT_ITERATIONS, reusedSalt, Pbkdf2Key.DEFAULT_KEY_BIT_COUNT); final Pbkdf2Key pbkdf2Key1 = new Pbkdf2Key(password1, Pbkdf2Key.DEFAULT_ITERATIONS, reusedSalt, Pbkdf2Key.DEFAULT_KEY_BIT_COUNT); // Assert Assert.assertNotEquals(pbkdf2Key0.getKey(), pbkdf2Key1.getKey()); } @Test public void should_create_unique_key_for_passwords_using_non_pow2_bit_length() { // Setup final String password0 = "<PASSWORD> false come shell air define poverty session have atom quiz debate crucial size glimpse smoke around radio inner drop snack"; final String password1 = "<PASSWORD> come shell air define poverty session have atom quiz debate crucial size glimpse smoke around radio inner drop horse"; final ByteArray reusedSalt = Pbkdf2Key.generateRandomSalt(); // The salt is reused only to ensure the entire password is used... // Action final Pbkdf2Key pbkdf2Key0 = new Pbkdf2Key(password0, Pbkdf2Key.DEFAULT_ITERATIONS, reusedSalt, 254); final Pbkdf2Key pbkdf2Key1 = new Pbkdf2Key(password1, Pbkdf2Key.DEFAULT_ITERATIONS, reusedSalt, 248); // 254 gets truncated to 248 bits... // Assert Assert.assertNotEquals(pbkdf2Key0.getKey(), pbkdf2Key1.getKey()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/slp/SlpTransactionDatabaseManagerCore.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.slp; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.row.Row; import com.softwareverde.util.Util; import java.util.LinkedHashMap; public class SlpTransactionDatabaseManagerCore implements SlpTransactionDatabaseManager { protected static final String LAST_SLP_VALIDATED_BLOCK_ID_KEY = "last_slp_validated_block_id"; protected final FullNodeDatabaseManager _databaseManager; protected LinkedHashMap<BlockId, List<TransactionId>> _getConfirmedPendingValidationSlpTransactions(final Integer maxCount) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final BlockId lastIndexedBlockId; { final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT value FROM properties WHERE `key` = ?") .setParameter(LAST_SLP_VALIDATED_BLOCK_ID_KEY) ); if (rows.isEmpty()) { lastIndexedBlockId = BlockId.wrap(0L); } else { final Row row = rows.get(0); lastIndexedBlockId = BlockId.wrap(row.getLong("value")); } } final java.util.List<Row> rows = databaseConnection.query( new Query( "SELECT " + "blocks.id AS block_id, indexed_transaction_outputs.transaction_id " + "FROM " + "indexed_transaction_outputs " + "INNER JOIN block_transactions " + "ON (block_transactions.transaction_id = indexed_transaction_outputs.transaction_id) " + "INNER JOIN blocks " + "ON (blocks.id = block_transactions.block_id AND blocks.id > ?) " + "WHERE " + "NOT EXISTS (SELECT * FROM validated_slp_transactions WHERE validated_slp_transactions.transaction_id = indexed_transaction_outputs.transaction_id) " + "AND indexed_transaction_outputs.slp_transaction_id IS NOT NULL " + "GROUP BY blocks.id, indexed_transaction_outputs.transaction_id " + "ORDER BY blocks.block_height ASC " + "LIMIT "+ maxCount ) .setParameter(lastIndexedBlockId) ); final LinkedHashMap<BlockId, List<TransactionId>> result = new LinkedHashMap<BlockId, List<TransactionId>>(); BlockId previousBlockId = null; ImmutableListBuilder<TransactionId> transactionIds = null; for (final Row row : rows) { final BlockId blockId = BlockId.wrap(row.getLong("block_id")); final TransactionId transactionId = TransactionId.wrap(row.getLong("transaction_id")); if ( (blockId == null) || (transactionId == null) ) { continue; } if ( (previousBlockId == null) || (! Util.areEqual(previousBlockId, blockId)) ) { if (transactionIds != null) { result.put(previousBlockId, transactionIds.build()); } previousBlockId = blockId; transactionIds = new ImmutableListBuilder<TransactionId>(); } transactionIds.add(transactionId); } if ( (previousBlockId != null) && (transactionIds != null) ) { result.put(previousBlockId, transactionIds.build()); } return result; } protected List<TransactionId> _getUnconfirmedPendingValidationSlpTransactions(final Integer maxCount) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query( "SELECT " + "indexed_transaction_outputs.transaction_id " + "FROM " + "indexed_transaction_outputs " + "INNER JOIN unconfirmed_transactions " + "ON (unconfirmed_transactions.transaction_id = indexed_transaction_outputs.transaction_id) " + "LEFT OUTER JOIN validated_slp_transactions " + "ON (validated_slp_transactions.transaction_id = indexed_transaction_outputs.transaction_id) " + "WHERE " + "validated_slp_transactions.id IS NULL " + "AND indexed_transaction_outputs.slp_transaction_id IS NOT NULL " + "GROUP BY indexed_transaction_outputs.transaction_id ASC " + "LIMIT " + maxCount ) ); final ImmutableListBuilder<TransactionId> transactionIds = new ImmutableListBuilder<TransactionId>(rows.size()); for (final Row row : rows) { final TransactionId transactionId = TransactionId.wrap(row.getLong("transaction_id")); if (transactionId == null) { continue; } transactionIds.add(transactionId); } return transactionIds.build(); } public SlpTransactionDatabaseManagerCore(final FullNodeDatabaseManager databaseManager) { _databaseManager = databaseManager; } /** * Returns the cached SLP validity of the TransactionId. * This function does not run validation on the transaction and only queries its cached value. */ @Override public Boolean getSlpTransactionValidationResult(final TransactionId transactionId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id, is_valid FROM validated_slp_transactions WHERE transaction_id = ?") .setParameter(transactionId) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); return row.getBoolean("is_valid"); } @Override public void setSlpTransactionValidationResult(final TransactionId transactionId, final Boolean isValid) throws DatabaseException { if (transactionId == null) { return; } final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final Integer isValidIntegerValue = ( (isValid != null) ? (isValid ? 1 : 0) : null ); databaseConnection.executeSql( new Query("INSERT INTO validated_slp_transactions (transaction_id, is_valid) VALUES (?, ?) ON DUPLICATE KEY UPDATE is_valid = ?") .setParameter(transactionId) .setParameter(isValidIntegerValue) .setParameter(isValidIntegerValue) ); } /** * Returns a mapping of (SLP) TransactionIds that have not been validated yet, ordered by their respective block's height. * Unconfirmed transactions are not returned by this function. */ @Override public LinkedHashMap<BlockId, List<TransactionId>> getConfirmedPendingValidationSlpTransactions(final Integer maxCount) throws DatabaseException { return _getConfirmedPendingValidationSlpTransactions(maxCount); } @Override public void setLastSlpValidatedBlockId(final BlockId blockId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); databaseConnection.executeSql( new Query("INSERT INTO properties (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = GREATEST(VALUES(value), value)") .setParameter(LAST_SLP_VALIDATED_BLOCK_ID_KEY) .setParameter(blockId) ); } /** * Returns a list of (SLP) TransactionIds that have not been validated yet that reside in the mempool. */ @Override public List<TransactionId> getUnconfirmedPendingValidationSlpTransactions(final Integer maxCount) throws DatabaseException { return _getUnconfirmedPendingValidationSlpTransactions(maxCount); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/stack/Stack.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.stack; import java.util.LinkedList; import java.util.List; public class Stack { public static final Value OVERFLOW_VALUE = Value.fromInteger(0L); protected final List<Value> _values = new LinkedList<Value>(); protected Boolean _didOverflow = false; protected Integer _maxItemCount = Integer.MAX_VALUE; protected Stack _altStack = null; protected Value _peak(final Integer index) { if ( (index < 0) || (index >= _values.size()) ) { _didOverflow = true; return OVERFLOW_VALUE; } return _values.get(_values.size() - index - 1); } protected void _initAltStack() { if (_altStack == null) { _altStack = new Stack(); } } public Stack() { } public Stack(final Stack stack) { _values.addAll(stack._values); _didOverflow = stack._didOverflow; _maxItemCount = stack._maxItemCount; _altStack = ((stack._altStack != null) ? new Stack(stack._altStack) : null); } public void push(final Value value) { if (value == null) { _didOverflow = true; return; } final int totalItemCount = (_values.size() + (_altStack != null ? _altStack.getSize() : 0)); if (totalItemCount >= _maxItemCount) { _didOverflow = true; return; } _values.add(value); } public void pushToAltStack(final Value value) { _initAltStack(); _altStack.push(value); } public Value peak() { return _peak(0); } public Value peakFromAltStack() { _initAltStack(); return _altStack.peak(); } public Value peak(final Integer index) { return _peak(index); } public Value peakFromAltStack(final Integer index) { _initAltStack(); return _altStack.peak(index); } public Value pop() { if (_values.isEmpty()) { _didOverflow = true; return OVERFLOW_VALUE; } return _values.remove(_values.size() - 1); } public Value popFromAltStack() { _initAltStack(); return _altStack.pop(); } public Value pop(final Integer index) { if ( (index < 0) || (index >= _values.size()) ) { _didOverflow = true; return OVERFLOW_VALUE; } return _values.remove(_values.size() - index - 1); } public Value popFromAltStack(final Integer index) { _initAltStack(); return _altStack.pop(index); } /** * Removes all items from the primary stack. * The altStack is not affected. */ public void clearStack() { _values.clear(); } /** * Removes all items from the alt stack. * The primary stack is not affected. */ public void clearAltStack() { if (_altStack != null) { _altStack.clearStack(); } } public Boolean isEmpty() { return _values.isEmpty(); } public Boolean altStackIsEmpty() { _initAltStack(); return _altStack.isEmpty(); } public Integer getSize() { return _values.size(); } public Integer getAltStackSize() { _initAltStack(); return _altStack.getSize(); } public Boolean didOverflow() { if (_altStack != null) { if (_altStack.didOverflow()) { return true; } } return (_didOverflow); } /** * Sets the maximum number of items allowed within the stack. * Exceeding this value results in push operations to be ignored, and overflows the stack. * This value includes the size of the stack and its altStack. */ public void setMaxItemCount(final Integer maxItemCount) { _maxItemCount = maxItemCount; } public Integer getMaxItemCount() { return _maxItemCount; } @Override public String toString() { final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < _values.size(); ++i) { final Value value = _peak(i); stringBuilder.append(value.toString()); stringBuilder.append("\n"); } if (_altStack != null) { stringBuilder.append("-----"); stringBuilder.append(_altStack.toString()); } return stringBuilder.toString(); } } <|start_filename|>src/main/java/com/softwareverde/concurrent/pool/ThreadPoolThrottle.java<|end_filename|> package com.softwareverde.concurrent.pool; import com.softwareverde.concurrent.service.SleepyService; import com.softwareverde.logging.Logger; import com.softwareverde.util.type.time.SystemTime; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; public class ThreadPoolThrottle extends SleepyService implements ThreadPool { public static final Integer MAX_QUEUE_SIZE = 10000; protected final SystemTime _systemTime = new SystemTime(); protected final ConcurrentLinkedQueue<Runnable> _queue = new ConcurrentLinkedQueue<Runnable>(); protected final AtomicInteger _queueSize = new AtomicInteger(0); protected final ThreadPool _threadPool; protected final Integer _maxSubmissionsPerSecond; protected Long _lastLogStatement = 0L; protected final AtomicLong _droppedSubmissionsCount = new AtomicLong(0); public ThreadPoolThrottle(final Integer maxSubmissionsPerSecond, final ThreadPool threadPool) { _maxSubmissionsPerSecond = maxSubmissionsPerSecond; _threadPool = threadPool; } @Override protected void _onStart() { } @Override protected Boolean _run() { final Runnable runnable = _queue.poll(); if (runnable == null) { return false; } _queueSize.decrementAndGet(); _threadPool.execute(runnable); try { Thread.sleep(1000L / _maxSubmissionsPerSecond); } catch (final InterruptedException exception) { Thread.currentThread().interrupt(); // Preserve the interrupted status... return false; } // Log when the queue exceeds the max submissions per second... if (_queueSize.get() > _maxSubmissionsPerSecond) { // Only log once every 5 seconds to prevent spam... final Long now = System.currentTimeMillis(); if (now - _lastLogStatement > 5000L) { Logger.warn("ThreadPoolThrottle is " + (_queueSize.get() / _maxSubmissionsPerSecond) + " seconds behind."); _lastLogStatement = now; } } return (_queueSize.get() > 0); } @Override protected void _onSleep() { } @Override public void execute(final Runnable runnable) { if (_queueSize.get() >= MAX_QUEUE_SIZE) { if (_droppedSubmissionsCount.get() % _maxSubmissionsPerSecond == 0) { Logger.warn("ThreadPoolThrottle: Exceeded max queue size. " + _droppedSubmissionsCount); } _droppedSubmissionsCount.incrementAndGet(); return; } _queue.offer(runnable); _queueSize.incrementAndGet(); this.wakeUp(); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeAtomicTransactionOutputIndexerContext.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.server.module.node.database.indexer.TransactionOutputId; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import java.util.HashMap; public class FakeAtomicTransactionOutputIndexerContext implements com.softwareverde.bitcoin.context.AtomicTransactionOutputIndexerContext { protected final HashMap<Sha256Hash, TransactionId> _transactionIds = new HashMap<Sha256Hash, TransactionId>(0); protected final HashMap<TransactionId, Transaction> _transactions = new HashMap<TransactionId, Transaction>(0); protected final MutableList<Address> _storedAddresses = new MutableList<Address>(0); protected final MutableList<TransactionId> _unprocessedTransactions = new MutableList<TransactionId>(0); protected final MutableList<IndexedOutput> _indexedOutputs = new MutableList<IndexedOutput>(0); protected final MutableList<IndexedInput> _indexedInputs = new MutableList<IndexedInput>(0); protected Boolean _wasCommitted = null; protected Boolean _wasRolledBack = false; protected Boolean _wasClosed = false; public void addTransaction(final Transaction transaction) { final Sha256Hash transactionHash = transaction.getHash(); if (_transactionIds.containsKey(transactionHash)) { return; } final TransactionId transactionId = TransactionId.wrap(_transactions.size() + 1L); _transactionIds.put(transactionHash, transactionId); _transactions.put(transactionId, transaction); } public void queueTransactionForProcessing(final Transaction transaction) { final Sha256Hash transactionHash = transaction.getHash(); final TransactionId transactionId; { if (_transactionIds.containsKey(transactionHash)) { transactionId = _transactionIds.get(transactionHash); } else { transactionId = TransactionId.wrap(_transactions.size() + 1L); _transactionIds.put(transactionHash, transactionId); _transactions.put(transactionId, transaction); } } _unprocessedTransactions.add(transactionId); } public Transaction getTransaction(final Sha256Hash transactionHash) { final TransactionId transactionId = _transactionIds.get(transactionHash); if (transactionId == null) { return null; } return _transactions.get(transactionId); } public List<TransactionId> getTransactionIds() { return new ImmutableList<TransactionId>(_transactionIds.values()); } public Boolean wasCommitted() { return _wasCommitted; } public Boolean wasRolledBack() { return _wasRolledBack; } public List<IndexedOutput> getIndexedOutputs() { return _indexedOutputs; } public List<Address> getStoredAddresses() { return _storedAddresses; } @Override public void startDatabaseTransaction() { _wasCommitted = false; } @Override public void commitDatabaseTransaction() { _wasCommitted = true; } @Override public void rollbackDatabaseTransaction() { _wasRolledBack = true; } @Override public List<TransactionId> getUnprocessedTransactions(final Integer batchSize) { final MutableList<TransactionId> transactionIds = new MutableList<TransactionId>(); for (int i = 0; i < batchSize; ++i) { if (i >= _unprocessedTransactions.getCount()) { break; } final TransactionId transactionId = _unprocessedTransactions.get(i); transactionIds.add(transactionId); } return transactionIds; } @Override public void dequeueTransactionsForProcessing(final List<TransactionId> transactionIds) { for (final TransactionId transactionId : transactionIds) { final int index = _unprocessedTransactions.indexOf(transactionId); if (index >= 0) { _unprocessedTransactions.remove(index); } } } @Override public TransactionId getTransactionId(final Sha256Hash transactionHash) { return _transactionIds.get(transactionHash); } @Override public TransactionId getTransactionId(final SlpTokenId slpTokenId) { return _transactionIds.get(slpTokenId); } @Override public Transaction getTransaction(final TransactionId transactionId) { return _transactions.get(transactionId); } @Override public void indexTransactionOutput(final TransactionId transactionId, final Integer outputIndex, final Long amount, final ScriptType scriptType, final Address address, final TransactionId slpTransactionId) { final IndexedOutput indexedOutput = new IndexedOutput(transactionId, outputIndex, amount, scriptType, address, slpTransactionId); _indexedOutputs.add(indexedOutput); } @Override public void indexTransactionInput(final TransactionId transactionId, final Integer inputIndex, final TransactionOutputId transactionOutputId) { final IndexedInput indexedInput = new IndexedInput(transactionId, inputIndex, transactionOutputId); _indexedInputs.add(indexedInput); } @Override public void close() { _wasClosed = true; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/endpoint/BlocksApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.endpoint; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.bitcoin.server.module.explorer.api.v1.get.GetBlockTransactionsHandler; import com.softwareverde.bitcoin.server.module.explorer.api.v1.get.ListBlockHeadersHandler; import com.softwareverde.http.HttpMethod; import com.softwareverde.json.Json; public class BlocksApi extends ExplorerApiEndpoint { public static class RecentBlocksResult extends ApiResult { private Json _blockHeadersJson = new Json(true); public void setBlockHeadersJson(final Json blockHeadersJson) { _blockHeadersJson = blockHeadersJson; } @Override public Json toJson() { final Json json = super.toJson(); json.put("blockHeaders", _blockHeadersJson); return json; } } public static class BlockTransactionsResult extends ApiResult { private Json _transactions = new Json(true); public BlockTransactionsResult() { super(); } public BlockTransactionsResult(final Boolean wasSuccess, final String errorMessage) { super(wasSuccess, errorMessage); } public void setTransactions(final Json transactions) { _transactions = transactions; } @Override public Json toJson() { final Json json = super.toJson(); json.put("transactions", _transactions); return json; } } public BlocksApi(final String apiPrePath, final Environment environment) { super(environment); _defineEndpoint((apiPrePath + "/blocks"), HttpMethod.GET, new ListBlockHeadersHandler()); _defineEndpoint((apiPrePath + "/blocks/<blockHash>/transactions"), HttpMethod.GET, new GetBlockTransactionsHandler()); } } <|start_filename|>src/main/java/com/softwareverde/concurrent/pool/MainThreadPool.java<|end_filename|> package com.softwareverde.concurrent.pool; import com.softwareverde.logging.Logger; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class MainThreadPool implements ThreadPool { protected final LinkedBlockingQueue<Runnable> _queue; protected final Integer _maxThreadCount; protected final Long _threadKeepAliveMilliseconds; protected ThreadPoolExecutor _executorService; protected Runnable _shutdownCallback; protected Integer _threadPriority = Thread.NORM_PRIORITY; final AtomicInteger _nextThreadId = new AtomicInteger(0); protected ThreadPoolExecutor _createExecutorService() { if (_maxThreadCount < 1) { return null; } final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(_maxThreadCount, _maxThreadCount, _threadKeepAliveMilliseconds, TimeUnit.MILLISECONDS, _queue, new ThreadFactory() { @Override public Thread newThread(final Runnable runnable) { final int nextThreadId = _nextThreadId.incrementAndGet(); final Thread thread = new Thread(runnable); thread.setName("MainThreadPool - " + nextThreadId); thread.setDaemon(false); thread.setPriority(_threadPriority); thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread thread, final Throwable throwable) { try { Logger.error("Uncaught exception in Thread Pool.", throwable); } catch (final Throwable exception) { } if (throwable instanceof Error) { final Runnable shutdownCallback = _shutdownCallback; if (shutdownCallback != null) { try { shutdownCallback.run(); } catch (final Throwable shutdownError) { } } } } }); return thread; } }); if (_threadKeepAliveMilliseconds > 0L) { threadPoolExecutor.allowCoreThreadTimeOut(true); } return threadPoolExecutor; } public MainThreadPool(final Integer maxThreadCount, final Long threadKeepAliveMilliseconds) { _queue = new LinkedBlockingQueue<Runnable>(); _maxThreadCount = maxThreadCount; _threadKeepAliveMilliseconds = threadKeepAliveMilliseconds; _executorService = _createExecutorService(); } public void setThreadPriority(final Integer threadPriority) { _threadPriority = threadPriority; } public Integer getThreadPriority() { return _threadPriority; } /** * Queues the Runnable to the ThreadPool. * If ThreadPool::stop has been invoked without a subsequent call to ThreadPool::start, the Runnable is dropped. */ @Override public void execute(final Runnable runnable) { final ExecutorService executorService = _executorService; if (executorService == null) { return; } try { executorService.submit(new Runnable() { @Override public void run() { try { runnable.run(); } catch (final Exception exception) { Logger.warn(exception); } } }); } catch (final RejectedExecutionException exception) { Logger.warn(exception); // Execution rejected due to shutdown race condition... } } /** * Resets the ThreadPool after a call to ThreadPool::shutdown. * Invoking ThreadPool::start without invoking ThreadPool::stop is safe but does nothing. * It is not necessary to invoke ThreadPool::start after instantiation. */ public void start() { if (_executorService != null) { return; } _executorService = _createExecutorService(); } /** * Immediately interrupts all pending threads and awaits termination for up to 1 minute. * Any calls to ThreadPool::execute after invoking ThreadPool::stop are ignored until ThreadPool::start is called. */ public void stop() { final ExecutorService executorService = _executorService; if (executorService == null) { return; } _executorService = null; executorService.shutdown(); // Disable new tasks from being submitted... try { // Wait a while for existing tasks to terminate... if (! executorService.awaitTermination(30, TimeUnit.SECONDS)) { executorService.shutdownNow(); // Cancel currently executing tasks... // Wait a while for tasks to respond to being cancelled... if (! executorService.awaitTermination(30, TimeUnit.SECONDS)) Logger.warn("ThreadPool did not exit cleanly."); } } catch (final InterruptedException exception) { executorService.shutdownNow(); // Re-cancel if current thread also interrupted... Thread.currentThread().interrupt(); // Preserve interrupt status... } } /** * Sets the callback that is executed when an java.lang.Error is thrown. * This procedure is not invoked if a thread encounters a recoverable Exception (i.e. An uncaught RuntimeException). * The shutdownCallback should attempt to gracefully terminate the application and not attempt to "recover"; * System.exit() should not be executed within shutdownCallback. */ public void setShutdownCallback(final Runnable shutdownCallback) { _shutdownCallback = shutdownCallback; } /** * Returns the current number of items in the ThreadPool queue. */ public Integer getQueueCount() { return _queue.size(); } public Integer getActiveThreadCount() { if (_executorService == null) { return 0; } return _executorService.getPoolSize(); } public Integer getMaxThreadCount() { return _maxThreadCount; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/fullnode/utxo/UnspentTransactionOutputDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManagerFactory; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.constable.list.List; import com.softwareverde.database.DatabaseException; import java.util.concurrent.locks.ReentrantReadWriteLock; public interface UnspentTransactionOutputDatabaseManager { Long DEFAULT_MAX_UTXO_CACHE_COUNT = 500000L; Float DEFAULT_PURGE_PERCENT = 0.5F; Long BYTES_PER_UTXO = 128L; // NOTE: This value is larger than the actual size. // TODO: Research a more accurate UTXO byte count. interface SpentState { Boolean isSpent(); Boolean isFlushedToDisk(); } static void lockUtxoSet() { UTXO_WRITE_MUTEX.lock(); } static void unlockUtxoSet() { UTXO_WRITE_MUTEX.unlock(); } /** * Marks the UTXO set as invalid, equivalently putting it in an error-state. * Once invalidated, UTXOs may not be accessed until it is reset via ::clearUncommittedUtxoSet. * This function cannot throw and ensures the current UTXO will not be committed to disk. */ static void invalidateUncommittedUtxoSet() { // First immediately invalidate the UTXO set without a lock, to ensure the set cannot be committed to desk, even upon deadlock or error. UnspentTransactionOutputJvmManager.UNCOMMITTED_UTXO_BLOCK_HEIGHT.value = -1L; // Second, acquire the write lock and re-set the invalidation state to ensure any functions mid-execution did not accidentally clear the above invalidation. UTXO_WRITE_MUTEX.lock(); try { UnspentTransactionOutputJvmManager.UNCOMMITTED_UTXO_BLOCK_HEIGHT.value = -1L; } finally { UTXO_WRITE_MUTEX.unlock(); } } ReentrantReadWriteLock.ReadLock UTXO_READ_MUTEX = UnspentTransactionOutputJvmManager.READ_MUTEX; ReentrantReadWriteLock.WriteLock UTXO_WRITE_MUTEX = UnspentTransactionOutputJvmManager.WRITE_MUTEX; void markTransactionOutputsAsSpent(List<TransactionOutputIdentifier> spentTransactionOutputIdentifiers) throws DatabaseException; void insertUnspentTransactionOutputs(List<TransactionOutputIdentifier> unspentTransactionOutputIdentifiers, Long blockHeight) throws DatabaseException; /** * Marks the provided UTXOs as spent, logically removing them from the UTXO set, and forces the outputs to be synchronized to disk on the next UTXO commit. */ void undoCreationOfTransactionOutputs(List<TransactionOutputIdentifier> transactionOutputIdentifiers) throws DatabaseException; /** * Re-inserts the provided UTXOs into the UTXO set and looks up their original associated blockHeight. These UTXOs will be synchronized to disk during the next UTXO commit. */ void undoSpendingOfTransactionOutputs(List<TransactionOutputIdentifier> transactionOutputIdentifiers) throws DatabaseException; TransactionOutput getUnspentTransactionOutput(TransactionOutputIdentifier transactionOutputIdentifier) throws DatabaseException; List<TransactionOutput> getUnspentTransactionOutputs(List<TransactionOutputIdentifier> transactionOutputIdentifiers) throws DatabaseException; /** * Flushes all queued UTXO set changes to disk. The UTXO set is locked for the duration of this call. */ void commitUnspentTransactionOutputs(DatabaseManagerFactory databaseManagerFactory) throws DatabaseException; void commitUnspentTransactionOutputs(DatabaseManagerFactory databaseManagerFactory, Boolean blockUntilComplete) throws DatabaseException; Long getUncommittedUnspentTransactionOutputCount() throws DatabaseException; Long getUncommittedUnspentTransactionOutputCount(Boolean noLock) throws DatabaseException; Long getCommittedUnspentTransactionOutputBlockHeight() throws DatabaseException; Long getCommittedUnspentTransactionOutputBlockHeight(Boolean noLock) throws DatabaseException; void setUncommittedUnspentTransactionOutputBlockHeight(Long blockHeight) throws DatabaseException; Long getUncommittedUnspentTransactionOutputBlockHeight() throws DatabaseException; Long getUncommittedUnspentTransactionOutputBlockHeight(Boolean noLock) throws DatabaseException; void clearCommittedUtxoSet() throws DatabaseException; void clearUncommittedUtxoSet() throws DatabaseException; Long getMaxUtxoCount(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/opcode/controlstate/CodeBlock.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode.controlstate; public class CodeBlock { public final Boolean condition; public final CodeBlockType type; public CodeBlock parent = null; public CodeBlock(final CodeBlockType type, final Boolean condition) { this.type = type; this.condition = condition; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/DatabaseModule.java<|end_filename|> package com.softwareverde.bitcoin.server.module; import com.softwareverde.bitcoin.server.Environment; public class DatabaseModule { protected final Environment _environment; public DatabaseModule(final Environment environment) { _environment = environment; } public void loop() { while (true) { try { Thread.sleep(5000); } catch (final Exception exception) { break; } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/node/address/BitcoinNodeIpAddress.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.node.address; import com.softwareverde.bitcoin.server.message.type.node.feature.NodeFeatures; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.network.ip.Ipv4; import com.softwareverde.network.ip.Ipv6; import com.softwareverde.network.p2p.node.address.NodeIpAddress; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class BitcoinNodeIpAddress extends NodeIpAddress { public static final Integer BYTE_COUNT_WITHOUT_TIMESTAMP = 26; public static final Integer BYTE_COUNT_WITH_TIMESTAMP = 30; private static class ByteData { public final byte[] timestamp = new byte[4]; public final byte[] nodeFeatureFlags = new byte[8]; public final byte[] ip = new byte[16]; public final byte[] port = new byte[2]; } protected Long _timestamp; protected final NodeFeatures _nodeFeatures; protected ByteData _createByteData() { final ByteData byteData = new ByteData(); ByteUtil.setBytes(byteData.timestamp, ByteUtil.longToBytes(_timestamp)); ByteUtil.setBytes(byteData.nodeFeatureFlags, ByteUtil.longToBytes(_nodeFeatures.getFeatureFlags())); { if (_ip instanceof Ipv4) { final ByteArray paddedBytes = Ipv6.createIpv4CompatibleIpv6((Ipv4) _ip).getBytes(); ByteUtil.setBytes(byteData.ip, paddedBytes.getBytes()); } else { final ByteArray ipBytes = _ip.getBytes(); ByteUtil.setBytes(byteData.ip, ipBytes.getBytes()); } } { final int portIntValue = (_port == null ? 0x0000 : _port); byteData.port[0] = (byte) (portIntValue >>> 8); byteData.port[1] = (byte) portIntValue; } return byteData; } public BitcoinNodeIpAddress() { _timestamp = (System.currentTimeMillis() / 1000L); _nodeFeatures = new NodeFeatures(); _ip = new Ipv4(); _port = 0x0000; } public BitcoinNodeIpAddress(final NodeIpAddress nodeIpAddress) { _timestamp = (System.currentTimeMillis() / 1000L); if (nodeIpAddress != null) { _ip = nodeIpAddress.getIp(); _port = nodeIpAddress.getPort(); } else { _ip = new Ipv4(); _port = 0; } if (nodeIpAddress instanceof BitcoinNodeIpAddress) { _nodeFeatures = ((BitcoinNodeIpAddress) nodeIpAddress).getNodeFeatures(); } else { _nodeFeatures = new NodeFeatures(); } } public void setNodeFeatures(final NodeFeatures nodeFeatures) { _nodeFeatures.setFeaturesFlags(nodeFeatures); } public NodeFeatures getNodeFeatures() { return _nodeFeatures; } public byte[] getBytesWithoutTimestamp() { final ByteData byteData = _createByteData(); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(byteData.nodeFeatureFlags, Endian.LITTLE); byteArrayBuilder.appendBytes(byteData.ip, Endian.BIG); byteArrayBuilder.appendBytes(byteData.port, Endian.BIG); return byteArrayBuilder.build(); } public byte[] getBytesWithTimestamp() { final ByteData byteData = _createByteData(); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(byteData.timestamp, Endian.LITTLE); byteArrayBuilder.appendBytes(byteData.nodeFeatureFlags, Endian.LITTLE); byteArrayBuilder.appendBytes(byteData.ip, Endian.BIG); byteArrayBuilder.appendBytes(byteData.port, Endian.BIG); return byteArrayBuilder.build(); } @Override public BitcoinNodeIpAddress copy() { final BitcoinNodeIpAddress nodeIpAddress = new BitcoinNodeIpAddress(); nodeIpAddress._timestamp = _timestamp; nodeIpAddress._nodeFeatures.setFeaturesFlags(_nodeFeatures); nodeIpAddress._ip = _ip; nodeIpAddress._port = _port; return nodeIpAddress; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/output/MutableTransactionOutput.java<|end_filename|> package com.softwareverde.bitcoin.transaction.output; import com.softwareverde.bitcoin.transaction.script.locking.ImmutableLockingScript; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.json.Json; import com.softwareverde.util.Util; public class MutableTransactionOutput implements TransactionOutput { protected Long _amount = 0L; protected Integer _index = 0; protected LockingScript _lockingScript = LockingScript.EMPTY_SCRIPT; protected Integer _cachedHashCode = null; public MutableTransactionOutput() { } public MutableTransactionOutput(final TransactionOutput transactionOutput) { _amount = transactionOutput.getAmount(); _index = transactionOutput.getIndex(); _lockingScript = transactionOutput.getLockingScript().asConst(); } @Override public Long getAmount() { return _amount; } public void setAmount(final Long amount) { _amount = amount; _cachedHashCode = null; } @Override public Integer getIndex() { return _index; } public void setIndex(final Integer index) { _index = index; _cachedHashCode = null; } @Override public LockingScript getLockingScript() { return _lockingScript; } public void setLockingScript(final LockingScript lockingScript) { _lockingScript = lockingScript.asConst(); _cachedHashCode = null; } public void setLockingScript(final ByteArray bytes) { _lockingScript = new ImmutableLockingScript(bytes); } @Override public ImmutableTransactionOutput asConst() { return new ImmutableTransactionOutput(this); } @Override public Json toJson() { final TransactionOutputDeflater transactionOutputDeflater = new TransactionOutputDeflater(); return transactionOutputDeflater.toJson(this); } @Override public int hashCode() { final Integer cachedHashCode = _cachedHashCode; if (cachedHashCode != null) { return cachedHashCode; } final TransactionOutputDeflater transactionOutputDeflater = new TransactionOutputDeflater(); final Integer hashCode = transactionOutputDeflater.toBytes(this).hashCode(); _cachedHashCode = hashCode; return hashCode; } @Override public boolean equals(final Object object) { if (! (object instanceof TransactionOutput)) { return false; } final TransactionOutput transactionOutput = (TransactionOutput) object; if (! Util.areEqual(_amount, transactionOutput.getAmount())) { return false; } if (! Util.areEqual(_index, transactionOutput.getIndex())) { return false; } if (! Util.areEqual(_lockingScript, transactionOutput.getLockingScript())) { return false; } return true; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/genesis/ImmutableSlpGenesisScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp.genesis; import com.softwareverde.constable.Const; public class ImmutableSlpGenesisScript extends SlpGenesisScriptCore implements Const { public ImmutableSlpGenesisScript(final SlpGenesisScript slpGenesisScript) { super(slpGenesisScript); } @Override public ImmutableSlpGenesisScript asConst() { return this; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/node/address/NodeIpAddressInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.node.address; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.network.ip.Ipv4; import com.softwareverde.network.ip.Ipv6; import com.softwareverde.util.HexUtil; import com.softwareverde.util.bytearray.ByteArrayReader; import com.softwareverde.util.bytearray.Endian; public class NodeIpAddressInflater { public BitcoinNodeIpAddress fromBytes(final byte[] bytes) { final BitcoinNodeIpAddress nodeIpAddress = new BitcoinNodeIpAddress(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); nodeIpAddress._timestamp = ((bytes.length > 26) ? byteArrayReader.readLong(4, Endian.LITTLE) : 0L); nodeIpAddress._nodeFeatures.setFeatureFlags(byteArrayReader.readLong(8, Endian.LITTLE)); { final byte[] ipv4CompatibilityBytes = HexUtil.hexStringToByteArray("00000000000000000000FFFF"); final byte[] nextBytes = byteArrayReader.peakBytes(12, Endian.BIG); final Boolean isIpv4Address = ByteUtil.areEqual(ipv4CompatibilityBytes, nextBytes); if (isIpv4Address) { byteArrayReader.skipBytes(12); nodeIpAddress.setIp(Ipv4.fromBytes(byteArrayReader.readBytes(4, Endian.BIG))); } else { nodeIpAddress.setIp(Ipv6.fromBytes(byteArrayReader.readBytes(16, Endian.BIG))); } } nodeIpAddress.setPort(byteArrayReader.readInteger(2, Endian.BIG)); if (byteArrayReader.didOverflow()) { return null; } return nodeIpAddress; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/signature/ScriptSignatureContext.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.signature; public enum ScriptSignatureContext { CHECK_SIGNATURE, CHECK_DATA_SIGNATURE } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/Environment.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api; import com.softwareverde.bitcoin.server.configuration.ExplorerProperties; import com.softwareverde.bitcoin.server.module.node.rpc.NodeJsonRpcConnection; import com.softwareverde.bitcoin.server.module.stratum.rpc.StratumJsonRpcConnection; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.logging.Logger; import java.net.Socket; public class Environment implements com.softwareverde.http.server.servlet.routed.Environment { protected final ExplorerProperties _explorerProperties; protected final ThreadPool _threadPool; public Environment(final ExplorerProperties explorerProperties, final ThreadPool threadPool) { _explorerProperties = explorerProperties; _threadPool = threadPool; } public ExplorerProperties getExplorerProperties() { return _explorerProperties; } public ThreadPool getThreadPool() { return _threadPool; } public NodeJsonRpcConnection getNodeJsonRpcConnection() { final String bitcoinRpcUrl = _explorerProperties.getBitcoinRpcUrl(); final Integer bitcoinRpcPort = _explorerProperties.getBitcoinRpcPort(); try { final Socket socket = new Socket(bitcoinRpcUrl, bitcoinRpcPort); if (socket.isConnected()) { return new NodeJsonRpcConnection(socket, _threadPool); } } catch (final Exception exception) { Logger.warn(exception); } return null; } public StratumJsonRpcConnection getStratumJsonRpcConnection() { final String stratumRpcUrl = _explorerProperties.getStratumRpcUrl(); final Integer stratumRpcPort = _explorerProperties.getStratumRpcPort(); try { final Socket socket = new Socket(stratumRpcUrl, stratumRpcPort); if (socket.isConnected()) { return new StratumJsonRpcConnection(socket, _threadPool); } } catch (final Exception exception) { Logger.warn(exception); } return null; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/script/slp/SlpScriptInflaterTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp; import com.softwareverde.bitcoin.test.UnitTest; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.bitcoin.transaction.script.ScriptInflater; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.util.IoUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.json.Json; import com.softwareverde.logging.Logger; import com.softwareverde.util.Util; import org.junit.Assert; import org.junit.Test; public class SlpScriptInflaterTests extends UnitTest { @Test public void run_slp_test_vectors() { // Setup final Json testVectors = Json.parse(IoUtil.getResource("/slp_test_vectors.json")); final ScriptInflater scriptInflater = new ScriptInflater(); final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); int failCount = 0; // Action for (int i = 0; i < testVectors.length(); ++i) { final Json testVector = testVectors.get(i); final String message = testVector.getString("msg"); final String scriptHex = testVector.getString("script"); final Integer code = testVector.getInteger("code"); final Boolean expectedValidity = message.startsWith("OK"); final ByteArray script = ByteArray.fromHexString(scriptHex); final Script bitcoinScript = scriptInflater.fromBytes(script); final LockingScript lockingScript = LockingScript.castFrom(bitcoinScript); Exception exception = null; Boolean isValid = null; try { final SlpScript slpScript = slpScriptInflater.fromLockingScript(lockingScript); isValid = (slpScript != null); } catch (final Exception inflationException) { exception = inflationException; } Logger.info("Test: " + i + " " + (Util.areEqual(expectedValidity, isValid) ? "PASSED" : "FAILED") + " Expected: " + expectedValidity + " Result: " + isValid + " Message: " + message); if (exception != null) { Logger.info(exception); } if (! Util.areEqual(expectedValidity, isValid)) { failCount += 1; } } // Assert Assert.assertEquals(0, failCount); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/merkleroot/PartialMerkleTreeNode.java<|end_filename|> package com.softwareverde.bitcoin.block.merkleroot; import com.softwareverde.bitcoin.util.BitcoinUtil; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.Util; public class PartialMerkleTreeNode<T> { public interface Visitor<T> { void visit(PartialMerkleTreeNode<T> partialMerkleTreeNode); } public static int calculateMaxDepth(final int itemCount) { if (itemCount < 1) { return 1; } return (BitcoinUtil.log2(itemCount - 1) + 1); } public static <T> PartialMerkleTreeNode<T> newRootNode(final int itemCount) { final int maxDepth = PartialMerkleTreeNode.calculateMaxDepth(itemCount); return new PartialMerkleTreeNode<T>(0, maxDepth); } protected PartialMerkleTreeNode(final int depth, final int maxDepth) { this.depth = depth; this.maxDepth = maxDepth; if (depth > maxDepth) { throw new IndexOutOfBoundsException(); } } public final int depth; public final int maxDepth; public PartialMerkleTreeNode<T> parent = null; public PartialMerkleTreeNode<T> left = null; public PartialMerkleTreeNode<T> right = null; public Sha256Hash value = null; // Optional Properties... public boolean include = true; public T object = null; public PartialMerkleTreeNode newLeftNode() { this.left = new PartialMerkleTreeNode<T>(depth + 1, this.maxDepth); this.left.parent = this; return this.left; } public PartialMerkleTreeNode newRightNode() { this.right = new PartialMerkleTreeNode<T>(depth + 1, this.maxDepth); this.right.parent = this; return this.right; } public boolean isLeafNode() { return (this.depth == this.maxDepth); } public Sha256Hash getHash() { if (this.value != null) { return this.value; } final Sha256Hash leftHash = this.left.getHash(); final Sha256Hash rightHash = (this.right == null ? leftHash : this.right.getHash()); if (Util.areEqual(leftHash, rightHash)) { if (this.right != null) { return null; } // The left hash must not equal the right hash unless it was not provided... } return MerkleTreeNode.calculateNodeHash(leftHash, rightHash); } public void visit(final Visitor<T> visitor) { if (visitor != null) { visitor.visit(this); } final PartialMerkleTreeNode<T> left = this.left; if (left != null) { left.visit(visitor); } final PartialMerkleTreeNode<T> right = this.right; if (right != null) { right.visit(visitor); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/wallet/SeedPhraseGenerator.java<|end_filename|> package com.softwareverde.bitcoin.wallet; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.ListUtil; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.cryptography.secp256k1.key.PublicKey; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.logging.Logger; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.HexUtil; import com.softwareverde.util.Util; import com.softwareverde.util.bytearray.ByteArrayBuilder; import java.util.Comparator; public class SeedPhraseGenerator { protected static final Comparator<String> COMPARATOR = new Comparator<String>() { @Override public int compare(final String string0, final String string1) { return string0.compareToIgnoreCase(string1); } }; protected final List<String> _seedWords; protected String _toSeedPhrase(final ByteArray data) { final ByteArray checksum = _getChecksum(data); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(data); byteArrayBuilder.appendBytes(checksum.getBytes()); final ByteArray byteArray = MutableByteArray.wrap(byteArrayBuilder.build()); final StringBuilder stringBuilder = new StringBuilder(); int bitIndex = 0; int byteArrayBitLength = (byteArray.getByteCount() * 8 / 11) * 11; // only use length aligned to a multiple of 11 while (bitIndex < byteArrayBitLength) { int wordIndex = 0; for (int j = 10; (j >= 0) && (bitIndex < byteArrayBitLength); --j) { boolean bitIsSet = byteArray.getBit(bitIndex); if (bitIsSet) { wordIndex += (1 << j); } bitIndex += 1; } final String word = _seedWords.get(wordIndex); if (stringBuilder.length() != 0) { stringBuilder.append(" "); } stringBuilder.append(word); } return stringBuilder.toString(); } protected ByteArray _getChecksum(final ByteArray data) { // A checksum is generated by taking the first length / 32 bits of the SHA256 hash of the data final int checksumByteLength = (int) Math.ceil(data.getByteCount() / 32.0); final int checksumBitLength = (data.getByteCount() * 8) / 32; final ByteArray dataHash = HashUtil.sha256(data); final MutableByteArray checksum = MutableByteArray.wrap(dataHash.getBytes(0, checksumByteLength)); for (int i = checksumBitLength; i < (checksumByteLength * 8); ++i) { checksum.setBit(i, false); } return checksum; } protected ByteArray _fromSeedPhrase(final String expectedSeedPhrase) throws IllegalArgumentException { final String[] seedWords = expectedSeedPhrase.split(" "); final int byteArrayLength = (int) Math.ceil((seedWords.length * 11.0) / 8); final MutableByteArray byteArray = new MutableByteArray(byteArrayLength); int runningBitIndex = 0; for (final String seedWord : seedWords) { final int index = _seedWords.indexOf(seedWord.toLowerCase()); if (index < 0) { throw new IllegalArgumentException("Invalid seed word: " + seedWord); } final ByteArray seedWordIndexBytes = MutableByteArray.wrap(ByteUtil.integerToBytes(index)); final int seedWordIndexBitCount = seedWordIndexBytes.getByteCount() * 8; for (int i = 10; i >= 0; --i) { final boolean seedWordBitIsSet = seedWordIndexBytes.getBit(seedWordIndexBitCount - 1 - i); byteArray.setBit(runningBitIndex, seedWordBitIsSet); runningBitIndex++; } } final int checksumLength = (int) Math.ceil(byteArrayLength / 33.0); final int originalDataLength = byteArrayLength - checksumLength; final ByteArray originalData = MutableByteArray.wrap(byteArray.getBytes(0, originalDataLength)); final byte[] extractedChecksumBytes = byteArray.getBytes(originalDataLength, checksumLength); final ByteArray calculatedChecksum = _getChecksum(originalData); if (! Util.areEqual(calculatedChecksum.getBytes(), extractedChecksumBytes)) { throw new IllegalArgumentException("Invalid seed phrase checksum: expected " + HexUtil.toHexString(extractedChecksumBytes) + " but found " + calculatedChecksum.toString()); } return originalData; } /** * Initializes the SeedPhraseGenerator. * The list of seed words must be already sorted and should contain 2048 unique words. */ public SeedPhraseGenerator(final List<String> seedWords) { _seedWords = seedWords.asConst(); } public String toSeedPhrase(final PrivateKey privateKey) { return _toSeedPhrase(privateKey); } public String toSeedPhrase(final PublicKey publicKey) { return _toSeedPhrase(publicKey); } public String toSeedPhrase(final ByteArray data) { return _toSeedPhrase(data); } /** * <p>Returns a list of validation errors.</p> * * <p>If the seed phrase is valid, an empty list is returned.</p> * @param expectedSeedPhrase * @return */ public List<String> validateSeedPhrase(final String expectedSeedPhrase) { final MutableList<String> errors = new MutableList<String>(); final String[] seedWords = expectedSeedPhrase.split(" "); for (final String word : seedWords) { final int index = ListUtil.binarySearch(_seedWords, word, COMPARATOR); if (index < 0) { errors.add("Invalid word: " + word); } } if (errors.isEmpty()) { try { _fromSeedPhrase(expectedSeedPhrase); } catch (final Exception exception) { errors.add("Unable to parse seed phrase: " + exception.getMessage()); } } return errors; } public Boolean isSeedPhraseValid(final String seedPhrase) { try { _fromSeedPhrase(seedPhrase); return true; } catch (final Exception exception) { return false; } } public ByteArray fromSeedPhrase(final String seedPhrase) { try { return _fromSeedPhrase(seedPhrase); } catch (final Exception exception) { Logger.warn(exception); return null; } } public List<String> getSeedWords() { return _seedWords; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/version/acknowledge/BitcoinAcknowledgeVersionMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.version.acknowledge; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.util.bytearray.ByteArrayReader; public class BitcoinAcknowledgeVersionMessageInflater extends BitcoinProtocolMessageInflater { public BitcoinAcknowledgeVersionMessageInflater() { super(); } @Override public BitcoinAcknowledgeVersionMessage fromBytes(final byte[] bytes) { final BitcoinAcknowledgeVersionMessage synchronizeVersionMessage = new BitcoinAcknowledgeVersionMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.ACKNOWLEDGE_VERSION); if (protocolMessageHeader == null) { return null; } return synchronizeVersionMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/rpc/handler/QueryAddressHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.rpc.handler; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.indexer.BlockchainIndexerDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.TransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.rpc.NodeRpcHandler; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.logging.Logger; import com.softwareverde.util.SortUtil; import java.util.HashMap; public class QueryAddressHandler implements NodeRpcHandler.QueryAddressHandler { protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; public QueryAddressHandler(final FullNodeDatabaseManagerFactory databaseManagerFactory) { _databaseManagerFactory = databaseManagerFactory; } @Override public Long getBalance(final Address address) { try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BlockchainDatabaseManager blockchainDatabaseManager = databaseManager.getBlockchainDatabaseManager(); final BlockchainIndexerDatabaseManager blockchainIndexerDatabaseManager = databaseManager.getBlockchainIndexerDatabaseManager(); final BlockchainSegmentId headChainSegmentId = blockchainDatabaseManager.getHeadBlockchainSegmentId(); return blockchainIndexerDatabaseManager.getAddressBalance(headChainSegmentId, address); } catch (final Exception exception) { Logger.warn(exception); return null; } } @Override public List<Transaction> getAddressTransactions(final Address address) { try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BlockchainDatabaseManager blockchainDatabaseManager = databaseManager.getBlockchainDatabaseManager(); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final TransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); final BlockchainIndexerDatabaseManager blockchainIndexerDatabaseManager = databaseManager.getBlockchainIndexerDatabaseManager(); final BlockchainSegmentId headChainSegmentId = blockchainDatabaseManager.getHeadBlockchainSegmentId(); final List<TransactionId> transactionIds = blockchainIndexerDatabaseManager.getTransactionIds(headChainSegmentId, address, true); final MutableList<Transaction> pendingTransactions = new MutableList<Transaction>(0); final HashMap<Long, MutableList<Transaction>> transactionTimestamps = new HashMap<Long, MutableList<Transaction>>(transactionIds.getCount()); for (final TransactionId transactionId : transactionIds) { final BlockId blockId = transactionDatabaseManager.getBlockId(headChainSegmentId, transactionId); final Transaction transaction = transactionDatabaseManager.getTransaction(transactionId); if (blockId != null) { final Long transactionTimestamp = blockHeaderDatabaseManager.getBlockTimestamp(blockId); MutableList<Transaction> transactions = transactionTimestamps.get(transactionTimestamp); if (transactions == null) { transactions = new MutableList<Transaction>(1); transactionTimestamps.put(transactionTimestamp, transactions); } if (transaction != null) { transactions.add(transaction); } } else if (transaction != null) { pendingTransactions.add(transaction); } } final ImmutableListBuilder<Transaction> transactions = new ImmutableListBuilder<Transaction>(transactionIds.getCount()); { // Add the Transactions in descending order by timestamp... final MutableList<Long> timestamps = new MutableList<Long>(transactionTimestamps.keySet()); timestamps.sort(SortUtil.longComparator.reversed()); transactions.addAll(pendingTransactions); // Display unconfirmed transactions first... for (final Long timestamp : timestamps) { transactions.addAll(transactionTimestamps.get(timestamp)); } } return transactions.build(); } catch (final Exception exception) { Logger.warn(exception); return null; } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/fullnode/output/UnconfirmedTransactionOutputDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.output; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.query.BatchedInsertQuery; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.TransactionDatabaseManager; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.output.MutableTransactionOutput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.UnconfirmedTransactionOutputId; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.script.locking.ImmutableLockingScript; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.row.Row; import java.util.Map; public class UnconfirmedTransactionOutputDatabaseManager { protected final FullNodeDatabaseManager _databaseManager; protected UnconfirmedTransactionOutputId _insertUnconfirmedTransactionOutput(final TransactionId transactionId, final TransactionOutput transactionOutput) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final Integer index; { final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT COUNT(*) AS `index` FROM unconfirmed_transaction_outputs WHERE transaction_id = ?") .setParameter(transactionId) ); final Row row = rows.get(0); index = row.getInteger("index"); } final Long amount = transactionOutput.getAmount(); final LockingScript lockingScript = transactionOutput.getLockingScript(); final Long transactionOutputId = databaseConnection.executeSql( new Query("INSERT INTO unconfirmed_transaction_outputs (transaction_id, `index`, amount, locking_script) VALUES (?, ?, ?, ?)") .setParameter(transactionId) .setParameter(index) .setParameter(amount) .setParameter(lockingScript.getBytes()) ); return UnconfirmedTransactionOutputId.wrap(transactionOutputId); } public UnconfirmedTransactionOutputDatabaseManager(final FullNodeDatabaseManager databaseManager) { _databaseManager = databaseManager; } public UnconfirmedTransactionOutputId insertUnconfirmedTransactionOutput(final TransactionId transactionId, final TransactionOutput transactionOutput) throws DatabaseException { return _insertUnconfirmedTransactionOutput(transactionId, transactionOutput); } public List<UnconfirmedTransactionOutputId> insertUnconfirmedTransactionOutputs(final Map<Sha256Hash, TransactionId> transactionIds, final List<Transaction> transactions) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final BatchedInsertQuery batchedInsertQuery = new BatchedInsertQuery("INSERT INTO unconfirmed_transaction_outputs (transaction_id, `index`, amount, locking_script) VALUES (?, ?, ?, ?)"); for (final Transaction transaction : transactions) { final Sha256Hash transactionHash = transaction.getHash(); final TransactionId transactionId = transactionIds.get(transactionHash); int index = 0; for (final TransactionOutput transactionOutput : transaction.getTransactionOutputs()) { final Long amount = transactionOutput.getAmount(); final LockingScript lockingScript = transactionOutput.getLockingScript(); batchedInsertQuery.setParameter(transactionId); batchedInsertQuery.setParameter(index); batchedInsertQuery.setParameter(amount); batchedInsertQuery.setParameter(lockingScript.getBytes()); index += 1; } } final Long firstInsertId = databaseConnection.executeSql(batchedInsertQuery); final MutableList<UnconfirmedTransactionOutputId> transactionOutputIds = new MutableList<UnconfirmedTransactionOutputId>(transactions.getCount()); for (int i = 0; i < transactions.getCount(); ++i) { final UnconfirmedTransactionOutputId transactionOutputId = UnconfirmedTransactionOutputId.wrap(firstInsertId + i); transactionOutputIds.add(transactionOutputId); } return transactionOutputIds; } public UnconfirmedTransactionOutputId getUnconfirmedTransactionOutputId(final TransactionOutputIdentifier transactionOutputIdentifier) throws DatabaseException { final TransactionDatabaseManager transactionDatabaseManager = _databaseManager.getTransactionDatabaseManager(); final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionOutputIdentifier.getTransactionHash()); if (transactionId == null) { return null; } final Integer outputIndex = transactionOutputIdentifier.getOutputIndex(); final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id FROM unconfirmed_transaction_outputs WHERE transaction_id = ? AND `index` = ?") .setParameter(transactionId) .setParameter(outputIndex) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); return UnconfirmedTransactionOutputId.wrap(row.getLong("id")); } public Boolean isTransactionOutputSpent(final TransactionOutputIdentifier transactionOutputIdentifier) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT * FROM unconfirmed_transaction_inputs WHERE previous_transaction_hash = ? AND previous_transaction_output_index = ?") .setParameter(transactionOutputIdentifier.getTransactionHash()) .setParameter(transactionOutputIdentifier.getOutputIndex()) ); return (! rows.isEmpty()); } public TransactionOutput getUnconfirmedTransactionOutput(final UnconfirmedTransactionOutputId transactionOutputId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT * FROM unconfirmed_transaction_outputs WHERE id = ?") .setParameter(transactionOutputId) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); final Integer index = row.getInteger("index"); final Long amount = row.getLong("amount"); final LockingScript lockingScript = new ImmutableLockingScript(MutableByteArray.wrap(row.getBytes("locking_script"))); final MutableTransactionOutput transactionOutput = new MutableTransactionOutput(); transactionOutput.setIndex(index); transactionOutput.setAmount(amount); transactionOutput.setLockingScript(lockingScript); return transactionOutput; } public TransactionOutput getUnconfirmedTransactionOutput(final TransactionId transactionId, final Integer outputIndex) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT * FROM unconfirmed_transaction_outputs WHERE transaction_id = ? AND `index` = ?") .setParameter(transactionId) .setParameter(outputIndex) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); final Integer index = row.getInteger("index"); final Long amount = row.getLong("amount"); final LockingScript lockingScript = new ImmutableLockingScript(MutableByteArray.wrap(row.getBytes("locking_script"))); final MutableTransactionOutput transactionOutput = new MutableTransactionOutput(); transactionOutput.setIndex(index); transactionOutput.setAmount(amount); transactionOutput.setLockingScript(lockingScript); return transactionOutput; } public List<UnconfirmedTransactionOutputId> getUnconfirmedTransactionOutputIds(final TransactionId transactionId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id FROM unconfirmed_transaction_outputs WHERE transaction_id = ? ORDER BY `index` ASC") .setParameter(transactionId) ); final MutableList<UnconfirmedTransactionOutputId> transactionOutputIds = new MutableList<UnconfirmedTransactionOutputId>(rows.size()); for (final Row row : rows) { final UnconfirmedTransactionOutputId transactionOutputId = UnconfirmedTransactionOutputId.wrap(row.getLong("id")); transactionOutputIds.add(transactionOutputId); } return transactionOutputIds; } public void deleteTransactionOutput(final UnconfirmedTransactionOutputId unconfirmedTransactionOutputId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); databaseConnection.executeSql( new Query("DELETE FROM unconfirmed_transaction_outputs WHERE id = ?") .setParameter(unconfirmedTransactionOutputId) ); } public TransactionId getTransactionId(final UnconfirmedTransactionOutputId unconfirmedTransactionOutputId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id, transaction_id FROM unconfirmed_transaction_outputs WHERE id = ?") .setParameter(unconfirmedTransactionOutputId) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); return TransactionId.wrap(row.getLong("transaction_id")); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/manager/health/NodeHealthTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager.health; import com.softwareverde.network.p2p.node.NodeId; import com.softwareverde.test.time.FakeSystemTime; import org.junit.Assert; import org.junit.Test; public class NodeHealthTests { @Test public void should_have_full_health_initially() { // Setup final FakeSystemTime fakeTime = new FakeSystemTime(); final MutableNodeHealth nodeHealth = new MutableNodeHealth(NodeId.wrap(1L), fakeTime); // Action final Long nodeHealthValue = nodeHealth.getHealth(); // Assert Assert.assertEquals(MutableNodeHealth.FULL_HEALTH, nodeHealthValue); } @Test public void should_reduce_health_for_request() { // Setup final FakeSystemTime fakeTime = new FakeSystemTime(); final MutableNodeHealth nodeHealth = new MutableNodeHealth(NodeId.wrap(1L), fakeTime); final Long execTime = 250L; final Long restTime = 0L; final Long damage = (long) (execTime / MutableNodeHealth.REGEN_TO_REQUEST_TIME_RATIO); final Long expectedHealth = (MutableNodeHealth.FULL_HEALTH - damage + restTime); // Action final MutableNodeHealth.Request request = nodeHealth.onRequestSent(); fakeTime.advanceTimeInMilliseconds(execTime); nodeHealth.onResponseReceived(request); fakeTime.advanceTimeInMilliseconds(restTime); final Long nodeHealthValue = nodeHealth.getHealth(); // Assert Assert.assertEquals(expectedHealth, nodeHealthValue); } @Test public void should_heal_after_duration_of_recent_requests() { // Setup final FakeSystemTime fakeTime = new FakeSystemTime(); final MutableNodeHealth nodeHealth = new MutableNodeHealth(NodeId.wrap(1L), fakeTime); final Long execTime = 250L; final Long restTime = (long) (250L / MutableNodeHealth.REGEN_TO_REQUEST_TIME_RATIO); final Long expectedHealth = MutableNodeHealth.FULL_HEALTH; // Action final MutableNodeHealth.Request request = nodeHealth.onRequestSent(); fakeTime.advanceTimeInMilliseconds(execTime); nodeHealth.onResponseReceived(request); fakeTime.advanceTimeInMilliseconds(restTime); final Long nodeHealthValue = nodeHealth.getHealth(); // Assert Assert.assertEquals(expectedHealth, nodeHealthValue); } @Test public void should_heal_after_duration_of_recent_requests_2() { // Setup final FakeSystemTime fakeTime = new FakeSystemTime(); final MutableNodeHealth nodeHealth = new MutableNodeHealth(NodeId.wrap(1L), fakeTime); final Long execTime = 250L; final Long restTime = 200L; final Long damage = (long) (execTime / MutableNodeHealth.REGEN_TO_REQUEST_TIME_RATIO); final Long expectedHealth = (MutableNodeHealth.FULL_HEALTH - damage + restTime); // Action final MutableNodeHealth.Request request = nodeHealth.onRequestSent(); fakeTime.advanceTimeInMilliseconds(execTime); nodeHealth.onResponseReceived(request); fakeTime.advanceTimeInMilliseconds(restTime); final Long nodeHealthValue = nodeHealth.getHealth(); // Assert Assert.assertEquals(expectedHealth, nodeHealthValue); } @Test public void should_heal_after_duration_of_recent_requests_3() { // Setup final FakeSystemTime fakeTime = new FakeSystemTime(); final MutableNodeHealth nodeHealth = new MutableNodeHealth(NodeId.wrap(1L), fakeTime); final Long execCount = 2L; final Long execTime = 250L; final Long restTime = 200L; final Long damage = (long) (execTime / MutableNodeHealth.REGEN_TO_REQUEST_TIME_RATIO); final Long expectedHealth = (MutableNodeHealth.FULL_HEALTH - (damage * execCount) + restTime); MutableNodeHealth.Request request; // Action request = nodeHealth.onRequestSent(); // execCount = 1 fakeTime.advanceTimeInMilliseconds(execTime); nodeHealth.onResponseReceived(request); fakeTime.advanceTimeInMilliseconds(restTime); request = nodeHealth.onRequestSent(); // execCount = 2 fakeTime.advanceTimeInMilliseconds(execTime); nodeHealth.onResponseReceived(request); final Long nodeHealthValue = nodeHealth.getHealth(); // Assert Assert.assertEquals(expectedHealth, nodeHealthValue); } @Test public void should_not_heal_past_max_health() { // Setup final FakeSystemTime fakeTime = new FakeSystemTime(); final MutableNodeHealth nodeHealth = new MutableNodeHealth(NodeId.wrap(1L), fakeTime); // Action final MutableNodeHealth.Request request = nodeHealth.onRequestSent(); fakeTime.advanceTimeInMilliseconds(200L); nodeHealth.onResponseReceived(request); fakeTime.advanceTimeInMilliseconds(9999L); final Long nodeHealthValue = nodeHealth.getHealth(); // Assert Assert.assertEquals(MutableNodeHealth.FULL_HEALTH, nodeHealthValue); } @Test public void should_not_account_for_requests_that_are_too_old() { // Setup final FakeSystemTime fakeTime = new FakeSystemTime(); fakeTime.advanceTimeInMilliseconds(MutableNodeHealth.FULL_HEALTH); // Required to prevent minimumRequestTime from going negative... final MutableNodeHealth nodeHealth = new MutableNodeHealth(NodeId.wrap(1L), fakeTime); final Long requestTime = (MutableNodeHealth.FULL_HEALTH / 1024); // Action { // Drop the nodeHealth to zero... for (int i = 0; i < 2028; ++i) { // Only half of these are retained... final MutableNodeHealth.Request request = nodeHealth.onRequestSent(); fakeTime.advanceTimeInMilliseconds(requestTime); nodeHealth.onResponseReceived(request); } } Assert.assertEquals(0L, nodeHealth.getHealth().longValue()); fakeTime.advanceTimeInMilliseconds(requestTime); Assert.assertEquals(requestTime, nodeHealth.getHealth()); fakeTime.advanceTimeInMilliseconds(50L); // Restores an additional 50 hp... final Long nodeHealthValue = nodeHealth.getHealth(); // Assert Assert.assertEquals(requestTime + 50L, nodeHealthValue.longValue()); // Also assert the node eventually heals to full... fakeTime.advanceTimeInMilliseconds(MutableNodeHealth.FULL_HEALTH); Assert.assertEquals(MutableNodeHealth.FULL_HEALTH, nodeHealth.getHealth()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/opcode/OperationInflater.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.logging.Logger; import com.softwareverde.util.HexUtil; import com.softwareverde.util.bytearray.ByteArrayReader; public class OperationInflater { public Operation fromBytes(final ByteArrayReader byteArrayReader) { if (! byteArrayReader.hasBytes()) { return null; } final byte b = byteArrayReader.peakByte(); final Operation.Type type = Operation.Type.getType(b); if (type == null) { Logger.debug("Unknown Operation Type: 0x"+ HexUtil.toHexString(new byte[]{ b })); return null; } final Integer originalPosition = byteArrayReader.getPosition(); final Operation operation; switch (type) { case OP_PUSH: { operation = PushOperation.fromBytes(byteArrayReader); } break; case OP_DYNAMIC_VALUE: { operation = DynamicValueOperation.fromBytes(byteArrayReader); } break; case OP_CONTROL: { operation = ControlOperation.fromBytes(byteArrayReader); } break; case OP_STACK: { operation = StackOperation.fromBytes(byteArrayReader); } break; case OP_STRING: { operation = StringOperation.fromBytes(byteArrayReader); } break; case OP_COMPARISON: { operation = ComparisonOperation.fromBytes(byteArrayReader); } break; case OP_ARITHMETIC: { operation = ArithmeticOperation.fromBytes(byteArrayReader); } break; case OP_CRYPTOGRAPHIC: { operation = CryptographicOperation.fromBytes(byteArrayReader); } break; case OP_LOCK_TIME: { operation = LockTimeOperation.fromBytes(byteArrayReader); } break; case OP_NOTHING: { operation = NothingOperation.fromBytes(byteArrayReader); } break; case OP_INVALID: { operation = InvalidOperation.fromBytes(byteArrayReader, false); } break; case OP_BITWISE: { operation = BitwiseOperation.fromBytes(byteArrayReader); } break; default: { Logger.debug("Unimplemented Opcode Type: "+ type + " (0x" + HexUtil.toHexString(new byte[] { b }) + ")"); operation = null; } } if (operation != null) { return operation; } final boolean failIfPresent = (type == Operation.Type.OP_PUSH); byteArrayReader.setPosition(originalPosition); return InvalidOperation.fromBytes(byteArrayReader, failIfPresent); } public Operation fromBytes(final ByteArray byteArray) { return fromBytes(new ByteArrayReader(byteArray)); } } <|start_filename|>src/main/java/com/softwareverde/network/socket/JsonSocketServer.java<|end_filename|> package com.softwareverde.network.socket; import com.softwareverde.concurrent.pool.ThreadPool; import java.net.Socket; public class JsonSocketServer extends SocketServer<JsonSocket> { protected static class JsonSocketFactory implements SocketFactory<JsonSocket> { protected final ThreadPool _threadPool; public JsonSocketFactory(final ThreadPool threadPool) { _threadPool = threadPool; } @Override public JsonSocket newSocket(final Socket socket) { return new JsonSocket(socket, _threadPool); } } public interface SocketConnectedCallback extends SocketServer.SocketConnectedCallback<JsonSocket> { @Override void run(JsonSocket socketConnection); } public interface SocketDisconnectedCallback extends SocketServer.SocketDisconnectedCallback<JsonSocket> { @Override void run(JsonSocket socketConnection); } public JsonSocketServer(final Integer port, final ThreadPool threadPool) { super(port, new JsonSocketFactory(threadPool), threadPool); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/slp/QuerySlpStatusMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.slp; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.bytearray.Endian; public class QuerySlpStatusMessageInflater extends BitcoinProtocolMessageInflater { @Override public BitcoinProtocolMessage fromBytes(final byte[] bytes) { final QuerySlpStatusMessage queryAddressBlocksMessage = new QuerySlpStatusMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.QUERY_SLP_STATUS); if (protocolMessageHeader == null) { return null; } final int addressCount = byteArrayReader.readVariableSizedInteger().intValue(); if ( (addressCount < 0) || (addressCount >= QuerySlpStatusMessage.MAX_HASH_COUNT) ) { return null; } final Integer bytesRequired = (Sha256Hash.BYTE_COUNT * addressCount); if (byteArrayReader.remainingByteCount() < bytesRequired) { return null; } for (int i = 0; i < addressCount; ++i) { final Sha256Hash hash = MutableSha256Hash.wrap(byteArrayReader.readBytes(Sha256Hash.BYTE_COUNT, Endian.LITTLE)); queryAddressBlocksMessage.addHash(hash); } if (byteArrayReader.didOverflow()) { return null; } return queryAddressBlocksMessage; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/block/BlockTests.java<|end_filename|> package com.softwareverde.bitcoin.block; import com.softwareverde.bitcoin.test.BlockData; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.util.HexUtil; import org.junit.Assert; import org.junit.Test; public class BlockTests { @Test public void block_should_be_invalid_if_merkle_mismatch() { // Setup final BlockInflater blockInflater = new BlockInflater(); final BlockDeflater blockDeflater = new BlockDeflater(); final Transaction transaction; { final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(BlockData.MainChain.BLOCK_2)); transaction = block.getCoinbaseTransaction(); } final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(BlockData.MainChain.BLOCK_1)); Assert.assertTrue(block.isValid()); final MutableBlock mutableBlock = new MutableBlock(block, block.getTransactions()); Assert.assertTrue(mutableBlock.isValid()); // Action mutableBlock.addTransaction(transaction); final ByteArray blockBytes = blockDeflater.toBytes(mutableBlock); final Block reinflatedModifiedBlock = blockInflater.fromBytes(blockBytes); // Assert Assert.assertFalse(mutableBlock.isValid()); Assert.assertFalse(mutableBlock.asConst().isValid()); Assert.assertFalse(reinflatedModifiedBlock.isValid()); Assert.assertFalse(reinflatedModifiedBlock.asConst().isValid()); } } <|start_filename|>src/main/java/com/softwareverde/network/ip/Ip.java<|end_filename|> package com.softwareverde.network.ip; import com.softwareverde.constable.Const; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; public interface Ip extends Const { static Ip fromSocket(final Socket socket) { final SocketAddress socketAddress = socket.getRemoteSocketAddress(); if (socketAddress instanceof InetSocketAddress) { final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress(); if (inetAddress instanceof Inet4Address) { final Inet4Address inet4Address = (Inet4Address) inetAddress; return Ipv4.fromBytes(inet4Address.getAddress()); } else if (inetAddress instanceof Inet6Address) { final Inet6Address inet6Address = (Inet6Address) inetAddress; return Ipv6.fromBytes(inet6Address.getAddress()); } } return null; } static Ip fromString(final String string) { if (string == null) { return null; } if (string.matches("[^0-9:.]")) { return null; } final boolean isIpv4 = string.matches("^[0-9]+.[0-9]+.[0-9]+.[0-9]+$"); if (isIpv4) { return Ipv4.parse(string); } else { return Ipv6.parse(string); } } static Ip fromHostName(final String hostName) { try { final InetAddress inetAddress = InetAddress.getByName(hostName); if (inetAddress instanceof Inet4Address) { final Inet4Address inet4Address = (Inet4Address) inetAddress; return Ipv4.fromBytes(inet4Address.getAddress()); } else if (inetAddress instanceof Inet6Address) { final Inet6Address inet6Address = (Inet6Address) inetAddress; return Ipv6.fromBytes(inet6Address.getAddress()); } } catch (final UnknownHostException exception) { } return null; } static List<Ip> allFromHostName(final String hostName) { try { final InetAddress[] inetAddresses = InetAddress.getAllByName(hostName); final MutableList<Ip> ipAddresses = new MutableList<Ip>(inetAddresses.length); for (final InetAddress inetAddress : inetAddresses) { final Ip ip; if (inetAddress instanceof Inet4Address) { final Inet4Address inet4Address = (Inet4Address) inetAddress; ip = Ipv4.fromBytes(inet4Address.getAddress()); } else if (inetAddress instanceof Inet6Address) { final Inet6Address inet6Address = (Inet6Address) inetAddress; ip = Ipv6.fromBytes(inet6Address.getAddress()); } else { ip = null; } if (ip != null) { ipAddresses.add(ip); } } return ipAddresses; } catch (final UnknownHostException exception) { } return null; } static Ip fromStringOrHost(final String ipOrHostName) { final Ip ipFromString = Ip.fromString(ipOrHostName); if (ipFromString != null) { return ipFromString; } final Ip ipFromHost = Ip.fromHostName(ipOrHostName); if (ipFromHost != null) { return ipFromHost; } return null; } ByteArray getBytes(); @Override String toString(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/validator/thread/TransactionValidationTaskHandler.java<|end_filename|> package com.softwareverde.bitcoin.block.validator.thread; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.validator.TransactionValidationResult; import com.softwareverde.bitcoin.transaction.validator.TransactionValidator; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public class TransactionValidationTaskHandler implements TaskHandler<Transaction, TransactionValidationTaskHandler.TransactionValidationTaskResult> { public static class TransactionValidationTaskResult { public static TransactionValidationTaskResult invalid(final Transaction invalidTransaction, final TransactionValidationResult transactionValidationResult) { final Map<Sha256Hash, TransactionValidationResult> invalidTransactions = new HashMap<Sha256Hash, TransactionValidationResult>(0); invalidTransactions.put(invalidTransaction.getHash(), transactionValidationResult); return new TransactionValidationTaskResult(false, invalidTransactions, null); } public static TransactionValidationTaskResult invalid(final Map<Transaction, TransactionValidationResult> invalidTransactions) { final Map<Sha256Hash, TransactionValidationResult> invalidTransactionsMap = new HashMap<Sha256Hash, TransactionValidationResult>(0); for (final Transaction transaction : invalidTransactions.keySet()) { final TransactionValidationResult transactionValidationResult = invalidTransactions.get(transaction); invalidTransactionsMap.put(transaction.getHash(), transactionValidationResult); } return new TransactionValidationTaskResult(false, invalidTransactionsMap, null); } public static TransactionValidationTaskResult valid(final Integer signatureOperationCount) { return new TransactionValidationTaskResult(true, null, signatureOperationCount); } protected final Boolean _isValid; protected final Map<Sha256Hash, TransactionValidationResult> _invalidTransactions; protected final Integer _signatureOperationCount; protected TransactionValidationTaskResult(final Boolean isValid, final Map<Sha256Hash, TransactionValidationResult> invalidTransactions, final Integer signatureOperationCount) { _isValid = isValid; _invalidTransactions = invalidTransactions; _signatureOperationCount = signatureOperationCount; } public Boolean isValid() { return _isValid; } public List<Sha256Hash> getInvalidTransactions() { return new ImmutableList<Sha256Hash>(_invalidTransactions.keySet()); } public TransactionValidationResult getTransactionValidationResult(final Sha256Hash transactionHash) { return _invalidTransactions.get(transactionHash); } public Integer getSignatureOperationCount() { return _signatureOperationCount; } } protected final Long _blockHeight; protected final HashMap<Transaction, TransactionValidationResult> _invalidTransactions = new HashMap<Transaction, TransactionValidationResult>(0); protected final AtomicInteger _signatureOperationCount = new AtomicInteger(0); protected final TransactionValidator _transactionValidator; public TransactionValidationTaskHandler(final Long blockHeight, final TransactionValidator transactionValidator) { _blockHeight = blockHeight; _transactionValidator = transactionValidator; } @Override public void init() { } @Override public void executeTask(final Transaction transaction) { if (! _invalidTransactions.isEmpty()) { return; } final TransactionValidationResult transactionValidationResult; { TransactionValidationResult validationResult; try { validationResult = _transactionValidator.validateTransaction(_blockHeight, transaction); } catch (final Exception exception) { validationResult = TransactionValidationResult.invalid("An internal error occurred."); Logger.debug(exception); } transactionValidationResult = validationResult; } if (transactionValidationResult.isValid) { final Integer signatureOperationCount = transactionValidationResult.getSignatureOperationCount(); _signatureOperationCount.addAndGet(signatureOperationCount); } else { _invalidTransactions.put(transaction, transactionValidationResult); } } @Override public TransactionValidationTaskResult getResult() { if (! _invalidTransactions.isEmpty()) { return TransactionValidationTaskResult.invalid(_invalidTransactions); } final Integer signatureOperationCount = _signatureOperationCount.get(); return TransactionValidationTaskResult.valid(signatureOperationCount); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/Transaction.java<|end_filename|> package com.softwareverde.bitcoin.transaction; import com.softwareverde.bitcoin.block.merkleroot.Hashable; import com.softwareverde.bitcoin.server.main.BitcoinConstants; import com.softwareverde.bitcoin.transaction.coinbase.CoinbaseTransaction; import com.softwareverde.bitcoin.transaction.input.CoinbaseTransactionInputInflater; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.locktime.LockTime; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.opcode.Operation; import com.softwareverde.bitcoin.transaction.script.opcode.PushOperation; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptInflater; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.bloomfilter.BloomFilter; import com.softwareverde.constable.Constable; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.json.Jsonable; public interface Transaction extends Hashable, Constable<ConstTransaction>, Jsonable { Long VERSION = BitcoinConstants.getTransactionVersion(); Long SATOSHIS_PER_BITCOIN = 100_000_000L; static Boolean isCoinbaseTransaction(final Transaction transaction) { if (transaction == null) { return false; } final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); if (transactionInputs.getCount() != 1) { return false; } final TransactionInput transactionInput = transactionInputs.get(0); final boolean isCoinbaseInput = CoinbaseTransactionInputInflater.isCoinbaseInput(transactionInput); if (! isCoinbaseInput) { return false; } return true; } static Boolean isSlpTransaction(final Transaction transaction) { if (transaction == null) { return false; } final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final TransactionOutput transactionOutput = transactionOutputs.get(0); return SlpScriptInflater.matchesSlpFormat(transactionOutput.getLockingScript()); } /** * Returns true if transaction matches matches _bloomFilter or if _bloomFilter has not been set. */ static Boolean matchesFilter(final Transaction transaction, final BloomFilter bloomFilter) { if (bloomFilter == null) { return true; } // From BIP37: https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki // To determine if a transaction matches the filter, the following algorithm is used. Once a match is found the algorithm aborts. final Sha256Hash transactionHash = transaction.getHash(); if (bloomFilter.containsItem(transactionHash)) { return true; } // 1. Test the hash of the transaction itself. int transactionOutputIndex = 0; for (final TransactionOutput transactionOutput : transaction.getTransactionOutputs()) { // 2. For each output, test each data element of the output script. This means each hash and key in the output script is tested independently. final LockingScript lockingScript = transactionOutput.getLockingScript(); for (final Operation operation : lockingScript.getOperations()) { if (operation.getType() != PushOperation.TYPE) { continue; } final ByteArray value = ((PushOperation) operation).getValue(); if (bloomFilter.containsItem(value)) { return true; } } transactionOutputIndex += 1; } for (final TransactionInput transactionInput : transaction.getTransactionInputs()) { // 3. For each input, test the serialized COutPoint structure. final ByteArray cOutpoint; { // NOTE: "COutPoint" is a class in the reference client that follows the same serialization process as the a TransactionInput's prevout format (TxHash | OutputIndex, both as LittleEndian)... final Sha256Hash previousOutputTransactionHash = transactionInput.getPreviousOutputTransactionHash(); final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(previousOutputTransactionHash, transactionInput.getPreviousOutputIndex()); cOutpoint = transactionOutputIdentifier.toBytes(); } if (bloomFilter.containsItem(cOutpoint)) { return true; } // 4. For each input, test each data element of the input script. final UnlockingScript unlockingScript = transactionInput.getUnlockingScript(); for (final Operation operation : unlockingScript.getOperations()) { if (operation.getType() != PushOperation.TYPE) { continue; } final ByteArray value = ((PushOperation) operation).getValue(); if (bloomFilter.containsItem(value)) { return true; } } } return false; } Long getVersion(); List<TransactionInput> getTransactionInputs(); List<TransactionOutput> getTransactionOutputs(); LockTime getLockTime(); Long getTotalOutputValue(); Boolean matches(BloomFilter bloomFilter); CoinbaseTransaction asCoinbase(); Integer getByteCount(); @Override ConstTransaction asConst(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/locktime/LockTime.java<|end_filename|> package com.softwareverde.bitcoin.transaction.locktime; import com.softwareverde.constable.Constable; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.json.Jsonable; public interface LockTime extends Constable<ImmutableLockTime>, Jsonable { Long MAX_BLOCK_HEIGHT_VALUE = 500_000_000L; // NOTE: This value is exclusive; therefore 500000000 is a timestamp value. Long MAX_TIMESTAMP_VALUE = 0xFFFFFFFFL; Long MIN_TIMESTAMP_VALUE = 0x00000000L; LockTime MAX_BLOCK_HEIGHT = new ImmutableLockTime(MAX_BLOCK_HEIGHT_VALUE); LockTime MAX_TIMESTAMP = new ImmutableLockTime(LockTime.MAX_TIMESTAMP_VALUE); LockTime MIN_TIMESTAMP = new ImmutableLockTime(LockTime.MIN_TIMESTAMP_VALUE); LockTimeType getType(); Long getValue(); ByteArray getBytes(); @Override ImmutableLockTime asConst(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/block/BlockRelationship.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.block; public enum BlockRelationship { DESCENDANT, ANCESTOR, ANY } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/TransactionTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.test.util.TestUtil; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.HexUtil; import com.softwareverde.util.IoUtil; import org.junit.Assert; import org.junit.Test; public class TransactionTests { @Test public void should_calculate_transaction_hash_0() { // Setup final TransactionDeflater transactionDeflater = new TransactionDeflater(); final byte[] expectedTransactionBytes = HexUtil.hexStringToByteArray("01000000010000000000000000000000000000000000000000000000000000000000000000FFFFFFFF0704FFFF001D0134FFFFFFFF0100F2052A0100000043410411DB93E1DCDB8A016B49840F8C53BC1EB68A382E97B1482ECAD7B148A6909A5CB2E0EADDFB84CCF9744464F82E160BFA9B8B64F9D4C03F999B8643F656B412A3AC00000000"); final byte[] expectedTransactionHash = HexUtil.hexStringToByteArray("0437CD7F8525CEED2324359C2D0BA26006D92D856A9C20FA0241106EE5A597C9"); final TransactionInflater transactionInflater = new TransactionInflater(); final Transaction transaction = transactionInflater.fromBytes(expectedTransactionBytes); // Action final byte[] transactionBytes = transactionDeflater.toBytes(transaction).getBytes(); final Sha256Hash transactionHash = transaction.getHash(); // Assert TestUtil.assertEqual(expectedTransactionBytes, transactionBytes); TestUtil.assertEqual(expectedTransactionHash, transactionHash.getBytes()); } @Test public void should_calculate_transaction_hash_1() { // Setup final TransactionDeflater transactionDeflater = new TransactionDeflater(); final byte[] expectedTransactionBytes = HexUtil.hexStringToByteArray("0100000001C997A5E56E104102FA209C6A852DD90660A20B2D9C352423EDCE25857FCD3704000000004847304402204E45E16932B8AF514961A1D3A1A25FDF3F4F7732E9D624C6C61548AB5FB8CD410220181522EC8ECA07DE4860A4ACDD12909D831CC56CBBAC4622082221A8768D1D0901FFFFFFFF0200CA9A3B00000000434104AE1A62FE09C5F51B13905F07F06B99A2F7159B2225F374CD378D71302FA28414E7AAB37397F554A7DF5F142C21C1B7303B8A0626F1BADED5C72A704F7E6CD84CAC00286BEE0000000043410411DB93E1DCDB8A016B49840F8C53BC1EB68A382E97B1482ECAD7B148A6909A5CB2E0EADDFB84CCF9744464F82E160BFA9B8B64F9D4C03F999B8643F656B412A3AC00000000"); final byte[] expectedTransactionHash = HexUtil.hexStringToByteArray("F4184FC596403B9D638783CF57ADFE4C75C605F6356FBC91338530E9831E9E16"); final TransactionInflater transactionInflater = new TransactionInflater(); final Transaction transaction = transactionInflater.fromBytes(expectedTransactionBytes); // Action final byte[] transactionBytes = transactionDeflater.toBytes(transaction).getBytes(); final Sha256Hash transactionHash = transaction.getHash(); // Assert TestUtil.assertEqual(expectedTransactionBytes, transactionBytes); TestUtil.assertEqual(expectedTransactionHash, transactionHash.getBytes()); } @Test public void bug_0001_should_calculate_hash_for_block_29664() { // Setup final BlockInflater blockInflater = new BlockInflater(); final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(IoUtil.getResource("/blocks/00000000AFE94C578B4DC327AA64E1203283C5FD5F152CE886341766298CF523"))); final Transaction transaction = block.getTransactions().get(1); final Sha256Hash expectedTransactionHash = Sha256Hash.fromHexString("3A5769FB2126D870ADED5FCACED3BC49FA9768436101895931ADB5246E41E957"); final int expectedInputCount = 320; final int expectedOutputCount = 1; // Action final Sha256Hash transactionHash = transaction.getHash(); // Assert Assert.assertEquals(expectedInputCount, transaction.getTransactionInputs().getCount()); Assert.assertEquals(expectedOutputCount, transaction.getTransactionOutputs().getCount()); Assert.assertEquals(transactionHash, expectedTransactionHash); } } <|start_filename|>src/main/java/com/softwareverde/concurrent/pool/ThreadPool.java<|end_filename|> package com.softwareverde.concurrent.pool; public interface ThreadPool { void execute(Runnable runnable); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/thin/AssembleThinBlockResult.java<|end_filename|> package com.softwareverde.bitcoin.block.thin; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import java.util.Map; public class AssembleThinBlockResult { private BlockHeader _blockHeader; private List<Sha256Hash> _transactionHashes; private Map<Sha256Hash, Transaction> _mappedTransactions; protected AssembleThinBlockResult(final Block block, final List<Sha256Hash> missingTransactions) { this.block = block; this.missingTransactions = missingTransactions.asConst(); } protected void allowReassembly(final BlockHeader blockHeader, final List<Sha256Hash> transactionHashes, final Map<Sha256Hash, Transaction> mappedTransactions) { _blockHeader = blockHeader; _transactionHashes = transactionHashes; _mappedTransactions = mappedTransactions; } protected BlockHeader getBlockHeader() { return _blockHeader; } protected List<Sha256Hash> getTransactionHashes() { return _transactionHashes; } protected Map<Sha256Hash, Transaction> getMappedTransactions() { return _mappedTransactions; } public final Block block; public final List<Sha256Hash> missingTransactions; public Boolean wasSuccessful() { return (this.block != null); } public Boolean canBeReassembled() { return ( (_blockHeader != null) && (_transactionHashes != null) && (_mappedTransactions != null) ); } } <|start_filename|>explorer/www/css/main.css<|end_filename|> #main .address { } .button { border-radius: 1em; padding: 0.5em; border: solid 2px #262626; background-color: #F7931D; display: inline-block; cursor: pointer; color: #262626; } .button:hover { background-color: #FD9A26; border-color: #363636; } .documentation { margin: 1em; } #announcements { margin: auto; text-align: center; } .recent-blocks, .recent-transactions { display: inline-block; margin: 2em; box-sizing: border-box; /* width: calc(50% - 6em); */ border: solid 1px #AAAAAA; vertical-align: top; padding: 0.5em; padding-bottom: 0.75em; padding-right: 0.75em; min-height: 21em; min-width: 36em; background: #FFFFFF; color: #262626; } .recent-blocks::before, .recent-transactions::before { display: block; background-color: #FFFFFF; color: #8e8e8e; font-weight: bold; text-align: left; padding: 0.25em; margin: -0.5em; margin-right: -0.75em; margin-bottom: 0em; padding: 1em; background-color: #F3F3F3; border-bottom: solid 1px #dedede; } .recent-blocks::before { content: 'Recent Blocks'; } .recent-transactions::before { content: 'Recent Transactions'; } .recent-transactions .transaction::before, .recent-transactions .transaction .hash span.value::before, .recent-blocks .block::before { content: '' !important; display: none !important; } .recent-transactions .transaction, .recent-blocks .block { background-color: unset; margin: 0 !important; padding: 0 !important; border: none; } .recent-blocks .block .block-header > div, .recent-blocks .block .transactions { display: none; } .recent-blocks .block .block-header > div.hash { display: block; width: auto; background-color: unset; border: none; margin: 0; padding: 0; padding-left: 1.25em; } .recent-blocks .block .block-header > div.hash label { display: none; } .recent-blocks .block .block-header div .value { margin-top: 0; } .recent-transactions .transaction > div > div { display: none; } .recent-transactions .transaction > div > div.hash { display: block; } .recent-transactions .transaction .io { display: none; } .centered-content { text-align: center; } .bounded-content { display: inline-block; } .post-transaction { margin: auto; box-sizing: border-box; border: solid 1px #AAAAAA; vertical-align: top; padding: 0.5em; min-width: 36em; background: #FFFFFF; color: #262626; text-align: center; display: inline-flex; align-items: stretch; flex-direction: row; align-content: stretch; margin: 2em; width: calc(100% - 4em); } .post-transaction #post-transaction-button { background-color: #F99200; color: #FFFFFF; font-size: 150%; font-weight: bold; padding: 0.5em; margin: 0; box-sizing: border-box; flex-grow: 0; cursor: pointer; } .post-transaction #post-transaction-input { border: solid 1px #AAAAAA; background-color: #FFFFFF; font-family: monospace; text-align: left; font-size: 150%; padding: 0.5em; border-left: 0; box-sizing: border-box; flex-grow: 1; } @media only screen and (max-width: 1300px) { .post-transaction { width: 50%; } } @media only screen and (max-width: 1100px) { .bounded-content { display: block; } .post-transaction { width: unset; } } @media only screen and (max-width: 960px) { } @media only screen and (max-width: 800px) { } @media only screen and (max-width: 700px) { } @media only screen and (max-width: 600px) { .recent-blocks, .recent-transactions { min-width: unset; width: auto; margin: 0.5em; overflow-x: scroll; display: block; } .post-transaction { width: calc(100% - 1em); margin: 0.5em; flex-direction: column-reverse; min-width: unset; } .post-transaction #post-transaction-input { margin-bottom: 0.5em; border-left: inherit; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/HF20171113.java<|end_filename|> package com.softwareverde.bitcoin.bip; import com.softwareverde.util.Util; public class HF20171113 { public static final Long ACTIVATION_BLOCK_HEIGHT = 504032L; // Bitcoin Cash: 2017-11-07 Hard Fork: https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/nov-13-hardfork-spec.md // BIP 146: https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki public static Boolean isEnabled(final Long blockHeight) { return (Util.coalesce(blockHeight, Long.MAX_VALUE) >= ACTIVATION_BLOCK_HEIGHT); } protected HF20171113() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/node/feature/NewBlocksViaHeadersMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.node.feature; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; public class NewBlocksViaHeadersMessage extends BitcoinProtocolMessage { public NewBlocksViaHeadersMessage() { super(MessageType.ENABLE_NEW_BLOCKS_VIA_HEADERS); } @Override protected ByteArray _getPayload() { return new MutableByteArray(0); } @Override protected Integer _getPayloadByteCount() { return 0; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/v1/get/GetBlockchainSegmentsHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.v1.get; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.bitcoin.server.module.explorer.api.endpoint.BlockchainApi; import com.softwareverde.bitcoin.server.module.node.rpc.NodeJsonRpcConnection; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.http.server.servlet.routed.RequestHandler; import com.softwareverde.json.Json; import java.util.Map; public class GetBlockchainSegmentsHandler implements RequestHandler<Environment> { /** * GET BLOCKCHAIN METADATA * Requires GET: * Requires POST: */ @Override public Response handleRequest(final Request request, final Environment environment, final Map<String, String> parameters) throws Exception { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); try (final NodeJsonRpcConnection nodeJsonRpcConnection = environment.getNodeJsonRpcConnection()) { if (nodeJsonRpcConnection == null) { final BlockchainApi.BlockchainResult result = new BlockchainApi.BlockchainResult(); result.setWasSuccess(false); result.setErrorMessage("Unable to connect to node."); return new JsonResponse(Response.Codes.SERVER_ERROR, result); } final Json blockchainJson; { final Json rpcResponseJson = nodeJsonRpcConnection.getBlockchainMetadata(); if (rpcResponseJson == null) { return new JsonResponse(Response.Codes.SERVER_ERROR, new ApiResult(false, "Request timed out.")); } if (! rpcResponseJson.getBoolean("wasSuccess")) { final String errorMessage = rpcResponseJson.getString("errorMessage"); return new JsonResponse(Response.Codes.SERVER_ERROR, new ApiResult(false, errorMessage)); } blockchainJson = rpcResponseJson.get("blockchainMetadata"); } final BlockchainApi.BlockchainResult blockchainResult = new BlockchainApi.BlockchainResult(); blockchainResult.setWasSuccess(true); blockchainResult.setBlockchainMetadataJson(blockchainJson); return new JsonResponse(Response.Codes.OK, blockchainResult); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/ProcessBlockResult.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node; import com.softwareverde.bitcoin.block.Block; public class ProcessBlockResult { public static ProcessBlockResult invalid(final Block block, final Long blockHeight, final String errorMessage) { return new ProcessBlockResult(block, blockHeight, false, false, null); } public static ProcessBlockResult valid(final Block block, final Long blockHeight, final Boolean bestBlockchainHasChanged) { return new ProcessBlockResult(block, blockHeight, true, bestBlockchainHasChanged, null); } public final Block block; public final Long blockHeight; public final Boolean isValid; public final Boolean bestBlockchainHasChanged; protected final String errorMessage; protected ProcessBlockResult(final Block block, final Long blockHeight, final Boolean isValid, final Boolean bestBlockchainHasChanged, final String errorMessage) { this.block = block; this.blockHeight = blockHeight; this.isValid = isValid; this.bestBlockchainHasChanged = bestBlockchainHasChanged; this.errorMessage = errorMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/BlockId.java<|end_filename|> package com.softwareverde.bitcoin.block; import com.softwareverde.util.type.identifier.Identifier; public class BlockId extends Identifier { public static BlockId wrap(final Long value) { if (value == null) { return null; } return new BlockId(value); } protected BlockId(final Long value) { super(value); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/task/RelayedStratumMineBlockTaskBuilder.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.task; import com.softwareverde.constable.list.List; /** * Extended StratumMineBlockTaskBuilder interface for proxying stratum functions from external servers (e.g. ViaBTC). */ public interface RelayedStratumMineBlockTaskBuilder extends StratumMineBlockTaskBuilder { void setBlockVersion(String stratumBlockVersion); void setPreviousBlockHash(String stratumPreviousBlockHash); void setExtraNonce(String stratumExtraNonce); void setDifficulty(String stratumDifficulty); void setMerkleTreeBranches(List<String> merkleTreeBranches); // ViaBTC provides the merkleTreeBranches as little-endian byte strings. void setCoinbaseTransaction(String stratumCoinbaseTransactionHead, String stratumCoinbaseTransactionTail); } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/script/ScriptTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script; import com.softwareverde.bitcoin.test.util.TestUtil; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.script.opcode.Opcode; import com.softwareverde.bitcoin.transaction.script.opcode.Operation; import com.softwareverde.bitcoin.transaction.script.opcode.PushOperation; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.constable.list.List; import com.softwareverde.util.HexUtil; import org.junit.Assert; import org.junit.Test; public class ScriptTests { @Test public void should_transform_mutable_unlocking_script_to_immutable_unlocking_script() { // Setup final TransactionInflater transactionInflater = new TransactionInflater(); final Transaction transaction = transactionInflater.fromBytes(HexUtil.hexStringToByteArray("01000000024DE8B0C4C2582DB95FA6B3567A989B664484C7AD6672C85A3DA413773E63FDB8000000006B48304502205B282FBC9B064F3BC823A23EDCC0048CBB174754E7AA742E3C9F483EBE02911C022100E4B0B3A117D36CAB5A67404DDDBF43DB7BEA3C1530E0FE128EBC15621BD69A3B0121035AA98D5F77CD9A2D88710E6FC66212AFF820026F0DAD8F32D1F7CE87457DDE50FFFFFFFF4DE8B0C4C2582DB95FA6B3567A989B664484C7AD6672C85A3DA413773E63FDB8010000006F004730440220276D6DAD3DEFA37B5F81ADD3992D510D2F44A317FD85E04F93A1E2DAEA64660202200F862A0DA684249322CEB8ED842FB8C859C0CB94C81E1C5308B4868157A428EE01AB51210232ABDC893E7F0631364D7FD01CB33D24DA45329A00357B3A7886211AB414D55A51AEFFFFFFFF02E0FD1C00000000001976A914380CB3C594DE4E7E9B8E18DB182987BEBB5A4F7088ACC0C62D000000000017142A9BC5447D664C1D0141392A842D23DBA45C4F13B17500000000")); final TransactionInput transactionInput = transaction.getTransactionInputs().get(1); final MutableScript mutableUnlockingScript = new MutableScript(transactionInput.getUnlockingScript()); mutableUnlockingScript.subScript(3); { // Sanity Checking... final List<Operation> operations = mutableUnlockingScript.getOperations(); // (0x51 OP_PUSH-PUSH_VALUE Value: 01000000) Assert.assertEquals(1, ((PushOperation) operations.get(0)).getValue().asInteger().intValue()); // (0x21 OP_PUSH-PUSH_DATA Value: 0232ABDC893E7F0631364D7FD01CB33D24DA45329A00357B3A7886211AB414D55A) TestUtil.assertEqual(HexUtil.hexStringToByteArray("0232ABDC893E7F0631364D7FD01CB33D24DA45329A00357B3A7886211AB414D55A"), ((PushOperation) operations.get(1)).getValue().getBytes()); // (0x51 OP_PUSH-PUSH_VALUE Value: 01000000) Assert.assertEquals(1, ((PushOperation) operations.get(2)).getValue().asInteger().intValue()); // (0xAE OP_CRYPTOGRAPHIC-CHECK_MULTISIGNATURE) Assert.assertTrue(Opcode.CHECK_MULTISIGNATURE.matchesByte(operations.get(3).getOpcodeByte())); } // Action final UnlockingScript unlockingScript = UnlockingScript.castFrom(mutableUnlockingScript); // Assert final List<Operation> operations = unlockingScript.getOperations(); Assert.assertEquals(4, operations.getCount()); // (0x51 OP_PUSH-PUSH_VALUE Value: 01000000) Assert.assertEquals(1, ((PushOperation) operations.get(0)).getValue().asInteger().intValue()); // (0x21 OP_PUSH-PUSH_DATA Value: 0232ABDC893E7F0631364D7FD01CB33D24DA45329A00357B3A7886211AB414D55A) TestUtil.assertEqual(HexUtil.hexStringToByteArray("0232ABDC893E7F0631364D7FD01CB33D24DA45329A00357B3A7886211AB414D55A"), ((PushOperation) operations.get(1)).getValue().getBytes()); // (0x51 OP_PUSH-PUSH_VALUE Value: 01000000) Assert.assertEquals(1, ((PushOperation) operations.get(2)).getValue().asInteger().intValue()); // (0xAE OP_CRYPTOGRAPHIC-CHECK_MULTISIGNATURE) Assert.assertTrue(Opcode.CHECK_MULTISIGNATURE.matchesByte(operations.get(3).getOpcodeByte())); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/request/header/RequestBlockHeadersMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.request.header; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.bytearray.Endian; public class RequestBlockHeadersMessageInflater extends BitcoinProtocolMessageInflater { @Override public RequestBlockHeadersMessage fromBytes(final byte[] bytes) { final int blockHeaderHashByteCount = 32; final RequestBlockHeadersMessage requestBlockHeadersMessage = new RequestBlockHeadersMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.REQUEST_BLOCK_HEADERS); if (protocolMessageHeader == null) { return null; } requestBlockHeadersMessage._version = byteArrayReader.readInteger(4, Endian.LITTLE); final int blockHeaderCount = byteArrayReader.readVariableSizedInteger().intValue(); if (blockHeaderCount > RequestBlockHeadersMessage.MAX_BLOCK_HEADER_HASH_COUNT) { return null; } final Integer bytesRequired = (blockHeaderCount * blockHeaderHashByteCount); if (byteArrayReader.remainingByteCount() < bytesRequired) { return null; } for (int i = 0; i < blockHeaderCount; ++i) { final Sha256Hash blockHeaderHashBytes = Sha256Hash.wrap(byteArrayReader.readBytes(32, Endian.LITTLE)); requestBlockHeadersMessage.addBlockHash(blockHeaderHashBytes); } final Sha256Hash blockHeaderHash = Sha256Hash.wrap(byteArrayReader.readBytes(32, Endian.LITTLE)); requestBlockHeadersMessage.setStopBeforeBlockHash(blockHeaderHash); if (byteArrayReader.didOverflow()) { return null; } return requestBlockHeadersMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/ScriptInflater.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script; import com.softwareverde.bitcoin.transaction.script.opcode.Operation; import com.softwareverde.bitcoin.transaction.script.opcode.OperationInflater; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.logging.Logger; import com.softwareverde.util.HexUtil; import com.softwareverde.util.bytearray.ByteArrayReader; public class ScriptInflater { protected MutableList<Operation> _getOperationList(final ByteArray bytes) { final OperationInflater operationInflater = new OperationInflater(); final MutableList<Operation> mutableList = new MutableList<Operation>(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); while (byteArrayReader.hasBytes()) { final int scriptPosition = byteArrayReader.getPosition(); final Operation opcode = operationInflater.fromBytes(byteArrayReader); if (opcode == null) { byteArrayReader.setPosition(scriptPosition); Logger.debug("NOTICE: Unable to inflate opcode. 0x"+ HexUtil.toHexString(new byte[] { byteArrayReader.peakByte() })); return null; } mutableList.add(opcode); } return mutableList; } protected Script _fromByteArray(final ByteArray byteArray) { final List<Operation> operations = _getOperationList(byteArray); if (operations == null) { return null; } final MutableScript mutableScript = new MutableScript(); mutableScript._operations.addAll(operations); mutableScript._cachedByteCount = byteArray.getByteCount(); return mutableScript; } public MutableList<Operation> getOperationList(final ByteArray byteArray) { return _getOperationList(byteArray); } public Script fromBytes(final byte[] bytes) { final ByteArray byteArray = MutableByteArray.wrap(bytes); return _fromByteArray(byteArray); } public Script fromBytes(final ByteArray byteArray) { return _fromByteArray(byteArray); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/block/validator/difficulty/AsertDifficultyTests.java<|end_filename|> package com.softwareverde.bitcoin.block.validator.difficulty; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.test.UnitTest; import com.softwareverde.bitcoin.util.IoUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.util.Util; import org.junit.Assert; import org.junit.Test; import java.math.BigInteger; public class AsertDifficultyTests extends UnitTest { public static class TestVector { public final BigInteger blockHeight; public final Long previousBlockTimestamp; public final Difficulty difficulty; public TestVector(final BigInteger blockHeight, final Long previousBlockTimestamp, final Difficulty difficulty) { this.blockHeight = blockHeight; this.previousBlockTimestamp = previousBlockTimestamp; this.difficulty = difficulty; } } public static List<TestVector> inflateTests(final String testsString) { final MutableList<TestVector> tests = new MutableList<TestVector>(); final String[] testVectors = testsString.split("\n"); for (final String vector : testVectors) { if (vector.startsWith("#")) { continue; } final String[] parts = vector.split(" "); final BigInteger blockHeight = new BigInteger(parts[1], 10); final Long previousBlockTimestamp = Util.parseLong(parts[2]); final String encodedDifficulty = parts[3].replace("0x", ""); final Difficulty difficulty = Difficulty.decode(ByteArray.fromHexString(encodedDifficulty)); tests.add(new TestVector(blockHeight, previousBlockTimestamp, difficulty)); } return tests; } protected static void runCalculations(final List<TestVector> tests, final Difficulty anchorBits, final Long anchorBlockPreviousBlockTimestamp, final BigInteger anchorHeight) { final AsertDifficultyCalculator asertDifficultyCalculator = new AsertDifficultyCalculator(); for (TestVector testVector : tests) { final AsertReferenceBlock referenceBlock = new AsertReferenceBlock(anchorHeight, anchorBlockPreviousBlockTimestamp, anchorBits); final Difficulty nextTarget = asertDifficultyCalculator._computeAsertTarget(referenceBlock, testVector.previousBlockTimestamp, testVector.blockHeight); Assert.assertEquals(testVector.difficulty, nextTarget); } } @Test public void run01() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run01")); final BigInteger anchorHeight = BigInteger.ONE; final Long anchorTime = 0L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("1D00FFFF")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } @Test public void run02() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run02")); final BigInteger anchorHeight = BigInteger.ONE; final Long anchorTime = 0L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("1A2B3C4D")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } @Test public void run03() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run03")); final BigInteger anchorHeight = BigInteger.ONE; final Long anchorTime = 0L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("01010000")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } @Test public void run04() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run04")); final BigInteger anchorHeight = BigInteger.ONE; final Long anchorTime = 0L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("01010000")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } @Test public void run05() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run05")); final BigInteger anchorHeight = BigInteger.ONE; final Long anchorTime = 0L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("1D00FFFF")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } @Test public void run06() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run06")); final BigInteger anchorHeight = BigInteger.ONE; final Long anchorTime = 0L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("1802AEE8")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } @Test public void run07() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run07")); final BigInteger anchorHeight = BigInteger.ONE; final Long anchorTime = 0L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("1802AEE8")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } @Test public void run08() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run08")); final BigInteger anchorHeight = BigInteger.ONE; final Long anchorTime = 0L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("1802AEE8")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } @Test public void run09() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run09")); final BigInteger anchorHeight = BigInteger.valueOf(2147483642L); final Long anchorTime = 1234567290L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("1802AEE8")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } @Test public void run10() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run10")); final BigInteger anchorHeight = BigInteger.valueOf(9223372036854775802L); final Long anchorTime = 2147483047L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("1802AEE8")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } @Test public void run11() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run11")); final BigInteger anchorHeight = BigInteger.ONE; final Long anchorTime = 0L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("1802AEE8")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } @Test public void run12() { final List<TestVector> tests = AsertDifficultyTests.inflateTests(IoUtil.getResource("/aserti3-2d/test_vectors/run12")); final BigInteger anchorHeight = BigInteger.ONE; final Long anchorTime = 10000L; final Difficulty anchorBits = Difficulty.decode(ByteArray.fromHexString("1802AEE8")); AsertDifficultyTests.runCalculations(tests, anchorBits, anchorTime, anchorHeight); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/core/NodeModuleContext.java<|end_filename|> package com.softwareverde.bitcoin.context.core; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.SynchronizationStatus; import com.softwareverde.bitcoin.server.module.node.BlockProcessor; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.manager.BitcoinNodeManager; import com.softwareverde.bitcoin.server.module.node.store.BlockStore; import com.softwareverde.bitcoin.server.module.node.store.PendingBlockStore; import com.softwareverde.bitcoin.server.module.node.sync.BlockHeaderDownloader; import com.softwareverde.bitcoin.server.module.node.sync.BlockchainBuilder; import com.softwareverde.bitcoin.server.module.node.sync.block.BlockDownloader; import com.softwareverde.bitcoin.server.module.node.sync.blockloader.PendingBlockLoader; import com.softwareverde.bitcoin.server.module.node.sync.transaction.TransactionProcessor; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.validator.BlockOutputs; import com.softwareverde.bitcoin.transaction.validator.TransactionValidator; import com.softwareverde.bitcoin.transaction.validator.TransactionValidatorCore; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.network.time.VolatileNetworkTime; import com.softwareverde.util.type.time.SystemTime; public class NodeModuleContext implements BlockchainBuilder.Context, BlockDownloader.Context, BlockHeaderDownloader.Context, BlockProcessor.Context, PendingBlockLoader.Context, TransactionProcessor.Context { protected final BlockInflaters _blockInflaters; protected final TransactionInflaters _transactionInflaters; protected final PendingBlockStore _blockStore; protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; protected final BitcoinNodeManager _nodeManager; protected final SynchronizationStatus _synchronizationStatus; protected final MedianBlockTime _medianBlockTime; protected final SystemTime _systemTime; protected final ThreadPool _threadPool; protected final VolatileNetworkTime _networkTime; public NodeModuleContext(final BlockInflaters blockInflaters, final TransactionInflaters transactionInflaters, final PendingBlockStore pendingBlockStore, final FullNodeDatabaseManagerFactory databaseManagerFactory, final BitcoinNodeManager nodeManager, final SynchronizationStatus synchronizationStatus, final MedianBlockTime medianBlockTime, final SystemTime systemTime, final ThreadPool threadPool, final VolatileNetworkTime networkTime) { _blockInflaters = blockInflaters; _transactionInflaters = transactionInflaters; _blockStore = pendingBlockStore; _databaseManagerFactory = databaseManagerFactory; _nodeManager = nodeManager; _synchronizationStatus = synchronizationStatus; _medianBlockTime = medianBlockTime; _systemTime = systemTime; _threadPool = threadPool; _networkTime = networkTime; } @Override public BlockStore getBlockStore() { return _blockStore; } @Override public FullNodeDatabaseManagerFactory getDatabaseManagerFactory() { return _databaseManagerFactory; } @Override public VolatileNetworkTime getNetworkTime() { return _networkTime; } @Override public BitcoinNodeManager getBitcoinNodeManager() { return _nodeManager; } @Override public PendingBlockStore getPendingBlockStore() { return _blockStore; } @Override public SynchronizationStatus getSynchronizationStatus() { return _synchronizationStatus; } @Override public SystemTime getSystemTime() { return _systemTime; } @Override public ThreadPool getThreadPool() { return _threadPool; } @Override public BlockInflater getBlockInflater() { return _blockInflaters.getBlockInflater(); } @Override public BlockDeflater getBlockDeflater() { return _blockInflaters.getBlockDeflater(); } @Override public TransactionValidator getTransactionValidator(final BlockOutputs blockOutputs, final TransactionValidator.Context transactionValidatorContext) { return new TransactionValidatorCore(blockOutputs, transactionValidatorContext); } @Override public TransactionInflater getTransactionInflater() { return _transactionInflaters.getTransactionInflater(); } @Override public TransactionDeflater getTransactionDeflater() { return _transactionInflaters.getTransactionDeflater(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/query/Query.java<|end_filename|> package com.softwareverde.bitcoin.server.database.query; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.block.header.difficulty.work.Work; import com.softwareverde.bitcoin.server.message.type.node.feature.NodeFeatures; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.hash.Hash; import com.softwareverde.database.query.ValueExtractor; import com.softwareverde.database.query.parameter.InClauseParameter; import com.softwareverde.database.query.parameter.TypedParameter; import com.softwareverde.network.ip.Ip; import com.softwareverde.util.type.identifier.Identifier; public class Query extends com.softwareverde.database.query.Query { public Query(final String query) { super(query); } @Override public Query setParameter(final Boolean value) { super.setParameter(value); return this; } @Override public Query setParameter(final Long value) { super.setParameter(value); return this; } @Override public Query setParameter(final Integer value) { super.setParameter(value); return this; } @Override public Query setParameter(final Short value) { super.setParameter(value); return this; } @Override public Query setParameter(final Double value) { super.setParameter(value); return this; } @Override public Query setParameter(final Float value) { super.setParameter(value); return this; } @Override public Query setParameter(final byte[] value) { super.setParameter(value); return this; } @Override public Query setParameter(final ByteArray value) { super.setParameter(value); return this; } @Override public Query setParameter(final Identifier value) { super.setParameter(value); return this; } @Override public Query setParameter(final TypedParameter value) { super.setParameter(value); return this; } @Override public Query setParameter(final String value) { super.setParameter(value); return this; } public Query setParameter(final Hash value) { super.setParameter(value != null ? value.getBytes() : null); return this; } public Query setParameter(final SequenceNumber value) { super.setParameter(value != null ? value.toString() : null); return this; } public Query setParameter(final Ip value) { super.setParameter(value != null ? value.toString() : null); return this; } public Query setParameter(final NodeFeatures.Feature value) { super.setParameter(value != null ? value.toString() : null); return this; } public Query setParameter(final Difficulty value) { final ByteArray byteArray = (value != null ? value.encode() : null); super.setParameter(byteArray != null ? byteArray.getBytes() : null); return this; } public Query setParameter(final Work value) { super.setParameter(value != null ? value.getBytes() : null); return this; } @Override public Query setNullParameter() { super.setNullParameter(); return this; } @Override public Query setInClauseParameters(final InClauseParameter inClauseParameter, final InClauseParameter... extraInClauseParameters) { super.setInClauseParameters(inClauseParameter, extraInClauseParameters); return this; } @Override public <T> Query setInClauseParameters(final Iterable<? extends T> values, final ValueExtractor<T> valueExtractor) { super.setInClauseParameters(values, valueExtractor); return this; } @Override public <T> Query setExpandedInClauseParameters(final InClauseParameter inClauseParameter, final InClauseParameter... extraInClauseParameters) { super.setExpandedInClauseParameters(inClauseParameter, extraInClauseParameters); return this; } @Override public <T> Query setExpandedInClauseParameters(final Iterable<? extends T> values, final ValueExtractor<T> valueExtractor) { super.setExpandedInClauseParameters(values, valueExtractor); return this; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeBinarySocket.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.network.socket.BinarySocket; public class FakeBinarySocket extends BinarySocket { public final FakeSocket fakeSocket; public FakeBinarySocket(final FakeSocket fakeSocket, final ThreadPool threadPool) { super(fakeSocket, BitcoinProtocolMessage.BINARY_PACKET_FORMAT, threadPool); this.fakeSocket = fakeSocket; } @Override public String getHost() { return ""; } @Override public Integer getPort() { return 0; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/configuration/SeedNodeProperties.java<|end_filename|> package com.softwareverde.bitcoin.server.configuration; import com.softwareverde.logging.Logger; import com.softwareverde.network.ip.Ip; import com.softwareverde.network.p2p.node.address.NodeIpAddress; import java.net.InetAddress; public class SeedNodeProperties { /** * Converts SeedNodeProperties to a NodeIpAddress. * This process may incur a DNS lookup. * If the conversion/resolution fails, null is returned. */ public static NodeIpAddress toNodeIpAddress(final SeedNodeProperties seedNodeProperties) { final String host = seedNodeProperties.getAddress(); final String ipAddressString; try { final InetAddress ipAddress = InetAddress.getByName(host); ipAddressString = ipAddress.getHostAddress(); } catch (final Exception exception) { Logger.debug("Unable to determine host: " + host); return null; } final Integer port = seedNodeProperties.getPort(); final Ip ip = Ip.fromString(ipAddressString); return new NodeIpAddress(ip, port); } protected final String _address; protected final Integer _port; public SeedNodeProperties(final String address, final Integer port) { _address = address; _port = port; } public String getAddress() { return _address; } public Integer getPort() { return _port; } } <|start_filename|>src/main/java/com/softwareverde/network/p2p/message/ProtocolMessageHeader.java<|end_filename|> package com.softwareverde.network.p2p.message; public interface ProtocolMessageHeader { Integer getPayloadByteCount(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/miner/GpuSha256.java<|end_filename|> package com.softwareverde.bitcoin.miner; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface GpuSha256 { Integer getMaxBatchSize(); List<Sha256Hash> sha256(List<? extends ByteArray> inputs); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/DatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.module.node.database.block.BlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.node.BitcoinNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.TransactionDatabaseManager; import com.softwareverde.database.DatabaseException; public interface DatabaseManager extends AutoCloseable { DatabaseConnection getDatabaseConnection(); BitcoinNodeDatabaseManager getNodeDatabaseManager(); BlockchainDatabaseManager getBlockchainDatabaseManager(); BlockDatabaseManager getBlockDatabaseManager(); BlockHeaderDatabaseManager getBlockHeaderDatabaseManager(); TransactionDatabaseManager getTransactionDatabaseManager(); Integer getMaxQueryBatchSize(); @Override void close() throws DatabaseException; } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/request/RequestDataMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.request; import com.softwareverde.bitcoin.inflater.InventoryItemInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItem; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItemInflater; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; public class RequestDataMessageInflater extends BitcoinProtocolMessageInflater { protected final InventoryItemInflaters _inventoryItemInflaters; public RequestDataMessageInflater(final InventoryItemInflaters inventoryItemInflaters) { _inventoryItemInflaters = inventoryItemInflaters; } @Override public RequestDataMessage fromBytes(final byte[] bytes) { final InventoryItemInflater inventoryItemInflater = _inventoryItemInflaters.getInventoryItemInflater(); final RequestDataMessage inventoryMessage = new RequestDataMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.REQUEST_DATA); if (protocolMessageHeader == null) { return null; } final Long inventoryCount = byteArrayReader.readVariableSizedInteger(); for (int i = 0; i < inventoryCount; ++i) { final InventoryItem inventoryItem = inventoryItemInflater.fromBytes(byteArrayReader); inventoryMessage.addInventoryItem(inventoryItem); } if (byteArrayReader.didOverflow()) { return null; } return inventoryMessage; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/secp256k1/privatekey/PrivateKeyInflaterTests.java<|end_filename|> package com.softwareverde.bitcoin.secp256k1.privatekey; import com.softwareverde.bitcoin.test.UnitTest; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import org.junit.Assert; import org.junit.Test; public class PrivateKeyInflaterTests extends UnitTest { @Test public void shouldInflateUncompressedWifKey() { // Setup final PrivateKeyInflater privateKeyInflater = new PrivateKeyInflater(); final PrivateKey expectedPrivateKey = PrivateKey.fromHexString("0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D"); // Action final PrivateKey privateKey = privateKeyInflater.fromWalletImportFormat("<KEY>"); // Assert Assert.assertEquals(expectedPrivateKey, privateKey); } @Test public void shouldDeflateUncompressedWifKey() { // Setup final PrivateKeyDeflater privateKeyDeflater = new PrivateKeyDeflater(); final PrivateKey privateKey = PrivateKey.fromHexString("0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D");; final String expectedPrivateKeyString = "<KEY>"; // Action final String wifString = privateKeyDeflater.toWalletImportFormat(privateKey, false); // Assert Assert.assertEquals(expectedPrivateKeyString, wifString); } @Test public void shouldInflateCompressedWifKey() { // Setup final PrivateKeyInflater privateKeyInflater = new PrivateKeyInflater(); final PrivateKey expectedPrivateKey = PrivateKey.fromHexString("8147786C4D15106333BF278D71DADAF1079EF2D2440A4DDE37D747DED5403592"); // Action final PrivateKey privateKey = privateKeyInflater.fromWalletImportFormat("<KEY>"); // Assert Assert.assertEquals(expectedPrivateKey, privateKey); } @Test public void shouldDeflateCompressedWifKey() { // Setup final PrivateKeyDeflater privateKeyDeflater = new PrivateKeyDeflater(); final PrivateKey privateKey = PrivateKey.fromHexString("8147786C4D15106333BF278D71DADAF1079EF2D2440A4DDE37D747DED5403592");; final String expectedPrivateKeyString = "<KEY>"; // Action final String wifString = privateKeyDeflater.toWalletImportFormat(privateKey, true); // Assert Assert.assertEquals(expectedPrivateKeyString, wifString); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/manager/TransactionWhitelist.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface TransactionWhitelist { void addTransactionHash(Sha256Hash transactionHash); } <|start_filename|>src/main/java/com/softwareverde/network/socket/SocketServer.java<|end_filename|> package com.softwareverde.network.socket; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.constable.list.mutable.MutableList; import java.io.IOException; public class SocketServer<T extends Socket> { public interface SocketFactory<T> { T newSocket(java.net.Socket socket); } public interface SocketConnectedCallback<T> { void run(T socketConnection); } public interface SocketDisconnectedCallback<T> { void run(T socketConnection); } protected class ServerThread extends Thread { public ServerThread() { this.setName("Socket Server - Server Thread - " + this.getId()); } @Override public void run() { try { while (_shouldContinue) { if (_socket == null) { return; } final T connection = _socketFactory.newSocket(_socket.accept()); final boolean shouldPurgeConnections = ((_nextConnectionId % PURGE_EVERY_COUNT) == 0L); if (shouldPurgeConnections) { _purgeDisconnectedConnections(); } synchronized (_connections) { _connections.add(connection); _nextConnectionId += 1L; } _onConnect(connection); } } catch (final Exception exception) { } } } protected static final Long PURGE_EVERY_COUNT = 20L; protected final Integer _port; protected final SocketFactory<T> _socketFactory; protected java.net.ServerSocket _socket; protected final MutableList<T> _connections = new MutableList<T>(); protected Long _nextConnectionId = 0L; protected volatile Boolean _shouldContinue = true; protected Thread _serverThread = null; protected final ThreadPool _threadPool; protected SocketConnectedCallback<T> _socketConnectedCallback = null; protected SocketDisconnectedCallback<T> _socketDisconnectedCallback = null; protected void _purgeDisconnectedConnections() { final int socketCount = _connections.getCount(); final MutableList<T> disconnectedSockets = new MutableList<T>(socketCount); synchronized (_connections) { int socketIndex = 0; while (socketIndex < _connections.getCount()) { final T connection = _connections.get(socketIndex); if (! connection.isConnected()) { _connections.remove(socketIndex); disconnectedSockets.add(connection); } else { socketIndex += 1; } } } for (final T disconnectedSocket : disconnectedSockets) { _onDisconnect(disconnectedSocket); } } protected void _onConnect(final T socketConnection) { final SocketConnectedCallback<T> socketConnectedCallback = _socketConnectedCallback; if (socketConnectedCallback != null) { _threadPool.execute(new Runnable() { @Override public void run() { socketConnectedCallback.run(socketConnection); } }); } } protected void _onDisconnect(final T socketConnection) { final SocketDisconnectedCallback<T> socketDisconnectedCallback = _socketDisconnectedCallback; if (socketDisconnectedCallback != null) { _threadPool.execute(new Runnable() { @Override public void run() { socketDisconnectedCallback.run(socketConnection); } }); } } public SocketServer(final Integer port, final SocketFactory<T> socketFactory, final ThreadPool threadPool) { _port = port; _socketFactory = socketFactory; _threadPool = threadPool; } public void setSocketConnectedCallback(final SocketConnectedCallback<T> socketConnectedCallback) { _socketConnectedCallback = socketConnectedCallback; } public void setSocketDisconnectedCallback(final SocketDisconnectedCallback<T> socketDisconnectedCallback) { _socketDisconnectedCallback = socketDisconnectedCallback; } public void start() { _shouldContinue = true; try { _socket = new java.net.ServerSocket(_port); _serverThread = new ServerThread(); _serverThread.start(); } catch (final IOException exception) { } } public void stop() { _shouldContinue = false; if (_socket != null) { try { _socket.close(); } catch (final IOException exception) { } } _socket = null; try { _serverThread.interrupt(); if (_serverThread != null) { _serverThread.join(30000L); } } catch (final Exception exception) { } } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/manager/BitcoinNodeManagerTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.node.feature.LocalNodeFeatures; import com.softwareverde.bitcoin.server.message.type.node.feature.NodeFeatures; import com.softwareverde.bitcoin.server.module.node.manager.banfilter.BanFilterCore; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.bitcoin.server.node.BitcoinNodeFactory; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.concurrent.pool.MainThreadPool; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.concurrent.pool.ThreadPoolFactory; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.network.ip.Ip; import com.softwareverde.network.time.MutableNetworkTime; import com.softwareverde.util.type.time.SystemTime; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class BitcoinNodeManagerTests extends IntegrationTest { @Before @Override public void before() throws Exception { super.before(); } @After @Override public void after() throws Exception { super.after(); } @Test public void should_ban_node_after_multiple_failed_inbound_connections() throws Exception { // Setup final MainThreadPool threadPool = new MainThreadPool(32, 1L); final ThreadPoolFactory nodeThreadPoolFactory = new ThreadPoolFactory() { @Override public ThreadPool newThreadPool() { return threadPool; } }; final LocalNodeFeatures localNodeFeatures = new LocalNodeFeatures() { @Override public NodeFeatures getNodeFeatures() { final NodeFeatures nodeFeatures = new NodeFeatures(); nodeFeatures.enableFeature(NodeFeatures.Feature.BITCOIN_CASH_ENABLED); nodeFeatures.enableFeature(NodeFeatures.Feature.BLOCKCHAIN_ENABLED); return nodeFeatures; } }; final NodeInitializer nodeInitializer; { // Initialize NodeInitializer... final NodeInitializer.Context nodeInitializerContext = new NodeInitializer.Context(); nodeInitializerContext.synchronizationStatus = _synchronizationStatus; nodeInitializerContext.threadPoolFactory = nodeThreadPoolFactory; nodeInitializerContext.localNodeFeatures = localNodeFeatures; nodeInitializerContext.binaryPacketFormat = BitcoinProtocolMessage.BINARY_PACKET_FORMAT; nodeInitializer = new NodeInitializer(nodeInitializerContext); } final long banDurationInSeconds = 3L; final BanFilterCore banFilter = new BanFilterCore(_fullNodeDatabaseManagerFactory); banFilter.setBanDuration(banDurationInSeconds); final BitcoinNodeManager.Context bitcoinNodeContext = new BitcoinNodeManager.Context(); bitcoinNodeContext.maxNodeCount = 1; bitcoinNodeContext.databaseManagerFactory = _fullNodeDatabaseManagerFactory; bitcoinNodeContext.nodeFactory = new BitcoinNodeFactory(BitcoinProtocolMessage.BINARY_PACKET_FORMAT, nodeThreadPoolFactory, localNodeFeatures);; bitcoinNodeContext.networkTime = new MutableNetworkTime(); bitcoinNodeContext.nodeInitializer = nodeInitializer; bitcoinNodeContext.banFilter = banFilter; bitcoinNodeContext.memoryPoolEnquirer = null; bitcoinNodeContext.synchronizationStatusHandler = _synchronizationStatus; bitcoinNodeContext.threadPool = threadPool; bitcoinNodeContext.systemTime = new SystemTime(); final BitcoinNodeManager bitcoinNodeManager = new BitcoinNodeManager(bitcoinNodeContext); final String host = "127.0.0.1"; final Ip ip = Ip.fromString(host); final MutableList<BitcoinNode> bitcoinNodes = new MutableList<BitcoinNode>(); // Action // Spam the NodeManager with 10 connections that never handshake. for (int i = 0; i < 10; ++i) { final BitcoinNode bitcoinNode = new BitcoinNode(host, i, _threadPool, localNodeFeatures); bitcoinNodeManager.addNode(bitcoinNode); bitcoinNodes.add(bitcoinNode); } // Disconnect the nodes to prevent needing to waiting for connection timeout. for (final BitcoinNode bitcoinNode : bitcoinNodes) { bitcoinNode.disconnect(); } Thread.sleep((banDurationInSeconds * 1000) / 2); // Wait for async callbacks to execute. // Assert the BitcoinNodes are banned. Assert.assertTrue(banFilter.isIpBanned(ip)); // Wait for the ban to expire. Thread.sleep(banDurationInSeconds * 1000L); // Assert the BitcoinNodes are no longer banned. Assert.assertFalse(banFilter.isIpBanned(ip)); // Spam the NodeManager with 10 new failing connections. bitcoinNodes.clear(); for (int i = 0; i < 10; ++i) { final BitcoinNode bitcoinNode = new BitcoinNode(host, i, _threadPool, localNodeFeatures); bitcoinNodeManager.addNode(bitcoinNode); bitcoinNodes.add(bitcoinNode); } // Disconnect the nodes to prevent needing to waiting for connection timeout. for (final BitcoinNode bitcoinNode : bitcoinNodes) { bitcoinNode.disconnect(); } Thread.sleep(500L); // Allow for any callbacks to executed. // Assert the BitcoinNodes are re-banned. Assert.assertTrue(banFilter.isIpBanned(ip)); threadPool.stop(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/locktime/ImmutableLockTime.java<|end_filename|> package com.softwareverde.bitcoin.transaction.locktime; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.Const; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.json.Json; import com.softwareverde.util.DateUtil; public class ImmutableLockTime implements LockTime, Const { protected final Long _value; protected static LockTimeType _getType(final Long lockTime) { return ((lockTime < MAX_BLOCK_HEIGHT_VALUE) ? LockTimeType.BLOCK_HEIGHT: LockTimeType.TIMESTAMP); } public ImmutableLockTime() { _value = MIN_TIMESTAMP_VALUE; } public ImmutableLockTime(final Long value) { _value = value; } public ImmutableLockTime(final LockTime lockTime) { final Long value = lockTime.getValue(); _value = value; } @Override public LockTimeType getType() { return _getType(_value); } @Override public Long getValue() { return _value; } @Override public ByteArray getBytes() { // 4 Bytes... return MutableByteArray.wrap(ByteUtil.integerToBytes(_value)); } @Override public ImmutableLockTime asConst() { return this; } @Override public Json toJson() { final LockTimeType type = _getType(_value); final Json json = new Json(); json.put("type", type); json.put("date", (type == LockTimeType.TIMESTAMP ? DateUtil.Utc.timestampToDatetimeString(_value * 1000L) : null)); json.put("value", _value); json.put("bytes", this.getBytes()); return json; } @Override public boolean equals(final Object object) { if (object == null) { return false; } if (! (object instanceof LockTime)) { return false; } final LockTime lockTime = (LockTime) object; return _value.equals(lockTime.getValue()); } @Override public int hashCode() { return _value.hashCode(); } @Override public String toString() { return _value.toString(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/locking/ImmutableLockingScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.locking; import com.softwareverde.bitcoin.transaction.script.ImmutableScript; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.bitcoin.transaction.script.ScriptPatternMatcher; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.constable.bytearray.ByteArray; public class ImmutableLockingScript extends ImmutableScript implements LockingScript { protected ImmutableLockingScript() { super(); } public ImmutableLockingScript(final ByteArray bytes) { super(bytes); } public ImmutableLockingScript(final Script script) { super(script); } @Override public ScriptType getScriptType() { final ScriptPatternMatcher scriptPatternMatcher = new ScriptPatternMatcher(); return scriptPatternMatcher.getScriptType(this); } @Override public ImmutableLockingScript asConst() { return this; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/block/validator/difficulty/FakeDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.block.validator.difficulty; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.work.ChainWork; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.chain.time.MutableMedianBlockTime; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.test.fake.database.FakeBlockHeaderDatabaseManager; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; import com.softwareverde.util.Util; import java.util.HashMap; public class FakeDatabaseManager implements com.softwareverde.bitcoin.test.fake.database.FakeDatabaseManager { protected static final BlockchainSegmentId BLOCKCHAIN_SEGMENT_ID = BlockchainSegmentId.wrap(1L); protected Long _nextBlockId = 1L; protected final HashMap<Sha256Hash, BlockId> _blockIds = new HashMap<Sha256Hash, BlockId>(); protected final HashMap<BlockId, BlockHeader> _blockHeaders = new HashMap<BlockId, BlockHeader>(); protected final HashMap<BlockId, Long> _blockHeights = new HashMap<BlockId, Long>(); protected final HashMap<Long, BlockId> _blocksByBlockHeight = new HashMap<Long, BlockId>(); protected final HashMap<BlockId, ChainWork> _chainWork = new HashMap<BlockId, ChainWork>(); @Override public BlockHeaderDatabaseManager getBlockHeaderDatabaseManager() { return new FakeBlockHeaderDatabaseManager() { @Override public Sha256Hash getBlockHash(final BlockId blockId) throws DatabaseException { if (! _blockHeaders.containsKey(blockId)) { Logger.debug("Requested unregistered BlockHeader. blockId=" + blockId); } final BlockHeader blockHeader = _blockHeaders.get(blockId); return blockHeader.getHash(); } @Override public BlockchainSegmentId getBlockchainSegmentId(final BlockId blockId) { if (! _blockHeaders.containsKey(blockId)) { return null; } return BLOCKCHAIN_SEGMENT_ID; } @Override public BlockId getBlockHeaderId(final Sha256Hash blockHash) { if (! _blockIds.containsKey(blockHash)) { Logger.debug("Requested unregistered BlockId. blockHash=" + blockHash); } return _blockIds.get(blockHash); } @Override public Long getBlockHeight(final BlockId blockId) { if (! _blockHeights.containsKey(blockId)) { Logger.debug("Requested unregistered BlockHeight. blockId=" + blockId); } return _blockHeights.get(blockId); } @Override public BlockId getAncestorBlockId(final BlockId blockId, final Integer parentCount) { final Long blockHeight = _blockHeights.get(blockId); if (! _blockHeights.containsKey(blockId)) { Logger.debug("Requested unregistered BlockId. blockId=" + blockId); } final Long requestedBlockHeight = (blockHeight - parentCount); if (! _blocksByBlockHeight.containsKey(requestedBlockHeight)) { Logger.debug("Requested unregistered BlockHeight. blockHeight=" + requestedBlockHeight); } return _blocksByBlockHeight.get(requestedBlockHeight); } @Override public BlockId getBlockIdAtHeight(final BlockchainSegmentId blockchainSegmentId, final Long blockHeight) { if (! Util.areEqual(blockchainSegmentId, BLOCKCHAIN_SEGMENT_ID)) { return null; } if (! _blocksByBlockHeight.containsKey(blockHeight)) { Logger.debug("Requested unregistered BlockId. blockHeight=" + blockHeight); } return _blocksByBlockHeight.get(blockHeight); } @Override public Boolean isBlockInvalid(final Sha256Hash blockHash) throws DatabaseException { return false; } @Override public void markBlockAsInvalid(final Sha256Hash blockHash) throws DatabaseException { } @Override public void clearBlockAsInvalid(final Sha256Hash blockHash) throws DatabaseException { } @Override public BlockHeader getBlockHeader(final BlockId blockId) { if (! _blockHeaders.containsKey(blockId)) { Logger.debug("Requested unregistered BlockHeader. blockId=" + blockId); } return _blockHeaders.get(blockId); } @Override public ChainWork getChainWork(final BlockId blockId) { if (! _chainWork.containsKey(blockId)) { Logger.debug("Requested unregistered ChainWork. blockId=" + blockId); } return _chainWork.get(blockId); } @Override public MutableMedianBlockTime calculateMedianBlockTime(final BlockId blockId) throws DatabaseException { final Sha256Hash blockHash = this.getBlockHash(blockId); return FakeBlockHeaderDatabaseManager.newInitializedMedianBlockTime(this, blockHash); } @Override public MedianBlockTime getMedianBlockTime(final BlockId blockId) throws DatabaseException { return this.calculateMedianBlockTime(blockId); } @Override public MedianBlockTime getMedianTimePast(final BlockId blockId) throws DatabaseException { final Long blockHeight = _blockHeights.get(blockId); final BlockId previousBlockId = _blocksByBlockHeight.get(blockHeight - 1L); return this.calculateMedianBlockTime(previousBlockId); } }; } @Override public Integer getMaxQueryBatchSize() { return 1024; } public void registerBlockHeader(final BlockHeader blockHeader, final Long blockHeight, final ChainWork chainWork) { final Sha256Hash blockHash = blockHeader.getHash(); System.out.println("Registering " + blockHeader.getHash() + " -> " + blockHeight); final BlockId blockId = BlockId.wrap(_nextBlockId); _blockIds.put(blockHash, blockId); _blockHeights.put(blockId, blockHeight); _blockHeaders.put(blockId, blockHeader.asConst()); _blocksByBlockHeight.put(blockHeight, blockId); _chainWork.put(blockId, chainWork); _nextBlockId += 1L; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/wallet/WalletModule.java<|end_filename|> package com.softwareverde.bitcoin.server.module.wallet; import com.softwareverde.bitcoin.server.configuration.WalletProperties; import com.softwareverde.http.server.HttpServer; import com.softwareverde.http.server.endpoint.Endpoint; import com.softwareverde.http.server.servlet.DirectoryServlet; import com.softwareverde.http.server.servlet.Servlet; import java.io.File; public class WalletModule { protected final HttpServer _apiServer = new HttpServer(); protected final WalletProperties _walletProperties; protected <T extends Servlet> void _assignEndpoint(final String path, final T servlet) { final Endpoint endpoint = new Endpoint(servlet); endpoint.setStrictPathEnabled(true); endpoint.setPath(path); _apiServer.addEndpoint(endpoint); } public WalletModule(final WalletProperties walletProperties) { _walletProperties = walletProperties; final String tlsKeyFile = _walletProperties.getTlsKeyFile(); final String tlsCertificateFile = _walletProperties.getTlsCertificateFile(); if ( (tlsKeyFile != null) && (tlsCertificateFile != null) ) { _apiServer.setTlsPort(_walletProperties.getTlsPort()); _apiServer.setCertificate(_walletProperties.getTlsCertificateFile(), _walletProperties.getTlsKeyFile()); _apiServer.enableEncryption(true); _apiServer.redirectToTls(true); } _apiServer.setPort(_walletProperties.getPort()); { // Static Content final File servedDirectory = new File(_walletProperties.getRootDirectory() +"/"); final DirectoryServlet indexServlet = new DirectoryServlet(servedDirectory); indexServlet.setShouldServeDirectories(true); indexServlet.setIndexFile("index.html"); final Endpoint endpoint = new Endpoint(indexServlet); endpoint.setPath("/"); endpoint.setStrictPathEnabled(false); _apiServer.addEndpoint(endpoint); } } public void start() { _apiServer.start(); } public void stop() { _apiServer.stop(); } public void loop() { while (! Thread.interrupted()) { try { Thread.sleep(10000L); } catch (final Exception exception) { break; } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/AsertReferenceBlockContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.block.validator.difficulty.AsertReferenceBlock; public interface AsertReferenceBlockContext { AsertReferenceBlock getAsertReferenceBlock(); } <|start_filename|>stratum/www/js/account.js<|end_filename|> $(document).ready(function() { Ui.Account.setAuthenticated(false); Api.Account.validateAuthentication({ }, function(response) { Ui.Account.setAuthenticated(response.wasSuccess); }); }); (function() { Api.Account = { }; Api.Account.createAccount = function(parameters, callback) { const defaultParameters = { email: null, password: <PASSWORD> }; const apiParameters = $.extend({ }, defaultParameters, parameters); Http.post(Api.PREFIX + "account/create", apiParameters, callback); }; Api.Account.validateAuthentication = function(parameters, callback) { const defaultParameters = { }; const apiParameters = $.extend({ }, defaultParameters, parameters); Http.post(Api.PREFIX + "account/validate", apiParameters, callback); }; Api.Account.authenticate = function(parameters, callback) { const defaultParameters = { email: null, password: <PASSWORD> }; const apiParameters = $.extend({ }, defaultParameters, parameters); Http.post(Api.PREFIX + "account/authenticate", apiParameters, callback); }; Api.Account.unauthenticate = function(parameters, callback) { const defaultParameters = { }; const apiParameters = $.extend({ }, defaultParameters, parameters); Http.post(Api.PREFIX + "account/unauthenticate", apiParameters, callback); }; Api.Account.getPayoutAddress = function(parameters, callback) { const defaultParameters = { }; const apiParameters = $.extend({ }, defaultParameters, parameters); Http.get(Api.PREFIX + "account/address", apiParameters, callback); }; Api.Account.setPayoutAddress = function(parameters, callback) { const defaultParameters = { address: null }; const apiParameters = $.extend({ }, defaultParameters, parameters); Http.post(Api.PREFIX + "account/address", apiParameters, callback); }; Api.Account.updatePassword = function(parameters, callback) { const defaultParameters = { password: <PASSWORD>, newPassword: <PASSWORD> }; const apiParameters = $.extend({ }, defaultParameters, parameters); Http.post(Api.PREFIX + "account/password", apiParameters, callback); }; Api.Account.createWorker = function(parameters, callback) { const defaultParameters = { username: null, password: <PASSWORD> }; const apiParameters = $.extend({ }, defaultParameters, parameters); Http.post(Api.PREFIX + "account/workers/create", apiParameters, callback); }; Api.Account.deleteWorker = function(parameters, callback) { const defaultParameters = { workerId: null }; const apiParameters = $.extend({ }, defaultParameters, parameters); Http.post(Api.PREFIX + "account/workers/delete", apiParameters, callback); }; Api.Account.getWorkers = function(parameters, callback) { const defaultParameters = { }; const apiParameters = $.extend({ }, defaultParameters, parameters); Http.get(Api.PREFIX + "account/workers", apiParameters, callback); }; })(); (function() { const onEnterSubmit = function(input, button) { input.on("keypress", function(event) { const key = event.which; if (key != KeyCodes.ENTER) { return true; } $(this).blur(); button.trigger("click"); return false; }); }; Ui.Account = { }; Ui.Account.showUnauthenticatedNavigation = function() { const templates = $("#templates"); const navigationContainer = $("#main .navigation ul"); const view = $("ul.unauthenticated-navigation", templates).clone(); const navItems = view.children(); $(".authenticate-nav-button", view).on("click", function() { Ui.Account.showAuthenticateView(); }); $(".create-account-nav-button", view).on("click", function() { Ui.Account.showCreateAccountView(); }); navigationContainer.empty(); navigationContainer.append(navItems); }; Ui.Account.showAuthenticateView = function() { const templates = $("#templates"); const viewContainer = $("#main #view-container"); const view = $(".authenticate-container", templates).clone(); const button = $(".submit-button", view); button.on("click", function() { Api.Account.authenticate( { email: $("input.authenticate-email", view).val(), password: $("input.authenticate-password", view).val() }, function(data) { $(".results", view).text(data.wasSuccess ? "Authenticated." : data.errorMessage); if (data.wasSuccess) { $(".authenticate-email", view).val(""); $(".authenticate-password", view).val(""); Ui.Account.setAuthenticated(true); } } ); }); onEnterSubmit($("input", view), button); viewContainer.empty(); viewContainer.append(view); }; Ui.Account.showCreateAccountView = function() { const templates = $("#templates"); const viewContainer = $("#main #view-container"); const view = $(".create-account-container", templates).clone(); const button = $(".submit-button", view); button.on("click", function() { Api.Account.createAccount( { email: $("input.create-account-email", view).val(), password: $("input.create-account-password", view).val() }, function(data) { $(".results", view).text(data.wasSuccess ? "Authenticated." : data.errorMessage); if (data.wasSuccess) { $(".create-account-email", view).val(""); $(".create-account-password", view).val(""); Ui.Account.setAuthenticated(true); } } ); }); onEnterSubmit($("input", view), button); viewContainer.empty(); viewContainer.append(view); }; Ui.Account.showAuthenticatedNavigation = function() { const templates = $("#templates"); const navigationContainer = $("#main .navigation ul"); const view = $("ul.authenticated-navigation", templates).clone(); const navItems = view.children(); $(".set-payout-address-nav-button", view).on("click", function() { Ui.Account.showSetAddressView(); }); $(".update-password-nav-button", view).on("click", function() { Ui.Account.showUpdatePasswordView(); }); $(".manage-workers-nav-button", view).on("click", function() { Ui.Account.showManageWorkersView(); }); $(".unauthenticate-nav-button", view).on("click", function() { Api.Account.unauthenticate({ }, function(response) { Ui.Account.showUnauthenticatedNavigation(); Ui.Account.showAuthenticateView(); }); }); navigationContainer.empty(); navigationContainer.append(navItems); }; Ui.Account.showUpdatePasswordView = function() { const templates = $("#templates"); const viewContainer = $("#main #view-container"); const view = $(".update-password-container", templates).clone(); const timeoutContainer = this; const button = $(".submit-button", view); button.on("click", function() { const resultsView = $(".results", view); window.clearTimeout(timeoutContainer.timeout); if ($(".new-password", view).val() != $(".confirm-new-password", view).val()) { resultsView.text("Passwords do not match."); timeoutContainer.timeout = window.setTimeout(function() { resultsView.text(""); }, 3000); return; } Api.Account.updatePassword( { password: $("input.password", view).val(), newPassword: $("input.new-password", view).val() }, function(response) { let message = "Password updated."; if (! response.wasSuccess) { message = response.errorMessage; } resultsView.text(message); timeoutContainer.timeout = window.setTimeout(function() { resultsView.text(""); }, 3000); } ); }); onEnterSubmit($("input", view), button); viewContainer.empty(); viewContainer.append(view); Api.Account.getPayoutAddress({ }, function(response) { $("input.address", view).val(response.address); }); }; Ui.Account.showSetAddressView = function() { const templates = $("#templates"); const viewContainer = $("#main #view-container"); const view = $(".set-address-container", templates).clone(); const timeoutContainer = this; const button = $(".submit-button", view); button.on("click", function() { const resultsView = $(".results", view); window.clearTimeout(timeoutContainer.timeout); Api.Account.setPayoutAddress( { address: $("input.address", view).val() }, function(response) { let message = "Address updated."; if (! response.wasSuccess) { message = response.errorMessage; } resultsView.text(message); timeoutContainer.timeout = window.setTimeout(function() { resultsView.text(""); }, 3000); } ); }); onEnterSubmit($("input", view), button); viewContainer.empty(); viewContainer.append(view); Api.Account.getPayoutAddress({ }, function(response) { $("input.address", view).val(response.address); }); }; Ui.Account.updateWorkers = function(viewContainer) { const templates = $("#templates"); const headerView = $(".worker-header", templates).clone(); const template = $(".worker", templates); const workersTable = $(".workers", viewContainer); Api.Account.getWorkers({ }, function(response) { workersTable.empty(); if (! response.workers) { return; } if (response.workers.length) { workersTable.append(headerView); } for (let i in response.workers) { const workerData = response.workers[i]; const view = template.clone(); $(".id", view).text(workerData.id); $(".username", view).text(workerData.username); $(".shares-count", view).text(workerData.sharesCount); $(".delete", view).on("click", function() { Dialog.create( "Delete Worker", "Do you want to delete Worker \"" + workerData.username + "\"?", function() { Api.Account.deleteWorker( { workerId: workerData.id }, function() { Ui.Account.updateWorkers(viewContainer); } ); }, function() { } ); }); workersTable.append(view); } }); }; Ui.Account.showManageWorkersView = function() { const templates = $("#templates"); const viewContainer = $("#main #view-container"); const view = $(".manage-workers-container", templates).clone(); const timeoutContainer = this; const button = $(".submit-button", view); button.on("click", function() { const resultsView = $(".results", view); window.clearTimeout(timeoutContainer.timeout); Api.Account.createWorker( { username: $("input.username", view).val(), password: $("input.password", view).val() }, function(response) { let message = "Worker created."; if (! response.wasSuccess) { message = response.errorMessage; } resultsView.text(message); timeoutContainer.timeout = window.setTimeout(function() { resultsView.text(""); }, 3000); Ui.Account.updateWorkers(viewContainer); } ); }); onEnterSubmit($("input", view), button); viewContainer.empty(); viewContainer.append(view); Ui.Account.updateWorkers(view); Api.Account.getPayoutAddress({ }, function(response) { $("input.address", view).val(response.address); }); }; Ui.Account.setAuthenticated = function(isAuthenticated) { const viewContainer = $("#main #view-container"); if (isAuthenticated) { Ui.Account.showAuthenticatedNavigation(); Ui.Account.showSetAddressView(); } else { Ui.Account.showUnauthenticatedNavigation(); Ui.Account.showAuthenticateView(); } }; })(); <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/thin/block/ThinBlockMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.thin.block; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.BlockHeaderDeflater; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class ThinBlockMessage extends BitcoinProtocolMessage { protected BlockHeader _blockHeader; protected List<Sha256Hash> _transactionHashes = new MutableList<Sha256Hash>(0); protected List<Transaction> _missingTransactions = new MutableList<Transaction>(0); public ThinBlockMessage() { super(MessageType.THIN_BLOCK); } public BlockHeader getBlockHeader() { return _blockHeader; } public List<Sha256Hash> getTransactionHashes() { return _transactionHashes; } public List<Transaction> getMissingTransactions() { return _missingTransactions; } public void setBlockHeader(final BlockHeader blockHeader) { _blockHeader = blockHeader; } public void setTransactionHashes(final List<Sha256Hash> transactionHashes) { _transactionHashes = transactionHashes.asConst(); } public void setMissingTransactions(final List<Transaction> missingTransactions) { _missingTransactions = missingTransactions.asConst(); } @Override protected ByteArray _getPayload() { final BlockHeaderDeflater blockHeaderDeflater = new BlockHeaderDeflater(); final TransactionDeflater transactionDeflater = new TransactionDeflater(); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); { // Block Header... byteArrayBuilder.appendBytes(blockHeaderDeflater.toBytes(_blockHeader)); } { // Transaction (Short) Hashes... final int transactionCount = _transactionHashes.getCount(); byteArrayBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(transactionCount)); for (final Sha256Hash transactionHash : _transactionHashes) { byteArrayBuilder.appendBytes(transactionHash, Endian.LITTLE); } } { // Known Missing Transactions... final int missingTransactionCount = _missingTransactions.getCount(); byteArrayBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(missingTransactionCount)); for (final Transaction transaction : _missingTransactions) { byteArrayBuilder.appendBytes(transactionDeflater.toBytes(transaction)); } } return byteArrayBuilder; } @Override protected Integer _getPayloadByteCount() { final int transactionCount = _transactionHashes.getCount(); final byte[] transactionCountBytes = ByteUtil.variableLengthIntegerToBytes(transactionCount); final int missingTransactionCount = _missingTransactions.getCount(); final byte[] missingTransactionCountBytes = ByteUtil.variableLengthIntegerToBytes(missingTransactionCount); return ( BlockHeaderInflater.BLOCK_HEADER_BYTE_COUNT + transactionCountBytes.length + (transactionCount * Sha256Hash.BYTE_COUNT) + missingTransactionCountBytes.length + (missingTransactionCount * Sha256Hash.BYTE_COUNT) ); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/Bip113.java<|end_filename|> package com.softwareverde.bitcoin.bip; import com.softwareverde.util.Util; public class Bip113 { public static final Long ACTIVATION_BLOCK_HEIGHT = 419328L; // https://www.reddit.com/r/Bitcoin/comments/4r9tiv/csv_soft_fork_has_activated_as_of_block_419328 // Median Time-Past As Endpoint For LockTime Calculations -- https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki public static Boolean isEnabled(final Long blockHeight) { return (Util.coalesce(blockHeight, Long.MAX_VALUE) >= ACTIVATION_BLOCK_HEIGHT); } protected Bip113() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/bloomfilter/clear/ClearTransactionBloomFilterMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.bloomfilter.clear; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; public class ClearTransactionBloomFilterMessageInflater extends BitcoinProtocolMessageInflater { @Override public ClearTransactionBloomFilterMessage fromBytes(final byte[] bytes) { final ClearTransactionBloomFilterMessage clearTransactionBloomFilterMessage = new ClearTransactionBloomFilterMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.CLEAR_TRANSACTION_BLOOM_FILTER); if (protocolMessageHeader == null) { return null; } return clearTransactionBloomFilterMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/DatabaseConnectionCore.java<|end_filename|> package com.softwareverde.bitcoin.server.database; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.row.Row; import java.sql.Connection; import java.util.List; public abstract class DatabaseConnectionCore implements DatabaseConnection { protected final com.softwareverde.database.DatabaseConnection<Connection> _core; public DatabaseConnectionCore(final com.softwareverde.database.DatabaseConnection<Connection> core) { _core = core; } @Override public abstract Integer getRowsAffectedCount(); @Override public void executeDdl(final String queryString) throws DatabaseException { _core.executeDdl(queryString); } @Deprecated @Override public void executeDdl(final com.softwareverde.database.query.Query query) throws DatabaseException { _core.executeDdl(query); } public void executeDdl(final Query query) throws DatabaseException { _core.executeDdl(query); } @Override public Long executeSql(final String queryString, final String[] parameters) throws DatabaseException { return _core.executeSql(queryString, parameters); } @Deprecated @Override public Long executeSql(final com.softwareverde.database.query.Query query) throws DatabaseException { return _core.executeSql(query); } public Long executeSql(final Query query) throws DatabaseException { return _core.executeSql(query); } @Override public List<Row> query(final String queryString, final String[] parameters) throws DatabaseException { return _core.query(queryString, parameters); } @Deprecated @Override public List<Row> query(final com.softwareverde.database.query.Query query) throws DatabaseException { return _core.query(query); } public List<Row> query(final Query query) throws DatabaseException { return _core.query(query); } @Override public void close() throws DatabaseException { _core.close(); } @Override public Connection getRawConnection() { return _core.getRawConnection(); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeBlockHeaderStub.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.ImmutableBlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.merkleroot.MerkleRoot; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.json.Json; public class FakeBlockHeaderStub implements BlockHeader { @Override public Sha256Hash getPreviousBlockHash() { throw new UnsupportedOperationException(); } @Override public MerkleRoot getMerkleRoot() { throw new UnsupportedOperationException(); } @Override public Difficulty getDifficulty() { throw new UnsupportedOperationException(); } @Override public Long getVersion() { throw new UnsupportedOperationException(); } @Override public Long getTimestamp() { throw new UnsupportedOperationException(); } @Override public Long getNonce() { throw new UnsupportedOperationException(); } @Override public Boolean isValid() { throw new UnsupportedOperationException(); } @Override public ImmutableBlockHeader asConst() { throw new UnsupportedOperationException(); } @Override public Sha256Hash getHash() { throw new UnsupportedOperationException(); } @Override public Json toJson() { throw new UnsupportedOperationException(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/signer/SignatureContext.java<|end_filename|> package com.softwareverde.bitcoin.transaction.signer; import com.softwareverde.bitcoin.bip.Buip55; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.bitcoin.transaction.script.signature.hashtype.HashType; import com.softwareverde.bitcoin.transaction.script.signature.hashtype.Mode; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.util.Util; public class SignatureContext { private final Transaction _transaction; private final HashType _hashType; private final Long _blockHeight; private final MutableList<Boolean> _inputScriptsToSign = new MutableList<Boolean>(); // Determines if the script is left intact or replaced with an empty script... private final MutableList<TransactionOutput> _previousTransactionOutputsBeingSpent = new MutableList<TransactionOutput>(); private final MutableList<Integer> _codeSeparatorIndexes = new MutableList<Integer>(); private Integer _inputIndexBeingSigned = null; private Script _currentScript; private List<ByteArray> _bytesToExcludeFromScript = new MutableList<ByteArray>(); public SignatureContext(final Transaction transaction, final HashType hashType) { this(transaction, hashType, Long.MAX_VALUE); } public SignatureContext(final Transaction transaction, final HashType hashType, final Long blockHeight) { _transaction = transaction; _hashType = hashType; _blockHeight = blockHeight; final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); for (int i = 0; i < transactionInputs.getCount(); ++i) { _inputScriptsToSign.add(false); // All inputs are NOT signed by default... _previousTransactionOutputsBeingSpent.add(null); _codeSeparatorIndexes.add(0); } } public void setShouldSignInputScript(final Integer index, final Boolean shouldSignInput, final TransactionOutput outputBeingSpent) { _inputScriptsToSign.set(index, shouldSignInput); _previousTransactionOutputsBeingSpent.set(index, outputBeingSpent); _codeSeparatorIndexes.set(index, 0); } public void setLastCodeSeparatorIndex(final Integer index, final Integer lastCodeSeparatorIndex) { _codeSeparatorIndexes.set(index, lastCodeSeparatorIndex); } public void setInputIndexBeingSigned(final Integer inputIndex) { _inputIndexBeingSigned = inputIndex; } public void setCurrentScript(final Script script) { _currentScript = script; } public void setBytesToExcludeFromScript(final List<ByteArray> bytesToExcludeFromScript) { _bytesToExcludeFromScript = Util.coalesce(bytesToExcludeFromScript, _bytesToExcludeFromScript).asConst(); // NOTE: Ensure _bytesToExcludeFromScript is never null... } public Transaction getTransaction() { return _transaction; } public HashType getHashType() { return _hashType; } public Boolean shouldInputScriptBeSigned(final Integer inputIndex) { return _inputScriptsToSign.get(inputIndex); } public Boolean shouldInputBeSigned(final Integer inputIndex) { if (! _hashType.shouldSignOtherInputs()) { // SIGHASH_ANYONECANPAY return (inputIndex.intValue() == _inputIndexBeingSigned.intValue()); } return true; } public Boolean shouldInputSequenceNumberBeSigned(final Integer inputIndex) { final Mode mode = _hashType.getMode(); if ( (mode == Mode.SIGNATURE_HASH_SINGLE) || (mode == Mode.SIGNATURE_HASH_NONE) ) { if (inputIndex.intValue() != _inputIndexBeingSigned.intValue()) { return false; } } return true; } public Boolean shouldOutputBeSigned(final Integer outputIndex) { final Mode signatureMode = _hashType.getMode(); if (signatureMode == Mode.SIGNATURE_HASH_NONE) { return false; } if (signatureMode == Mode.SIGNATURE_HASH_SINGLE) { return (outputIndex <= _inputIndexBeingSigned); } return true; } public Boolean shouldOutputAmountBeSigned(final Integer outputIndex) { final Mode signatureMode = _hashType.getMode(); if (signatureMode == Mode.SIGNATURE_HASH_SINGLE) { if (outputIndex.intValue() != _inputIndexBeingSigned.intValue()) { return false; } } return true; } public Boolean shouldOutputScriptBeSigned(final Integer outputIndex) { final Mode signatureMode = _hashType.getMode(); if (signatureMode == Mode.SIGNATURE_HASH_SINGLE) { if (outputIndex.intValue() != _inputIndexBeingSigned.intValue()) { return false; } } return true; } public TransactionOutput getTransactionOutputBeingSpent(final Integer inputIndex) { return _previousTransactionOutputsBeingSpent.get(inputIndex); } public Integer getLastCodeSeparatorIndex(final Integer index) { return _codeSeparatorIndexes.get(index); } public Integer getInputIndexBeingSigned() { return _inputIndexBeingSigned; } public Script getCurrentScript() { return _currentScript; } public List<ByteArray> getBytesToExcludeFromScript() { return _bytesToExcludeFromScript; } public Boolean shouldUseBitcoinCashSigningAlgorithm() { if (! Buip55.isEnabled(_blockHeight)) { return false; } return _hashType.isBitcoinCashType(); } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/Account.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.mysql.MysqlDatabaseConnection; import com.softwareverde.database.row.Row; import com.softwareverde.json.Json; import com.softwareverde.json.Jsonable; import com.softwareverde.logging.Logger; import com.softwareverde.util.DateUtil; import com.softwareverde.util.StringUtil; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class Account implements Jsonable { private static final Map<Long, Account> _cachedAccounts = new ConcurrentHashMap<Long, Account>(); public static String hashPassword(final String rawPassword) { final ByteArray passwordBytes = MutableByteArray.wrap(StringUtil.stringToBytes(rawPassword)); final Sha256Hash hashedPassword = HashUtil.doubleSha256(passwordBytes); return hashedPassword.toString(); } /** * Retrieves the Account from the Database (or the cache, if already loaded). * @param id - The id of the Account. Returns null if the id is null or equal to zero. * @param databaseConnection - May be null if the id exists in the cache. */ public synchronized static Account loadAccount(final Long id, final MysqlDatabaseConnection databaseConnection) { if ((id == null) || (id == 0)) { return null; } if (_cachedAccounts.containsKey(id)) { return _cachedAccounts.get(id); } else if (databaseConnection == null) { return null; } final List<Row> rows; try { rows = databaseConnection.query( new Query("SELECT * FROM accounts WHERE id = ?") .setParameter(id) ); } catch (final DatabaseException exception) { Logger.warn(exception); return null; } if (rows.isEmpty()) { return null; } final Account account = new Account(id); _cachedAccounts.put(id, account); // NOTE: Append Account to cache before loading values to avoid circular dependencies. final Row accountRow = rows.get(0); // account._id = Util.parseLong(accountRow.getValue("id")); account._email = accountRow.getString("email"); account._password = accountRow.getString("password"); account._isEnabled = accountRow.getBoolean("is_enabled"); account._lastActivity = DateUtil.datetimeToTimestamp(accountRow.getString("last_activity")); account._authorizationToken = accountRow.getString("authorization_token"); return account; } /** * Retrieves the Account from the Database with the provided email and password. * @param email - The email of the Account. * @param password - The password for the Account. * @param databaseConnection - The database to retrieve the account from. * @return - Returns null if an account/password combination is not found. */ public static Account loadAccount(final String email, final String password, final MysqlDatabaseConnection databaseConnection) { final List<Row> rows; try { rows = databaseConnection.query( new Query("SELECT id FROM accounts WHERE email = ? AND password = ?") .setParameter(email) .setParameter(Account.hashPassword(password)) ); } catch (final DatabaseException exception) { Logger.warn(exception); return null; } if (rows.isEmpty()) { return null; } final Row row = rows.get(0); return Account.loadAccount(row.getLong("id"), databaseConnection); } /** * Retrieves the Account from the Database with the provided email. * @param email - The email of the Account. * @param databaseConnection - The database to retrieve the account from. * @return - Returns null if an account is not found. */ public static Account loadAccount(final String email, final MysqlDatabaseConnection databaseConnection) { final List<Row> rows; try { rows = databaseConnection.query( new Query("SELECT id FROM accounts WHERE email = ?") .setParameter(email) ); } catch (final DatabaseException exception) { Logger.warn(exception); return null; } if (rows.isEmpty()) { return null; } final Row row = rows.get(0); return Account.loadAccount(row.getLong("id"), databaseConnection); } /** * Retrieves the Account from the Database with the provided authorizationToken. * @param authorizationToken - The authorizationToken currently assigned to the Account. * @param databaseConnection - The database to retrieve the account from. * @return - Returns null if an account is not found. */ public static Account loadAccountFromAuthorizationToken(final String authorizationToken, final MysqlDatabaseConnection databaseConnection) { final List<Row> rows; try { rows = databaseConnection.query( new Query("SELECT id FROM accounts WHERE authorization_token = ?") .setParameter(authorizationToken) ); } catch (final DatabaseException exception) { Logger.warn(exception); return null; } if (rows.isEmpty()) { return null; } final Row row = rows.get(0); return Account.loadAccount(row.getLong("id"), databaseConnection); } /** * Creates an Account with the provided email and password. * Returns null if the email already has an account. * @param email - The email of the Account. * @param password - The database to retrieve the account from. * @param databaseConnection - The database to retrieve the account from. * @return - Returns null if an account is not found. */ public static Account createAccount(final String email, final String password, final MysqlDatabaseConnection databaseConnection) { if (Account.loadAccount(email, databaseConnection) != null) { return null; } final Long accountId; try { accountId = databaseConnection.executeSql( new Query("INSERT INTO accounts (email, password) VALUES (?, ?)") .setParameter(email) .setParameter(Account.hashPassword(password)) ); } catch (final DatabaseException exception) { Logger.warn(exception); return null; } return Account.loadAccount(accountId, databaseConnection); } /** * Clears the cache loaded from static load function. */ public static void clearCache() { _cachedAccounts.clear(); } protected final Long _id; protected String _email; protected String _password; volatile protected Boolean _isEnabled; volatile protected Long _lastActivity; protected String _authorizationToken; protected Account(final Long id) { _id = id; } public Long getId() { return _id; } public String getEmail() { return _email; } public String getPassword() { return _password; } public Boolean getIsEnabled() { return _isEnabled; } public Long getLastActivity() { return _lastActivity; } public String getAuthorizationToken() { return _authorizationToken; } public void setLastActivity(final Long lastActivity, final MysqlDatabaseConnection databaseConnection) { try { databaseConnection.executeSql( new Query("UPDATE accounts SET last_activity = ? WHERE id = ?") .setParameter(lastActivity) .setParameter(_id) ); } catch (final DatabaseException exception) { Logger.warn(exception); } _lastActivity = lastActivity; } public void setAuthorizationToken(final String authorizationToken, final MysqlDatabaseConnection databaseConnection) { try { databaseConnection.executeSql( new Query("UPDATE accounts SET authorization_token = ? WHERE id = ?") .setParameter(authorizationToken) .setParameter(_id) ); } catch (final DatabaseException exception) { Logger.warn(exception); } _authorizationToken = authorizationToken; } /** * Thread-safe. */ @Override public Json toJson() { final Json json = new Json(); json.put("id", _id); // json.put("email", _email); json.put("isEnabled", (_isEnabled ? 1 : 0)); json.put("lastActivity", _lastActivity); return json; } @Override public int hashCode() { return Account.class.getSimpleName().hashCode() + _id.hashCode(); } @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (! (obj instanceof Account)) { return false; } final Account accountObject = (Account) obj; return _id.equals(accountObject._id); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/secp256k1/privatekey/PrivateKeyInflater.java<|end_filename|> package com.softwareverde.bitcoin.secp256k1.privatekey; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.util.Base58Util; import com.softwareverde.util.Util; public class PrivateKeyInflater { public static class WalletImportFormat { protected static final int NETWORK_PREFIX_BYTE_COUNT = 1; protected static final int CHECKSUM_BYTE_COUNT = 4; protected static final int OPTIONAL_COMPRESSED_FLAG_BYTE_COUNT = 1; protected static final int UNCOMPRESSED_EXTENDED_KEY_BYTE_COUNT = (NETWORK_PREFIX_BYTE_COUNT + PrivateKey.KEY_BYTE_COUNT); protected static final int COMPRESSED_EXTENDED_KEY_BYTE_COUNT = (NETWORK_PREFIX_BYTE_COUNT + PrivateKey.KEY_BYTE_COUNT + OPTIONAL_COMPRESSED_FLAG_BYTE_COUNT); public static byte MAIN_NET_PREFIX = (byte) 0x80; public static byte TEST_NET_PREFIX = (byte) 0xEF; public static final Integer UNCOMPRESSED_BYTE_COUNT = (UNCOMPRESSED_EXTENDED_KEY_BYTE_COUNT + CHECKSUM_BYTE_COUNT); public static final Integer COMPRESSED_BYTE_COUNT = (COMPRESSED_EXTENDED_KEY_BYTE_COUNT + CHECKSUM_BYTE_COUNT); } public PrivateKey fromWalletImportFormat(final String wifString) { final ByteArray decodedBase58 = ByteArray.wrap(Base58Util.base58StringToByteArray(wifString)); final int decodedByteCount = decodedBase58.getByteCount(); if ( (decodedByteCount != WalletImportFormat.COMPRESSED_BYTE_COUNT) && (decodedByteCount != WalletImportFormat.UNCOMPRESSED_BYTE_COUNT) ) { return null; } final byte networkPrefix = decodedBase58.getByte(0); if (! Util.areEqual(networkPrefix, WalletImportFormat.MAIN_NET_PREFIX)) { return null; } // TODO: Support/Detect TestNet... final int checksumByteCount = WalletImportFormat.CHECKSUM_BYTE_COUNT; final int checksumStartIndex = (decodedBase58.getByteCount() - checksumByteCount); final ByteArray checksum = ByteArray.wrap(decodedBase58.getBytes(checksumStartIndex, checksumByteCount)); final int compressedByteCount = WalletImportFormat.COMPRESSED_BYTE_COUNT; final boolean isCompressed = Util.areEqual(decodedByteCount, compressedByteCount); final int extendedKeyByteCount = (isCompressed ? WalletImportFormat.COMPRESSED_EXTENDED_KEY_BYTE_COUNT : WalletImportFormat.UNCOMPRESSED_EXTENDED_KEY_BYTE_COUNT); final ByteArray extendedKeyBytes = ByteArray.wrap(decodedBase58.getBytes(0, extendedKeyByteCount)); final ByteArray recalculatedFullChecksum = HashUtil.doubleSha256(extendedKeyBytes); final ByteArray recalculatedChecksum = ByteArray.wrap(recalculatedFullChecksum.getBytes(0, checksumByteCount)); if (! Util.areEqual(recalculatedChecksum, checksum)) { return null; } // Checksum mismatch... return PrivateKey.fromBytes(extendedKeyBytes.getBytes(1, PrivateKey.KEY_BYTE_COUNT)); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/address/AddressInflaterTests.java<|end_filename|> package com.softwareverde.bitcoin.address; import com.softwareverde.bitcoin.test.util.TestUtil; import com.softwareverde.bitcoin.util.BitcoinUtil; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.cryptography.secp256k1.key.PublicKey; import com.softwareverde.util.HexUtil; import org.junit.Assert; import org.junit.Test; public class AddressInflaterTests { @Test public void should_inflate_base32_address() { // Setup final AddressInflater addressInflater = new AddressInflater(); final String base32AddressString = "bitcoincash:qqswr73n8gzgsygazzfn9qm3qk46dtescsyrzewzuj"; // Action final Address address = addressInflater.fromBase32Check(base32AddressString); // Assert Assert.assertNotNull(address); } @Test public void should_return_null_for_invalid_base32_address() { // Setup final AddressInflater addressInflater = new AddressInflater(); final String base32AddressString = "http://bitcoincash:qqswr73n8gzgsygazzfn9qm3qk46dtescsyrzewzuj"; // Action final Address address = addressInflater.fromBase32Check(base32AddressString); // Assert Assert.assertNull(address); } @Test public void should_create_valid_PublicKey_from_PrivateKey_when_even() { // Setup final byte[] privateKeyBytes = HexUtil.hexStringToByteArray("<KEY>"); final String expectedAddressString = "12Y8pRcJSrXCy1NuTuzTnPVbmM7Q63vTVo"; final String expectedCompressedAddressString = "152sweTR1yQsihW88hStanc6EN9aiKX87C"; final byte[] expectedAddress = BitcoinUtil.base58StringToBytes(expectedAddressString); final byte[] expectedCompressedAddress = BitcoinUtil.base58StringToBytes(expectedCompressedAddressString); final byte[] expectedPublicKey = HexUtil.hexStringToByteArray("<KEY>"); final byte[] expectedCompressedPublicKey = HexUtil.hexStringToByteArray("<KEY>"); final PrivateKey privateKey = PrivateKey.fromBytes(MutableByteArray.wrap(privateKeyBytes)); final AddressInflater addressInflater = new AddressInflater(); // Action final Address bitcoinAddress = addressInflater.fromPrivateKey(privateKey, false); final Address compressedAddress = addressInflater.fromPrivateKey(privateKey, true); final PublicKey publicKey = privateKey.getPublicKey(); final PublicKey compressedPublicKey = publicKey.compress(); // Assert TestUtil.assertEqual(expectedAddress, bitcoinAddress.getBytesWithChecksum()); TestUtil.assertEqual(expectedCompressedAddress, compressedAddress.getBytesWithChecksum()); TestUtil.assertEqual(expectedPublicKey, publicKey.getBytes()); TestUtil.assertEqual(expectedCompressedPublicKey, compressedPublicKey.getBytes()); Assert.assertEquals(expectedAddressString, bitcoinAddress.toBase58CheckEncoded()); Assert.assertEquals(expectedCompressedAddressString, compressedAddress.toBase58CheckEncoded()); } @Test public void should_create_valid_PublicKey_from_PrivateKey_when_odd() { // Setup final byte[] privateKeyBytes = HexUtil.hexStringToByteArray("<KEY>"); final String expectedAddressString = "1F9FjEKKHGnocaep99pqQL6oXv33vumjAz"; final String expectedCompressedAddressString = "1Bp3kke8HczZqWpQw9L5uvufunnYbGwKMZ"; final byte[] expectedAddress = BitcoinUtil.base58StringToBytes(expectedAddressString); final byte[] expectedCompressedAddress = BitcoinUtil.base58StringToBytes(expectedCompressedAddressString); final byte[] expectedPublicKey = HexUtil.hexStringToByteArray("040DD64F3EC3AEBBE5FD7E5C7360AD7A02D5E0648BFAA11ABD1BCD8A747D4D72EAB6A65A9D842943C631D2BB1B261179EE801DD09989B8DFFE3A49DE396CB4FB09"); final byte[] expectedCompressedPublicKey = HexUtil.hexStringToByteArray("030DD64F3EC3AEBBE5FD7E5C7360AD7A02D5E0648BFAA11ABD1BCD8A747D4D72EA"); final PrivateKey privateKey = PrivateKey.fromBytes(MutableByteArray.wrap(privateKeyBytes)); final AddressInflater addressInflater = new AddressInflater(); // Action final Address bitcoinAddress = addressInflater.fromPrivateKey(privateKey); final Address compressedAddress = addressInflater.fromPrivateKey(privateKey, true); final PublicKey publicKey = privateKey.getPublicKey(); final PublicKey compressedPublicKey = publicKey.compress(); // Assert TestUtil.assertEqual(expectedAddress, bitcoinAddress.getBytesWithChecksum()); TestUtil.assertEqual(expectedCompressedAddress, compressedAddress.getBytesWithChecksum()); TestUtil.assertEqual(expectedPublicKey, publicKey.getBytes()); TestUtil.assertEqual(expectedCompressedPublicKey, compressedPublicKey.getBytes()); Assert.assertEquals(expectedAddressString, bitcoinAddress.toBase58CheckEncoded()); Assert.assertEquals(expectedCompressedAddressString, compressedAddress.toBase58CheckEncoded()); } @Test public void should_create_valid_address_from_compressed_public_key() { // Setup final byte[] privateKeyBytes = HexUtil.hexStringToByteArray("<KEY>"); final byte[] expectedPublicKey = HexUtil.hexStringToByteArray("<KEY>"); final byte[] expectedCompressedPublicKey = HexUtil.hexStringToByteArray("<KEY>"); final String expectedAddressString = "12Y8pRcJSrXCy1NuTuzTnPVbmM7Q63vTVo"; final String expectedCompressedAddressString = "152sweTR1yQsihW88hStanc6EN9aiKX87C"; final PrivateKey privateKey = PrivateKey.fromBytes(MutableByteArray.wrap(privateKeyBytes)); final PublicKey publicKey = privateKey.getPublicKey(); final PublicKey compressedPublicKey = publicKey.compress(); final PublicKey decompressedPublicKey = compressedPublicKey.decompress(); final AddressInflater addressInflater = new AddressInflater(); // Action final Address compressedAddress = addressInflater.fromPublicKey(compressedPublicKey); final Address decompressedBitcoinAddress = addressInflater.fromPublicKey(decompressedPublicKey); // Assert TestUtil.assertEqual(expectedPublicKey, decompressedPublicKey.getBytes()); TestUtil.assertEqual(expectedCompressedPublicKey, compressedPublicKey.getBytes()); Assert.assertEquals(expectedAddressString, decompressedBitcoinAddress.toBase58CheckEncoded()); Assert.assertEquals(expectedCompressedAddressString, compressedAddress.toBase58CheckEncoded()); } @Test public void should_return_null_for_invalid_slp_address() { // Setup final AddressInflater addressInflater = new AddressInflater(); final String slpAddressString = "simpleledger:qpkpqwnht42ne6gzx3qtuuwjge2gpyqnkszwkc9rgz"; final String invalidSlpAddressString = "simpleledger:qpkpqwnht42ne6gzx3qtuuwjge2gpyqnkszwkc9rg"; // Missing the final letter of the checksum... // Action final Address address = addressInflater.fromBase32Check(invalidSlpAddressString); // Assert Assert.assertNull(address); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeTransactionOutputIndexerContext.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.context.AtomicTransactionOutputIndexerContext; import com.softwareverde.bitcoin.context.TransactionOutputIndexerContext; public class FakeTransactionOutputIndexerContext implements TransactionOutputIndexerContext { protected final FakeAtomicTransactionOutputIndexerContext _context; public FakeTransactionOutputIndexerContext() { _context = new FakeAtomicTransactionOutputIndexerContext(); } @Override public AtomicTransactionOutputIndexerContext newTransactionOutputIndexerContext() { return _context; } public FakeAtomicTransactionOutputIndexerContext getContext() { return _context; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/wallet/slp/SlpToken.java<|end_filename|> package com.softwareverde.bitcoin.wallet.slp; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.wallet.utxo.SpendableTransactionOutput; public interface SlpToken extends SpendableTransactionOutput { SlpTokenId getTokenId(); Long getTokenAmount(); Boolean isBatonHolder(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/Bip66.java<|end_filename|> package com.softwareverde.bitcoin.bip; import com.softwareverde.util.Util; public class Bip66 { public static final Long ACTIVATION_BLOCK_HEIGHT = 363725L; // Block: 00000000000000000379EAA19DCE8C9B722D46AE6A57C2F1A988119488B50931 // Strict DER signatures -- https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki public static Boolean isEnabled(final Long blockHeight) { return (Util.coalesce(blockHeight, Long.MAX_VALUE) >= ACTIVATION_BLOCK_HEIGHT); } protected Bip66() { } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/sync/SlpTransactionProcessorTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync; import com.softwareverde.bitcoin.context.TransactionOutputIndexerContext; import com.softwareverde.bitcoin.context.lazy.LazyTransactionOutputIndexerContext; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.indexer.BlockchainIndexerDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.FullNodeTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.slp.SlpTransactionDatabaseManager; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.concurrent.service.SleepyService; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class SlpTransactionProcessorTests extends IntegrationTest { @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } @Test public void should_index_slp_transaction_validation_results() throws Exception { // Setup final TransactionOutputIndexerContext transactionOutputIndexerContext = new LazyTransactionOutputIndexerContext(_fullNodeDatabaseManagerFactory); final BlockchainIndexer blockchainIndexer = new BlockchainIndexer(transactionOutputIndexerContext, 0); final List<Transaction> bvtTransactions = BlockchainIndexerTests.inflateBitcoinVerdeTestTokens(); try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final FullNodeTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); for (final Transaction transaction : bvtTransactions) { final Sha256Hash transactionHash = transaction.getHash(); transactionDatabaseManager.storeUnconfirmedTransaction(transaction); final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); transactionDatabaseManager.addToUnconfirmedTransactions(transactionId); final BlockchainIndexerDatabaseManager blockchainIndexerDatabaseManager = databaseManager.getBlockchainIndexerDatabaseManager(); blockchainIndexerDatabaseManager.queueTransactionsForProcessing(new ImmutableList<TransactionId>(transactionId)); } } final SlpTransactionProcessor slpTransactionProcessor = new SlpTransactionProcessor(_fullNodeDatabaseManagerFactory); // Index the outputs so the SLP indexer can reference them... try { final BlockchainIndexer.StatusMonitor statusMonitor = blockchainIndexer.getStatusMonitor(); blockchainIndexer.start(); final int maxSleepCount = 10; int sleepCount = 0; do { Thread.sleep(250L); sleepCount += 1; if (sleepCount >= maxSleepCount) { throw new RuntimeException("Test execution timeout exceeded."); } } while (statusMonitor.getStatus() != SleepyService.Status.SLEEPING); } finally { blockchainIndexer.stop(); } // Action try { final BlockchainIndexer.StatusMonitor statusMonitor = slpTransactionProcessor.getStatusMonitor(); slpTransactionProcessor.start(); final int maxSleepCount = 10; int sleepCount = 0; do { Thread.sleep(250L); sleepCount += 1; if (sleepCount >= maxSleepCount) { throw new RuntimeException("Test execution timeout exceeded."); } } while (statusMonitor.getStatus() != SleepyService.Status.SLEEPING); } finally { slpTransactionProcessor.stop(); } // Assert final List<TransactionOutputIdentifier> expectedSlpTransactionOutputIdentifiers; { final ImmutableListBuilder<TransactionOutputIdentifier> transactionOutputIdentifiers = new ImmutableListBuilder<TransactionOutputIdentifier>(); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("34DD2FE8F0C5BBA8FC4F280C3815C1E46C2F52404F00DA3067D7CE12962F2ED0", new int[] { 0, 1, 2 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("97BB8FFE6DC71AC5B263F322056069CF398CDA2677E21951364F00D2D572E887", new int[] { 0, 1, 2 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("8572AA67141E5FB6C48557508D036542AAD99C828F22B429612BDCABBAD95373", new int[] { 0, 1, 2 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("68092D36527D174CEA76797B3BB2677F61945FDECA01710976BF840664F7B71A", new int[] { 0, 1 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("0F58E80BF3E747E32BCF3218D77DC01495622D723589D1F1D1FD98AEFA798D3D", new int[] { 0, 1, 2 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("4C27492AA05C9D4248ADF3DA47A9915FB0694D00D01462FF48B461E36486DE99", new int[] { 0, 1, 2, 3 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("87B17979CC05E9E5F5FA9E8C6D78482478A4E6F6D78360E818E16311F7F157F0", new int[] { 0, 1, 2 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("731B7493DCAF21A368F384D75AD820F73F72DE9479622B35EF935E5D5C9D6F0E", new int[] { 0, 1, 2 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("AE0D9AE505E4B75619A376FA70F7C295245F8FD28F3B625FBEA19E26AB29A928", new int[] { 0, 1, 2 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("08937051BA961330600D382A749262753B8A941E9E155BA9798D2922C2CE3842", new int[] { 0, 1 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("9DF13E226887F408207F94E99108706B55149AF8C8EB9D2F36427BA3007DCD64", new int[] { 0, 1 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("25039E1E154AD0D0ED632AF5A6524898540EE8B310B878045343E8D93D7B88C1", new int[] { 0, 1 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("19DE9FFBBBCFB68BED5810ADE0F9B0929DBEEB4A7AA1236021324267209BF478", new int[] { 0, 1 })); transactionOutputIdentifiers.addAll(BlockchainIndexerTests.createOutputIdentifiers("9BD457D106B1EECBD43CD6ECA0A993420ABE16075B05012C8A76BB96D1AE16CE", new int[] { 0, 1 })); expectedSlpTransactionOutputIdentifiers = transactionOutputIdentifiers.build(); } final List<Sha256Hash> expectedInvalidSlpTransactions; { final ImmutableListBuilder<Sha256Hash> listBuilder = new ImmutableListBuilder<Sha256Hash>(); listBuilder.add(Sha256Hash.fromHexString("9BD457D106B1EECBD43CD6ECA0A993420ABE16075B05012C8A76BB96D1AE16CE")); listBuilder.add(Sha256Hash.fromHexString("08937051BA961330600D382A749262753B8A941E9E155BA9798D2922C2CE3842")); listBuilder.add(Sha256Hash.fromHexString("9DF13E226887F408207F94E99108706B55149AF8C8EB9D2F36427BA3007DCD64")); listBuilder.add(Sha256Hash.fromHexString("25039E1E154AD0D0ED632AF5A6524898540EE8B310B878045343E8D93D7B88C1")); listBuilder.add(Sha256Hash.fromHexString("19DE9FFBBBCFB68BED5810ADE0F9B0929DBEEB4A7AA1236021324267209BF478")); expectedInvalidSlpTransactions = listBuilder.build(); } try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final FullNodeTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); final SlpTransactionDatabaseManager slpTransactionDatabaseManager = databaseManager.getSlpTransactionDatabaseManager(); for (final TransactionOutputIdentifier transactionOutputIdentifier : expectedSlpTransactionOutputIdentifiers) { final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); final Boolean expectedValidationResult = (! expectedInvalidSlpTransactions.contains(transactionHash)); final Boolean isValidSlpTransaction = slpTransactionDatabaseManager.getSlpTransactionValidationResult(transactionId); Assert.assertEquals(expectedValidationResult, isValidSlpTransaction); } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/store/PendingBlockStore.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.store; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface PendingBlockStore extends BlockStore { Boolean storePendingBlock(Block block); void removePendingBlock(Sha256Hash blockHash); ByteArray getPendingBlockData(Sha256Hash blockHash); Boolean pendingBlockExists(Sha256Hash blockHash); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/fullnode/utxo/SpendableTransactionOutput.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; class SpendableTransactionOutput extends TransactionOutputIdentifier { protected final Long _blockHeight; protected final Boolean _isSpent; public SpendableTransactionOutput(final Sha256Hash transactionHash, final Integer index, final Boolean isSpent, final Long blockHeight) { super(transactionHash, index); _blockHeight = blockHeight; _isSpent = isSpent; } public Long getBlockHeight() { return _blockHeight; } public Boolean isSpent() { return _isSpent; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/slp/EnableSlpTransactionsMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.slp; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.util.bytearray.Endian; public class EnableSlpTransactionsMessageInflater extends BitcoinProtocolMessageInflater { @Override public BitcoinProtocolMessage fromBytes(final byte[] bytes) { final EnableSlpTransactionsMessage enableSlpTransactionsMessage = new EnableSlpTransactionsMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.ENABLE_SLP_TRANSACTIONS); if (protocolMessageHeader == null) { return null; } final Boolean isEnabled = (byteArrayReader.readInteger(4, Endian.LITTLE) > 0); enableSlpTransactionsMessage.setIsEnabled(isEnabled); if (byteArrayReader.didOverflow()) { return null; } return enableSlpTransactionsMessage; } } <|start_filename|>www-shared/css/bree-serif.css<|end_filename|> @font-face { font-family: 'Bree Serif'; font-style: normal; font-weight: 400; src: local('Bree Serif Regular'), local('BreeSerif-Regular'), url('../webfonts/bree-serif.woff2') format('woff2'), url('../webfonts/bree-serif.woff') format('woff'); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/validator/ValidationResult.java<|end_filename|> package com.softwareverde.bitcoin.block.validator; import com.softwareverde.json.Json; import com.softwareverde.json.Jsonable; public class ValidationResult implements Jsonable { public static ValidationResult valid() { return new ValidationResult(true, null); } public static ValidationResult invalid(final String errorMessage) { return new ValidationResult(false, errorMessage); } public final Boolean isValid; public final String errorMessage; public ValidationResult(final Boolean isValid, final String errorMessage) { this.isValid = isValid; this.errorMessage = errorMessage; } @Override public Json toJson() { final Json json = new Json(); json.put("isValid", this.isValid); json.put("errorMessage", this.errorMessage); return json; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/Bip34.java<|end_filename|> package com.softwareverde.bitcoin.bip; import com.softwareverde.util.Util; public class Bip34 { public static final Long ACTIVATION_BLOCK_HEIGHT = 227835L; // Block v2. Height in Coinbase public static Boolean isEnabled(final Long blockHeight) { return (Util.coalesce(blockHeight, Long.MAX_VALUE) > ACTIVATION_BLOCK_HEIGHT); } protected Bip34() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bytearray/FragmentedBytes.java<|end_filename|> package com.softwareverde.bitcoin.bytearray; public class FragmentedBytes { public final byte[] headBytes; public final byte[] tailBytes; public FragmentedBytes(final byte[] headBytes, final byte[] tailBytes) { this.headBytes = headBytes; this.tailBytes = tailBytes; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/slp/QuerySlpStatusMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.slp; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class QuerySlpStatusMessage extends BitcoinProtocolMessage { public static final Integer MAX_HASH_COUNT = 1024; protected final MutableList<Sha256Hash> _transactionHashes = new MutableList<>(); public QuerySlpStatusMessage() { super(MessageType.QUERY_SLP_STATUS); } public void addHash(final Sha256Hash slpTransactionHash) { if (_transactionHashes.getCount() >= MAX_HASH_COUNT) { return; } _transactionHashes.add(slpTransactionHash); } public List<Sha256Hash> getHashes() { return _transactionHashes; } @Override protected ByteArray _getPayload() { final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(_transactionHashes.getCount())); for (final Sha256Hash transactionHash : _transactionHashes) { byteArrayBuilder.appendBytes(transactionHash, Endian.LITTLE); } return byteArrayBuilder; } @Override protected Integer _getPayloadByteCount() { final int transactionCount = _transactionHashes.getCount(); final byte[] transactionCountBytes = ByteUtil.variableLengthIntegerToBytes(transactionCount); return (transactionCountBytes.length + (transactionCount * Sha256Hash.BYTE_COUNT)); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/node/address/NodeIpAddressMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.node.address; import com.softwareverde.bitcoin.inflater.ProtocolMessageInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.util.bytearray.Endian; public class NodeIpAddressMessageInflater extends BitcoinProtocolMessageInflater { protected final NodeIpAddressInflater _nodeIpAddressInflater; public NodeIpAddressMessageInflater(final ProtocolMessageInflaters protocolMessageInflaters) { _nodeIpAddressInflater = protocolMessageInflaters.getNodeIpAddressInflater(); } @Override public BitcoinNodeIpAddressMessage fromBytes(final byte[] bytes) { final int networkAddressByteCount = BitcoinNodeIpAddress.BYTE_COUNT_WITH_TIMESTAMP; final BitcoinNodeIpAddressMessage nodeIpAddressMessage = new BitcoinNodeIpAddressMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.NODE_ADDRESSES); if (protocolMessageHeader == null) { return null; } final int networkAddressCount = byteArrayReader.readVariableSizedInteger().intValue(); if (byteArrayReader.remainingByteCount() < (networkAddressCount * networkAddressByteCount)) { return null; } for (int i = 0; i < networkAddressCount; ++i) { final byte[] networkAddressBytes = byteArrayReader.readBytes(networkAddressByteCount, Endian.BIG); final BitcoinNodeIpAddress nodeIpAddress = _nodeIpAddressInflater.fromBytes(networkAddressBytes); nodeIpAddressMessage._nodeIpAddresses.add(nodeIpAddress); } if (byteArrayReader.didOverflow()) { return null; } return nodeIpAddressMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/client/message/SubscribeMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.client.message; import com.softwareverde.bitcoin.server.main.BitcoinConstants; import com.softwareverde.bitcoin.server.stratum.message.RequestMessage; public class SubscribeMessage extends RequestMessage { public SubscribeMessage() { super(ClientCommand.SUBSCRIBE.getValue()); _parameters.add("user agent/version"); _parameters.add(BitcoinConstants.getUserAgent()); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeBlockValidatorContext.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.CoreInflater; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.work.ChainWork; import com.softwareverde.bitcoin.block.validator.BlockValidator; import com.softwareverde.bitcoin.block.validator.difficulty.AsertReferenceBlock; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.validator.BlockOutputs; import com.softwareverde.bitcoin.transaction.validator.TransactionValidator; import com.softwareverde.bitcoin.transaction.validator.TransactionValidatorCore; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import com.softwareverde.network.time.NetworkTime; import com.softwareverde.network.time.VolatileNetworkTime; import java.util.HashMap; public class FakeBlockValidatorContext extends FakeUnspentTransactionOutputContext implements BlockValidator.Context { protected final TransactionInflaters _transactionInflaters; protected final VolatileNetworkTime _networkTime; protected final HashMap<Long, BlockHeader> _blocks = new HashMap<Long, BlockHeader>(); protected final HashMap<Long, MedianBlockTime> _medianBlockTimes = new HashMap<Long, MedianBlockTime>(); protected final HashMap<Long, ChainWork> _chainWorks = new HashMap<Long, ChainWork>(); protected final AsertReferenceBlock _asertReferenceBlock; public FakeBlockValidatorContext(final NetworkTime networkTime) { this(new CoreInflater(), networkTime, null); } public FakeBlockValidatorContext(final NetworkTime networkTime, final AsertReferenceBlock asertReferenceBlock) { this(new CoreInflater(), networkTime, asertReferenceBlock); } public FakeBlockValidatorContext(final TransactionInflaters transactionInflaters, final NetworkTime networkTime, final AsertReferenceBlock asertReferenceBlock) { _transactionInflaters = transactionInflaters; _networkTime = VolatileNetworkTimeWrapper.wrap(networkTime); _asertReferenceBlock = asertReferenceBlock; } public void addBlockHeader(final BlockHeader block, final Long blockHeight) { this.addBlockHeader(block, blockHeight, null, null); } public void addBlockHeader(final BlockHeader block, final Long blockHeight, final MedianBlockTime medianBlockTime, final ChainWork chainWork) { _blocks.put(blockHeight, block); _chainWorks.put(blockHeight, chainWork); _medianBlockTimes.put(blockHeight, medianBlockTime); } public void addBlock(final Block block, final Long blockHeight) { final MedianBlockTime genesisMedianTimePast = MedianBlockTime.fromSeconds(MedianBlockTime.GENESIS_BLOCK_TIMESTAMP); this.addBlock(block, blockHeight, genesisMedianTimePast, null); } public void addBlock(final Block block, final Long blockHeight, final MedianBlockTime medianBlockTime, final ChainWork chainWork) { this.addBlockHeader(block, blockHeight, medianBlockTime, chainWork); final Sha256Hash blockHash = block.getHash(); boolean isCoinbase = true; for (final Transaction transaction : block.getTransactions()) { super.addTransaction(transaction, blockHash, blockHeight, isCoinbase); isCoinbase = false; } } @Override public VolatileNetworkTime getNetworkTime() { return _networkTime; } @Override public MedianBlockTime getMedianBlockTime(final Long blockHeight) { if (! _medianBlockTimes.containsKey(blockHeight)) { Logger.debug("Requested non-existent MedianBlockTime: " + blockHeight, new Exception()); } return _medianBlockTimes.get(blockHeight); } @Override public ChainWork getChainWork(final Long blockHeight) { if (! _chainWorks.containsKey(blockHeight)) { Logger.debug("Requested non-existent ChainWork: " + blockHeight, new Exception()); } return _chainWorks.get(blockHeight); } @Override public BlockHeader getBlockHeader(final Long blockHeight) { if (! _medianBlockTimes.containsKey(blockHeight)) { Logger.debug("Requested non-existent BlockHeader: " + blockHeight, new Exception()); } return _blocks.get(blockHeight); } @Override public TransactionValidator getTransactionValidator(final BlockOutputs blockOutputs, final TransactionValidator.Context transactionValidatorContext) { return new TransactionValidatorCore(blockOutputs, transactionValidatorContext); } @Override public TransactionInflater getTransactionInflater() { return _transactionInflaters.getTransactionInflater(); } @Override public TransactionDeflater getTransactionDeflater() { return _transactionInflaters.getTransactionDeflater(); } @Override public AsertReferenceBlock getAsertReferenceBlock() { return _asertReferenceBlock; } } <|start_filename|>www-shared/js/constants.js<|end_filename|> var _HREF_ROOT = "/"; var _IMG_ROOT = "/img/"; var _JS_ROOT = "/js/"; var _CSS_ROOT = "/css/"; <|start_filename|>src/main/java/com/softwareverde/network/ip/Ipv6.java<|end_filename|> package com.softwareverde.network.ip; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.ImmutableByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.util.HexUtil; import com.softwareverde.util.StringUtil; import com.softwareverde.util.Util; public class Ipv6 implements Ip { public static final Integer BYTE_COUNT = 16; protected static byte[] _createIpv4CompatibleIpv6(final Ipv4 ipv4) { final byte[] ipSegmentBytes = new byte[BYTE_COUNT]; final ByteArray ipv4Bytes = ipv4.getBytes(); ipSegmentBytes[10] = (byte) 0xFF; ipSegmentBytes[11] = (byte) 0xFF; final int offset = (BYTE_COUNT - Ipv4.BYTE_COUNT); for (int i = 0; i < ipv4Bytes.getByteCount(); ++i) { ipSegmentBytes[offset + i] = ipv4Bytes.getByte(i); } return ipSegmentBytes; } protected static byte[] _parse(final String string) { final String trimmedString = string.trim(); final Boolean matchesIpv4CompatibilityMode = (! StringUtil.pregMatch("^::[fF]{4}:([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)$", trimmedString).isEmpty()); if (matchesIpv4CompatibilityMode) { final Integer offset = "::FFFF:".length(); final Ipv4 ipv4 = Ipv4.parse(trimmedString.substring(offset)); if (ipv4 == null) { return null; } return _createIpv4CompatibleIpv6(ipv4); } final String strippedIpString = trimmedString.replaceAll("[^0-9A-Fa-f:]", ""); final Boolean stringContainedInvalidCharacters = (strippedIpString.length() != trimmedString.length()); if (stringContainedInvalidCharacters) { return null; } final String[] ipSegmentStrings = new String[8]; { final Boolean containsShorthandMarker = (strippedIpString.contains("::")); if (containsShorthandMarker) { final String firstHalf; final String secondHalf; { final String[] halves = strippedIpString.split("::", 2); firstHalf = halves[0]; secondHalf = halves[1]; } final Boolean containsMultipleShorthandMarkers = ( (firstHalf.contains("::")) || (secondHalf.contains("::")) ); if ( containsMultipleShorthandMarkers ) { return null; } // Ipv6 may only have one shorthand-marker. { final String[] firstHalfSegments = firstHalf.split(":"); final String[] secondHalfSegments = secondHalf.split(":"); final Boolean containsTooManySegments = ((firstHalfSegments.length + secondHalfSegments.length) >= 8); if (containsTooManySegments) { return null; } for (int i = 0; i < firstHalfSegments.length; ++i) { ipSegmentStrings[i] = firstHalfSegments[i]; } for (int i = 0; i < (8 - firstHalfSegments.length - secondHalfSegments.length); ++i) { ipSegmentStrings[firstHalfSegments.length + i] = "0"; } for (int i = 0; i < secondHalfSegments.length; ++i) { ipSegmentStrings[(ipSegmentStrings.length - i) - 1] = secondHalfSegments[(secondHalfSegments.length - i) - 1]; } } } else { final String[] splitIpSegments = strippedIpString.split(":"); if (splitIpSegments.length != 8) { return null; } for (int i = 0; i < 8; ++i) { ipSegmentStrings[i] = splitIpSegments[i]; } } } final byte[] ipSegmentBytes = new byte[BYTE_COUNT]; for (int i = 0; i < ipSegmentStrings.length; ++i) { final String ipSegmentString; { final String originalIpSegmentString = ipSegmentStrings[i]; final Integer availableCharCount = originalIpSegmentString.length(); final char[] charArray = new char[4]; for (int j = 0; j < charArray.length; ++j) { final char c = (j < availableCharCount ? originalIpSegmentString.charAt((availableCharCount - j) - 1) : '0'); charArray[(charArray.length - j) - 1] = c; } ipSegmentString = new String(charArray); } final byte[] segmentBytes = HexUtil.hexStringToByteArray(ipSegmentString); if ( (segmentBytes == null) || (segmentBytes.length != 2) ) { return null; } ipSegmentBytes[(i * 2)] = segmentBytes[0]; ipSegmentBytes[(i * 2) + 1] = segmentBytes[1]; } return ipSegmentBytes; } public static Ipv6 fromBytes(final byte[] bytes) { if (bytes.length == Ipv4.BYTE_COUNT) { return Ipv6.createIpv4CompatibleIpv6(Ipv4.fromBytes(bytes)); } if (bytes.length != BYTE_COUNT) { return null; } return new Ipv6(bytes); } public static Ipv6 parse(final String string) { final byte[] segments = _parse(string); if (segments == null) { return null; } return new Ipv6(segments); } public static Ipv6 createIpv4CompatibleIpv6(final Ipv4 ipv4) { final byte[] bytes = _createIpv4CompatibleIpv6(ipv4); return new Ipv6(bytes); } private final ByteArray _bytes; public Ipv6() { _bytes = new MutableByteArray(BYTE_COUNT); } public Ipv6(final byte[] bytes) { if (bytes.length == 16) { _bytes = new ImmutableByteArray(bytes); } else { _bytes = new MutableByteArray(16); } } @Override public ByteArray getBytes() { return _bytes; } @Override public String toString() { final StringBuilder stringBuilder = new StringBuilder(); String separator = ""; for (int i = 0; i < BYTE_COUNT; i += 2) { final byte[] segmentBytes = _bytes.getBytes(i, 2); final String segmentString = HexUtil.toHexString(segmentBytes); stringBuilder.append(separator); stringBuilder.append(segmentString); separator = ":"; } return stringBuilder.toString(); } @Override public boolean equals(final Object object) { if (object == null) { return false; } if (! (object instanceof Ipv6)) { return false; } final Ipv6 ipv6 = (Ipv6) object; return Util.areEqual(_bytes, ipv6._bytes); } @Override public int hashCode() { return _bytes.hashCode(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/header/difficulty/work/BlockWork.java<|end_filename|> package com.softwareverde.bitcoin.block.header.difficulty.work; import com.softwareverde.constable.bytearray.ByteArray; public interface BlockWork extends Work { static BlockWork fromByteArray(final ByteArray byteArray) { if (byteArray.getByteCount() != 32) { return null; } return new ImmutableBlockWork(byteArray); } MutableChainWork add(final Work work); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/header/ImmutableBlockHeaderWithTransactionCount.java<|end_filename|> package com.softwareverde.bitcoin.block.header; import com.softwareverde.json.Json; public class ImmutableBlockHeaderWithTransactionCount extends ImmutableBlockHeader implements BlockHeaderWithTransactionCount { protected final Integer _transactionCount; public ImmutableBlockHeaderWithTransactionCount(final BlockHeader blockHeader, final Integer transactionCount) { super(blockHeader); _transactionCount = transactionCount; } @Override public Integer getTransactionCount() { return _transactionCount; } @Override public Json toJson() { final Json json = super.toJson(); BlockHeaderWithTransactionCountCore.toJson(json, _transactionCount); return json; } @Override public boolean equals(final Object object) { final Boolean transactionCountIsEqual = BlockHeaderWithTransactionCountCore.equals(this, object); if (! transactionCountIsEqual) { return false; } return super.equals(object); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/query/BatchedUpdateQuery.java<|end_filename|> package com.softwareverde.bitcoin.server.database.query; public class BatchedUpdateQuery extends Query { protected static class BatchedUpdateQueryWrapper extends com.softwareverde.database.query.BatchedUpdateQuery { public BatchedUpdateQueryWrapper(final Query query, final Boolean shouldConsumeQuery) { super(query, shouldConsumeQuery, new ParameterFactory()); } } protected com.softwareverde.database.query.BatchedUpdateQuery _batchedUpdateQuery = null; protected void _requireBatchedUpdateQuery() { if (_batchedUpdateQuery == null) { _batchedUpdateQuery = new BatchedUpdateQueryWrapper(this, true); } } public BatchedUpdateQuery(final String query) { super(query); } @Override public String getQueryString() { _requireBatchedUpdateQuery(); return _batchedUpdateQuery.getQueryString(); } public void clear() { _requireBatchedUpdateQuery(); _batchedUpdateQuery.clear(); } } <|start_filename|>explorer/www/js/toggle.js<|end_filename|> $(window).on("load", function() { $(".toggle > .toggle-bar").on("click", function() { const toggleWidget = $(this).parent(); const isOff = toggleWidget.hasClass("off"); toggleWidget.toggleClass("off", (! isOff)); toggleWidget.trigger("change", isOff); }); }); <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/DatabaseConfigurerTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module; import com.softwareverde.bitcoin.server.configuration.DatabaseProperties; import com.softwareverde.bitcoin.server.main.DatabaseConfigurer; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.database.mysql.embedded.DatabaseCommandLineArguments; import com.softwareverde.util.Util; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; public class DatabaseConfigurerTests { @Test public void should_configure_linux_database_with_large_memory_available() { // Setup final Long systemByteCount = (64L * ByteUtil.Unit.Binary.GIBIBYTES); final long logFileByteCount = ByteUtil.Unit.Binary.GIBIBYTES; final DatabaseProperties databaseProperties = new DatabaseProperties() { @Override public Long getMaxMemoryByteCount() { return systemByteCount; } @Override public Long getLogFileByteCount() { return logFileByteCount; } }; final DatabaseCommandLineArguments commandLineArguments = new DatabaseCommandLineArguments(); final Integer maxDatabaseThreadCount = 5000; // Reasonably large number of connections. (MySQL allows up to 10k) final Long overhead = (maxDatabaseThreadCount * (11L * ByteUtil.Unit.Binary.MEBIBYTES)); // 3MB overhead + 8 max packet final Long usableSystemMemory = (systemByteCount - overhead); // Action DatabaseConfigurer.configureCommandLineArguments(commandLineArguments, maxDatabaseThreadCount, databaseProperties, null); final HashMap<String, String> arguments = new HashMap<String, String>(); for (final String string : commandLineArguments.getArguments()) { final String[] splitArgument = string.split("="); if (splitArgument.length != 2) { continue; } // Ignore flags... arguments.put(splitArgument[0], splitArgument[1]); } // Assert final Long expectedBufferPoolByteCount = (usableSystemMemory - (logFileByteCount / 4L)); // Slightly more than 10GB due to 3MB per-connection overhead... Assert.assertEquals(Long.valueOf(logFileByteCount / 4L), Util.parseLong(arguments.get("--innodb_log_buffer_size"))); Assert.assertEquals(expectedBufferPoolByteCount, Util.parseLong(arguments.get("--innodb_buffer_pool_size"))); } @Test public void should_configure_linux_database_with_little_memory_available() { // Setup final long systemByteCount = ByteUtil.Unit.Binary.GIBIBYTES; final long logFileByteCount = (512L * ByteUtil.Unit.Binary.MEBIBYTES); final DatabaseProperties databaseProperties = new DatabaseProperties() { @Override public Long getMaxMemoryByteCount() { return systemByteCount; } @Override public Long getLogFileByteCount() { return logFileByteCount; } }; final DatabaseCommandLineArguments commandLineArguments = new DatabaseCommandLineArguments(); final Integer maxDatabaseThreadCount = 32; // Maximum supported by MySql... final Long overhead = (maxDatabaseThreadCount * (11L * ByteUtil.Unit.Binary.MEBIBYTES)); // 3MB overhead + 8 max packet final Long usableSystemMemory = (systemByteCount - overhead); // Action DatabaseConfigurer.configureCommandLineArguments(commandLineArguments, maxDatabaseThreadCount, databaseProperties, null); final HashMap<String, String> arguments = new HashMap<String, String>(); for (final String string : commandLineArguments.getArguments()) { final String[] splitArgument = string.split("="); if (splitArgument.length != 2) { continue; } // Ignore flags... arguments.put(splitArgument[0], splitArgument[1]); } // Assert final Long bufferPoolByteCount = (usableSystemMemory - (logFileByteCount / 4L)); Assert.assertEquals(Long.valueOf(logFileByteCount / 4L), Util.parseLong(arguments.get("--innodb_log_buffer_size"))); Assert.assertEquals(bufferPoolByteCount, Util.parseLong(arguments.get("--innodb_buffer_pool_size"))); } @Test public void should_configure_linux_database_with_little_non_aligned_size() { // Setup final long systemByteCount = (ByteUtil.Unit.Binary.GIBIBYTES + 1L); final DatabaseProperties databaseProperties = new DatabaseProperties() { @Override public Long getMaxMemoryByteCount() { return systemByteCount; } @Override public Long getLogFileByteCount() { return systemByteCount; } }; final DatabaseCommandLineArguments commandLineArguments = new DatabaseCommandLineArguments(); final Integer maxDatabaseThreadCount = 64; final Long overhead = (maxDatabaseThreadCount * (11L * ByteUtil.Unit.Binary.MEBIBYTES)); // 3MB overhead + 8 max packet final Long usableSystemMemory = (systemByteCount - overhead); // Action DatabaseConfigurer.configureCommandLineArguments(commandLineArguments, maxDatabaseThreadCount, databaseProperties, null); final HashMap<String, String> arguments = new HashMap<String, String>(); for (final String string : commandLineArguments.getArguments()) { final String[] splitArgument = string.split("="); if (splitArgument.length != 2) { continue; } // Ignore flags... arguments.put(splitArgument[0], splitArgument[1]); } // Assert Assert.assertEquals(Long.valueOf(usableSystemMemory / 4L), Util.parseLong(arguments.get("--innodb_log_buffer_size"))); Assert.assertEquals(Long.valueOf(usableSystemMemory * 3L / 4L), Util.parseLong(arguments.get("--innodb_buffer_pool_size"))); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/locktime/SequenceNumberType.java<|end_filename|> package com.softwareverde.bitcoin.transaction.locktime; public enum SequenceNumberType { SECONDS_ELAPSED, BLOCK_COUNT } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/account/ValidateAuthenticationApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account; import com.softwareverde.bitcoin.miner.pool.AccountId; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.servlet.AuthenticatedServlet; public class ValidateAuthenticationApi extends AuthenticatedServlet { public ValidateAuthenticationApi(final StratumProperties stratumProperties) { super(stratumProperties); } @Override protected Response _onAuthenticatedRequest(final AccountId accountId, final Request request) { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); { // VALIDATE AUTHENTICATION TOKEN // Requires GET: // Requires POST: return new JsonResponse(Response.Codes.OK, new StratumApiResult(true, null)); } } } <|start_filename|>src/test/java/com/softwareverde/network/p2p/node/manager/FakeNode.java<|end_filename|> package com.softwareverde.network.p2p.node.manager; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.node.feature.LocalNodeFeatures; import com.softwareverde.bitcoin.server.message.type.node.feature.NodeFeatures; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.network.p2p.message.ProtocolMessage; import com.softwareverde.network.p2p.message.type.AcknowledgeVersionMessage; import com.softwareverde.network.p2p.message.type.NodeIpAddressMessage; import com.softwareverde.network.p2p.message.type.PingMessage; import com.softwareverde.network.p2p.message.type.PongMessage; import com.softwareverde.network.p2p.message.type.SynchronizeVersionMessage; import com.softwareverde.network.p2p.node.address.NodeIpAddress; public class FakeNode extends BitcoinNode { protected static long _nextNonce = 0L; protected Long _lastMessageReceivedTimestamp = 0L; public FakeNode(final String host, final ThreadPool threadPool) { super(host, 0, BitcoinProtocolMessage.BINARY_PACKET_FORMAT, threadPool, new LocalNodeFeatures() { @Override public NodeFeatures getNodeFeatures() { return new NodeFeatures(); } }); } @Override protected PingMessage _createPingMessage() { return new PingMessage() { @Override public Long getNonce() { return 0L; } @Override public ByteArray getBytes() { return new MutableByteArray(0); } }; } @Override protected PongMessage _createPongMessage(final PingMessage pingMessage) { return new PongMessage() { @Override public Long getNonce() { return 0L; } @Override public ByteArray getBytes() { return new MutableByteArray(0); } }; } @Override protected SynchronizeVersionMessage _createSynchronizeVersionMessage() { return new SynchronizeVersionMessage() { @Override public Long getNonce() { return _nextNonce++; } @Override public NodeIpAddress getLocalNodeIpAddress() { return null; } @Override public NodeIpAddress getRemoteNodeIpAddress() { return null; } @Override public Long getTimestamp() { return 0L; } @Override public String getUserAgent() { return "TestAgent"; } @Override public ByteArray getBytes() { return new MutableByteArray(0); } }; } @Override public void connect() { } @Override protected AcknowledgeVersionMessage _createAcknowledgeVersionMessage(final SynchronizeVersionMessage synchronizeVersionMessage) { return null; } @Override protected NodeIpAddressMessage _createNodeIpAddressMessage() { return null; } @Override public Boolean hasActiveConnection() { return true; } @Override public Long getLastMessageReceivedTimestamp() { return _lastMessageReceivedTimestamp; } @Override public Boolean handshakeIsComplete() { return true; } @Override protected void _queueMessage(final ProtocolMessage message) { super._queueMessage(message); } public void triggerConnected() { _onConnect(); } public void triggerHandshakeComplete() { _onAcknowledgeVersionMessageReceived(null); } public void respondWithPong() { _onPongReceived(new PongMessage() { @Override public Long getNonce() { return 0L; } @Override public ByteArray getBytes() { return new MutableByteArray(0); } }); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/wallet/slp/SlpPaymentAmount.java<|end_filename|> package com.softwareverde.bitcoin.wallet.slp; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.wallet.PaymentAmount; public class SlpPaymentAmount extends PaymentAmount { public final Long tokenAmount; public SlpPaymentAmount(final Address address, final Long amount, final Long tokenAmount) { super(address, amount); this.tokenAmount = tokenAmount; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/HF20180515.java<|end_filename|> package com.softwareverde.bitcoin.bip; import com.softwareverde.util.Util; public class HF20180515 { public static final Long ACTIVATION_BLOCK_HEIGHT = 530359L; // Bitcoin Cash: 2018-05-15 Hard Fork: https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/may-2018-hardfork.md // https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/may-2018-reenabled-opcodes.md public static Boolean isEnabled(final Long blockHeight) { return (Util.coalesce(blockHeight, Long.MAX_VALUE) >= ACTIVATION_BLOCK_HEIGHT); } protected HF20180515() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/version/synchronize/BitcoinSynchronizeVersionMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.version.synchronize; import com.softwareverde.bitcoin.inflater.ProtocolMessageInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.server.message.type.node.address.NodeIpAddressInflater; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.util.bytearray.Endian; public class BitcoinSynchronizeVersionMessageInflater extends BitcoinProtocolMessageInflater { protected final NodeIpAddressInflater _nodeIpAddressInflater; public BitcoinSynchronizeVersionMessageInflater(final ProtocolMessageInflaters protocolMessageInflaters) { _nodeIpAddressInflater = protocolMessageInflaters.getNodeIpAddressInflater(); } @Override public BitcoinSynchronizeVersionMessage fromBytes(final byte[] bytes) { final BitcoinSynchronizeVersionMessage synchronizeVersionMessage = new BitcoinSynchronizeVersionMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.SYNCHRONIZE_VERSION); if (protocolMessageHeader == null) { return null; } synchronizeVersionMessage._version = byteArrayReader.readInteger(4, Endian.LITTLE); final Long nodeFeatureFlags = byteArrayReader.readLong(8, Endian.LITTLE); synchronizeVersionMessage._nodeFeatures.setFeatureFlags(nodeFeatureFlags); synchronizeVersionMessage._timestampInSeconds = byteArrayReader.readLong(8, Endian.LITTLE); final byte[] remoteNetworkAddressBytes = byteArrayReader.readBytes(26, Endian.BIG); synchronizeVersionMessage._remoteNodeIpAddress = _nodeIpAddressInflater.fromBytes(remoteNetworkAddressBytes); final byte[] localNetworkAddressBytes = byteArrayReader.readBytes(26, Endian.BIG); synchronizeVersionMessage._localNodeIpAddress = _nodeIpAddressInflater.fromBytes(localNetworkAddressBytes); synchronizeVersionMessage._nonce = byteArrayReader.readLong(8, Endian.LITTLE); synchronizeVersionMessage._userAgent = byteArrayReader.readVariableLengthString(); synchronizeVersionMessage._currentBlockHeight = byteArrayReader.readLong(4, Endian.LITTLE); synchronizeVersionMessage._transactionRelayIsEnabled = byteArrayReader.readBoolean(); if (byteArrayReader.didOverflow()) { return null; } return synchronizeVersionMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/node/feature/LocalNodeFeatures.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.node.feature; public interface LocalNodeFeatures { NodeFeatures getNodeFeatures(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/HF20181115.java<|end_filename|> package com.softwareverde.bitcoin.bip; import com.softwareverde.util.Util; public class HF20181115 { public static final Long ACTIVATION_BLOCK_HEIGHT = 556767L; // Bitcoin Cash: 2018-11-15 Hard Fork: https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/2018-nov-upgrade.md // https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/op_checkdatasig.md public static Boolean isEnabled(final Long blockHeight) { return (Util.coalesce(blockHeight, Long.MAX_VALUE) >= ACTIVATION_BLOCK_HEIGHT); } protected HF20181115() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/configuration/ProxyProperties.java<|end_filename|> package com.softwareverde.bitcoin.server.configuration; import com.softwareverde.constable.list.List; public class ProxyProperties { public static final Integer HTTP_PORT = 8080; public static final Integer TLS_PORT = 4480; protected Integer _httpPort; protected Integer _externalTlsPort; protected Integer _tlsPort; protected List<String> _tlsKeyFiles; protected List<String> _tlsCertificateFiles; public Integer getHttpPort() { return _httpPort; } public Integer getTlsPort() { return _tlsPort; } public Integer getExternalTlsPort() { return _externalTlsPort; } public List<String> getTlsKeyFiles() { return _tlsKeyFiles; } public List<String> getTlsCertificateFiles() { return _tlsCertificateFiles; } } <|start_filename|>src/main/java/com/softwareverde/concurrent/service/GracefulSleepyService.java<|end_filename|> package com.softwareverde.concurrent.service; public abstract class GracefulSleepyService extends SleepyService { private volatile Boolean _isShuttingDown = false; @Override protected Boolean _shouldAbort() { return (super._shouldAbort() || _isShuttingDown); } @Override public synchronized void stop() { if (_isShuttingDown) { // stop was invoked twice; shutdown via interrupt. super.stop(); return; } _isShuttingDown = true; try { for (int i = 0; i < 20; ++i) { if (_status == Status.ACTIVE) { break; } Thread.sleep(_stopTimeoutMs / 20L); } if (_status != Status.ACTIVE) { // If the service still hasn't exited then interrupt the thread. super.stop(); } } catch (final Exception exception) { super.stop(); } finally { _isShuttingDown = false; } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/MinerModule.java<|end_filename|> package com.softwareverde.bitcoin.server.module; import com.softwareverde.bitcoin.CoreInflater; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.inflater.MasterInflater; import com.softwareverde.bitcoin.miner.Miner; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.logging.Logger; public class MinerModule { protected void _printError(final String errorMessage) { System.err.println(errorMessage); } protected final MasterInflater _masterInflater; protected final Integer _cpuThreadCount; protected final MutableBlock _prototypeBlock; public MinerModule(final Integer cpuThreadCount, final String prototypeBlock) { _masterInflater = new CoreInflater(); _cpuThreadCount = cpuThreadCount; final BlockInflater blockInflater = _masterInflater.getBlockInflater(); _prototypeBlock = blockInflater.fromBytes(ByteArray.fromHexString(prototypeBlock)); } public void run() { try { final Miner miner = new Miner(_cpuThreadCount, 0, null, _masterInflater); miner.setShouldMutateTimestamp(true); final Block block = miner.mineBlock(_prototypeBlock); if (block == null) { Logger.info("No block found."); return; } final BlockDeflater blockDeflater = _masterInflater.getBlockDeflater(); Logger.info(block.getHash()); Logger.info(blockDeflater.toBytes(block)); } catch (final Exception exception) { Logger.debug(exception); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/output/ImmutableTransactionOutput.java<|end_filename|> package com.softwareverde.bitcoin.transaction.output; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.constable.Const; import com.softwareverde.json.Json; import com.softwareverde.util.Util; public class ImmutableTransactionOutput implements TransactionOutput, Const { protected final Long _amount; protected final Integer _index; protected final LockingScript _lockingScript; protected Integer _cachedHashCode = null; public ImmutableTransactionOutput(final TransactionOutput transactionOutput) { _amount = transactionOutput.getAmount(); _index = transactionOutput.getIndex(); _lockingScript = transactionOutput.getLockingScript().asConst(); } @Override public Long getAmount() { return _amount; } @Override public Integer getIndex() { return _index; } @Override public LockingScript getLockingScript() { return _lockingScript; } @Override public ImmutableTransactionOutput asConst() { return this; } @Override public Json toJson() { final TransactionOutputDeflater transactionOutputDeflater = new TransactionOutputDeflater(); return transactionOutputDeflater.toJson(this); } @Override public int hashCode() { final Integer cachedHashCode = _cachedHashCode; if (cachedHashCode != null) { return cachedHashCode; } final TransactionOutputDeflater transactionOutputDeflater = new TransactionOutputDeflater(); _cachedHashCode = transactionOutputDeflater.toBytes(this).hashCode(); return _cachedHashCode; } @Override public boolean equals(final Object object) { if (! (object instanceof TransactionOutput)) { return false; } final TransactionOutput transactionOutput = (TransactionOutput) object; if (! Util.areEqual(_amount, transactionOutput.getAmount())) { return false; } if (! Util.areEqual(_index, transactionOutput.getIndex())) { return false; } if (! Util.areEqual(_lockingScript, transactionOutput.getLockingScript())) { return false; } return true; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/util/ByteUtil.java<|end_filename|> package com.softwareverde.bitcoin.util; public class ByteUtil extends com.softwareverde.util.ByteUtil { public static byte[] variableLengthIntegerToBytes(final long value) { final byte[] bytes = ByteUtil.longToBytes(value); if (value < 0xFDL) { return new byte[] { bytes[7] }; } else if (value <= 0xFFFFL) { return new byte[] { (byte) 0xFD, bytes[7], bytes[6] }; } else if (value <= 0xFFFFFFFFL) { return new byte[] { (byte) 0xFE, bytes[7], bytes[6], bytes[5], bytes[4] }; } else { return new byte[] { (byte) 0xFF, bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0] }; } } public static byte[] variableLengthStringToBytes(final String variableLengthString) { final int stringLength = variableLengthString.length(); final byte[] variableLengthIntegerBytes = ByteUtil.variableLengthIntegerToBytes(stringLength); final byte[] bytes = new byte[variableLengthString.length() + variableLengthIntegerBytes.length]; ByteUtil.setBytes(bytes, variableLengthIntegerBytes); ByteUtil.setBytes(bytes, variableLengthString.getBytes(), variableLengthIntegerBytes.length); return bytes; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/MemoryPoolEnquirer.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bloomfilter.BloomFilter; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface MemoryPoolEnquirer { BloomFilter getBloomFilter(Sha256Hash blockHash); Integer getMemoryPoolTransactionCount(); Transaction getTransaction(Sha256Hash transactionHash); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/indexer/TransactionOutputId.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.indexer; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.constable.Const; import com.softwareverde.util.Util; public class TransactionOutputId implements Const, Comparable<TransactionOutputId> { protected final TransactionId _transactionId; protected final Integer _outputIndex; public TransactionOutputId(final TransactionId transactionId, final Integer outputIndex) { _transactionId = transactionId; _outputIndex = outputIndex; } public TransactionId getTransactionId() { return _transactionId; } public Integer getOutputIndex() { return _outputIndex; } @Override public boolean equals(final Object object) { if (object == this) { return true; } if (! (object instanceof TransactionOutputId)) { return false; } final TransactionOutputId transactionOutputId = (TransactionOutputId) object; if (! Util.areEqual(_transactionId, transactionOutputId.getTransactionId())) { return false; } if (! Util.areEqual(_outputIndex, transactionOutputId.getOutputIndex())) { return false; } return true; } @Override public int hashCode() { return (_transactionId.hashCode() + _outputIndex.hashCode()); } @Override public String toString() { return (_transactionId + ":" + _outputIndex); } @Override public int compareTo(final TransactionOutputId transactionOutputId) { final int transactionIdComparison = _transactionId.compareTo(transactionOutputId.getTransactionId()); if (transactionIdComparison != 0) { return transactionIdComparison; } return _outputIndex.compareTo(transactionOutputId.getOutputIndex()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/node/address/request/RequestPeersMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.node.address.request; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.util.bytearray.ByteArrayReader; public class RequestPeersMessageInflater extends BitcoinProtocolMessageInflater { @Override public RequestPeersMessage fromBytes(final byte[] bytes) { final RequestPeersMessage requestPeersMessage = new RequestPeersMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.REQUEST_PEERS); if (protocolMessageHeader == null) { return null; } if (byteArrayReader.didOverflow()) { return null; } return requestPeersMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/store/PendingBlockStoreCore.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.store; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.inflater.BlockHeaderInflaters; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.util.IoUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import java.io.File; public class PendingBlockStoreCore extends BlockStoreCore implements PendingBlockStore { protected final String _pendingBlockDataDirectory; protected String _getPendingBlockDataDirectory(final Sha256Hash blockHash) { final String cachedBlockDirectory = _pendingBlockDataDirectory; if (cachedBlockDirectory == null) { return null; } final String blockHashString = blockHash.toString(); int zeroCount = 0; for (final char c : blockHashString.toCharArray()) { if (c != '0') { break; } zeroCount += 1; } return (cachedBlockDirectory + "/" + zeroCount); } protected String _getPendingBlockDataPath(final Sha256Hash blockHash) { if (_pendingBlockDataDirectory == null) { return null; } final String blockHeightDirectory = _getPendingBlockDataDirectory(blockHash); return (blockHeightDirectory + "/" + blockHash); } protected void _deletePendingBlockData(final String blockPath) { final File file = new File(blockPath); file.delete(); } public PendingBlockStoreCore(final String blockDataDirectory, final String pendingBlockDataDirectory, final BlockHeaderInflaters blockHeaderInflaters, final BlockInflaters blockInflaters) { super(blockDataDirectory, blockHeaderInflaters, blockInflaters); _pendingBlockDataDirectory = pendingBlockDataDirectory; } @Override public Boolean storePendingBlock(final Block block) { if (_pendingBlockDataDirectory == null) { return false; } final Sha256Hash blockHash = block.getHash(); final String blockPath = _getPendingBlockDataPath(blockHash); if (blockPath == null) { return false; } if (! IoUtil.isEmpty(blockPath)) { return true; } { // Create the directory, if necessary... final String cacheDirectory = _getPendingBlockDataDirectory(blockHash); final File directory = new File(cacheDirectory); if (! directory.exists()) { final boolean mkdirSuccessful = directory.mkdirs(); if (! mkdirSuccessful) { Logger.warn("Unable to create block cache directory: " + cacheDirectory); return false; } } } final BlockDeflater blockDeflater = _blockInflaters.getBlockDeflater(); final ByteArray byteArray = blockDeflater.toBytes(block); return IoUtil.putFileContents(blockPath, byteArray); } @Override public void removePendingBlock(final Sha256Hash blockHash) { if (_pendingBlockDataDirectory == null) { return; } final String blockPath = _getPendingBlockDataPath(blockHash); if (blockPath == null) { return; } if (! IoUtil.fileExists(blockPath)) { return; } _deletePendingBlockData(blockPath); } @Override public ByteArray getPendingBlockData(final Sha256Hash blockHash) { if (_pendingBlockDataDirectory == null) { return null; } final String blockPath = _getPendingBlockDataPath(blockHash); if (blockPath == null) { return null; } if (! IoUtil.fileExists(blockPath)) { return null; } return MutableByteArray.wrap(IoUtil.getFileContents(blockPath)); } @Override public Boolean pendingBlockExists(final Sha256Hash blockHash) { if (_pendingBlockDataDirectory == null) { return false; } final String blockPath = _getPendingBlockDataPath(blockHash); if (blockPath == null) { return false; } return IoUtil.fileExists(blockPath); } public String getPendingBlockDataDirectory() { return _pendingBlockDataDirectory; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/Bip16.java<|end_filename|> package com.softwareverde.bitcoin.bip; import com.softwareverde.util.Util; public class Bip16 { public static final Long ACTIVATION_BLOCK_HEIGHT = 173805L; // Pay to Script Hash - https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki public static Boolean isEnabled(final Long blockHeight) { return (Util.coalesce(blockHeight, Long.MAX_VALUE) >= ACTIVATION_BLOCK_HEIGHT); } protected Bip16() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/lazy/LazyTransactionOutputIndexerContext.java<|end_filename|> package com.softwareverde.bitcoin.context.lazy; import com.softwareverde.bitcoin.context.AtomicTransactionOutputIndexerContext; import com.softwareverde.bitcoin.context.ContextException; import com.softwareverde.bitcoin.context.TransactionOutputIndexerContext; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.database.DatabaseException; public class LazyTransactionOutputIndexerContext implements TransactionOutputIndexerContext { protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; protected FullNodeDatabaseManager _databaseManager; public LazyTransactionOutputIndexerContext(final FullNodeDatabaseManagerFactory databaseManagerFactory) { _databaseManagerFactory = databaseManagerFactory; } @Override public AtomicTransactionOutputIndexerContext newTransactionOutputIndexerContext() throws ContextException { FullNodeDatabaseManager databaseManager = null; try { databaseManager = _databaseManagerFactory.newDatabaseManager(); return new LazyAtomicTransactionOutputIndexerContext(databaseManager); } catch (final Exception exception) { try { if (databaseManager != null) { databaseManager.close(); } } catch (final DatabaseException databaseException) { exception.addSuppressed(databaseException); } throw new ContextException(exception); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/ContextException.java<|end_filename|> package com.softwareverde.bitcoin.context; public class ContextException extends Exception { public ContextException(final String message) { super(message); } public ContextException(final Exception baseException) { super(baseException); } public ContextException(final String message, final Exception baseException) { super(message, baseException); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/inflater/MasterInflater.java<|end_filename|> package com.softwareverde.bitcoin.inflater; public interface MasterInflater extends ProtocolMessageInflaters, BlockInflaters, ExtendedBlockHeaderInflaters, TransactionInflaters, MerkleTreeInflaters, BloomFilterInflaters, InventoryItemInflaters, AddressInflaters { } <|start_filename|>src/test/java/com/softwareverde/network/ip/Ipv6Tests.java<|end_filename|> package com.softwareverde.network.ip; import org.junit.Assert; import org.junit.Test; public class Ipv6Tests { @Test public void should_parse_loopback_ip_string() { // Setup final String ipString = "0000:0000:0000:0000:0000:0000:0000:0001"; final byte[] expectedBytes = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 }; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv6.getBytes().getBytes()); } @Test public void should_parse_zeroed_ip_string() { // Setup final String ipString = "0000:0000:0000:0000:0000:0000:0000:0000"; final byte[] expectedBytes = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv6.getBytes().getBytes()); } @Test public void should_parse_compact_ip_string() { // Setup final String ipString = ":FFFF:::0:A:1FF:1"; final byte[] expectedBytes = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0A, (byte) 0x01, (byte) 0xFF, (byte) 0x00, (byte) 0x01 }; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv6.getBytes().getBytes()); } @Test public void should_parse_max_ip_string() { // Setup final String ipString = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"; final byte[] expectedBytes = new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv6.getBytes().getBytes()); } @Test public void should_return_null_when_segment_is_not_hex() { // Setup final String ipString = "FFFF:FFFF:FFFF:ZZZZ:FFFF:FFFF:FFFF:FFFF"; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } @Test public void should_return_null_when_segment_count_is_less_than_8() { // Setup final String ipString = "FFFF:FFFF:FFFF:FFFF"; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } @Test public void should_return_null_when_segment_count_is_greater_than_8() { // Setup final String ipString = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } @Test public void should_return_null_when_empty() { // Setup final String ipString = ""; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } @Test public void should_return_null_when_whitespace() { // Setup final String ipString = " \t "; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } @Test public void should_return_null_when_double_shorthand_markers_are_used() { // Setup final String ipString = "FF::FF::FF"; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } @Test public void should_return_null_when_beginning_with_shorthand_markers_and_multiple_are_used() { // Setup final String ipString = "::FF::FF"; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } @Test public void should_parse_untrimmed_loopback_ip_string() { // Setup final String ipString = " \t 0000:0000:0000:0000:0000:0000:0000:0001 \t "; final byte[] expectedBytes = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 }; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv6.getBytes().getBytes()); } @Test public void should_parse_compact_loopback_address() { // Setup final String ipString = "::1"; final byte[] expectedBytes = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 }; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv6.getBytes().getBytes()); } @Test public void should_parse_compact_address() { // Setup final String ipString = "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:1"; final byte[] expectedBytes = new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x01 }; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv6.getBytes().getBytes()); } @Test public void should_return_null_when_too_many_segments_are_provided_with_shorthand_marker() { // Setup final String ipString = "fc00:e968:6179::de52:7100:1:1:1:1:1"; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } @Test public void should_return_null_when_early_segments_contain_decimal_when_not_ipv4() { // Setup final String ipString = "1:1.0:1:1:1:1:1:1"; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } @Test public void should_return_null_when_late_segments_contain_decimal_when_not_ipv4() { // Setup final String ipString = "1:1:1:1:1.1.1.1"; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } @Test public void should_return_null_when_deprecated_ipv4_compatibility_address() { // Setup final String ipString = "::1.1.1.1"; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } @Test public void should_parse_ipv6_compatible_ipv4_address() { // Setup final String ipString = "::FFFF:192.168.1.1"; final byte[] expectedBytes = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xC0, (byte) 0xA8, (byte) 0x01, (byte) 0x01 }; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv6.getBytes().getBytes()); } @Test public void should_return_null_when_ipv6_compatible_ipv4_address_is_invalid_ipv4() { // Setup final String ipString = "::FF:Z.Z.Z.Z"; // Action final Ipv6 ipv6 = Ipv6.parse(ipString); // Assert Assert.assertNull(ipv6); } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/account/worker/CreateWorkerApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.worker; import com.softwareverde.bitcoin.miner.pool.AccountId; import com.softwareverde.bitcoin.miner.pool.WorkerId; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.bitcoin.server.module.stratum.database.AccountDatabaseManager; import com.softwareverde.database.DatabaseException; import com.softwareverde.http.HttpMethod; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.logging.Logger; import com.softwareverde.servlet.AuthenticatedServlet; public class CreateWorkerApi extends AuthenticatedServlet { protected final DatabaseConnectionFactory _databaseConnectionFactory; public CreateWorkerApi(final StratumProperties stratumProperties, final DatabaseConnectionFactory databaseConnectionFactory) { super(stratumProperties); _databaseConnectionFactory = databaseConnectionFactory; } @Override protected Response _onAuthenticatedRequest(final AccountId accountId, final Request request) { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); if (request.getMethod() != HttpMethod.POST) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid method.")); } { // CREATE WORKER // Requires GET: // Requires POST: username, password final String username = postParameters.get("username").trim(); final String password = postParameters.get("password"); if (username.isEmpty()) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid worker username.")); } try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { final AccountDatabaseManager accountDatabaseManager = new AccountDatabaseManager(databaseConnection); final WorkerId existingWorkerId = accountDatabaseManager.getWorkerId(username); if (existingWorkerId != null) { return new JsonResponse(Response.Codes.OK, new StratumApiResult(false, "A worker with that username already exists.")); } final WorkerId workerId = accountDatabaseManager.createWorker(accountId, username, password); if (workerId == null) { return new JsonResponse(Response.Codes.SERVER_ERROR, new StratumApiResult(false, "Unable to create worker.")); } final StratumApiResult result = new StratumApiResult(true, null); result.put("workerId", workerId); return new JsonResponse(Response.Codes.OK, result); } catch (final DatabaseException exception) { Logger.warn(exception); return new JsonResponse(Response.Codes.SERVER_ERROR, new StratumApiResult(false, "An internal error occurred.")); } } } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/sync/transaction/TransactionProcessorTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync.transaction; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.context.core.BlockProcessorContext; import com.softwareverde.bitcoin.context.core.BlockchainBuilderContext; import com.softwareverde.bitcoin.context.core.PendingBlockLoaderContext; import com.softwareverde.bitcoin.context.core.TransactionProcessorContext; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.module.node.BlockProcessor; import com.softwareverde.bitcoin.server.module.node.database.block.pending.fullnode.FullNodePendingBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.pending.PendingTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.sync.BlockchainBuilder; import com.softwareverde.bitcoin.server.module.node.sync.BlockchainBuilderTests; import com.softwareverde.bitcoin.server.module.node.sync.blockloader.PendingBlockLoader; import com.softwareverde.bitcoin.test.BlockData; import com.softwareverde.bitcoin.test.FakeBlockStore; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.bitcoin.test.util.BlockTestUtil; import com.softwareverde.bitcoin.test.util.TransactionTestUtil; import com.softwareverde.bitcoin.transaction.MutableTransaction; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.signer.HashMapTransactionOutputRepository; import com.softwareverde.concurrent.service.SleepyService; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.network.time.MutableNetworkTime; import com.softwareverde.util.HexUtil; import com.softwareverde.util.type.time.SystemTime; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TransactionProcessorTests extends IntegrationTest { protected static Long COINBASE_MATURITY = null; @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } @Test public void transaction_spending_output_spent_by_other_mempool_tx_should_be_invalid() throws Exception { // This test inserts MainChain's Genesis -> Block01 -> Block02, then creates a fake Block03 with a spendable coinbase. // The test then creates two transactions spending Block03's coinbase, and queues both for processing into the mempool. // Only one of the transactions should be added to the mempool. // Setup final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final TransactionInflaters transactionInflaters = _masterInflater; final AddressInflater addressInflater = new AddressInflater(); final FakeBlockStore blockStore = new FakeBlockStore(); final BlockchainBuilderTests.FakeBitcoinNodeManager bitcoinNodeManager = new BlockchainBuilderTests.FakeBitcoinNodeManager(); final BlockInflaters blockInflaters = BlockchainBuilderTests.FAKE_BLOCK_INFLATERS; final BlockProcessorContext blockProcessorContext = new BlockProcessorContext(blockInflaters, transactionInflaters, blockStore, _fullNodeDatabaseManagerFactory, new MutableNetworkTime(), _synchronizationStatus, _transactionValidatorFactory); final PendingBlockLoaderContext pendingBlockLoaderContext = new PendingBlockLoaderContext(blockInflaters, _fullNodeDatabaseManagerFactory, _threadPool); final BlockchainBuilderContext blockchainBuilderContext = new BlockchainBuilderContext(blockInflaters, _fullNodeDatabaseManagerFactory, bitcoinNodeManager, _threadPool); final BlockProcessor blockProcessor = new BlockProcessor(blockProcessorContext); final PendingBlockLoader pendingBlockLoader = new PendingBlockLoader(pendingBlockLoaderContext, 1); final Sha256Hash block02Hash; { final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(BlockData.MainChain.BLOCK_2)); block02Hash = block.getHash(); } final PrivateKey privateKey = PrivateKey.createNewKey(); final Block fakeBlock03; { final MutableBlock mutableBlock = BlockTestUtil.createBlock(); mutableBlock.setPreviousBlockHash(block02Hash); // Create a transaction that will be spent in the signed transaction. // This transaction will create an output that can be spent by the private key. final Transaction transactionToSpend = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(privateKey); mutableBlock.addTransaction(transactionToSpend); fakeBlock03 = mutableBlock; } final Transaction transactionToSpend = fakeBlock03.getCoinbaseTransaction(); final Transaction signedTransaction0; { final Transaction unsignedTransaction; { final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); final TransactionOutputIdentifier transactionOutputIdentifierToSpend = new TransactionOutputIdentifier(transactionToSpend.getHash(), 0); final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(transactionOutputIdentifierToSpend); mutableTransaction.addTransactionInput(transactionInput); final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput(addressInflater.fromBase58Check("149uLAy8vkn1Gm68t5NoLQtUqBtngjySLF", false)); mutableTransaction.addTransactionOutput(transactionOutput); unsignedTransaction = mutableTransaction; } { final HashMapTransactionOutputRepository transactionOutputRepository = new HashMapTransactionOutputRepository(); final List<TransactionOutput> transactionOutputsToSpend = transactionToSpend.getTransactionOutputs(); transactionOutputRepository.put(new TransactionOutputIdentifier(transactionToSpend.getHash(), 0), transactionOutputsToSpend.get(0)); signedTransaction0 = TransactionTestUtil.signTransaction(transactionOutputRepository, unsignedTransaction, privateKey); } } final Transaction signedTransaction1; { final Transaction unsignedTransaction; { final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); final TransactionOutputIdentifier transactionOutputIdentifierToSpend = new TransactionOutputIdentifier(transactionToSpend.getHash(), 0); final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(transactionOutputIdentifierToSpend); mutableTransaction.addTransactionInput(transactionInput); final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput(addressInflater.fromBase58Check("12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX", false)); mutableTransaction.addTransactionOutput(transactionOutput); unsignedTransaction = mutableTransaction; } { final HashMapTransactionOutputRepository transactionOutputRepository = new HashMapTransactionOutputRepository(); final List<TransactionOutput> transactionOutputsToSpend = transactionToSpend.getTransactionOutputs(); transactionOutputRepository.put(new TransactionOutputIdentifier(transactionToSpend.getHash(), 0), transactionOutputsToSpend.get(0)); signedTransaction1 = TransactionTestUtil.signTransaction(transactionOutputRepository, unsignedTransaction, privateKey); } } try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final FullNodePendingBlockDatabaseManager pendingBlockDatabaseManager = databaseManager.getPendingBlockDatabaseManager(); for (final String blockData : new String[]{ BlockData.MainChain.GENESIS_BLOCK, BlockData.MainChain.BLOCK_1, BlockData.MainChain.BLOCK_2 }) { final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(blockData)); pendingBlockDatabaseManager.storeBlock(block); } for (final Block block : new Block[] { fakeBlock03 }) { pendingBlockDatabaseManager.storeBlock(block); } final PendingTransactionDatabaseManager pendingTransactionDatabaseManager = databaseManager.getPendingTransactionDatabaseManager(); pendingTransactionDatabaseManager.storeTransaction(signedTransaction0); pendingTransactionDatabaseManager.storeTransaction(signedTransaction1); } { // Store the prerequisite blocks which sets up the utxo set for the mempool... final BlockchainBuilder blockchainBuilder = new BlockchainBuilder(blockchainBuilderContext, blockProcessor, pendingBlockLoader, BlockchainBuilderTests.FAKE_DOWNLOAD_STATUS_MONITOR, BlockchainBuilderTests.FAKE_BLOCK_DOWNLOAD_REQUESTER); final BlockchainBuilder.StatusMonitor statusMonitor = blockchainBuilder.getStatusMonitor(); blockchainBuilder.start(); final int maxSleepCount = 10; int sleepCount = 0; do { Thread.sleep(250L); sleepCount += 1; if (sleepCount >= maxSleepCount) { throw new RuntimeException("Test execution timeout exceeded."); } } while (statusMonitor.getStatus() != SleepyService.Status.SLEEPING); blockchainBuilder.stop(); } final MutableList<Transaction> processedTransactions = new MutableList<Transaction>(); final TransactionProcessorContext transactionProcessorContext = new TransactionProcessorContext(transactionInflaters, _fullNodeDatabaseManagerFactory, new MutableNetworkTime(), new SystemTime(), _transactionValidatorFactory); final TransactionProcessor transactionProcessor = new TransactionProcessor(transactionProcessorContext); transactionProcessor.setNewTransactionProcessedCallback(new TransactionProcessor.Callback() { @Override public void onNewTransactions(final List<Transaction> transactions) { processedTransactions.addAll(transactions); } }); { // Action final TransactionProcessor.StatusMonitor statusMonitor = transactionProcessor.getStatusMonitor(); transactionProcessor.start(); final int maxSleepCount = 50; int sleepCount = 0; do { Thread.sleep(250L); sleepCount += 1; if (sleepCount >= maxSleepCount) { throw new RuntimeException("Test execution timeout exceeded."); } } while (statusMonitor.getStatus() != SleepyService.Status.SLEEPING); transactionProcessor.stop(); } // Assert Assert.assertEquals(1, processedTransactions.getCount()); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/database/PendingBlockDatabaseManagerTests.java<|end_filename|> package com.softwareverde.bitcoin.server.database; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.bitcoin.server.module.node.database.block.fullnode.FullNodeBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.pending.fullnode.FullNodePendingBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.node.fullnode.FullNodeBitcoinNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.sync.block.pending.PendingBlockId; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.bitcoin.test.BlockData; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.bitcoin.test.fake.FakeBitcoinNode; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.database.DatabaseException; import com.softwareverde.network.p2p.node.NodeId; import com.softwareverde.util.HexUtil; import com.softwareverde.util.type.time.SystemTime; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class PendingBlockDatabaseManagerTests extends IntegrationTest { @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } protected void _insertFakePendingBlock(final Sha256Hash blockHash, final Long blockHeight) throws DatabaseException { final SystemTime systemTime = new SystemTime(); try (final DatabaseConnection databaseConnection = _database.newConnection()) { databaseConnection.executeSql( new Query("INSERT INTO pending_blocks (hash, timestamp, priority) VALUES (?, ?, ?)") .setParameter(blockHash) .setParameter(systemTime.getCurrentTimeInSeconds()) .setParameter(blockHeight) ); } } protected Map<NodeId, BitcoinNode> _insertFakePeers(final Integer peerCount) throws DatabaseException { final HashMap<NodeId, BitcoinNode> nodes = new HashMap<NodeId, BitcoinNode>(peerCount); try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final FullNodeBitcoinNodeDatabaseManager nodeDatabaseManager = databaseManager.getNodeDatabaseManager(); for (int i = 0; i < peerCount; i++) { final BitcoinNode node = new FakeBitcoinNode("192.168.1." + i, 8333, null, null); nodeDatabaseManager.storeNode(node); final NodeId nodeId = nodeDatabaseManager.getNodeId(node); nodes.put(nodeId, node); } } return nodes; } protected void _insertFakePeerInventory(final BitcoinNode node, final Long blockHeight, final Sha256Hash blockHash) throws DatabaseException { try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final FullNodeBitcoinNodeDatabaseManager nodeDatabaseManager = databaseManager.getNodeDatabaseManager(); nodeDatabaseManager.updateBlockInventory(node, blockHeight, blockHash); } } @Test public void should_return_priority_incomplete_blocks() throws DatabaseException { // Setup try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final FullNodeBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); synchronized (BlockHeaderDatabaseManager.MUTEX) { // Store the Genesis Block... final Block genesisBlock = blockInflater.fromBytes(HexUtil.hexStringToByteArray(BlockData.MainChain.GENESIS_BLOCK)); blockDatabaseManager.storeBlock(genesisBlock); } // Create fake peers... final Map<NodeId, BitcoinNode> nodes = _insertFakePeers(6); final HashMap<Sha256Hash, Long> blockHeights = new HashMap<Sha256Hash, Long>(1024); { // Store 1024 pending blocks... for (int i = 0; i < 1024; ++i) { final Long blockHeight = (i + 1L); final Sha256Hash blockHash = Sha256Hash.wrap(HashUtil.sha256(ByteUtil.integerToBytes(blockHeight))); blockHeights.put(blockHash, blockHeight); _insertFakePendingBlock(blockHash, blockHeight); // Ensure all peers have the block as available inventory... for (final NodeId nodeId : nodes.keySet()) { final BitcoinNode node = nodes.get(nodeId); _insertFakePeerInventory(node, blockHeight, blockHash); } } } final FullNodePendingBlockDatabaseManager pendingBlockDatabaseManager = databaseManager.getPendingBlockDatabaseManager(); { // Should return pendingBlocks when available... final List<NodeId> connectedNodeIds = new MutableList<NodeId>(nodes.keySet()); // Action final List<PendingBlockId> downloadPlan = pendingBlockDatabaseManager.selectIncompletePendingBlocks(1024); // Assert Assert.assertEquals(1024, downloadPlan.getCount()); } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/AbstractDatabaseConnectionFactory.java<|end_filename|> package com.softwareverde.bitcoin.server.database; import com.softwareverde.database.DatabaseException; import java.sql.Connection; public abstract class AbstractDatabaseConnectionFactory implements DatabaseConnectionFactory { protected final com.softwareverde.database.DatabaseConnectionFactory<Connection> _core; public AbstractDatabaseConnectionFactory(final com.softwareverde.database.DatabaseConnectionFactory<Connection> core) { _core = core; } @Override public abstract DatabaseConnection newConnection() throws DatabaseException; @Override public void close() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/coinbase/MutableCoinbaseTransaction.java<|end_filename|> package com.softwareverde.bitcoin.transaction.coinbase; import com.softwareverde.bitcoin.transaction.MutableTransaction; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.MutableTransactionInput; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.MutableTransactionOutput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.logging.Logger; public class MutableCoinbaseTransaction extends MutableTransaction implements CoinbaseTransaction { public MutableCoinbaseTransaction() { } public MutableCoinbaseTransaction(final Transaction transaction) { super(transaction); } public void setCoinbaseScript(final UnlockingScript unlockingScript) { if (_transactionInputs.isEmpty()) { Logger.warn("Attempted to set unlocking script on invalid coinbase transaction."); return; } final MutableTransactionInput transactionInput = new MutableTransactionInput(_transactionInputs.get(0)); transactionInput.setUnlockingScript(unlockingScript.asConst()); _transactionInputs.set(0, transactionInput); } @Override public UnlockingScript getCoinbaseScript() { if (_transactionInputs.isEmpty()) { return null; } final TransactionInput transactionInput = _transactionInputs.get(0); return transactionInput.getUnlockingScript(); } public void setBlockReward(final Long satoshis) { if (_transactionOutputs.isEmpty()) { Logger.warn("Attempted to set block reward on invalid coinbase transaction."); return; } final TransactionOutput transactionOutput = _transactionOutputs.get(0); final MutableTransactionOutput mutableTransactionOutput = new MutableTransactionOutput(transactionOutput); mutableTransactionOutput.setAmount(satoshis); _transactionOutputs.set(0, mutableTransactionOutput); } @Override public Long getBlockReward() { if (_transactionOutputs.isEmpty()) { return null; } final TransactionOutput transactionOutput = _transactionOutputs.get(0); return transactionOutput.getAmount(); } @Override public MutableCoinbaseTransaction asCoinbase() { return this; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/sync/BlockchainIndexerContextTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync; import com.softwareverde.bitcoin.context.AtomicTransactionOutputIndexerContext; import com.softwareverde.bitcoin.context.TransactionOutputIndexerContext; import com.softwareverde.bitcoin.context.lazy.LazyTransactionOutputIndexerContext; import com.softwareverde.bitcoin.test.IntegrationTest; import org.junit.After; import org.junit.Before; import org.junit.Test; public class BlockchainIndexerContextTests extends IntegrationTest { @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } @Test public void should_index_transaction_output() throws Exception { // Setup final TransactionOutputIndexerContext transactionOutputIndexerContext = new LazyTransactionOutputIndexerContext(_fullNodeDatabaseManagerFactory); // Action try (final AtomicTransactionOutputIndexerContext context = transactionOutputIndexerContext.newTransactionOutputIndexerContext()) { } // Assert } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/lazy/LazyUnconfirmedTransactionUtxoSet.java<|end_filename|> package com.softwareverde.bitcoin.context.lazy; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.context.UnspentTransactionOutputContext; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.FullNodeTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.output.UnconfirmedTransactionOutputDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.UnspentTransactionOutputDatabaseManager; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.UnconfirmedTransactionOutputId; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; public class LazyUnconfirmedTransactionUtxoSet implements UnspentTransactionOutputContext { protected final FullNodeDatabaseManager _databaseManager; protected final Boolean _includeUnconfirmedTransactions; public LazyUnconfirmedTransactionUtxoSet(final FullNodeDatabaseManager databaseManager) { this(databaseManager, false); } public LazyUnconfirmedTransactionUtxoSet(final FullNodeDatabaseManager databaseManager, final Boolean includeUnconfirmedTransactions) { _databaseManager = databaseManager; _includeUnconfirmedTransactions = includeUnconfirmedTransactions; } @Override public TransactionOutput getTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { try { if (_includeUnconfirmedTransactions) { final UnconfirmedTransactionOutputDatabaseManager unconfirmedTransactionOutputDatabaseManager = _databaseManager.getUnconfirmedTransactionOutputDatabaseManager(); final Boolean transactionOutputIsSpentWithinMempool = unconfirmedTransactionOutputDatabaseManager.isTransactionOutputSpent(transactionOutputIdentifier); if (transactionOutputIsSpentWithinMempool) { return null; } } final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = _databaseManager.getUnspentTransactionOutputDatabaseManager(); final TransactionOutput transactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(transactionOutputIdentifier); if (! _includeUnconfirmedTransactions) { return transactionOutput; } else if (transactionOutput == null) { final UnconfirmedTransactionOutputDatabaseManager unconfirmedTransactionOutputDatabaseManager = _databaseManager.getUnconfirmedTransactionOutputDatabaseManager(); final UnconfirmedTransactionOutputId transactionOutputId = unconfirmedTransactionOutputDatabaseManager.getUnconfirmedTransactionOutputId(transactionOutputIdentifier); return unconfirmedTransactionOutputDatabaseManager.getUnconfirmedTransactionOutput(transactionOutputId); } else { return transactionOutput; } } catch (final DatabaseException exception) { Logger.debug(exception); return null; } } @Override public Long getBlockHeight(final TransactionOutputIdentifier transactionOutputIdentifier) { try { final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); final BlockchainDatabaseManager blockchainDatabaseManager = _databaseManager.getBlockchainDatabaseManager(); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = _databaseManager.getBlockHeaderDatabaseManager(); final FullNodeTransactionDatabaseManager transactionDatabaseManager = _databaseManager.getTransactionDatabaseManager(); final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); if (transactionId == null) { return null; } // final Boolean isUnconfirmedTransaction = transactionDatabaseManager.isUnconfirmedTransaction(transactionId); // if (isUnconfirmedTransaction) { // final BlockId headBlockId = blockHeaderDatabaseManager.getHeadBlockHeaderId(); // return (blockHeaderDatabaseManager.getBlockHeight(headBlockId) + 1L); // } final BlockchainSegmentId blockchainSegmentId = blockchainDatabaseManager.getHeadBlockchainSegmentId(); final BlockId blockId = transactionDatabaseManager.getBlockId(blockchainSegmentId, transactionId); if (blockId == null) { return null; } return blockHeaderDatabaseManager.getBlockHeight(blockId); } catch (final DatabaseException exception) { Logger.debug(exception); return null; } } @Override public Sha256Hash getBlockHash(final TransactionOutputIdentifier transactionOutputIdentifier) { try { final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); final BlockchainDatabaseManager blockchainDatabaseManager = _databaseManager.getBlockchainDatabaseManager(); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = _databaseManager.getBlockHeaderDatabaseManager(); final FullNodeTransactionDatabaseManager transactionDatabaseManager = _databaseManager.getTransactionDatabaseManager(); final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); if (transactionId == null) { return null; } // final Boolean isUnconfirmedTransaction = transactionDatabaseManager.isUnconfirmedTransaction(transactionId); // if (isUnconfirmedTransaction) { return null; } final BlockchainSegmentId blockchainSegmentId = blockchainDatabaseManager.getHeadBlockchainSegmentId(); final BlockId blockId = transactionDatabaseManager.getBlockId(blockchainSegmentId, transactionId); if (blockId == null) { return null; } return blockHeaderDatabaseManager.getBlockHash(blockId); } catch (final DatabaseException exception) { Logger.debug(exception); return null; } } @Override public Boolean isCoinbaseTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { try { final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash(); final FullNodeTransactionDatabaseManager transactionDatabaseManager = _databaseManager.getTransactionDatabaseManager(); final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); if (transactionId == null) { return null; } return transactionDatabaseManager.isCoinbaseTransaction(transactionHash); } catch (final DatabaseException exception) { Logger.debug(exception); return null; } } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/v1/get/GetBlockTransactionsHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.v1.get; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.bitcoin.server.module.explorer.api.endpoint.BlocksApi; import com.softwareverde.bitcoin.server.module.node.rpc.NodeJsonRpcConnection; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.http.server.servlet.routed.RequestHandler; import com.softwareverde.json.Json; import com.softwareverde.util.Util; import java.util.Map; public class GetBlockTransactionsHandler implements RequestHandler<Environment> { /** * LIST TRANSACTIONS FOR BLOCK * Requires GET: blockHash, pageSize, pageNumber * Requires POST: */ @Override public Response handleRequest(final Request request, final Environment environment, final Map<String, String> urlParameters) throws Exception { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); final Sha256Hash blockHash = (urlParameters.containsKey("blockHash") ? Sha256Hash.fromHexString(urlParameters.get("blockHash")) : null); if (blockHash == null) { final BlocksApi.BlockTransactionsResult result = new BlocksApi.BlockTransactionsResult(); result.setWasSuccess(false); result.setErrorMessage("Invalid block hash."); return new JsonResponse(Response.Codes.BAD_REQUEST, result); } final Integer pageSize = (getParameters.containsKey("pageSize") ? Util.parseInt(getParameters.get("pageSize")) : null); if ( (pageSize == null) || (pageSize < 1) ) { final BlocksApi.BlockTransactionsResult result = new BlocksApi.BlockTransactionsResult(); result.setWasSuccess(false); result.setErrorMessage("Invalid page size."); return new JsonResponse(Response.Codes.BAD_REQUEST, result); } final Integer pageNumber = (getParameters.containsKey("pageNumber") ? Util.parseInt(getParameters.get("pageNumber")) : null); if ( (pageNumber == null) || (pageNumber < 0) ) { final BlocksApi.BlockTransactionsResult result = new BlocksApi.BlockTransactionsResult(); result.setWasSuccess(false); result.setErrorMessage("Invalid page number."); return new JsonResponse(Response.Codes.BAD_REQUEST, result); } final Json rpcResponseJson; try (final NodeJsonRpcConnection nodeJsonRpcConnection = environment.getNodeJsonRpcConnection()) { if (nodeJsonRpcConnection == null) { final BlocksApi.BlockTransactionsResult result = new BlocksApi.BlockTransactionsResult(); result.setWasSuccess(false); result.setErrorMessage("Unable to connect to node."); return new JsonResponse(Response.Codes.SERVER_ERROR, result); } rpcResponseJson = nodeJsonRpcConnection.getBlockTransactions(blockHash, pageSize, pageNumber); if (rpcResponseJson == null) { return new JsonResponse(Response.Codes.SERVER_ERROR, new BlocksApi.BlockTransactionsResult(false, "Request timed out.")); } } if (! rpcResponseJson.getBoolean("wasSuccess")) { final String errorMessage = rpcResponseJson.getString("errorMessage"); return new JsonResponse(Response.Codes.SERVER_ERROR, new BlocksApi.BlockTransactionsResult(false, errorMessage)); } final Json transactionsJson = rpcResponseJson.get("transactions"); final BlocksApi.BlockTransactionsResult blockTransactionsResult = new BlocksApi.BlockTransactionsResult(); blockTransactionsResult.setWasSuccess(true); blockTransactionsResult.setTransactions(transactionsJson); return new JsonResponse(Response.Codes.OK, blockTransactionsResult); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/opcode/Opcode.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode; import com.softwareverde.bitcoin.util.ByteUtil; public enum Opcode { // VALUE PUSH_NEGATIVE_ONE (0x4F), PUSH_ZERO (0x00), PUSH_VALUE (0x51, 0x60), PUSH_DATA (0x01, 0x4B), PUSH_DATA_BYTE (0x4C), PUSH_DATA_SHORT (0x4D), PUSH_DATA_INTEGER (0x4E), PUSH_VERSION (0x62, false), // DYNAMIC VALUE PUSH_STACK_SIZE (0x74), COPY_1ST (0x76), COPY_NTH (0x79), COPY_2ND (0x78), COPY_2ND_THEN_1ST (0x6E), COPY_3RD_THEN_2ND_THEN_1ST (0x6F), COPY_4TH_THEN_3RD (0x70), COPY_1ST_THEN_MOVE_TO_3RD (0x7D), // CONTROL IF (0x63), NOT_IF (0x64), ELSE (0x67), END_IF (0x68), VERIFY (0x69), RETURN (0x6A), IF_VERSION (0x65, false, true), IF_NOT_VERSION (0x66, false, true), // STACK POP_TO_ALT_STACK (0x6B), POP_FROM_ALT_STACK (0x6C), IF_1ST_TRUE_THEN_COPY_1ST (0x73), POP (0x75), REMOVE_2ND_FROM_TOP (0x77), MOVE_NTH_TO_1ST (0x7A), ROTATE_TOP_3 (0x7B), SWAP_1ST_WITH_2ND (0x7C), POP_THEN_POP (0x6D), MOVE_5TH_AND_6TH_TO_TOP (0x71), SWAP_1ST_2ND_WITH_3RD_4TH (0x72), // STRING CONCATENATE (0x7E), SPLIT (0x7F), NUMBER_TO_BYTES (0x80), ENCODE_NUMBER (0x81), PUSH_1ST_BYTE_COUNT (0x82), REVERSE_BYTES (0xBC), // BITWISE BITWISE_INVERT (0x83, false, true), BITWISE_AND (0x84), BITWISE_OR (0x85), BITWISE_XOR (0x86), SHIFT_LEFT (0x98, false, true), SHIFT_RIGHT (0x99, false, true), // COMPARISON INTEGER_AND (0x9A), INTEGER_OR (0x9B), IS_EQUAL (0x87), IS_EQUAL_THEN_VERIFY (0x88), IS_TRUE (0x92), IS_NUMERICALLY_EQUAL (0x9C), IS_NUMERICALLY_EQUAL_THEN_VERIFY (0x9D), IS_NUMERICALLY_NOT_EQUAL (0x9E), IS_LESS_THAN (0x9F), IS_GREATER_THAN (0xA0), IS_LESS_THAN_OR_EQUAL (0xA1), IS_GREATER_THAN_OR_EQUAL (0xA2), IS_WITHIN_RANGE (0xA5), // ARITHMETIC ADD_ONE (0x8B), SUBTRACT_ONE (0x8C), MULTIPLY_BY_TWO (0x8D, false, true), DIVIDE_BY_TWO (0x8E, false, true), NEGATE (0x8F), ABSOLUTE_VALUE (0x90), NOT (0x91), ADD (0x93), SUBTRACT (0x94), MULTIPLY (0x95, false, true), DIVIDE (0x96), MODULUS (0x97), MIN (0xA3), MAX (0xA4), // CRYPTOGRAPHIC RIPEMD_160 (0xA6), SHA_1 (0xA7), SHA_256 (0xA8), SHA_256_THEN_RIPEMD_160 (0xA9), DOUBLE_SHA_256 (0xAA), CHECK_SIGNATURE (0xAC), CHECK_SIGNATURE_THEN_VERIFY (0xAD), CHECK_MULTISIGNATURE (0xAE), CHECK_MULTISIGNATURE_THEN_VERIFY (0xAF), // CODE_SEPARATOR's intended use was to designate where signed-content is supposed to begin (rendering parts of the script mutable). // Its benefit seems rare and borderline useless, and is likely a security risk. // https://bitcoin.stackexchange.com/questions/34013/what-is-op-codeseparator-used-for CODE_SEPARATOR (0xAB), CHECK_DATA_SIGNATURE (0xBA), CHECK_DATA_SIGNATURE_THEN_VERIFY (0xBB), // LOCK TIME CHECK_LOCK_TIME_THEN_VERIFY (0xB1), CHECK_SEQUENCE_NUMBER_THEN_VERIFY (0xB2), // NO OPERATION NO_OPERATION (0x61), NO_OPERATION_1 (0xB0), NO_OPERATION_2 (0xB3, 0xB9), RESERVED (0x50, false), RESERVED_1 (0x89, 0x8A, false) ; // END ENUMS private final boolean _failIfPresent; private final boolean _isEnabled; private final int _minValue; private final int _maxValue; Opcode(final int base) { _minValue = base; _maxValue = base; _isEnabled = true; _failIfPresent = false; } Opcode(final int base, final boolean isEnabled) { _minValue = base; _maxValue = base; _isEnabled = isEnabled; _failIfPresent = false; } Opcode(final int base, final boolean isEnabled, final boolean failIfPresent) { _minValue = base; _maxValue = base; _isEnabled = isEnabled; _failIfPresent = failIfPresent; } Opcode(final int minValue, final int maxValue) { _minValue = minValue; _maxValue = maxValue; _isEnabled = true; _failIfPresent = false; } Opcode(final int minValue, final int maxValue, final boolean isEnabled) { _minValue = minValue; _maxValue = maxValue; _isEnabled = isEnabled; _failIfPresent = false; } Opcode(final int minValue, final int maxValue, final boolean isEnabled, final boolean failIfPresent) { _minValue = minValue; _maxValue = maxValue; _isEnabled = isEnabled; _failIfPresent = failIfPresent; } public boolean isEnabled() { return _isEnabled; } public byte getValue() { return (byte) _minValue; } public int getMinValue() { return _minValue; } public int getMaxValue() { return _maxValue; } public boolean failIfPresent() { return _failIfPresent; } public boolean matchesByte(final byte b) { final int bValue = ByteUtil.byteToInteger(b); return (_minValue <= bValue && bValue <= _maxValue); } } <|start_filename|>src/main/java/com/softwareverde/network/socket/BinarySocketReadThread.java<|end_filename|> package com.softwareverde.network.socket; import com.softwareverde.logging.Logger; import com.softwareverde.logging.LoggerInstance; import com.softwareverde.network.p2p.message.ProtocolMessage; import java.io.IOException; import java.io.InputStream; public class BinarySocketReadThread extends Thread implements Socket.ReadThread { private static final LoggerInstance LOG = Logger.getInstance(BinarySocketReadThread.class); private final PacketBuffer _protocolMessageBuffer; private InputStream _rawInputStream; private Callback _callback; private Long _totalBytesReceived = 0L; public BinarySocketReadThread(final Integer bufferPageSize, final Integer maxByteCount, final BinaryPacketFormat binaryPacketFormat) { this.setName("Binary Socket - Read Thread - " + this.getId()); _protocolMessageBuffer = new PacketBuffer(binaryPacketFormat); _protocolMessageBuffer.setPageByteCount(bufferPageSize); _protocolMessageBuffer.setMaxByteCount(maxByteCount); } @Override public void run() { while (true) { try { final byte[] buffer = _protocolMessageBuffer.getRecycledBuffer(); final int bytesRead = _rawInputStream.read(buffer); if (bytesRead < 0) { throw new IOException("IO: Remote socket closed the connection."); } _totalBytesReceived += bytesRead; _protocolMessageBuffer.appendBytes(buffer, bytesRead); _protocolMessageBuffer.evictCorruptedPackets(); if (LOG.isDebugEnabled()) { final int byteCount = _protocolMessageBuffer.getByteCount(); final int bufferPageCount = _protocolMessageBuffer.getPageCount(); final int bufferPageByteCount = _protocolMessageBuffer.getPageByteCount(); final float utilizationPercent = ((int) (byteCount / (bufferPageCount * ((float) bufferPageByteCount)) * 100)); LOG.debug("[Received " + bytesRead + " bytes from socket.] (Bytes In Buffer: " + byteCount + ") (Buffer Count: " + bufferPageCount + ") (" + utilizationPercent + "%)"); } while (_protocolMessageBuffer.hasMessage()) { final ProtocolMessage message = _protocolMessageBuffer.popMessage(); _protocolMessageBuffer.evictCorruptedPackets(); if (_callback != null) { if (message != null) { _callback.onNewMessage(message); } } } if (this.isInterrupted()) { break; } } catch (final Exception exception) { LOG.debug(exception); break; } } if (_callback != null) { _callback.onExit(); } } @Override public void setInputStream(final InputStream inputStream) { if (_rawInputStream != null) { try { _rawInputStream.close(); } catch (final Exception exception) { } } _rawInputStream = inputStream; } @Override public void setCallback(final Callback callback) { _callback = callback; } public void setBufferPageByteCount(final Integer pageSize) { _protocolMessageBuffer.setPageByteCount(pageSize); } public void setBufferMaxByteCount(final Integer bufferSize) { _protocolMessageBuffer.setMaxByteCount(bufferSize); } public PacketBuffer getProtocolMessageBuffer() { return _protocolMessageBuffer; } @Override public Long getTotalBytesReceived() { return _totalBytesReceived; } } <|start_filename|>src/main/java/com/softwareverde/network/p2p/node/address/NodeIpAddress.java<|end_filename|> package com.softwareverde.network.p2p.node.address; import com.softwareverde.network.ip.Ip; import com.softwareverde.network.ip.Ipv4; import com.softwareverde.util.Util; public class NodeIpAddress { protected Ip _ip; protected Integer _port; public NodeIpAddress() { _ip = new Ipv4(); _port = 0x0000; } public NodeIpAddress(final Ip ip, final Integer port) { _ip = ip; _port = port; } public void setIp(final Ip ip) { _ip = ip; } public Ip getIp() { return _ip; } public void setPort(final Integer port) { _port = port; } public Integer getPort() { return _port; } public NodeIpAddress copy() { final NodeIpAddress nodeIpAddress = new NodeIpAddress(); nodeIpAddress._ip = _ip; nodeIpAddress._port = _port; return nodeIpAddress; } @Override public boolean equals(final Object object) { if (object == null) { return false; } if (! (object instanceof NodeIpAddress)) { return false; } final NodeIpAddress nodeIpAddress = (NodeIpAddress) object; if (! Util.areEqual(_ip, nodeIpAddress._ip)) { return false; } return Util.areEqual(_port, nodeIpAddress._port); } @Override public int hashCode() { return (_ip.hashCode() + _port.hashCode()); } @Override public String toString() { return (_ip.toString() + ":" + _port); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/node/ping/BitcoinPingMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.node.ping; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.util.bytearray.ByteArrayReader; import com.softwareverde.util.bytearray.Endian; public class BitcoinPingMessageInflater extends BitcoinProtocolMessageInflater { @Override public BitcoinPingMessage fromBytes(final byte[] bytes) { final BitcoinPingMessage pingMessage = new BitcoinPingMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.PING); if (protocolMessageHeader == null) { return null; } pingMessage._nonce = byteArrayReader.readLong(8, Endian.LITTLE); if (byteArrayReader.didOverflow()) { return null; } return pingMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/block/pending/inventory/MutableUnknownBlockInventory.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.block.pending.inventory; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public class MutableUnknownBlockInventory implements UnknownBlockInventory { protected Sha256Hash _previousBlockHash; protected Sha256Hash _firstUnknownBlockHash; protected Sha256Hash _lastUnknownBlockHash; public MutableUnknownBlockInventory() { this(null, null, null); } public MutableUnknownBlockInventory(final Sha256Hash firstUnknownBlockHash, final Sha256Hash lastUnknownBlockHash) { this(null, firstUnknownBlockHash, lastUnknownBlockHash); } public MutableUnknownBlockInventory(final Sha256Hash previousBlockHash, final Sha256Hash requestedBlockHash, final Sha256Hash stopAtBlockHash) { _previousBlockHash = previousBlockHash; _firstUnknownBlockHash = requestedBlockHash; _lastUnknownBlockHash = stopAtBlockHash; } public void setPreviousBlockHash(final Sha256Hash previousBlockHash) { _previousBlockHash = previousBlockHash; } public void setFirstUnknownBlockHash(final Sha256Hash firstUnknownBlockHash) { _firstUnknownBlockHash = firstUnknownBlockHash; } public void setLastUnknownBlockHash(final Sha256Hash lastUnknownBlockHash) { _lastUnknownBlockHash = lastUnknownBlockHash; } @Override public Sha256Hash getPreviousBlockHash() { return _previousBlockHash; } @Override public Sha256Hash getFirstUnknownBlockHash() { return _previousBlockHash; } @Override public Sha256Hash getLastUnknownBlockHash() { return _lastUnknownBlockHash; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/opcode/Operation.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode; import com.softwareverde.bitcoin.bip.HF20191115; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.transaction.script.opcode.controlstate.CodeBlock; import com.softwareverde.bitcoin.transaction.script.runner.ControlState; import com.softwareverde.bitcoin.transaction.script.runner.context.MutableTransactionContext; import com.softwareverde.bitcoin.transaction.script.runner.context.TransactionContext; import com.softwareverde.bitcoin.transaction.script.stack.Stack; import com.softwareverde.bitcoin.transaction.script.stack.Value; import com.softwareverde.constable.Const; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.util.HexUtil; import com.softwareverde.util.Util; import java.util.ArrayList; import java.util.List; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.ABSOLUTE_VALUE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.ADD; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.ADD_ONE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.BITWISE_AND; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.BITWISE_INVERT; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.BITWISE_OR; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.BITWISE_XOR; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.CHECK_DATA_SIGNATURE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.CHECK_DATA_SIGNATURE_THEN_VERIFY; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.CHECK_LOCK_TIME_THEN_VERIFY; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.CHECK_MULTISIGNATURE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.CHECK_MULTISIGNATURE_THEN_VERIFY; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.CHECK_SEQUENCE_NUMBER_THEN_VERIFY; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.CHECK_SIGNATURE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.CHECK_SIGNATURE_THEN_VERIFY; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.CODE_SEPARATOR; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.CONCATENATE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.COPY_1ST; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.COPY_1ST_THEN_MOVE_TO_3RD; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.COPY_2ND; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.COPY_2ND_THEN_1ST; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.COPY_3RD_THEN_2ND_THEN_1ST; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.COPY_4TH_THEN_3RD; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.COPY_NTH; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.DIVIDE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.DIVIDE_BY_TWO; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.DOUBLE_SHA_256; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.ELSE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.ENCODE_NUMBER; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.END_IF; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IF; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IF_1ST_TRUE_THEN_COPY_1ST; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IF_NOT_VERSION; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IF_VERSION; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.INTEGER_AND; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.INTEGER_OR; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IS_EQUAL; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IS_EQUAL_THEN_VERIFY; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IS_GREATER_THAN; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IS_GREATER_THAN_OR_EQUAL; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IS_LESS_THAN; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IS_LESS_THAN_OR_EQUAL; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IS_NUMERICALLY_EQUAL; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IS_NUMERICALLY_EQUAL_THEN_VERIFY; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IS_NUMERICALLY_NOT_EQUAL; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IS_TRUE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.IS_WITHIN_RANGE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.MAX; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.MIN; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.MODULUS; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.MOVE_5TH_AND_6TH_TO_TOP; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.MOVE_NTH_TO_1ST; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.MULTIPLY; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.MULTIPLY_BY_TWO; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.NEGATE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.NOT; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.NOT_IF; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.NO_OPERATION; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.NO_OPERATION_1; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.NO_OPERATION_2; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.NUMBER_TO_BYTES; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.POP; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.POP_FROM_ALT_STACK; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.POP_THEN_POP; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.POP_TO_ALT_STACK; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.PUSH_1ST_BYTE_COUNT; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.PUSH_DATA; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.PUSH_DATA_BYTE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.PUSH_DATA_INTEGER; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.PUSH_DATA_SHORT; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.PUSH_NEGATIVE_ONE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.PUSH_STACK_SIZE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.PUSH_VALUE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.PUSH_VERSION; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.PUSH_ZERO; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.REMOVE_2ND_FROM_TOP; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.RESERVED; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.RESERVED_1; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.RETURN; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.REVERSE_BYTES; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.RIPEMD_160; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.ROTATE_TOP_3; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.SHA_1; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.SHA_256; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.SHA_256_THEN_RIPEMD_160; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.SHIFT_LEFT; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.SHIFT_RIGHT; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.SPLIT; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.SUBTRACT; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.SUBTRACT_ONE; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.SWAP_1ST_2ND_WITH_3RD_4TH; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.SWAP_1ST_WITH_2ND; import static com.softwareverde.bitcoin.transaction.script.opcode.Opcode.VERIFY; public abstract class Operation implements Const { public static class ScriptOperationExecutionException extends Exception { } public enum Type { OP_PUSH (PUSH_NEGATIVE_ONE, PUSH_ZERO, PUSH_VALUE, PUSH_DATA, PUSH_DATA_BYTE, PUSH_DATA_SHORT, PUSH_DATA_INTEGER, PUSH_VERSION), OP_DYNAMIC_VALUE(PUSH_STACK_SIZE, COPY_1ST, COPY_NTH, COPY_2ND, COPY_2ND_THEN_1ST, COPY_3RD_THEN_2ND_THEN_1ST, COPY_4TH_THEN_3RD, COPY_1ST_THEN_MOVE_TO_3RD), OP_CONTROL (IF, NOT_IF, ELSE, END_IF, VERIFY, RETURN, IF_VERSION, IF_NOT_VERSION), OP_STACK (POP_TO_ALT_STACK, POP_FROM_ALT_STACK, IF_1ST_TRUE_THEN_COPY_1ST, POP, REMOVE_2ND_FROM_TOP, MOVE_NTH_TO_1ST, ROTATE_TOP_3, SWAP_1ST_WITH_2ND, POP_THEN_POP, MOVE_5TH_AND_6TH_TO_TOP, SWAP_1ST_2ND_WITH_3RD_4TH), OP_STRING (CONCATENATE, SPLIT, ENCODE_NUMBER, NUMBER_TO_BYTES, PUSH_1ST_BYTE_COUNT, REVERSE_BYTES), OP_BITWISE (BITWISE_INVERT, BITWISE_AND, BITWISE_OR, BITWISE_XOR, SHIFT_LEFT, SHIFT_RIGHT), OP_COMPARISON (INTEGER_AND, INTEGER_OR, IS_EQUAL, IS_EQUAL_THEN_VERIFY, IS_TRUE, IS_NUMERICALLY_EQUAL, IS_NUMERICALLY_EQUAL_THEN_VERIFY, IS_NUMERICALLY_NOT_EQUAL, IS_LESS_THAN, IS_GREATER_THAN, IS_LESS_THAN_OR_EQUAL, IS_GREATER_THAN_OR_EQUAL, IS_WITHIN_RANGE), OP_ARITHMETIC (ADD_ONE, SUBTRACT_ONE, MULTIPLY_BY_TWO, DIVIDE_BY_TWO, NEGATE, ABSOLUTE_VALUE, NOT, ADD, SUBTRACT, MULTIPLY, DIVIDE, MODULUS, MIN, MAX), OP_CRYPTOGRAPHIC(RIPEMD_160, SHA_1, SHA_256, SHA_256_THEN_RIPEMD_160, DOUBLE_SHA_256, CODE_SEPARATOR, CHECK_SIGNATURE, CHECK_SIGNATURE_THEN_VERIFY, CHECK_MULTISIGNATURE, CHECK_MULTISIGNATURE_THEN_VERIFY, CHECK_DATA_SIGNATURE, CHECK_DATA_SIGNATURE_THEN_VERIFY), OP_LOCK_TIME (CHECK_LOCK_TIME_THEN_VERIFY, CHECK_SEQUENCE_NUMBER_THEN_VERIFY), OP_NOTHING (NO_OPERATION, NO_OPERATION_1, NO_OPERATION_2, RESERVED, RESERVED_1), OP_INVALID () ; // END ENUMS public static Type getType(final byte typeByte) { for (final Type type : Type.values()) { for (final Opcode opcode : type._opcodes) { if (opcode.matchesByte(typeByte)) { return type; } } } return OP_INVALID; } private final Opcode[] _opcodes; Type(final Opcode... opcodes) { _opcodes = Util.copyArray(opcodes); } public List<Opcode> getSubtypes() { final List<Opcode> opcodes = new ArrayList<Opcode>(_opcodes.length); for (final Opcode opcode : _opcodes) { opcodes.add(opcode); } return opcodes; } public Opcode getSubtype(final byte b) { for (final Opcode opcode : _opcodes) { if (opcode.matchesByte(b)) { return opcode; } } return null; } } protected static Boolean isWithinIntegerRange(final Long value) { return ( (value <= Integer.MAX_VALUE) && (value > Integer.MIN_VALUE) ); // MIP-Encoding -2147483648 requires 5 bytes... } protected static Boolean isMinimallyEncoded(final ByteArray byteArray) { final ByteArray minimallyEncodedByteArray = Value.minimallyEncodeBytes(byteArray); if (minimallyEncodedByteArray == null) { return false; } return (byteArray.getByteCount() == minimallyEncodedByteArray.getByteCount()); } protected static Boolean validateMinimalEncoding(final Value value, final TransactionContext transactionContext) { final MedianBlockTime medianBlockTime = transactionContext.getMedianBlockTime(); if (! HF20191115.isEnabled(medianBlockTime)) { return true; } return Operation.isMinimallyEncoded(value); } protected final byte _opcodeByte; protected final Type _type; protected Operation(final byte value, final Type type) { _opcodeByte = value; _type = type; } public byte getOpcodeByte() { return _opcodeByte; } public Type getType() { return _type; } public abstract Boolean applyTo(final Stack stack, final ControlState controlState, final MutableTransactionContext context) throws ScriptOperationExecutionException; public Boolean shouldExecute(final Stack stack, final ControlState controlState, final TransactionContext transactionContext) { if (controlState.isInCodeBlock()) { final CodeBlock codeBlock = controlState.getCodeBlock(); return Util.coalesce(codeBlock.condition, false); } return true; } public Boolean failIfPresent() { final Opcode opcode = _type.getSubtype(_opcodeByte); if (opcode == null) { return false; } // Undefined subtypes are allowed to be present... return opcode.failIfPresent(); } public byte[] getBytes() { return new byte[] { _opcodeByte }; } @Override public boolean equals(final Object object) { if (object == null) { return false; } if (! (object instanceof Operation)) { return false ;} final Operation operation = (Operation) object; if (operation._type != _type) { return false; } if (operation._opcodeByte != _opcodeByte) { return false; } return true; } @Override public String toString() { return "0x" + HexUtil.toHexString(new byte[] { _opcodeByte } ) + " " + _type; } public String toStandardString() { return "0x" + HexUtil.toHexString(new byte[] { _opcodeByte } ); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/rpc/blockchain/BlockchainMetadata.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.rpc.blockchain; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.constable.Const; import com.softwareverde.json.Json; import com.softwareverde.json.Jsonable; public class BlockchainMetadata implements Const, Jsonable { protected BlockchainSegmentId _blockchainSegmentId; protected BlockchainSegmentId _parentBlockchainSegmentId; protected Integer _nestedSetLeft; protected Integer _nestedSetRight; protected Long _blockCount; protected Long _minBlockHeight; protected Long _maxBlockHeight; public BlockchainSegmentId getBlockchainSegmentId() { return _blockchainSegmentId; } public BlockchainSegmentId getParentBlockchainSegmentId() { return _parentBlockchainSegmentId; } public Integer getNestedSetLeft() { return _nestedSetLeft; } public Integer getNestedSetRight() { return _nestedSetRight; } public Long getBlockCount() { return _blockCount; } public Long getMinBlockHeight() { return _minBlockHeight; } public Long getMaxBlockHeight() { return _maxBlockHeight; } @Override public Json toJson() { final Json json = new Json(); json.put("blockchainSegmentId", _blockchainSegmentId); json.put("parentBlockchainSegmentId", _parentBlockchainSegmentId); json.put("nestedSetLeft", _nestedSetLeft); json.put("nestedSetRight", _nestedSetRight); json.put("blockCount", _blockCount); json.put("minBlockHeight", _minBlockHeight); json.put("maxBlockHeight", _maxBlockHeight); return json; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/sync/blockloader/BlockFuture.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync.blockloader; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.concurrent.Pin; import com.softwareverde.logging.Logger; import java.util.concurrent.ConcurrentLinkedDeque; public class BlockFuture implements PreloadedBlock { protected final Pin _pin; protected final Long _blockHeight; protected final ConcurrentLinkedDeque<PendingBlockFuture> _predecessorBlocks = new ConcurrentLinkedDeque<PendingBlockFuture>(); protected volatile Block _block; public BlockFuture(final Long blockHeight) { _pin = new Pin(); _blockHeight = blockHeight; _block = null; } @Override public Long getBlockHeight() { return _blockHeight; } /** * Returns the Block once it has been loaded, or null if it has not been loaded yet. */ @Override public Block getBlock() { if (! _pin.wasReleased()) { Logger.debug("Attempted to get block on unreleased block.", new Exception()); return null; } return _block; } /** * Blocks until the PendingBlock and its TransactionOutputSet have been loaded. */ public void waitFor() { _pin.waitForRelease(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/MedianBlockTimeContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; public interface MedianBlockTimeContext { MedianBlockTime getMedianBlockTime(Long blockHeight); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/signature/hashtype/HashType.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.signature.hashtype; public class HashType { public static final Integer BYTE_COUNT = 1; protected static final byte ANYONE_CAN_PAY_FLAG = (byte) 0x80; protected static final byte BITCOIN_CASH_FLAG = (byte) 0x40; protected static final byte USED_BITS_MASK = (BITCOIN_CASH_FLAG | ANYONE_CAN_PAY_FLAG | Mode.USED_BITS_MASK); // Bitmask containing the range of bits used to determine the HashType. public static HashType fromByte(final byte b) { return new HashType(b); } protected final byte _value; // NOTE: The raw byte provided to HashType.fromByte() is needed in order to verify // the signature, since it may have other bits set that are currently meaningless... protected final Mode _mode; protected final Boolean _shouldSignOtherInputs; // Bitcoin calls this "ANYONECANPAY" (_shouldSignOtherInputs being false indicates anyone can pay)... protected HashType(final byte value) { final Boolean shouldSignOnlyOneInput = ((value & 0x80) != 0x00); _value = value; _mode = Mode.fromByte(value); _shouldSignOtherInputs = (! shouldSignOnlyOneInput); } public HashType(final Mode mode, final Boolean shouldSignOtherInputs, final Boolean useBitcoinCash) { { byte value = mode.getValue(); if (! shouldSignOtherInputs) { value |= ANYONE_CAN_PAY_FLAG; } if (useBitcoinCash) { value |= BITCOIN_CASH_FLAG; } _value = value; } _mode = mode; _shouldSignOtherInputs = shouldSignOtherInputs; } public Mode getMode() { return _mode; } // NOTE: Bitcoin refers to this as "SIGHASH_FORKID"... public Boolean isBitcoinCashType() { return ((_value & BITCOIN_CASH_FLAG) != 0x00); } public Boolean shouldSignOtherInputs() { return _shouldSignOtherInputs; } public byte toByte() { return _value; } public Boolean hasUnknownFlags() { return ((_value & ~(HashType.USED_BITS_MASK)) != 0x00); } @Override public int hashCode() { return (_mode.hashCode() + _shouldSignOtherInputs.hashCode()); } @Override public boolean equals(final Object object) { if (object == null) { return false; } if (! (object instanceof HashType)) { return false; } final HashType hashType = (HashType) object; if (hashType._shouldSignOtherInputs != _shouldSignOtherInputs) { return false; } if (! hashType._mode.equals(_mode)) { return false; } return true; } @Override public String toString() { return _mode + ":" + _shouldSignOtherInputs; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/message/server/MinerSubmitBlockResult.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.message.server; import com.softwareverde.bitcoin.server.stratum.message.ResponseMessage; public class MinerSubmitBlockResult extends ResponseMessage { public MinerSubmitBlockResult(final Integer messageId, final Boolean wasAccepted) { super(messageId); _result = (wasAccepted ? RESULT_TRUE : RESULT_FALSE); } } <|start_filename|>explorer/www/js/list-blocks.js<|end_filename|> class ListBlocksUi { static search(objectHash) { document.location.href = "/?search=" + window.encodeURIComponent(objectHash); } } $(document).ready(function() { const searchInput = $("#search"); const loadingImage = $("#search-loading-image"); searchInput.keypress(function(event) { const key = event.which; if (key == KeyCodes.ENTER) { loadingImage.css("visibility", "visible"); const hash = searchInput.val(); ListBlocksUi.search(hash); return false; } }); loadingImage.css("visibility", "visible"); const parameters = { blockHeight: null, maxBlockCount: 25 }; Api.listBlockHeaders(parameters, function(data) { loadingImage.css("visibility", "hidden"); const wasSuccess = data.wasSuccess; const errorMessage = data.errorMessage; const blockHeaders = data.blockHeaders; if (wasSuccess) { $("#main > div:not(.table-header)").remove(); for (const i in blockHeaders) { const blockHeader = blockHeaders[i]; const blockUi = Ui.inflateBlock(blockHeader); const blockHashSpan = $(".block-header .hash .value", blockUi); blockHashSpan.toggleClass("clickable", true); blockHashSpan.on("click", function(event) { ListBlocksUi.search(blockHeader.hash); }); blockUi.hide(); $("#main").append(blockUi); blockUi.fadeIn(500); } } else { console.log(errorMessage); } }); }); <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/task/StratumMineBlockTask.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.task; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.ImmutableBlock; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.MutableBlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.merkleroot.MerkleRoot; import com.softwareverde.bitcoin.merkleroot.MutableMerkleRoot; import com.softwareverde.bitcoin.server.stratum.message.RequestMessage; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.util.BitcoinUtil; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.json.Json; import com.softwareverde.util.HexUtil; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.type.time.SystemTime; public class StratumMineBlockTask { protected List<String> _merkleTreeBranches; // Little-endian merkle tree (intermediary) branch hashes... protected final ByteArray _id; protected final Long _idLong; protected final Block _prototypeBlock; protected final String _extraNonce1; protected final String _coinbaseTransactionHead; protected final String _coinbaseTransactionTail; protected final Long _timestampInSeconds; // Creates the partialMerkleTree Json as little-endian hashes... protected void _buildMerkleTreeBranches() { final ImmutableListBuilder<String> listBuilder = new ImmutableListBuilder<String>(); final List<Sha256Hash> partialMerkleTree = _prototypeBlock.getPartialMerkleTree(0); for (final Sha256Hash hash : partialMerkleTree) { final String hashString = hash.toString(); listBuilder.add(BitcoinUtil.reverseEndianString(hashString)); } _merkleTreeBranches = listBuilder.build(); } public static MerkleRoot calculateMerkleRoot(final Transaction coinbaseTransaction, final List<String> merkleTreeBranches) { final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byte[] merkleRoot = coinbaseTransaction.getHash().toReversedEndian().getBytes(); for (final String merkleBranch : merkleTreeBranches) { final byte[] concatenatedHashes; { byteArrayBuilder.appendBytes(merkleRoot); byteArrayBuilder.appendBytes(HexUtil.hexStringToByteArray(merkleBranch)); concatenatedHashes = byteArrayBuilder.build(); byteArrayBuilder.clear(); } merkleRoot = HashUtil.doubleSha256(concatenatedHashes); } return MutableMerkleRoot.wrap(ByteUtil.reverseEndian(merkleRoot)); } protected Transaction _assembleCoinbaseTransaction(final String stratumExtraNonce2) { final TransactionInflater transactionInflater = new TransactionInflater(); return transactionInflater.fromBytes(HexUtil.hexStringToByteArray( _coinbaseTransactionHead + _extraNonce1 + stratumExtraNonce2 + _coinbaseTransactionTail )); } protected BlockHeader _assembleBlockHeader(final String stratumNonce, final String stratumExtraNonce2, final String stratumTimestamp) { final Transaction coinbaseTransaction = _assembleCoinbaseTransaction(stratumExtraNonce2); return _assembleBlockHeader(stratumNonce, coinbaseTransaction, stratumTimestamp); } protected BlockHeader _assembleBlockHeader(final String stratumNonce, final Transaction coinbaseTransaction, final String stratumTimestamp) { final MutableBlockHeader blockHeader = new MutableBlockHeader(_prototypeBlock); final MerkleRoot merkleRoot = calculateMerkleRoot(coinbaseTransaction, _merkleTreeBranches); blockHeader.setMerkleRoot(merkleRoot); blockHeader.setNonce(ByteUtil.bytesToLong(HexUtil.hexStringToByteArray(stratumNonce))); final Long timestamp = ByteUtil.bytesToLong(HexUtil.hexStringToByteArray(stratumTimestamp)); blockHeader.setTimestamp(timestamp); return blockHeader; } protected RequestMessage _createRequest(final Boolean abandonOldJobs) { final RequestMessage mineBlockMessage = new RequestMessage(RequestMessage.ServerCommand.NOTIFY.getValue()); final Json parametersJson = new Json(true); parametersJson.add(_id); parametersJson.add(StratumUtil.swabHexString(BitcoinUtil.reverseEndianString(HexUtil.toHexString(_prototypeBlock.getPreviousBlockHash().getBytes())))); parametersJson.add(_coinbaseTransactionHead); parametersJson.add(_coinbaseTransactionTail); final Json partialMerkleTreeJson = new Json(true); for (final String hashString : _merkleTreeBranches) { partialMerkleTreeJson.add(hashString); } parametersJson.add(partialMerkleTreeJson); parametersJson.add(HexUtil.toHexString(ByteUtil.integerToBytes(_prototypeBlock.getVersion()))); parametersJson.add(_prototypeBlock.getDifficulty().encode()); parametersJson.add(HexUtil.toHexString(ByteUtil.integerToBytes(_timestampInSeconds))); parametersJson.add(abandonOldJobs); mineBlockMessage.setParameters(parametersJson); return mineBlockMessage; } public StratumMineBlockTask(final ByteArray id, final Block prototypeBlock, final String coinbaseTransactionHead, final String coinbaseTransactionTail, final String extraNonce1) { _id = id.asConst(); _prototypeBlock = prototypeBlock.asConst(); _coinbaseTransactionHead = coinbaseTransactionHead; _coinbaseTransactionTail = coinbaseTransactionTail; _extraNonce1 = extraNonce1; final SystemTime systemTime = new SystemTime(); _timestampInSeconds = systemTime.getCurrentTimeInSeconds(); _idLong = ByteUtil.bytesToLong(_id.getBytes()); _buildMerkleTreeBranches(); } public Long getId() { return _idLong; } public String getExtraNonce() { return _extraNonce1; } public Difficulty getDifficulty() { return _prototypeBlock.getDifficulty(); } public Long getTimestamp() { return _timestampInSeconds; } public BlockHeader assembleBlockHeader(final String stratumNonce, final String stratumExtraNonce2, final String stratumTimestamp) { final MutableBlockHeader blockHeader = new MutableBlockHeader(_prototypeBlock); final TransactionInflater transactionInflater = new TransactionInflater(); final MerkleRoot merkleRoot; { final Transaction coinbaseTransaction = transactionInflater.fromBytes(HexUtil.hexStringToByteArray( _coinbaseTransactionHead + _extraNonce1 + stratumExtraNonce2 + _coinbaseTransactionTail )); merkleRoot = calculateMerkleRoot(coinbaseTransaction, _merkleTreeBranches); } blockHeader.setMerkleRoot(merkleRoot); blockHeader.setNonce(ByteUtil.bytesToLong(HexUtil.hexStringToByteArray(stratumNonce))); final Long timestamp = ByteUtil.bytesToLong(HexUtil.hexStringToByteArray(stratumTimestamp)); blockHeader.setTimestamp(timestamp); return blockHeader; } public Block assembleBlock(final String stratumNonce, final String stratumExtraNonce2, final String stratumTimestamp) { final Transaction coinbaseTransaction = _assembleCoinbaseTransaction(stratumExtraNonce2); final BlockHeader blockHeader = _assembleBlockHeader(stratumNonce, coinbaseTransaction, stratumTimestamp); final List<Transaction> transactions; { final List<Transaction> prototypeBlockTransaction = _prototypeBlock.getTransactions(); final MutableList<Transaction> mutableList = new MutableList<Transaction>(prototypeBlockTransaction); mutableList.set(0, coinbaseTransaction); transactions = mutableList; } return new ImmutableBlock(blockHeader, transactions); } public RequestMessage createRequest(final Boolean abandonOldJobs) { return _createRequest(abandonOldJobs); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/opcode/CryptographicOperation.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode; import com.softwareverde.bitcoin.bip.Bip66; import com.softwareverde.bitcoin.bip.Buip55; import com.softwareverde.bitcoin.bip.HF20171113; import com.softwareverde.bitcoin.bip.HF20181115; import com.softwareverde.bitcoin.bip.HF20191115; import com.softwareverde.bitcoin.bip.HF20200515; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.secp256k1.Secp256k1; import com.softwareverde.bitcoin.server.main.BitcoinConstants; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.bitcoin.transaction.script.runner.ControlState; import com.softwareverde.bitcoin.transaction.script.runner.context.MutableTransactionContext; import com.softwareverde.bitcoin.transaction.script.runner.context.TransactionContext; import com.softwareverde.bitcoin.transaction.script.signature.ScriptSignature; import com.softwareverde.bitcoin.transaction.script.signature.ScriptSignatureContext; import com.softwareverde.bitcoin.transaction.script.signature.hashtype.HashType; import com.softwareverde.bitcoin.transaction.script.stack.Stack; import com.softwareverde.bitcoin.transaction.script.stack.Value; import com.softwareverde.bitcoin.transaction.signer.SignatureContext; import com.softwareverde.bitcoin.transaction.signer.TransactionSigner; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.cryptography.hash.ripemd160.Ripemd160Hash; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.cryptography.secp256k1.Schnorr; import com.softwareverde.cryptography.secp256k1.key.PublicKey; import com.softwareverde.cryptography.secp256k1.signature.Signature; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.util.Util; import com.softwareverde.util.bytearray.ByteArrayReader; public class CryptographicOperation extends SubTypedOperation { public static final Type TYPE = Type.OP_CRYPTOGRAPHIC; public static final Integer MAX_MULTI_SIGNATURE_PUBLIC_KEY_COUNT = 20; public static final CryptographicOperation RIPEMD_160 = new CryptographicOperation(Opcode.RIPEMD_160.getValue(), Opcode.RIPEMD_160); public static final CryptographicOperation SHA_1 = new CryptographicOperation(Opcode.SHA_1.getValue(), Opcode.SHA_1); public static final CryptographicOperation SHA_256 = new CryptographicOperation(Opcode.SHA_256.getValue(), Opcode.SHA_256); public static final CryptographicOperation SHA_256_THEN_RIPEMD_160 = new CryptographicOperation(Opcode.SHA_256_THEN_RIPEMD_160.getValue(), Opcode.SHA_256_THEN_RIPEMD_160); public static final CryptographicOperation DOUBLE_SHA_256 = new CryptographicOperation(Opcode.DOUBLE_SHA_256.getValue(), Opcode.DOUBLE_SHA_256); public static final CryptographicOperation CODE_SEPARATOR = new CryptographicOperation(Opcode.CODE_SEPARATOR.getValue(), Opcode.CODE_SEPARATOR); public static final CryptographicOperation CHECK_SIGNATURE = new CryptographicOperation(Opcode.CHECK_SIGNATURE.getValue(), Opcode.CHECK_SIGNATURE); public static final CryptographicOperation CHECK_SIGNATURE_THEN_VERIFY = new CryptographicOperation(Opcode.CHECK_SIGNATURE_THEN_VERIFY.getValue(), Opcode.CHECK_SIGNATURE_THEN_VERIFY); public static final CryptographicOperation CHECK_MULTISIGNATURE = new CryptographicOperation(Opcode.CHECK_MULTISIGNATURE.getValue(), Opcode.CHECK_MULTISIGNATURE); public static final CryptographicOperation CHECK_MULTISIGNATURE_THEN_VERIFY = new CryptographicOperation(Opcode.CHECK_MULTISIGNATURE_THEN_VERIFY.getValue(), Opcode.CHECK_MULTISIGNATURE_THEN_VERIFY); public static final CryptographicOperation CHECK_DATA_SIGNATURE = new CryptographicOperation(Opcode.CHECK_DATA_SIGNATURE.getValue(), Opcode.CHECK_DATA_SIGNATURE); public static final CryptographicOperation CHECK_DATA_SIGNATURE_THEN_VERIFY = new CryptographicOperation(Opcode.CHECK_DATA_SIGNATURE_THEN_VERIFY.getValue(), Opcode.CHECK_DATA_SIGNATURE_THEN_VERIFY); protected static CryptographicOperation fromBytes(final ByteArrayReader byteArrayReader) { if (! byteArrayReader.hasBytes()) { return null; } final byte opcodeByte = byteArrayReader.readByte(); final Type type = Type.getType(opcodeByte); if (type != TYPE) { return null; } final Opcode opcode = TYPE.getSubtype(opcodeByte); if (opcode == null) { return null; } return new CryptographicOperation(opcodeByte, opcode); } protected CryptographicOperation(final byte value, final Opcode opcode) { super(value, TYPE, opcode); } protected static Boolean verifySignature(final TransactionContext transactionContext, final PublicKey publicKey, final ScriptSignature scriptSignature, final List<ByteArray> bytesToExcludeFromScript) { final Transaction transaction = transactionContext.getTransaction(); final Integer transactionInputIndexBeingSigned = transactionContext.getTransactionInputIndex(); final TransactionOutput transactionOutputBeingSpent = transactionContext.getTransactionOutput(); final Integer codeSeparatorIndex = transactionContext.getScriptLastCodeSeparatorIndex(); final Script currentScript = transactionContext.getCurrentScript(); final HashType hashType = scriptSignature.getHashType(); final Long blockHeight = transactionContext.getBlockHeight(); final TransactionSigner transactionSigner = new TransactionSigner(); final SignatureContext signatureContext = new SignatureContext(transaction, hashType, blockHeight); signatureContext.setInputIndexBeingSigned(transactionInputIndexBeingSigned); signatureContext.setShouldSignInputScript(transactionInputIndexBeingSigned, true, transactionOutputBeingSpent); signatureContext.setLastCodeSeparatorIndex(transactionInputIndexBeingSigned, codeSeparatorIndex); signatureContext.setCurrentScript(currentScript); signatureContext.setBytesToExcludeFromScript(bytesToExcludeFromScript); return transactionSigner.isSignatureValid(signatureContext, publicKey, scriptSignature); } protected static Boolean validateStrictSignatureEncoding(final ScriptSignature scriptSignature, final ScriptSignatureContext scriptSignatureContext, final TransactionContext transactionContext) { if (scriptSignature == null) { return false; } if (scriptSignature.isEmpty()) { return true; } if (scriptSignature.hasExtraBytes()) { return false; } if (scriptSignatureContext == ScriptSignatureContext.CHECK_SIGNATURE) { // CheckDataSignatures do not contain a HashType... // Enforce SCRIPT_VERIFY_STRICTENC... (https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/uahf-technical-spec.md) (BitcoinXT: src/script/interpreter.cpp ::IsValidSignatureEncoding) (BitcoinXT: src/script/sigencoding.cpp ::IsValidSignatureEncoding) // https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki final HashType hashType = scriptSignature.getHashType(); if (hashType == null) { return false; } if (hashType.getMode() == null) { return false; } if (hashType.hasUnknownFlags()) { return false; } if (BitcoinConstants.requireBitcoinCashForkId()) { if (! hashType.isBitcoinCashType()) { return false; } } } { final Signature signature = scriptSignature.getSignature(); if (signature != null) { // Check for negative-encoded DER signatures... if (signature.getType() == Signature.Type.ECDSA) { // Bip66 only applies to DER encoded signatures... if (Bip66.isEnabled(transactionContext.getBlockHeight())) { // Enforce non-negative R and S encoding for DER encoded signatures... final ByteArray signatureR = signature.getR(); if (signatureR.getByteCount() == 0) { return false; } if ((signatureR.getByte(0) & 0x80) != 0) { return false; } final ByteArray signatureS = signature.getS(); if (signatureS.getByteCount() == 0) { return false; } if ((signatureS.getByte(0) & 0x80) != 0) { return false; } } } } } return true; } protected static Boolean validateCanonicalSignatureEncoding(final ScriptSignature scriptSignature) { if (scriptSignature == null) { return false; } if (scriptSignature.isEmpty()) { return true; } // "If a signature passing to ECDSA verification does not pass the Low S value check and is not an empty byte array, the entire script evaluates to false immediately." final Signature signature = scriptSignature.getSignature(); if (signature != null) { // Enforce LOW_S Signature Encoding... (https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki#low_s) final Boolean isCanonical = signature.isCanonical(); if (! isCanonical) { return false; } } return true; } protected static Boolean validateStrictPublicKeyEncoding(final PublicKey publicKey) { return ( publicKey.isCompressed() || publicKey.isDecompressed() ); } protected Boolean _executeCheckSignature(final Stack stack, final MutableTransactionContext transactionContext) { final ScriptSignatureContext scriptSignatureContext = ScriptSignatureContext.CHECK_SIGNATURE; final Value publicKeyValue = stack.pop(); final Value signatureValue = stack.pop(); if (stack.didOverflow()) { return false; } final List<ByteArray> bytesToRemoveFromScript; { // NOTE: All instances of the signature should be purged from the signed script... final ImmutableListBuilder<ByteArray> signatureBytesBuilder = new ImmutableListBuilder<ByteArray>(1); signatureBytesBuilder.add(MutableByteArray.wrap(signatureValue.getBytes())); bytesToRemoveFromScript = signatureBytesBuilder.build(); } final Long blockHeight = transactionContext.getBlockHeight(); final boolean signatureIsValid; { final ScriptSignature scriptSignature = signatureValue.asScriptSignature(scriptSignatureContext); if (Buip55.isEnabled(blockHeight)) { // Enforce strict signature encoding (SCRIPT_VERIFY_STRICTENC)... final Boolean signatureIsStrictlyEncoded = CryptographicOperation.validateStrictSignatureEncoding(scriptSignature, scriptSignatureContext, transactionContext); if (! signatureIsStrictlyEncoded) { return false; } } if (HF20171113.isEnabled(blockHeight)) { // Enforce canonical signature encoding (LOW_S)... final Boolean signatureIsCanonicallyEncoded = CryptographicOperation.validateCanonicalSignatureEncoding(scriptSignature); if (! signatureIsCanonicallyEncoded) { return false; } } final PublicKey publicKey = publicKeyValue.asPublicKey(); if (Buip55.isEnabled(blockHeight)) { if (! publicKey.isValid()) { return false; } // Attempting to use an invalid public key fails, even if the signature is empty. } if ( (scriptSignature != null) && (! scriptSignature.isEmpty()) ) { if (Buip55.isEnabled(blockHeight)) { // Enforce strict signature encoding (SCRIPT_VERIFY_STRICTENC)... final Boolean publicKeyIsStrictlyEncoded = CryptographicOperation.validateStrictPublicKeyEncoding(publicKey); if (! publicKeyIsStrictlyEncoded) { return false; } } signatureIsValid = CryptographicOperation.verifySignature(transactionContext, publicKey, scriptSignature, bytesToRemoveFromScript); } else { // NOTE: An invalid scriptSignature is permitted, and just simply fails... // Example Transaction: 9FB65B7304AAA77AC9580823C2C06B259CC42591E5CCE66D76A81B6F51CC5C28 signatureIsValid = false; } } if (_opcode == Opcode.CHECK_SIGNATURE_THEN_VERIFY) { if (! signatureIsValid) { return false; } } else { if (BitcoinConstants.immediatelyFailOnNonEmptyInvalidSignatures()) { // Enforce NULLFAIL... (https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki#nullfail) if (HF20171113.isEnabled(blockHeight)) { if ((! signatureIsValid) && (! signatureValue.isEmpty())) { return false; } } } stack.push(Value.fromBoolean(signatureIsValid)); } { // Enforce Signature operation counting... final MedianBlockTime medianBlockTime = transactionContext.getMedianBlockTime(); if (HF20200515.isEnabled(medianBlockTime)) { if (! signatureValue.isEmpty()) { transactionContext.incrementSignatureOperationCount(1); } } } return (! stack.didOverflow()); } protected Boolean _executeCheckMultiSignature(final Stack stack, final MutableTransactionContext transactionContext) { // Unlike some other script methods, Stack::didOverflow is checked immediately since values can be popped a variable number of times; // this helps to mitigate attack vectors that would otherwise capitalize on this effect. final MedianBlockTime medianBlockTime = transactionContext.getMedianBlockTime(); final ScriptSignatureContext scriptSignatureContext = ScriptSignatureContext.CHECK_SIGNATURE; final int publicKeyCount; { final Value publicKeyCountValue = stack.pop(); if (stack.didOverflow()) { return false; } if (HF20191115.isEnabled(medianBlockTime)) { if (! Operation.validateMinimalEncoding(publicKeyCountValue, transactionContext)) { return false; } } publicKeyCount = publicKeyCountValue.asLong().intValue(); if (publicKeyCount < 0) { return false; } if (publicKeyCount > MAX_MULTI_SIGNATURE_PUBLIC_KEY_COUNT) { return false; } } final List<PublicKey> publicKeys; { final ImmutableListBuilder<PublicKey> listBuilder = new ImmutableListBuilder<PublicKey>(); for (int i = 0; i < publicKeyCount; ++i) { final Value publicKeyValue = stack.pop(); if (stack.didOverflow()) { return false; } final PublicKey publicKey = publicKeyValue.asPublicKey(); listBuilder.add(publicKey); } publicKeys = listBuilder.build(); } final int signatureCount; { final Value signatureCountValue = stack.pop(); if (stack.didOverflow()) { return false; } if (HF20191115.isEnabled(medianBlockTime)) { if (! Operation.validateMinimalEncoding(signatureCountValue, transactionContext)) { return false; } } signatureCount = signatureCountValue.asLong().intValue(); if (signatureCount < 0) { return false; } if (signatureCount > publicKeyCount) { return false; } } final boolean allSignaturesWereEmpty; final List<ByteArray> bytesToRemoveFromScript; final List<ScriptSignature> signatures; { boolean signaturesAreEmpty = true; final ImmutableListBuilder<ByteArray> signatureBytesBuilder = new ImmutableListBuilder<ByteArray>(signatureCount); final ImmutableListBuilder<ScriptSignature> listBuilder = new ImmutableListBuilder<ScriptSignature>(signatureCount); for (int i = 0; i < signatureCount; ++i) { final Value signatureValue = stack.pop(); if (stack.didOverflow()) { return false; } if (! signatureValue.isEmpty()) { signaturesAreEmpty = false; } final ScriptSignature scriptSignature = signatureValue.asScriptSignature(scriptSignatureContext); if (! HF20191115.isEnabled(medianBlockTime)) { if ( (scriptSignature != null) && (! scriptSignature.isEmpty()) ) { // Schnorr signatures are disabled for OP_CHECKMULTISIG until the 2019-11-15 HF... final Signature signature = scriptSignature.getSignature(); if (signature.getType() == Signature.Type.SCHNORR) { return false; } } } signatureBytesBuilder.add(MutableByteArray.wrap(signatureValue.getBytes())); // NOTE: All instances of the signature should be purged from the signed script... listBuilder.add(scriptSignature); } signatures = listBuilder.build(); bytesToRemoveFromScript = signatureBytesBuilder.build(); allSignaturesWereEmpty = signaturesAreEmpty; } // The checkBits field is used as an index within the publicKeys list for Schnorr MultiSig batching. // For ECDSA signatures, checkBits must be an empty value. // This value was previously unused and referred to as "nullDummy" before the 2019-11-15 HF. final Value checkBitsValue = stack.pop(); if (stack.didOverflow()) { return false; } final List<Integer> publicKeyIndexesToTry; final Signature.Type allowedSignatureType; final boolean abortIfAnySignaturesFail; final boolean signatureVerificationCountMustEqualPublicKeyIndexCount; final boolean shouldReverseSignatureOrder; if ( (! HF20191115.isEnabled(medianBlockTime)) || (Util.areEqual(checkBitsValue, Value.ZERO)) ) { allowedSignatureType = Signature.Type.ECDSA; abortIfAnySignaturesFail = false; signatureVerificationCountMustEqualPublicKeyIndexCount = false; shouldReverseSignatureOrder = false; { // Build `publicKeyIndexesToTry` as a list of indexes into the public key list. // This operation mimics the legacy/ecdsa style of multi-sig validation, where all signatures are tested but are allowed to fail. final ImmutableListBuilder<Integer> publicKeyIndexesBuilder = new ImmutableListBuilder<Integer>(publicKeyCount); for (int i = 0; i < publicKeyCount; ++i) { // The public keys must be attempted in order, starting with the last public key pushed must be the first attempted. // This specific order is required due to strict-encoding rules that were added throughout the protocol's evolution. publicKeyIndexesBuilder.add(i); } publicKeyIndexesToTry = publicKeyIndexesBuilder.build(); } } else { allowedSignatureType = Signature.Type.SCHNORR; abortIfAnySignaturesFail = true; signatureVerificationCountMustEqualPublicKeyIndexCount = true; shouldReverseSignatureOrder = true; { // Ensure the bit field is not excessively large... final int maxByteCount = ((publicKeyCount + 7) / 8); if (checkBitsValue.getByteCount() != maxByteCount) { return false; } } { // Build `publicKeyIndexesToTry` as a list of indexes into the `publicKeys` list. // The `publicKeys` list is created in reverse order (i.e. the last PublicKey pushed is listed first). // The checkBits bit array is defined so that the 0th-bit (i.e. 0x01) corresponds to the first-pushed PublicKey. // Example: // Assume: // publicKeys := [ publicKey1, publicKey0 ] # Where publicKey0 was pushed to the script first, followed by publicKey1. // checkBits := 0b00000010 # The 2nd bit was set, accessible via ByteArray::getBit(6). // This configuration results in only signature1 being validated. final ImmutableListBuilder<Integer> publicKeyIndexesBuilder = new ImmutableListBuilder<Integer>(); final int bitCount = (checkBitsValue.getByteCount() * 8); int bitSetCount = 0; for (int i = 0; i < bitCount; ++i) { // checkBits is little endian encoded, therefore the first flag occurs within the 0th byte. // The flags are organized numerically, i.e. 0x01 would require the first public key be used, and 0x80 would require only the 8th public key be used. // Furthermore, 0xFFFF0F (0b111111111111111100001111) would require the first 20 public keys be used, which is structured differently than the bit-field // in a bloom filter, which is more akin to an array of bits. final boolean isSet = (((checkBitsValue.getByte(i / 8) >> (i % 8)) & 0x01) == 0x01); if (isSet) { bitSetCount += 1; if (i >= publicKeyCount) { return false; } // The bit index was set that is greater than the number of public keys available... final int publicKeyIndex = (publicKeyCount - i - 1); publicKeyIndexesBuilder.add(publicKeyIndex); if (publicKeyIndexesBuilder.getCount() > publicKeyCount) { // The number of PublicKeys to check is greater than the number of PublicKeys available... return false; } } } if (bitSetCount != signatureCount) { return false; } publicKeyIndexesToTry = publicKeyIndexesBuilder.build(); } } final Long blockHeight = transactionContext.getBlockHeight(); final boolean signaturesAreValid; { // For the legacy implementation, signatures must appear in the same order as their paired public key, but the number of signatures may be less than the number of public keys. // Example: P1, P2, P3 <-> S2, S3 // P1, P2, P3 <-> S1, S3 // P1, P2, P3 <-> S1, S2 // P1, P2, P3 <-> S1, S2, S3 // // For the MultiSig-Schnorr batching mode, the public keys to test are provided within the old "nullDummy" parameter as a bit-array. boolean signaturesHaveMatchedPublicKeys = true; int signatureValidationCount = 0; for (int i = 0; i < signatureCount; ++i) { final int remainingSignatureCount = (signatureCount - i); final ScriptSignature scriptSignature; { if (shouldReverseSignatureOrder) { scriptSignature = signatures.get(signatureCount - i - 1); } else { scriptSignature = signatures.get(i); } } boolean signatureHasPublicKeyMatch = false; int publicKeyIndexIndex = signatureValidationCount; while (publicKeyIndexIndex < publicKeyIndexesToTry.getCount()) { { // Discontinue checking signatures if it is no longer possible that the required number of valid signatures will ever be met. // This unfortunately disables checking publicKey validity, but this is intended according to ABC's implementation (TestVector ECE529A3309EB43E5A84DEAB9EA8F2577B0EAE4840C1BB1B20258D2F48C17424). final int remainingPublicKeyCount = (publicKeyIndexesToTry.getCount() - publicKeyIndexIndex); if (remainingSignatureCount > remainingPublicKeyCount) { break; } } final int nextPublicKeyIndex = publicKeyIndexesToTry.get(publicKeyIndexIndex); final PublicKey publicKey = publicKeys.get(nextPublicKeyIndex); if (Buip55.isEnabled(blockHeight)) { if (! publicKey.isValid()) { return false; } // Attempting to use an invalid public key fails, even if the signature is empty. } // Signatures and PublicKeys that are not used are allowed to be coded incorrectly. // Therefore, the publicKey checking is performed immediately before the signature check, and not when popped from the stack. if (Buip55.isEnabled(transactionContext.getBlockHeight())) { // Enforce strict signature encoding (SCRIPT_VERIFY_STRICTENC)... final Boolean publicKeyIsStrictlyEncoded = CryptographicOperation.validateStrictPublicKeyEncoding(publicKey); if (! publicKeyIsStrictlyEncoded) { return false; } final Boolean meetsStrictEncodingStandard = CryptographicOperation.validateStrictSignatureEncoding(scriptSignature, scriptSignatureContext, transactionContext); if (! meetsStrictEncodingStandard) { return false; } } if (HF20171113.isEnabled(blockHeight)) { // Enforce canonical signature encoding (LOW_S)... final Boolean signatureIsCanonicallyEncoded = CryptographicOperation.validateCanonicalSignatureEncoding(scriptSignature); if (! signatureIsCanonicallyEncoded) { return false; } } final boolean signatureIsValid; { if ( (scriptSignature != null) && (! scriptSignature.isEmpty()) ) { final Signature.Type signatureType = scriptSignature.getSignatureType(); if (signatureType != allowedSignatureType) { return false; } signatureIsValid = CryptographicOperation.verifySignature(transactionContext, publicKey, scriptSignature, bytesToRemoveFromScript); } else { signatureIsValid = false; // NOTE: An invalid scriptSignature is permitted, and just simply fails... } } signatureValidationCount += 1; if (signatureIsValid) { signatureHasPublicKeyMatch = true; break; } else if (abortIfAnySignaturesFail) { return false; } publicKeyIndexIndex += 1; } if (! signatureHasPublicKeyMatch) { signaturesHaveMatchedPublicKeys = false; break; } } if (signatureVerificationCountMustEqualPublicKeyIndexCount) { if (signatureValidationCount != publicKeyIndexesToTry.getCount()) { return false; } } signaturesAreValid = signaturesHaveMatchedPublicKeys; } if (_opcode == Opcode.CHECK_MULTISIGNATURE_THEN_VERIFY) { if (! signaturesAreValid) { return false; } } else { if (BitcoinConstants.immediatelyFailOnNonEmptyInvalidSignatures()) { // Enforce NULLFAIL... (https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki#nullfail) if (HF20171113.isEnabled(blockHeight)) { if ((! signaturesAreValid) && (! allSignaturesWereEmpty)) { return false; } } } stack.push(Value.fromBoolean(signaturesAreValid)); } { // Enforce Signature operation counting... if (HF20200515.isEnabled(medianBlockTime)) { if (! allSignaturesWereEmpty) { transactionContext.incrementSignatureOperationCount(signatureCount); } } } return (! stack.didOverflow()); } protected Boolean _executeCheckDataSignature(final Stack stack, final MutableTransactionContext transactionContext) { final Long blockHeight = transactionContext.getBlockHeight(); final ScriptSignatureContext scriptSignatureContext = ScriptSignatureContext.CHECK_DATA_SIGNATURE; final Value publicKeyValue = stack.pop(); final Value messageValue = stack.pop(); final Value signatureValue = stack.pop(); if (stack.didOverflow()) { return false; } final ScriptSignature scriptSignature = signatureValue.asScriptSignature(scriptSignatureContext); if (Buip55.isEnabled(blockHeight)) { // Enforce strict signature encoding (SCRIPT_VERIFY_STRICTENC)... final Boolean meetsStrictEncodingStandard = CryptographicOperation.validateStrictSignatureEncoding(scriptSignature, scriptSignatureContext, transactionContext); if (! meetsStrictEncodingStandard) { return false; } } if (HF20171113.isEnabled(blockHeight)) { // Enforce canonical signature encoding (LOW_S)... final Boolean signatureIsCanonicallyEncoded = CryptographicOperation.validateCanonicalSignatureEncoding(scriptSignature); if (! signatureIsCanonicallyEncoded) { return false; } } final MutableSha256Hash messageHash = HashUtil.sha256(messageValue); final Boolean signatureIsValid; if ( (scriptSignature != null) && (! scriptSignature.isEmpty()) ) { final PublicKey publicKey = publicKeyValue.asPublicKey(); // if (publicKey == null) { return false; } // The PublicKey must be a valid for OP_CHECKDATASIG... if (Buip55.isEnabled(blockHeight)) { // Enforce strict signature encoding (SCRIPT_VERIFY_STRICTENC)... final Boolean publicKeyIsStrictlyEncoded = CryptographicOperation.validateStrictPublicKeyEncoding(publicKey); if (! publicKeyIsStrictlyEncoded) { return false; } } final Signature signature = scriptSignature.getSignature(); if (signature.getType() == Signature.Type.SCHNORR) { signatureIsValid = Schnorr.verifySignature(signature, publicKey, messageHash.unwrap()); } else { signatureIsValid = Secp256k1.verifySignature(signature, publicKey, messageHash); } } else { signatureIsValid = false; } if (BitcoinConstants.immediatelyFailOnNonEmptyInvalidSignatures()) { if ( (! signatureIsValid) && (! signatureValue.isEmpty()) ) { return false; } // Enforce NULLFAIL... } if (_opcode == Opcode.CHECK_DATA_SIGNATURE_THEN_VERIFY) { if (! signatureIsValid) { return false; } } else { stack.push(Value.fromBoolean(signatureIsValid)); } { // Enforce Signature operation counting... final MedianBlockTime medianBlockTime = transactionContext.getMedianBlockTime(); if (HF20200515.isEnabled(medianBlockTime)) { if (! signatureValue.isEmpty()) { transactionContext.incrementSignatureOperationCount(1); } } } return (! stack.didOverflow()); } @Override public Boolean applyTo(final Stack stack, final ControlState controlState, final MutableTransactionContext context) { switch (_opcode) { case RIPEMD_160: { final Value input = stack.pop(); final Ripemd160Hash bytes = HashUtil.ripemd160(input); stack.push(Value.fromBytes(bytes)); return (! stack.didOverflow()); } case SHA_1: { final Value input = stack.pop(); final ByteArray bytes = HashUtil.sha1(input); stack.push(Value.fromBytes(bytes)); return (! stack.didOverflow()); } case SHA_256: { final Value input = stack.pop(); final ByteArray bytes = HashUtil.sha256(input); stack.push(Value.fromBytes(bytes)); return (! stack.didOverflow()); } case SHA_256_THEN_RIPEMD_160: { final Value input = stack.pop(); final Ripemd160Hash bytes = HashUtil.ripemd160(HashUtil.sha256(input)); stack.push(Value.fromBytes(bytes)); return (! stack.didOverflow()); } case DOUBLE_SHA_256: { final Value input = stack.pop(); final MutableSha256Hash bytes = HashUtil.doubleSha256(input); stack.push(Value.fromBytes(bytes)); return (! stack.didOverflow()); } case CODE_SEPARATOR: { final Integer postCodeSeparatorScriptIndex = context.getScriptIndex(); // NOTE: Context.CurrentLockingScriptIndex has already been incremented. So this value is one-past the current opcode index. context.setCurrentScriptLastCodeSeparatorIndex(postCodeSeparatorScriptIndex); return true; } case CHECK_SIGNATURE: case CHECK_SIGNATURE_THEN_VERIFY:{ return _executeCheckSignature(stack, context); } case CHECK_MULTISIGNATURE: case CHECK_MULTISIGNATURE_THEN_VERIFY: { return _executeCheckMultiSignature(stack, context); } case CHECK_DATA_SIGNATURE: case CHECK_DATA_SIGNATURE_THEN_VERIFY: { if (! HF20181115.isEnabled(context.getBlockHeight())) { return false; } return _executeCheckDataSignature(stack, context); } default: { return false; } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/BitcoinProtocolMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeaderInflater; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.logging.Logger; import com.softwareverde.util.bytearray.ByteArrayReader; import com.softwareverde.util.bytearray.Endian; public abstract class BitcoinProtocolMessageInflater { public abstract BitcoinProtocolMessage fromBytes(byte[] bytes); protected final BitcoinProtocolMessageHeaderInflater _protocolMessageHeaderParser; protected BitcoinProtocolMessageHeader _parseHeader(final ByteArrayReader byteArrayReader, final MessageType command) { final BitcoinProtocolMessageHeader protocolMessageHeader = _protocolMessageHeaderParser.fromBytes(byteArrayReader); { // Validate MessageType Type if (command != protocolMessageHeader.command) { Logger.debug("ProtocolMessage: Command mismatch."); return null; } } final Integer actualPayloadByteCount = byteArrayReader.remainingByteCount(); { // Validate Payload Byte Count if (protocolMessageHeader.payloadByteCount != actualPayloadByteCount) { Logger.debug("ProtocolMessage: Bad payload size. "+ protocolMessageHeader.payloadByteCount +" != "+ actualPayloadByteCount); return null; } } final byte[] payload = byteArrayReader.peakBytes(protocolMessageHeader.payloadByteCount, Endian.BIG); { // Validate Checksum final ByteArray calculatedChecksum = BitcoinProtocolMessage.calculateChecksum(MutableByteArray.wrap(payload)); if (! ByteUtil.areEqual(protocolMessageHeader.payloadChecksum, calculatedChecksum.getBytes())) { Logger.debug("ProtocolMessage: Bad message checksum."); return null; } } if (byteArrayReader.didOverflow()) { Logger.debug("ProtocolMessage: Buffer overflow."); return null; } return protocolMessageHeader; } public BitcoinProtocolMessageInflater() { _protocolMessageHeaderParser = new BitcoinProtocolMessageHeaderInflater(); } public BitcoinProtocolMessageInflater(final BitcoinProtocolMessageHeaderInflater protocolMessageHeaderParser) { _protocolMessageHeaderParser = protocolMessageHeaderParser; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/SlpScriptInflater.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp; import com.softwareverde.bitcoin.merkleroot.MerkleRoot; import com.softwareverde.bitcoin.merkleroot.MutableMerkleRoot; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.opcode.Opcode; import com.softwareverde.bitcoin.transaction.script.opcode.Operation; import com.softwareverde.bitcoin.transaction.script.opcode.PushOperation; import com.softwareverde.bitcoin.transaction.script.slp.commit.MutableSlpCommitScript; import com.softwareverde.bitcoin.transaction.script.slp.commit.SlpCommitScript; import com.softwareverde.bitcoin.transaction.script.slp.genesis.MutableSlpGenesisScript; import com.softwareverde.bitcoin.transaction.script.slp.genesis.SlpGenesisScript; import com.softwareverde.bitcoin.transaction.script.slp.mint.MutableSlpMintScript; import com.softwareverde.bitcoin.transaction.script.slp.mint.SlpMintScript; import com.softwareverde.bitcoin.transaction.script.slp.send.MutableSlpSendScript; import com.softwareverde.bitcoin.transaction.script.slp.send.SlpSendScript; import com.softwareverde.bitcoin.transaction.script.stack.Value; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.bitcoin.util.StringUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.Util; public class SlpScriptInflater { protected static final Long TOKEN_TYPE_VALUE = ByteUtil.bytesToLong(SlpScriptType.TOKEN_TYPE); protected static Boolean _matchesSlpFormat(final LockingScript lockingScript) { final List<Operation> operations = lockingScript.getOperations(); if (operations.getCount() < 5) { return false; } for (int i = 0; i < operations.getCount(); ++i) { final Operation operation = operations.get(i); if (i == 0) { final boolean firstOperationIsReturn = (operation.getOpcodeByte() == Opcode.RETURN.getValue()); if (! firstOperationIsReturn) { return false; } } else { if (operation.getType() != Operation.Type.OP_PUSH) { return false; } final PushOperation pushOperation = (PushOperation) operation; // PUSH_DATA (0x01, 0x4B), // PUSH_DATA_BYTE (0x4C), // PUSH_DATA_SHORT (0x4D), // PUSH_DATA_INTEGER (0x4E) final int opcodeByte = ByteUtil.byteToInteger(pushOperation.getOpcodeByte()); if ( (opcodeByte < 0x01) || (opcodeByte > 0x4E) ) { return false; } if (i == 1) { if (! Util.areEqual(SlpScriptType.LOKAD_ID, pushOperation.getValue())) { return false; } } else if (i == 2) { final Value value = pushOperation.getValue(); final int valueByteCount = value.getByteCount(); if ( (valueByteCount < 1) || (valueByteCount > 2) ) { return false; } final Long bigEndianLongValue = ByteUtil.bytesToLong(value); if (! Util.areEqual(TOKEN_TYPE_VALUE, bigEndianLongValue)) { return false; } } } } return true; } protected static SlpScriptType _getScriptType(final LockingScript lockingScript) { final List<Operation> operations = lockingScript.getOperations(); final PushOperation scriptTypeOperation = (PushOperation) operations.get(3); final ByteArray scriptTypeBytes = scriptTypeOperation.getValue(); return SlpScriptType.fromBytes(scriptTypeBytes); } protected static SlpTokenId _getTokenId(final LockingScript lockingScript) { final List<Operation> operations = lockingScript.getOperations(); if (operations.getCount() < 5) { return null; } final PushOperation tokenPushOperation = (PushOperation) operations.get(4); final ByteArray tokenIdBytes = tokenPushOperation.getValue(); return SlpTokenId.copyOf(tokenIdBytes.getBytes()); } protected static SlpGenesisScript _genesisScriptFromScript(final LockingScript lockingScript) { final List<Operation> operations = lockingScript.getOperations(); if (operations.getCount() != 11) { return null; } final MutableSlpGenesisScript slpGenesisScript = new MutableSlpGenesisScript(); final Value tokenAbbreviationValue = ((PushOperation) operations.get(4)).getValue(); slpGenesisScript.setTokenAbbreviation(StringUtil.bytesToString(tokenAbbreviationValue.getBytes())); final Value tokenNameValue = ((PushOperation) operations.get(5)).getValue(); slpGenesisScript.setTokenName(StringUtil.bytesToString(tokenNameValue.getBytes())); final Value tokenDocumentUrlValue = ((PushOperation) operations.get(6)).getValue(); slpGenesisScript.setDocumentUrl(tokenDocumentUrlValue.getByteCount() > 0 ? StringUtil.bytesToString(tokenDocumentUrlValue.getBytes()) : null); final Value tokenDocumentHashValue = ((PushOperation) operations.get(7)).getValue(); if ( (tokenDocumentHashValue.getByteCount() != 0) && (tokenDocumentHashValue.getByteCount() != Sha256Hash.BYTE_COUNT) ) { return null; } slpGenesisScript.setDocumentHash((! tokenDocumentHashValue.isEmpty()) ? Sha256Hash.copyOf(tokenDocumentHashValue.getBytes()) : null); final Value tokenDecimalValue = ((PushOperation) operations.get(8)).getValue(); if (tokenDecimalValue.getByteCount() != 1) { return null; } // The "decimal" value must be 1 byte according to the specification. final int decimalCount = ByteUtil.bytesToInteger(tokenDecimalValue.getBytes()); if ( (decimalCount < 0) || (decimalCount > 9) ) { return null; } slpGenesisScript.setDecimalCount(decimalCount); final Value batonOutputIndexValue = ((PushOperation) operations.get(9)).getValue(); final int batonOutputByteCount = batonOutputIndexValue.getByteCount(); if (batonOutputByteCount > 1) { return null; } final Integer batonOutputIndex = (batonOutputByteCount == 0 ? null : ByteUtil.bytesToInteger(batonOutputIndexValue.getBytes())); if (batonOutputByteCount == 1) { if (batonOutputIndex < 2) { return null; } } slpGenesisScript.setBatonOutputIndex(batonOutputIndex); final Value totalTokenCountValue = ((PushOperation) operations.get(10)).getValue(); if (totalTokenCountValue.getByteCount() != 8) { return null; } slpGenesisScript.setTokenCount(ByteUtil.bytesToLong(totalTokenCountValue.getBytes())); return slpGenesisScript; } protected static SlpMintScript _mintScriptFromScript(final LockingScript lockingScript) { final SlpTokenId tokenId = _getTokenId(lockingScript); if (tokenId == null) { return null; } final MutableSlpMintScript slpMintScript = new MutableSlpMintScript(); slpMintScript.setTokenId(tokenId); final List<Operation> operations = lockingScript.getOperations(); if (operations.getCount() != 7) { return null; } final Value batonOutputIndexValue = ((PushOperation) operations.get(5)).getValue(); if (batonOutputIndexValue.getByteCount() > 1) { return null; } final Integer batonOutputIndex = ByteUtil.bytesToInteger(batonOutputIndexValue.getBytes()); if (batonOutputIndexValue.getByteCount() == 1) { if (batonOutputIndex < 2) { return null; } } slpMintScript.setBatonOutputIndex(batonOutputIndex); final Value totalTokenCountValue = ((PushOperation) operations.get(6)).getValue(); if (totalTokenCountValue.getByteCount() != 8) { return null; } slpMintScript.setTokenCount(ByteUtil.bytesToLong(totalTokenCountValue.getBytes())); return slpMintScript; } protected static SlpSendScript _sendScriptFromScript(final LockingScript lockingScript) { final SlpTokenId tokenId = _getTokenId(lockingScript); if (tokenId == null) { return null; } final MutableSlpSendScript slpSendScript = new MutableSlpSendScript(); slpSendScript.setTokenId(tokenId); final List<Operation> operations = lockingScript.getOperations(); final int outputCount = ((operations.getCount() - 5) + 1); // +1 for the OP_RETURN output... if (outputCount > SlpSendScript.MAX_OUTPUT_COUNT) { return null; } int transactionOutputIndex = 1; for (int i = 5; i < operations.getCount(); ++i) { final PushOperation operation = (PushOperation) operations.get(i); final ByteArray value = operation.getValue(); if (value.getByteCount() != 8) { return null; } // The "amount" byte count must be 8, according to the specification. final Long amount = ByteUtil.bytesToLong(value.getBytes()); slpSendScript.setAmount(transactionOutputIndex, amount); transactionOutputIndex += 1; } return slpSendScript; } protected static SlpCommitScript _commitScriptFromScript(final LockingScript lockingScript) { final SlpTokenId tokenId = _getTokenId(lockingScript); if (tokenId == null) { return null; } final MutableSlpCommitScript slpCommitScript = new MutableSlpCommitScript(); slpCommitScript.setTokenId(tokenId); final List<Operation> operations = lockingScript.getOperations(); if (operations.getCount() < 9) { return null; } { // Block Hash... final PushOperation operation = (PushOperation) operations.get(5); final ByteArray value = operation.getValue(); final Sha256Hash blockHash = MutableSha256Hash.wrap(value.getBytes()); if (blockHash == null) { return null; } slpCommitScript.setBlockHash(blockHash); } { // Block Height... final PushOperation operation = (PushOperation) operations.get(6); final ByteArray value = operation.getValue(); final Long blockHeight = ByteUtil.bytesToLong(value.getBytes()); slpCommitScript.setBlockHeight(blockHeight); } { // Merkle Root... final PushOperation operation = (PushOperation) operations.get(7); final ByteArray value = operation.getValue(); final MerkleRoot merkleRoot = MutableMerkleRoot.wrap(value.getBytes()); if (merkleRoot == null) { return null; } slpCommitScript.setMerkleRoot(merkleRoot); } { // Merkle Tree Data Url... final PushOperation operation = (PushOperation) operations.get(8); final ByteArray value = operation.getValue(); final String merkleTreeUrl = StringUtil.bytesToString(value.getBytes()); if (merkleTreeUrl == null) { return null; } slpCommitScript.setMerkleTreeUrl(merkleTreeUrl); } return slpCommitScript; } public static Boolean matchesSlpFormat(final LockingScript lockingScript) { return _matchesSlpFormat(lockingScript); } public static SlpScriptType getScriptType(final LockingScript lockingScript) { if (! _matchesSlpFormat(lockingScript)) { return null; } return _getScriptType(lockingScript); } public static SlpTokenId getTokenId(final LockingScript lockingScript) { if (! _matchesSlpFormat(lockingScript)) { return null; } return _getTokenId(lockingScript); } public SlpGenesisScript genesisScriptFromScript(final LockingScript lockingScript) { if (! _matchesSlpFormat(lockingScript)) { return null; } final SlpScriptType slpScriptType = _getScriptType(lockingScript); if (! Util.areEqual(SlpScriptType.GENESIS, slpScriptType)) { return null; } return _genesisScriptFromScript(lockingScript); } public SlpMintScript mintScriptFromScript(final LockingScript lockingScript) { if (! _matchesSlpFormat(lockingScript)) { return null; } final SlpScriptType slpScriptType = _getScriptType(lockingScript); if (! Util.areEqual(SlpScriptType.MINT, slpScriptType)) { return null; } return _mintScriptFromScript(lockingScript); } public SlpSendScript sendScriptFromScript(final LockingScript lockingScript) { if (! _matchesSlpFormat(lockingScript)) { return null; } final SlpScriptType slpScriptType = _getScriptType(lockingScript); if (! Util.areEqual(SlpScriptType.SEND, slpScriptType)) { return null; } return _sendScriptFromScript(lockingScript); } public SlpCommitScript commitScriptFromScript(final LockingScript lockingScript) { if (! _matchesSlpFormat(lockingScript)) { return null; } final SlpScriptType slpScriptType = _getScriptType(lockingScript); if (! Util.areEqual(SlpScriptType.COMMIT, slpScriptType)) { return null; } return _commitScriptFromScript(lockingScript); } public SlpScript fromLockingScript(final LockingScript lockingScript) { if (! _matchesSlpFormat(lockingScript)) { return null; } final SlpScriptType slpScriptType = _getScriptType(lockingScript); if (slpScriptType == null) { return null; } switch (slpScriptType) { case GENESIS: { return _genesisScriptFromScript(lockingScript); } case MINT: { return _mintScriptFromScript(lockingScript); } case COMMIT: { return _commitScriptFromScript(lockingScript); } case SEND: { return _sendScriptFromScript(lockingScript); } } return null; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/TransactionOutputIndexerContext.java<|end_filename|> package com.softwareverde.bitcoin.context; public interface TransactionOutputIndexerContext { AtomicTransactionOutputIndexerContext newTransactionOutputIndexerContext() throws ContextException; } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/database/FakeDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.test.fake.database; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.BlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.node.BitcoinNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.TransactionDatabaseManager; import com.softwareverde.database.DatabaseException; public interface FakeDatabaseManager extends DatabaseManager { @Override default DatabaseConnection getDatabaseConnection() { throw new UnsupportedOperationException(); } @Override default BitcoinNodeDatabaseManager getNodeDatabaseManager() { throw new UnsupportedOperationException(); } @Override default BlockchainDatabaseManager getBlockchainDatabaseManager() { throw new UnsupportedOperationException(); } @Override default BlockDatabaseManager getBlockDatabaseManager() { throw new UnsupportedOperationException(); } @Override default BlockHeaderDatabaseManager getBlockHeaderDatabaseManager() { throw new UnsupportedOperationException(); } @Override default TransactionDatabaseManager getTransactionDatabaseManager() { throw new UnsupportedOperationException(); } @Override default Integer getMaxQueryBatchSize() { return 1024; } @Override default void close() throws DatabaseException { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/node/feature/NewBlocksViaHeadersMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.node.feature; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.util.bytearray.ByteArrayReader; public class NewBlocksViaHeadersMessageInflater extends BitcoinProtocolMessageInflater { @Override public NewBlocksViaHeadersMessage fromBytes(final byte[] bytes) { final NewBlocksViaHeadersMessage enableDirectHeadersMessage = new NewBlocksViaHeadersMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.ENABLE_NEW_BLOCKS_VIA_HEADERS); if (protocolMessageHeader == null) { return null; } if (byteArrayReader.didOverflow()) { return null; } return enableDirectHeadersMessage; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/account/worker/DeleteWorkerApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account.worker; import com.softwareverde.bitcoin.miner.pool.AccountId; import com.softwareverde.bitcoin.miner.pool.WorkerId; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.bitcoin.server.module.stratum.database.AccountDatabaseManager; import com.softwareverde.database.DatabaseException; import com.softwareverde.http.HttpMethod; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.logging.Logger; import com.softwareverde.servlet.AuthenticatedServlet; import com.softwareverde.util.Util; public class DeleteWorkerApi extends AuthenticatedServlet { protected final DatabaseConnectionFactory _databaseConnectionFactory; public DeleteWorkerApi(final StratumProperties stratumProperties, final DatabaseConnectionFactory databaseConnectionFactory) { super(stratumProperties); _databaseConnectionFactory = databaseConnectionFactory; } @Override protected Response _onAuthenticatedRequest(final AccountId accountId, final Request request) { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); if (request.getMethod() != HttpMethod.POST) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid method.")); } { // DELETE WORKER // Requires GET: // Requires POST: workerId final WorkerId workerId = WorkerId.wrap(Util.parseLong(postParameters.get("workerId"))); if ( (workerId == null) || (workerId.longValue() < 1) ) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid worker id.")); } try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { final AccountDatabaseManager accountDatabaseManager = new AccountDatabaseManager(databaseConnection); final AccountId workerAccountId = accountDatabaseManager.getWorkerAccountId(workerId); if (! Util.areEqual(accountId, workerAccountId)) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid worker id.")); } accountDatabaseManager.deleteWorker(workerId); return new JsonResponse(Response.Codes.OK, new StratumApiResult(true, null)); } catch (final DatabaseException exception) { Logger.warn(exception); return new JsonResponse(Response.Codes.SERVER_ERROR, new StratumApiResult(false, "An internal error occurred.")); } } } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/handler/BlockInventoryMessageHandlerTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.handler; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.test.UnitTest; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.util.HashUtil; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; public class BlockInventoryMessageHandlerTests extends UnitTest { public class FakeBlockIdStore implements BlockInventoryMessageHandlerUtil.BlockIdStore { final HashMap<Sha256Hash, BlockId> _blockIds = new HashMap<Sha256Hash, BlockId>(); @Override public BlockId getBlockId(final Sha256Hash blockHash) throws Exception { return _blockIds.get(blockHash); } public void storeBlockId(final Sha256Hash blockHash, final BlockId blockId) { _blockIds.put(blockHash, blockId); } } protected static Sha256Hash generateBlockHash(final Long index) { return Sha256Hash.copyOf(HashUtil.doubleSha256(ByteUtil.longToBytes(index))); } protected static List<Sha256Hash> generateBlockHashes(final Integer blockHashCount, final Long firstUnknownIndex, final FakeBlockIdStore blockIdStore) { final MutableList<Sha256Hash> blockHashes = new MutableList<Sha256Hash>(blockHashCount); for (long i = 0L; i < blockHashCount; ++i) { final Sha256Hash blockHash = BlockInventoryMessageHandlerTests.generateBlockHash(i); final BlockId blockId = BlockId.wrap(i); blockHashes.add(blockHash); if (i < firstUnknownIndex) { blockIdStore.storeBlockId(blockHash, blockId); } } return blockHashes; } @Test public void should_return_first_unknown_block_ix0() throws Exception { final FakeBlockIdStore blockIdStore = new FakeBlockIdStore(); final long blockHeightOffset = 1000L; final long firstUnknownIndex = 0L; final Sha256Hash firstUnknownHash = BlockInventoryMessageHandlerTests.generateBlockHash(firstUnknownIndex); final int blockHashCount = 1024; final List<Sha256Hash> blockHashes = BlockInventoryMessageHandlerTests.generateBlockHashes(blockHashCount, firstUnknownIndex, blockIdStore); final BlockInventoryMessageHandlerUtil.NodeInventory nodeInventory = BlockInventoryMessageHandlerUtil.getHeadBlockInventory(blockHeightOffset, blockHashes, blockIdStore); Assert.assertEquals(Long.valueOf(blockHeightOffset + firstUnknownIndex), nodeInventory.blockHeight); Assert.assertEquals(firstUnknownHash, nodeInventory.blockHash); } @Test public void should_return_first_unknown_block_ix768() throws Exception { final FakeBlockIdStore blockIdStore = new FakeBlockIdStore(); final long blockHeightOffset = 1000L; final long firstUnknownIndex = 768L; final Sha256Hash firstUnknownHash = BlockInventoryMessageHandlerTests.generateBlockHash(firstUnknownIndex); final int blockHashCount = 1024; final List<Sha256Hash> blockHashes = BlockInventoryMessageHandlerTests.generateBlockHashes(blockHashCount, firstUnknownIndex, blockIdStore); final BlockInventoryMessageHandlerUtil.NodeInventory nodeInventory = BlockInventoryMessageHandlerUtil.getHeadBlockInventory(blockHeightOffset, blockHashes, blockIdStore); Assert.assertEquals(Long.valueOf(blockHeightOffset + firstUnknownIndex), nodeInventory.blockHeight); Assert.assertEquals(firstUnknownHash, nodeInventory.blockHash); } @Test public void should_return_first_unknown_block_ix1023() throws Exception { final FakeBlockIdStore blockIdStore = new FakeBlockIdStore(); final long blockHeightOffset = 1000L; final long firstUnknownIndex = 1023L; final Sha256Hash firstUnknownHash = BlockInventoryMessageHandlerTests.generateBlockHash(firstUnknownIndex); final int blockHashCount = 1024; final List<Sha256Hash> blockHashes = BlockInventoryMessageHandlerTests.generateBlockHashes(blockHashCount, firstUnknownIndex, blockIdStore); final BlockInventoryMessageHandlerUtil.NodeInventory nodeInventory = BlockInventoryMessageHandlerUtil.getHeadBlockInventory(blockHeightOffset, blockHashes, blockIdStore); Assert.assertEquals(Long.valueOf(blockHeightOffset + firstUnknownIndex), nodeInventory.blockHeight); Assert.assertEquals(firstUnknownHash, nodeInventory.blockHash); } @Test public void should_return_first_unknown_block_ix512() throws Exception { final FakeBlockIdStore blockIdStore = new FakeBlockIdStore(); final long blockHeightOffset = 1000L; final long firstUnknownIndex = 512L; final Sha256Hash firstUnknownHash = BlockInventoryMessageHandlerTests.generateBlockHash(firstUnknownIndex); final int blockHashCount = 1024; final List<Sha256Hash> blockHashes = BlockInventoryMessageHandlerTests.generateBlockHashes(blockHashCount, firstUnknownIndex, blockIdStore); final BlockInventoryMessageHandlerUtil.NodeInventory nodeInventory = BlockInventoryMessageHandlerUtil.getHeadBlockInventory(blockHeightOffset, blockHashes, blockIdStore); Assert.assertEquals(Long.valueOf(blockHeightOffset + firstUnknownIndex), nodeInventory.blockHeight); Assert.assertEquals(firstUnknownHash, nodeInventory.blockHash); } @Test public void should_return_first_unknown_block_ix256() throws Exception { final FakeBlockIdStore blockIdStore = new FakeBlockIdStore(); final long blockHeightOffset = 1000L; final long firstUnknownIndex = 256L; final Sha256Hash firstUnknownHash = BlockInventoryMessageHandlerTests.generateBlockHash(firstUnknownIndex); final int blockHashCount = 1024; final List<Sha256Hash> blockHashes = BlockInventoryMessageHandlerTests.generateBlockHashes(blockHashCount, firstUnknownIndex, blockIdStore); final BlockInventoryMessageHandlerUtil.NodeInventory nodeInventory = BlockInventoryMessageHandlerUtil.getHeadBlockInventory(blockHeightOffset, blockHashes, blockIdStore); Assert.assertEquals(Long.valueOf(blockHeightOffset + firstUnknownIndex), nodeInventory.blockHeight); Assert.assertEquals(firstUnknownHash, nodeInventory.blockHash); } @Test public void should_return_first_unknown_block_ix255() throws Exception { final FakeBlockIdStore blockIdStore = new FakeBlockIdStore(); final long blockHeightOffset = 1000L; final long firstUnknownIndex = 255L; final Sha256Hash firstUnknownHash = BlockInventoryMessageHandlerTests.generateBlockHash(firstUnknownIndex); final int blockHashCount = 1024; final List<Sha256Hash> blockHashes = BlockInventoryMessageHandlerTests.generateBlockHashes(blockHashCount, firstUnknownIndex, blockIdStore); final BlockInventoryMessageHandlerUtil.NodeInventory nodeInventory = BlockInventoryMessageHandlerUtil.getHeadBlockInventory(blockHeightOffset, blockHashes, blockIdStore); Assert.assertEquals(Long.valueOf(blockHeightOffset + firstUnknownIndex), nodeInventory.blockHeight); Assert.assertEquals(firstUnknownHash, nodeInventory.blockHash); } @Test public void should_return_first_unknown_block_ix1() throws Exception { final FakeBlockIdStore blockIdStore = new FakeBlockIdStore(); final long blockHeightOffset = 1000L; final long firstUnknownIndex = 1L; final Sha256Hash firstUnknownHash = BlockInventoryMessageHandlerTests.generateBlockHash(firstUnknownIndex); final int blockHashCount = 1024; final List<Sha256Hash> blockHashes = BlockInventoryMessageHandlerTests.generateBlockHashes(blockHashCount, firstUnknownIndex, blockIdStore); final BlockInventoryMessageHandlerUtil.NodeInventory nodeInventory = BlockInventoryMessageHandlerUtil.getHeadBlockInventory(blockHeightOffset, blockHashes, blockIdStore); Assert.assertEquals(Long.valueOf(blockHeightOffset + firstUnknownIndex), nodeInventory.blockHeight); Assert.assertEquals(firstUnknownHash, nodeInventory.blockHash); } @Test public void should_return_first_unknown_block_ix1022() throws Exception { final FakeBlockIdStore blockIdStore = new FakeBlockIdStore(); final long blockHeightOffset = 1000L; final long firstUnknownIndex = 512L; final Sha256Hash firstUnknownHash = BlockInventoryMessageHandlerTests.generateBlockHash(firstUnknownIndex); final int blockHashCount = 1024; final List<Sha256Hash> blockHashes = BlockInventoryMessageHandlerTests.generateBlockHashes(blockHashCount, firstUnknownIndex, blockIdStore); final BlockInventoryMessageHandlerUtil.NodeInventory nodeInventory = BlockInventoryMessageHandlerUtil.getHeadBlockInventory(blockHeightOffset, blockHashes, blockIdStore); Assert.assertEquals(Long.valueOf(blockHeightOffset + firstUnknownIndex), nodeInventory.blockHeight); Assert.assertEquals(firstUnknownHash, nodeInventory.blockHash); } @Test public void should_return_first_unknown_block_ix769() throws Exception { final FakeBlockIdStore blockIdStore = new FakeBlockIdStore(); final long blockHeightOffset = 1000L; final long firstUnknownIndex = 769L; final Sha256Hash firstUnknownHash = BlockInventoryMessageHandlerTests.generateBlockHash(firstUnknownIndex); final int blockHashCount = 1024; final List<Sha256Hash> blockHashes = BlockInventoryMessageHandlerTests.generateBlockHashes(blockHashCount, firstUnknownIndex, blockIdStore); final BlockInventoryMessageHandlerUtil.NodeInventory nodeInventory = BlockInventoryMessageHandlerUtil.getHeadBlockInventory(blockHeightOffset, blockHashes, blockIdStore); Assert.assertEquals(Long.valueOf(blockHeightOffset + firstUnknownIndex), nodeInventory.blockHeight); Assert.assertEquals(firstUnknownHash, nodeInventory.blockHash); } @Test public void should_return_first_unknown_block_ix767() throws Exception { final FakeBlockIdStore blockIdStore = new FakeBlockIdStore(); final long blockHeightOffset = 1000L; final long firstUnknownIndex = 767L; final Sha256Hash firstUnknownHash = BlockInventoryMessageHandlerTests.generateBlockHash(firstUnknownIndex); final int blockHashCount = 1024; final List<Sha256Hash> blockHashes = BlockInventoryMessageHandlerTests.generateBlockHashes(blockHashCount, firstUnknownIndex, blockIdStore); final BlockInventoryMessageHandlerUtil.NodeInventory nodeInventory = BlockInventoryMessageHandlerUtil.getHeadBlockInventory(blockHeightOffset, blockHashes, blockIdStore); Assert.assertEquals(Long.valueOf(blockHeightOffset + firstUnknownIndex), nodeInventory.blockHeight); Assert.assertEquals(firstUnknownHash, nodeInventory.blockHash); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/node/MerkleBlockParameters.java<|end_filename|> package com.softwareverde.bitcoin.server.node; import com.softwareverde.bitcoin.block.MerkleBlock; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.util.Util; public class MerkleBlockParameters { protected final MerkleBlock _merkleBlock; protected final MutableList<Transaction> _transactions = new MutableList<Transaction>(); public MerkleBlock getMerkleBlock() { return _merkleBlock; } public List<Transaction> getTransactions() { return _transactions; } public MerkleBlockParameters(final MerkleBlock merkleBlock) { _merkleBlock = merkleBlock.asConst(); } protected Boolean hasAllTransactions() { return Util.areEqual(_merkleBlock.getTransactionCount(), _transactions.getCount()); } protected void addTransaction(final Transaction transaction) { _transactions.add(transaction.asConst()); } public Integer getByteCount() { int byteCount = 0; byteCount += _merkleBlock.getByteCount(); for (final Transaction transaction : _transactions) { byteCount += transaction.getByteCount(); } return byteCount; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/manager/NodeInitializer.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager; import com.softwareverde.bitcoin.server.SynchronizationStatus; import com.softwareverde.bitcoin.server.message.BitcoinBinaryPacketFormat; import com.softwareverde.bitcoin.server.message.type.node.feature.LocalNodeFeatures; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.concurrent.pool.ThreadPoolFactory; public class NodeInitializer { public interface TransactionsAnnouncementHandlerFactory { BitcoinNode.TransactionInventoryAnnouncementHandler createTransactionsAnnouncementHandler(BitcoinNode bitcoinNode); } public static class Context { public SynchronizationStatus synchronizationStatus; public BitcoinNode.BlockInventoryAnnouncementHandler blockInventoryMessageHandler; public TransactionsAnnouncementHandlerFactory _transactionsAnnouncementHandlerFactory; public BitcoinNode.RequestBlockHashesHandler requestBlockHashesHandler; public BitcoinNode.RequestBlockHeadersHandler requestBlockHeadersHandler; public BitcoinNode.RequestDataHandler requestDataHandler; public BitcoinNode.RequestSpvBlocksHandler requestSpvBlocksHandler; public BitcoinNode.RequestSlpTransactionsHandler requestSlpTransactionsHandler; public ThreadPoolFactory threadPoolFactory; public LocalNodeFeatures localNodeFeatures; public BitcoinNode.RequestPeersHandler requestPeersHandler; public BitcoinNode.RequestUnconfirmedTransactionsHandler requestUnconfirmedTransactionsHandler; public BitcoinNode.SpvBlockInventoryAnnouncementHandler spvBlockInventoryAnnouncementHandler; public BitcoinBinaryPacketFormat binaryPacketFormat; public BitcoinNode.NewBloomFilterHandler newBloomFilterHandler; } protected final SynchronizationStatus _synchronizationStatus; protected final BitcoinNode.BlockInventoryAnnouncementHandler blockInventoryAnnouncementHandler; protected final TransactionsAnnouncementHandlerFactory _transactionsAnnouncementHandlerFactory; protected final BitcoinNode.RequestBlockHashesHandler _requestBlockHashesHandler; protected final BitcoinNode.RequestBlockHeadersHandler _requestBlockHeadersHandler; protected final BitcoinNode.RequestDataHandler _requestDataHandler; protected final BitcoinNode.RequestSpvBlocksHandler _requestSpvBlocksHandler; protected final BitcoinNode.RequestSlpTransactionsHandler _requestSlpTransactionsHandler; protected final ThreadPoolFactory _threadPoolFactory; protected final LocalNodeFeatures _localNodeFeatures; protected final BitcoinNode.RequestPeersHandler _requestPeersHandler; protected final BitcoinNode.RequestUnconfirmedTransactionsHandler _requestUnconfirmedTransactionsHandler; protected final BitcoinNode.SpvBlockInventoryAnnouncementHandler _spvBlockInventoryAnnouncementHandler; protected final BitcoinBinaryPacketFormat _binaryPacketFormat; protected final BitcoinNode.NewBloomFilterHandler _newBloomFilterHandler; protected void _initializeNode(final BitcoinNode bitcoinNode) { bitcoinNode.setSynchronizationStatusHandler(_synchronizationStatus); bitcoinNode.setRequestBlockHashesHandler(_requestBlockHashesHandler); bitcoinNode.setRequestBlockHeadersHandler(_requestBlockHeadersHandler); bitcoinNode.setRequestDataHandler(_requestDataHandler); bitcoinNode.setRequestSpvBlocksHandler(_requestSpvBlocksHandler); bitcoinNode.setRequestSlpTransactionsHandler(_requestSlpTransactionsHandler); bitcoinNode.setSpvBlockInventoryAnnouncementHandler(_spvBlockInventoryAnnouncementHandler); bitcoinNode.setBlockInventoryMessageHandler(blockInventoryAnnouncementHandler); bitcoinNode.setRequestUnconfirmedTransactionsHandler(_requestUnconfirmedTransactionsHandler); final TransactionsAnnouncementHandlerFactory transactionsAnnouncementHandlerFactory = _transactionsAnnouncementHandlerFactory; if (transactionsAnnouncementHandlerFactory != null) { final BitcoinNode.TransactionInventoryAnnouncementHandler transactionInventoryAnnouncementHandler = transactionsAnnouncementHandlerFactory.createTransactionsAnnouncementHandler(bitcoinNode); bitcoinNode.setTransactionsAnnouncementCallback(transactionInventoryAnnouncementHandler); } bitcoinNode.setRequestPeersHandler(_requestPeersHandler); bitcoinNode.setNewBloomFilterHandler(_newBloomFilterHandler); } public NodeInitializer(final Context properties) { _synchronizationStatus = properties.synchronizationStatus; blockInventoryAnnouncementHandler = properties.blockInventoryMessageHandler; _transactionsAnnouncementHandlerFactory = properties._transactionsAnnouncementHandlerFactory; _requestBlockHashesHandler = properties.requestBlockHashesHandler; _requestBlockHeadersHandler = properties.requestBlockHeadersHandler; _requestDataHandler = properties.requestDataHandler; _requestSpvBlocksHandler = properties.requestSpvBlocksHandler; _requestSlpTransactionsHandler = properties.requestSlpTransactionsHandler; _threadPoolFactory = properties.threadPoolFactory; _localNodeFeatures = properties.localNodeFeatures; _requestPeersHandler = properties.requestPeersHandler; _requestUnconfirmedTransactionsHandler = properties.requestUnconfirmedTransactionsHandler; _spvBlockInventoryAnnouncementHandler = properties.spvBlockInventoryAnnouncementHandler; _binaryPacketFormat = properties.binaryPacketFormat; _newBloomFilterHandler = properties.newBloomFilterHandler; } public void initializeNode(final BitcoinNode bitcoinNode) { _initializeNode(bitcoinNode); } public BitcoinBinaryPacketFormat getBinaryPacketFormat() { return _binaryPacketFormat; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/main/DatabaseConfigurer.java<|end_filename|> package com.softwareverde.bitcoin.server.main; import com.softwareverde.bitcoin.server.configuration.BitcoinProperties; import com.softwareverde.bitcoin.server.configuration.DatabaseProperties; import com.softwareverde.database.mysql.embedded.DatabaseCommandLineArguments; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.SystemUtil; public class DatabaseConfigurer { public static Long toNearestMegabyte(final Long byteCount) { return ((byteCount / ByteUtil.Unit.Binary.MEBIBYTES) * ByteUtil.Unit.Binary.MEBIBYTES); } public static void configureCommandLineArguments(final DatabaseCommandLineArguments commandLineArguments, final Integer maxDatabaseThreadCount, final DatabaseProperties databaseProperties, final BitcoinProperties bitcoinProperties) { // TODO: too many arguments: // commandLineArguments.addArgument("--sql-mode='STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'"); // Disable ONLY_FULL_GROUP_BY. final long connectionsReservedForRoot = 1; final long maxAllowedPacketByteCount = (32L * ByteUtil.Unit.Binary.MEBIBYTES); commandLineArguments.setMaxAllowedPacketByteCount(maxAllowedPacketByteCount); if (SystemUtil.isWindowsOperatingSystem()) { // MariaDb4j currently only supports 32 bit on Windows, so the log file and memory settings must be less than 2 GB... commandLineArguments.setInnoDbBufferPoolByteCount(Math.min(ByteUtil.Unit.Binary.GIBIBYTES, databaseProperties.getMaxMemoryByteCount())); commandLineArguments.setQueryCacheByteCount(0L); commandLineArguments.addArgument("--max-connections=" + (maxDatabaseThreadCount + connectionsReservedForRoot)); } else { // The default per_thread_buffer is roughly 3mb excluding the max_allowed_packet. // per_thread_buffer = read_buffer_size + read_rnd_buffer_size + sort_buffer_size + thread_stack + join_buffer_size + max_allowed_packet // Technically for the worst-case scenario, the bytesPerConnection should be a function of maxAllowedPacketByteCount, // but since the vast majority of queries only use a fraction of this amount, the calculation takes the "steadyState" packet size instead. final long steadyStatePacketSize = (8L * ByteUtil.Unit.Binary.MEBIBYTES); final long bytesPerConnection = ((3L * ByteUtil.Unit.Binary.MEBIBYTES) + steadyStatePacketSize); final long overheadByteCount = (bytesPerConnection * maxDatabaseThreadCount); final long minMemoryRequired = (256L * ByteUtil.Unit.Binary.MEBIBYTES); final long maxDatabaseMemory = (databaseProperties.getMaxMemoryByteCount() - overheadByteCount); if (maxDatabaseMemory < minMemoryRequired) { throw new RuntimeException("Insufficient memory available to allocate desired settings. Consider reducing the number of allowed connections."); } final Long logFileByteCount = DatabaseConfigurer.toNearestMegabyte(databaseProperties.getLogFileByteCount()); final Long logBufferByteCount = DatabaseConfigurer.toNearestMegabyte(Math.min((logFileByteCount / 4L), (maxDatabaseMemory / 4L))); // 25% of the logFile size but no larger than 25% of the total database memory. final Long bufferPoolByteCount = DatabaseConfigurer.toNearestMegabyte(maxDatabaseMemory - logBufferByteCount); final int bufferPoolInstanceCount; { // https://www.percona.com/blog/2020/08/13/how-many-innodb_buffer_pool_instances-do-you-need-in-mysql-8/ final int segmentCount = (int) (bufferPoolByteCount / (256L * ByteUtil.Unit.Binary.MEBIBYTES)); if (segmentCount < 1) { bufferPoolInstanceCount = 1; } else if (segmentCount > 32) { bufferPoolInstanceCount = 32; } else { bufferPoolInstanceCount = segmentCount; } } // TODO: Experiment with innodb_change_buffer_max_size and innodb_change_buffering for better IBD performance. commandLineArguments.setInnoDbLogFileByteCount(logFileByteCount); // Redo Log file (on-disk) commandLineArguments.setInnoDbLogBufferByteCount(logBufferByteCount); // Redo Log (in-memory) commandLineArguments.setInnoDbBufferPoolByteCount(bufferPoolByteCount); // Innodb Dirty Page Cache commandLineArguments.setInnoDbBufferPoolInstanceCount(bufferPoolInstanceCount); // Innodb Dirt Page Concurrency commandLineArguments.addArgument("--innodb-io-capacity=2000"); // 2000 for SSDs/NVME, 400 for low-end SSD, 200 for HDD. commandLineArguments.addArgument("--innodb-flush-log-at-trx-commit=0"); // Write directly to disk; database crashing may result in data corruption. commandLineArguments.addArgument("--innodb-flush-method=O_DIRECT"); commandLineArguments.addArgument("--innodb-io-capacity=5000"); // 2000 for SSDs/NVME, 400 for low-end SSD, 200 for HDD. Higher encourages fewer dirty pages passively. commandLineArguments.addArgument("--innodb-io-capacity-max=10000"); // Higher facilitates active dirty-page flushing. commandLineArguments.addArgument("--innodb-page-cleaners=" + bufferPoolInstanceCount); commandLineArguments.addArgument("--innodb-max-dirty-pages-pct=0"); // Encourage no dirty buffers in order to facilitate faster writes. commandLineArguments.addArgument("--innodb-max-dirty-pages-pct-lwm=5"); // Encourage no dirty buffers in order to facilitate faster writes. commandLineArguments.addArgument("--innodb-read-io-threads=16"); commandLineArguments.addArgument("--innodb-write-io-threads=32"); commandLineArguments.addArgument("--innodb-lru-scan-depth=2048"); commandLineArguments.addArgument("--myisam-sort-buffer-size=4096"); // Reduce per-connection memory allocation (only used for MyISAM DDL statements). commandLineArguments.setQueryCacheByteCount(null); // Deprecated, removed in Mysql 8. commandLineArguments.addArgument("--max-connections=" + (maxDatabaseThreadCount + connectionsReservedForRoot)); // commandLineArguments.enableSlowQueryLog("slow-query.log", 1L); // commandLineArguments.addArgument("--general-log-file=query.log"); // commandLineArguments.addArgument("--general-log=1"); commandLineArguments.addArgument("--performance-schema=OFF"); } } protected DatabaseConfigurer() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/header/BlockHeaderInflater.java<|end_filename|> package com.softwareverde.bitcoin.block.header; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.merkleroot.MutableMerkleRoot; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.util.bytearray.Endian; public class BlockHeaderInflater { public static final Integer BLOCK_HEADER_BYTE_COUNT = 80; protected MutableBlockHeader _fromByteArrayReader(final ByteArrayReader byteArrayReader) { final MutableBlockHeader blockHeader = new MutableBlockHeader(); // 0100 0000 // Version // 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 // Previous Block Hash // 3BA3 EDFD 7A7B 12B2 7AC7 2C3E 6776 8F61 7FC8 1BC3 888A 5132 3A9F B8AA 4B1E 5E4A // Merkle Root // 29AB 5F49 // Timestamp // FFFF 001D // Difficulty // 1DAC 2B7C // Nonce // 0101 0000 0001 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 FFFF FFFF 4D04 FFFF 001D 0104 4554 6865 2054 696D 6573 2030 332F 4A61 6E2F 3230 3039 2043 6861 6E63 656C 6C6F 7220 6F6E 2062 7269 6E6B 206F 6620 7365 636F 6E64 2062 6169 6C6F 7574 2066 6F72 2062 616E 6B73 FFFF FFFF 0100 F205 2A01 0000 0043 4104 678A FDB0 FE55 4827 1967 F1A6 7130 B710 5CD6 A828 E039 09A6 7962 E0EA 1F61 DEB6 49F6 BC3F 4CEF 38C4 F355 04E5 1EC1 12DE 5C38 4DF7 BA0B 8D57 8A4C 702B 6BF1 1D5F AC00 0000 00 blockHeader._version = byteArrayReader.readLong(4, Endian.LITTLE); blockHeader._previousBlockHash = MutableSha256Hash.wrap(byteArrayReader.readBytes(32, Endian.LITTLE)); blockHeader._merkleRoot = MutableMerkleRoot.wrap(byteArrayReader.readBytes(32, Endian.LITTLE)); blockHeader._timestamp = byteArrayReader.readLong(4, Endian.LITTLE); final byte[] difficultyBytes = byteArrayReader.readBytes(4, Endian.LITTLE); blockHeader._difficulty = Difficulty.decode(ByteArray.wrap(difficultyBytes)); blockHeader._nonce = byteArrayReader.readLong(4, Endian.LITTLE); // blockHeader._transactionCount = byteArrayReader.readVariableSizedInteger().intValue(); // Always 0 for Block Headers... if (byteArrayReader.didOverflow()) { return null; } return blockHeader; } public MutableBlockHeader fromBytes(final ByteArrayReader byteArrayReader) { if (byteArrayReader == null) { return null; } return _fromByteArrayReader(byteArrayReader); } public MutableBlockHeader fromBytes(final ByteArray byteArray) { if (byteArray == null) { return null; } final ByteArrayReader byteArrayReader = new ByteArrayReader(byteArray.getBytes()); return _fromByteArrayReader(byteArrayReader); } public MutableBlockHeader fromBytes(final byte[] bytes) { if (bytes == null) { return null; } final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); return _fromByteArrayReader(byteArrayReader); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/locktime/SequenceNumber.java<|end_filename|> package com.softwareverde.bitcoin.transaction.locktime; import com.softwareverde.constable.Constable; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.json.Jsonable; public interface SequenceNumber extends Constable<ImmutableSequenceNumber>, Jsonable { Long SECONDS_PER_SEQUENCE_NUMBER = 512L; SequenceNumber MAX_SEQUENCE_NUMBER = new ImmutableSequenceNumber(LockTime.MAX_TIMESTAMP_VALUE); SequenceNumber EMPTY_SEQUENCE_NUMBER = new ImmutableSequenceNumber(LockTime.MIN_TIMESTAMP_VALUE); SequenceNumberType getType(); Long getValue(); ByteArray getBytes(); Boolean isRelativeLockTimeDisabled(); Long getMaskedValue(); // Returns the last 2 bytes of the value, as per Bip68... (https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki) Long asSecondsElapsed(); // Returns the masked value transformed to the number of seconds the input is required to be locked... Long asBlockCount(); // Returns the masked value transformed to the number of blocks the input is required to be locked... @Override ImmutableSequenceNumber asConst(); } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/account/PasswordApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account; import com.softwareverde.bitcoin.miner.pool.AccountId; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.bitcoin.server.module.stratum.database.AccountDatabaseManager; import com.softwareverde.database.DatabaseException; import com.softwareverde.http.HttpMethod; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.logging.Logger; import com.softwareverde.servlet.AuthenticatedServlet; public class PasswordApi extends AuthenticatedServlet { protected final DatabaseConnectionFactory _databaseConnectionFactory; public PasswordApi(final StratumProperties stratumProperties, final DatabaseConnectionFactory databaseConnectionFactory) { super(stratumProperties); _databaseConnectionFactory = databaseConnectionFactory; } @Override protected Response _onAuthenticatedRequest(final AccountId accountId, final Request request) { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); if (request.getMethod() != HttpMethod.POST) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid method.")); } { // CREATE ACCOUNT // Requires GET: // Requires POST: password, new_password final String currentPassword = postParameters.get("password"); final String newPassword = postParameters.get("newPassword"); if (newPassword.length() < CreateAccountApi.MIN_PASSWORD_LENGTH) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid password length.")); } try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { final AccountDatabaseManager accountDatabaseManager = new AccountDatabaseManager(databaseConnection); final Boolean passwordIsCorrect = accountDatabaseManager.authenticateAccount(accountId, currentPassword); if (! passwordIsCorrect) { return new JsonResponse(Response.Codes.OK, new StratumApiResult(false, "Invalid credentials.")); } accountDatabaseManager.setAccountPassword(accountId, newPassword); return new JsonResponse(Response.Codes.OK, new StratumApiResult(true, null)); } catch (final DatabaseException exception) { Logger.warn(exception); return new JsonResponse(Response.Codes.SERVER_ERROR, new StratumApiResult(false, "An internal error occurred.")); } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/ReadUncommittedDatabaseConnectionConfigurer.java<|end_filename|> package com.softwareverde.bitcoin.server.database; import com.softwareverde.database.DatabaseException; public interface ReadUncommittedDatabaseConnectionConfigurer { void setReadUncommittedTransactionIsolationLevel(final DatabaseConnection databaseConnection) throws DatabaseException; } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/pool/PoolPrototypeBlockApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint.pool; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiEndpoint; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumDataHandler; import com.softwareverde.http.HttpMethod; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.json.Json; public class PoolPrototypeBlockApi extends StratumApiEndpoint { protected final StratumDataHandler _stratumDataHandler; public PoolPrototypeBlockApi(final StratumProperties stratumProperties, final StratumDataHandler stratumDataHandler) { super(stratumProperties); _stratumDataHandler = stratumDataHandler; } @Override protected Response _onRequest(final Request request) { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); if (request.getMethod() != HttpMethod.GET) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid method.")); } { // GET PROTOTYPE BLOCK // Requires GET: // Requires POST: final Block prototypeBlock = _stratumDataHandler.getPrototypeBlock(); final Json prototypeBlockJson = prototypeBlock.toJson(); prototypeBlockJson.put("height", _stratumDataHandler.getPrototypeBlockHeight()); final StratumApiResult apiResult = new StratumApiResult(); apiResult.setWasSuccess(true); apiResult.put("block", prototypeBlockJson); return new JsonResponse(Response.Codes.OK, apiResult); } } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/block/validator/difficulty/DifficultyCalculatorUnitTests.java<|end_filename|> package com.softwareverde.bitcoin.block.validator.difficulty; import com.softwareverde.bitcoin.bip.Buip55; import com.softwareverde.bitcoin.bip.HF20171113; import com.softwareverde.bitcoin.bip.HF20201115; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.block.header.MutableBlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.block.header.difficulty.work.ChainWork; import com.softwareverde.bitcoin.block.validator.BlockHeaderValidator; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.context.DifficultyCalculatorContext; import com.softwareverde.bitcoin.context.core.AsertReferenceBlockLoader; import com.softwareverde.bitcoin.merkleroot.ImmutableMerkleRoot; import com.softwareverde.bitcoin.merkleroot.MerkleRoot; import com.softwareverde.bitcoin.test.UnitTest; import com.softwareverde.bitcoin.test.fake.FakeBlockHeaderStub; import com.softwareverde.bitcoin.test.fake.FakeBlockHeaderValidatorContext; import com.softwareverde.bitcoin.test.fake.FakeDifficultyCalculatorContext; import com.softwareverde.bitcoin.test.fake.FakeReferenceBlockLoaderContext; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.bitcoin.util.IoUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.json.Json; import com.softwareverde.logging.Logger; import com.softwareverde.network.time.MutableNetworkTime; import com.softwareverde.util.Util; import org.junit.Assert; import org.junit.Test; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class DifficultyCalculatorUnitTests extends UnitTest { protected void _validatePreOrdering(final BlockHeader[] blockHeaders, final Map<Sha256Hash, Long> blockHeights) { Assert.assertNotNull(blockHeaders); Assert.assertEquals(Long.valueOf(587196L), blockHeights.get(blockHeaders[0].getHash())); Assert.assertEquals(Long.valueOf(587197L), blockHeights.get(blockHeaders[1].getHash())); Assert.assertEquals(Long.valueOf(587198L), blockHeights.get(blockHeaders[2].getHash())); if (blockHeaders.length > 3) { Assert.assertEquals(Long.valueOf(587199L), blockHeights.get(blockHeaders[3].getHash())); } } @Test public void should_pre_order_blocks_before_sorting() { // Setup final BlockHeaderInflater blockHeaderInflater = new BlockHeaderInflater(); final BlockHeader blockHeader_587196 = blockHeaderInflater.fromBytes(ByteArray.fromHexString("0000802029442002438B76394DB51AD4DFEBE6034FF760CC102B21020000000000000000DB02CFEED980E0B1DE1FBC2F32467C58948162931A119F99384BB8F980B6FC911870055D73440318CC25AE45")); final BlockHeader blockHeader_587197 = blockHeaderInflater.fromBytes(ByteArray.fromHexString("000000204EC6D6C4A07F0D351A48DAA35E684B2ADC806D3F4C0397000000000000000000C67013C6B366AF5A19A8DB92187427384A097950E9E21B0F4BA3A3E271955ACF2370055DEA3D03188963EFB2")); final BlockHeader blockHeader_587198 = blockHeaderInflater.fromBytes(ByteArray.fromHexString("00E0FF3FEA3DA6788DDDFB4BC584A6F342CE5AB6C4C67DDB4319860100000000000000003FB1703177952BCFA51D4AD1A099FE56D5E681266BDF4DAE12941DE9AC685AF3F871055D144703183F87E206")); final BlockHeader blockHeader_587199 = blockHeaderInflater.fromBytes(ByteArray.fromHexString("000000208D950B2E905F563F7DD5B268218FC71A5650BCB6A06EB601000000000000000062FAE64FAFFBCE8F47250501AF1C9DEF00585B4668DA8A0B2E635DFC02A5B2CA2972055D0D41031882224C0B")); final HashMap<Sha256Hash, Long> blockHeights = new HashMap<Sha256Hash, Long>(3); blockHeights.put(blockHeader_587196.getHash(), 587196L); blockHeights.put(blockHeader_587197.getHash(), 587197L); blockHeights.put(blockHeader_587198.getHash(), 587198L); blockHeights.put(blockHeader_587199.getHash(), 587199L); { // Ensure all possible permutations for a 3-header array succeed... final int[][] permutations = new int[][]{ {0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0} }; for (final int[] permutation : permutations) { final BlockHeader[] blockHeaders = new BlockHeader[3]; blockHeaders[permutation[0]] = blockHeader_587196; blockHeaders[permutation[1]] = blockHeader_587197; blockHeaders[permutation[2]] = blockHeader_587198; // System.out.println("Test: {" + permutation[0] + "," + permutation[1] + "," + permutation[2] + "}"); final BlockHeader[] preSortedBlockHeaders = MedianBlockHeaderSelector.preOrderBlocks(blockHeaders); _validatePreOrdering(preSortedBlockHeaders, blockHeights); } } { // Ensure unrelated headers preSort to null... final BlockHeader[] blockHeaders = new BlockHeader[3]; blockHeaders[0] = blockHeader_587196; blockHeaders[1] = blockHeader_587197; blockHeaders[2] = blockHeader_587199; final BlockHeader[] preSortedBlockHeaders = MedianBlockHeaderSelector.preOrderBlocks(blockHeaders); Assert.assertNull(preSortedBlockHeaders); } } static class FakeBlockHeader extends FakeBlockHeaderStub { protected final Long _blockHeight; protected final Sha256Hash _hash; protected final Sha256Hash _previousBlockHash; protected Long _timestamp = 0L; public FakeBlockHeader(final Long blockHeight) { _blockHeight = blockHeight; _hash = Sha256Hash.wrap(HashUtil.sha256(ByteUtil.longToBytes(blockHeight))); _previousBlockHash = Sha256Hash.wrap(HashUtil.sha256(ByteUtil.longToBytes(blockHeight - 1L))); } public FakeBlockHeader(final Long blockHeight, final Long timestamp) { _blockHeight = blockHeight; _hash = Sha256Hash.wrap(HashUtil.sha256(ByteUtil.longToBytes(blockHeight))); _previousBlockHash = Sha256Hash.wrap(HashUtil.sha256(ByteUtil.longToBytes(blockHeight - 1L))); _timestamp = timestamp; } @Override public Sha256Hash getHash() { return _hash; } @Override public Sha256Hash getPreviousBlockHash() { return _previousBlockHash; } @Override public Long getTimestamp() { return _timestamp; } public Long getBlockHeight() { return _blockHeight; } public void setTimestamp(final Long timestamp) { _timestamp = timestamp; } @Override public boolean equals(final Object object) { if (! (object instanceof BlockHeader)) { return false; } final BlockHeader blockHeader = (BlockHeader) object; return Util.areEqual(_hash, blockHeader.getHash()); } } /** * This test asserts that the block-selection algorithm for the new Bitcoin Cash Difficulty Adjustment Algorithm * selects the same "median" block when 2 of the 3 sequenced blocks share the same timestamp. * Reference: https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/nov-13-hardfork-spec.md#footnotes * """A block is chosen via the following mechanism: * Given a list: S = [B_n-2, B_n-1, B_n] * a. If timestamp(S[0]) greater than timestamp(S[2]) then swap S[0] and S[2]. * b. If timestamp(S[0]) greater than timestamp(S[1]) then swap S[0] and S[1]. * c. If timestamp(S[1]) greater than timestamp(S[2]) then swap S[1] and S[2]. * d. Return S[1]. * """ */ @Test public void should_select_block_header_based_on_insert_order_when_timestamps_are_identical() { final MedianBlockHeaderSelector medianBlockHeaderSelector = new MedianBlockHeaderSelector(); { // The first three elements per permutation are the timestamps, the fourth element is the index expected to be selected (which is also the fake blockHeight)... final int[][] timestampsAndExpectedHeight = new int[][]{ {0, 0, 0, 1}, {0, 0, 1, 1}, {0, 1, 0, 2}, {0, 1, 1, 1}, {1, 0, 0, 1}, {1, 0, 1, 0}, {1, 1, 0, 1}, {1, 1, 1, 1} }; for (final int[] permutation : timestampsAndExpectedHeight) { final BlockHeader[] blockHeaders = new BlockHeader[3]; blockHeaders[0] = new FakeBlockHeader(0L, (long) permutation[0]); blockHeaders[1] = new FakeBlockHeader(1L, (long) permutation[1]); blockHeaders[2] = new FakeBlockHeader(2L, (long) permutation[2]); final BlockHeader expectedBlockHeader = new FakeBlockHeader((long) permutation[3]); final BlockHeader blockHeader = medianBlockHeaderSelector.selectMedianBlockHeader(blockHeaders); // System.out.println("Timestamps={" + permutation[0] + "," + permutation[1] + "," + permutation[2] + "} -> " + ((FakeBlockHeader) blockHeader).getBlockHeight()); Assert.assertEquals(expectedBlockHeader, blockHeader); } } } @Test public void should_calculate_difficulty_for_block_000000000000000001B66EA0B6BC50561AC78F2168B2D57D3F565F902E0B958D() { // Setup final BlockHeaderInflater blockHeaderInflater = new BlockHeaderInflater(); final HashMap<Long, BlockHeader> blockHeaders = new HashMap<Long, BlockHeader>(); final HashMap<Long, ChainWork> chainWorks = new HashMap<Long, ChainWork>(); final HashMap<Long, MedianBlockTime> medianBlockTimes = new HashMap<Long, MedianBlockTime>(); { final Long blockHeight = 587051L; final BlockHeader blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("00004020C35BA39E60207C9E9E05AC8569DB177FEDF3BE12473BCB0200000000000000008CD5A7960DCEF83D1052C06F04001BE551A30CDABB56BD910D45D66EE44A8CF9350E045D7B5203182A4FA63D")); blockHeaders.put(blockHeight, blockHeader); chainWorks.put(blockHeight, ChainWork.fromHexString("000000000000000000000000000000000000000000F029B70179FA4FAC8588F7")); } { final Long blockHeight = 587052L; final BlockHeader blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("000000209A11547FA6AECAAEFCFCAE16CA8920D6A0958889952C29020000000000000000A1DA137F6D29BBA1FDA473292F62EB0613A8EED8ABDD18DF335D0F7601FCE82A030F045D435003187B87D418")); blockHeaders.put(blockHeight, blockHeader); chainWorks.put(blockHeight, ChainWork.fromHexString("000000000000000000000000000000000000000000F02A0443D339E6B9A4CCD5")); } { final Long blockHeight = 587053L; final BlockHeader blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("0000002053C807F29DBFEE3B06D7B3AF9DC26E7AEB4AC8C716CD4D03000000000000000056EEC5C2537DDD1E6C0927FE4FD5B9238E9A7B57F096EF5CCB22E6481C4238D02F0F045DCD4803182F2E01FE")); blockHeaders.put(blockHeight, blockHeader); chainWorks.put(blockHeight, ChainWork.fromHexString("000000000000000000000000000000000000000000F02A5235ADD723B435AB4E")); } { final Long blockHeight = 587195L; final BlockHeader blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("0000FF3F396F0BFE2648C252F2E83DA61DB3164E228E9A08699ECC000000000000000000B5F208E22E350C16DA7AF7015FD375ED4CF86DF6833399F46767AE1A5A075B452370055D0B45031889818CB6")); blockHeaders.put(blockHeight, blockHeader); chainWorks.put(blockHeight, ChainWork.fromHexString("000000000000000000000000000000000000000000F057FC0614743ACE1E0524")); } { final Long blockHeight = 587196L; final BlockHeader blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("0000802029442002438B76394DB51AD4DFEBE6034FF760CC102B21020000000000000000DB02CFEED980E0B1DE1FBC2F32467C58948162931A119F99384BB8F980B6FC911870055D73440318CC25AE45")); blockHeaders.put(blockHeight, blockHeader); chainWorks.put(blockHeight, ChainWork.fromHexString("000000000000000000000000000000000000000000F0584A5FBE03CB7F1CF1FF")); } { final Long blockHeight = 587197L; final BlockHeader blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("000000204EC6D6C4A07F0D351A48DAA35E684B2ADC806D3F4C0397000000000000000000C67013C6B366AF5A19A8DB92187427384A097950E9E21B0F4BA3A3E271955ACF2370055DEA3D03188963EFB2")); blockHeaders.put(blockHeight, blockHeader); chainWorks.put(blockHeight, ChainWork.fromHexString("000000000000000000000000000000000000000000F0589957593E319806C814")); } final BlockHeader blockHeader; { // Height: 587198 final Long blockHeight = 587198L; blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("00E0FF3FEA3DA6788DDDFB4BC584A6F342CE5AB6C4C67DDB4319860100000000000000003FB1703177952BCFA51D4AD1A099FE56D5E681266BDF4DAE12941DE9AC685AF3F871055D144703183F87E206")); blockHeaders.put(blockHeight, blockHeader); chainWorks.put(blockHeight, ChainWork.fromHexString("000000000000000000000000000000000000000000F058E7722B23D4DA9E5DF1")); medianBlockTimes.put(blockHeight, MedianBlockTime.fromSeconds(1560637323L)); } final DifficultyCalculatorContext difficultyCalculatorContext = new DifficultyCalculatorContext() { @Override public AsertReferenceBlock getAsertReferenceBlock() { return null; } @Override public BlockHeader getBlockHeader(final Long blockHeight) { if (! blockHeaders.containsKey(blockHeight)) { Assert.fail("Requesting unregistered BlockHeader for blockHeight: " + blockHeight); } return blockHeaders.get(blockHeight); } @Override public ChainWork getChainWork(final Long blockHeight) { if (! chainWorks.containsKey(blockHeight)) { Assert.fail("Requesting unregistered ChainWork for blockHeight: " + blockHeight); } return chainWorks.get(blockHeight); } @Override public MedianBlockTime getMedianBlockTime(final Long blockHeight) { if (! medianBlockTimes.containsKey(blockHeight)) { Assert.fail("Requesting unregistered MedianBlockTime for blockHeight: " + blockHeight); } return medianBlockTimes.get(blockHeight); } }; final DifficultyCalculator difficultyCalculator = new DifficultyCalculator(difficultyCalculatorContext); // Action final Difficulty difficulty = difficultyCalculator.calculateRequiredDifficulty(587198L); // Assert Assert.assertEquals(blockHeader.getDifficulty(), difficulty); } @Test public void should_calculate_emergency_difficulty() { // Setup final BlockHeaderInflater blockHeaderInflater = new BlockHeaderInflater(); final FakeDifficultyCalculatorContext difficultyCalculatorContext = new FakeDifficultyCalculatorContext(); final HashMap<Long, BlockHeader> blockHeaders = difficultyCalculatorContext.getBlockHeaders(); final HashMap<Long, MedianBlockTime> medianBlockTimes = difficultyCalculatorContext.getMedianBlockTimes(); { final Long blockHeight = 499962L; medianBlockTimes.put(blockHeight, MedianBlockTime.fromSeconds(1509240003L)); } { final Long blockHeight = 499968L; final BlockHeader blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("00000020C989289B55C9ED4D296DCD6F459726C9B28AE8D6098F8C09000000000000000051D0E4A45E846EA18B3CED0BA2C5585D2C7312005F2424FE92C243491082F82C2135F5598AFB03184C8D2FE2")); blockHeaders.put(blockHeight, blockHeader); medianBlockTimes.put(blockHeight, MedianBlockTime.fromSeconds(1509240426L)); } final Long blockHeight = 499969L; final BlockHeader blockHeader; { blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("00000020F779752E58AA1CDB2CD2F59BFE69D4B327886D2CF43FAA030000000000000000CD2F883DC10C2140CCB5A12E84F188924BF209902FEB31191F60AA318A0D9068EB36F5598AFB031896833D85")); blockHeaders.put(blockHeight, blockHeader); medianBlockTimes.put(blockHeight, MedianBlockTime.fromSeconds(1509240436L)); } final DifficultyCalculator difficultyCalculator = new DifficultyCalculator(difficultyCalculatorContext); { // Ensure the Difficulty calculation is using the emergency calculation... Assert.assertTrue(Buip55.isEnabled(blockHeight)); // Emergency Difficulty adjustment activation... Assert.assertFalse(HF20171113.isEnabled(blockHeight)); // Current BCH Difficulty adjustment activation... Assert.assertNotEquals(0L, (blockHeight % DifficultyCalculator.BLOCK_COUNT_PER_DIFFICULTY_ADJUSTMENT)); // Legacy Difficulty adjustment... } // Action final Difficulty difficulty = difficultyCalculator.calculateRequiredDifficulty(blockHeight); // Assert Assert.assertEquals(blockHeader.getDifficulty(), difficulty); } @Test public void should_calculate_difficulty_for_block_0000000000000000037DF1664BEE98AF9EF9BBCDEF882FDF16F91C6EC94334DF() { // Setup final BlockHeaderInflater blockHeaderInflater = new BlockHeaderInflater(); final FakeBlockHeaderValidatorContext context = new FakeBlockHeaderValidatorContext(new MutableNetworkTime()); final HashMap<Long, BlockHeader> blockHeaders = context.getBlockHeaders(); final HashMap<Long, MedianBlockTime> medianBlockTimes = context.getMedianBlockTimes(); { final long blockHeight = 478575L; final BlockHeader blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("000000205841AEA6F06F4A0E3560EA076CF1DF217EBDE943A92C16010000000000000000CF8FC3BAD8DAD139A3DD6A30481D87E1F760122573168002CC9EF7A58FC53AD387848259354701188A3B54F7")); blockHeaders.put(blockHeight, blockHeader); medianBlockTimes.put(blockHeight, MedianBlockTime.fromSeconds(1501643701L)); } { final long blockHeight = 478581L; final BlockHeader blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("00000020F3C6E921BB46DE2EBE0923C6FEF9433510F57E15543D1301000000000000000071CCD70BC227084B74BDA5634BE313C63C213F46AB8801411CB78809F8408C3D81C182598BE6031894141AA2")); blockHeaders.put(blockHeight, blockHeader); medianBlockTimes.put(blockHeight, MedianBlockTime.fromSeconds(1501727260L)); } final Long blockHeight = 478582L; final BlockHeader blockHeader; { blockHeader = blockHeaderInflater.fromBytes(ByteArray.fromHexString("000000201C9C41FFE35BA49571E759BAD99C416F48594C8BEB7EA5030000000000000000FF562FBEAD0871D7ED63B2BCF2E8D49434980E5CEF8F72C399CCFD6C07BEC8E76FCE82592DE00418F963C170")); blockHeaders.put(blockHeight, blockHeader); medianBlockTimes.put(blockHeight, MedianBlockTime.fromSeconds(1501730885L)); } final DifficultyCalculator difficultyCalculator = new DifficultyCalculator(context); { // Ensure the Difficulty calculation is using the emergency calculation... Assert.assertTrue(Buip55.isEnabled(blockHeight)); // Emergency Difficulty adjustment activation... Assert.assertFalse(HF20171113.isEnabled(blockHeight)); // Current BCH Difficulty adjustment activation... Assert.assertNotEquals(0L, (blockHeight % DifficultyCalculator.BLOCK_COUNT_PER_DIFFICULTY_ADJUSTMENT)); // Legacy Difficulty adjustment... } final BlockHeaderValidator blockHeaderValidator = new BlockHeaderValidator(context); // Action final Difficulty difficulty = difficultyCalculator.calculateRequiredDifficulty(blockHeight); final BlockHeaderValidator.BlockHeaderValidationResult blockHeaderValidationResult = blockHeaderValidator.validateBlockHeader(blockHeader, blockHeight); // Assert Assert.assertTrue(difficulty.isSatisfiedBy(blockHeader.getHash())); Assert.assertEquals(difficulty, blockHeader.getDifficulty()); System.out.println(blockHeaderValidationResult.errorMessage); Assert.assertTrue(blockHeaderValidationResult.isValid); } @Test public void should_activate_testnet_headers() { // Setup HF20201115.enableTestNet(); final Long testNetHalfLife = (3600L); try { final Json headersObjectJson = Json.parse(IoUtil.getResource("/aserti3-2d/test-net-headers.json")); final BlockchainSegmentId blockchainSegmentId = BlockchainSegmentId.wrap(1L); final FakeReferenceBlockLoaderContext referenceBlockLoaderContext = new FakeReferenceBlockLoaderContext(); final FakeDifficultyCalculatorContext difficultyCalculatorContext = new FakeDifficultyCalculatorContext() { final AsertReferenceBlockLoader _asertReferenceBlockLoader = new AsertReferenceBlockLoader(referenceBlockLoaderContext); @Override public AsertReferenceBlock getAsertReferenceBlock() { try { return _asertReferenceBlockLoader.getAsertReferenceBlock(blockchainSegmentId); } catch (final Exception exception) { throw new RuntimeException(exception); } } }; final HashMap<Long, BlockHeader> blockHeaders = difficultyCalculatorContext.getBlockHeaders(); final HashMap<Long, MedianBlockTime> medianBlockTimes = difficultyCalculatorContext.getMedianBlockTimes(); final HashMap<Long, ChainWork> chainWorks = difficultyCalculatorContext.getChainWorks(); { // Inflate the context from the testnet json resource... final int headerCount = headersObjectJson.length(); for (int i = 0; i < headerCount; ++i) { final Json json = headersObjectJson.get(i); final Long blockHeight = json.getLong("height"); final Long blockTimestamp = json.getLong("time"); final MutableBlockHeader blockHeader = new MutableBlockHeader(); blockHeader.setVersion(json.getLong("version")); blockHeader.setTimestamp(blockTimestamp); blockHeader.setNonce(json.getLong("nonce")); final ByteArray difficultyBytes = ByteArray.fromHexString(json.getString("bits")); final Difficulty difficulty = Difficulty.decode(difficultyBytes); blockHeader.setDifficulty(difficulty); final MerkleRoot merkleRoot = ImmutableMerkleRoot.fromHexString(json.getString("merkleroot")); blockHeader.setMerkleRoot(merkleRoot); final Sha256Hash previousBlockHash = Sha256Hash.fromHexString(json.getString("previousblockhash")); blockHeader.setPreviousBlockHash(previousBlockHash); final Sha256Hash expectedBlockHash = Sha256Hash.fromHexString(json.getString("hash")); final Sha256Hash blockHash = blockHeader.getHash(); Assert.assertEquals(expectedBlockHash, blockHash); // BlockHeader blockHeaders.put(blockHeight, blockHeader); // ChainWork final ChainWork chainWork = ChainWork.fromHexString(json.getString("chainwork")); chainWorks.put(blockHeight, chainWork); // MedianTimePast final MedianBlockTime medianTimePast = MedianBlockTime.fromSeconds(json.getLong("mediantime")); medianBlockTimes.put(blockHeight, medianTimePast); // AsertReferenceBlockLoader final BlockId blockId = BlockId.wrap(blockHeight + 1L); referenceBlockLoaderContext.setBlockHeader(blockchainSegmentId, blockId, blockHeight, medianTimePast, blockTimestamp, difficulty); // Debug Logger.debug("TestNet Block: " + blockHeight + ": " + blockHash + " " + difficultyBytes + " " + medianTimePast + " " + chainWork); } } final DifficultyCalculator difficultyCalculator = new DifficultyCalculator( difficultyCalculatorContext, new MedianBlockHeaderSelector(), new AsertDifficultyCalculator() { @Override protected BigInteger _getHalfLife() { return BigInteger.valueOf(testNetHalfLife); } } ) { }; final Long blockHeight = 1416399L; // Action final AsertReferenceBlock asertReferenceBlock = difficultyCalculatorContext.getAsertReferenceBlock(); final Difficulty difficulty = difficultyCalculator.calculateRequiredDifficulty(blockHeight); // Assert Assert.assertEquals(BigInteger.valueOf(1416397L), asertReferenceBlock.blockHeight); final BlockHeader blockHeader = blockHeaders.get(blockHeight); Assert.assertEquals(blockHeader.getDifficulty(), difficulty); } finally { HF20201115.enableMainNet(); } } } <|start_filename|>src/main/java/com/softwareverde/network/socket/BinaryPacketFormat.java<|end_filename|> package com.softwareverde.network.socket; import com.softwareverde.constable.Const; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.network.p2p.message.ProtocolMessageFactory; import com.softwareverde.network.p2p.message.ProtocolMessageHeaderInflater; public class BinaryPacketFormat implements Const { protected final ByteArray _magicNumber; protected final ProtocolMessageHeaderInflater _protocolMessageHeaderInflater; protected final ProtocolMessageFactory<?> _protocolMessageFactory; public BinaryPacketFormat(final ByteArray magicNumber, final ProtocolMessageHeaderInflater protocolMessageHeaderInflater, final ProtocolMessageFactory<?> protocolMessageFactory) { _magicNumber = magicNumber; _protocolMessageHeaderInflater = protocolMessageHeaderInflater; _protocolMessageFactory = protocolMessageFactory; } public ByteArray getMagicNumber() { return _magicNumber; } public ProtocolMessageHeaderInflater getProtocolMessageHeaderInflater() { return _protocolMessageHeaderInflater; } public ProtocolMessageFactory<?> getProtocolMessageFactory() { return _protocolMessageFactory; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/node/feefilter/FeeFilterMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.node.feefilter; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.util.bytearray.ByteArrayReader; import com.softwareverde.util.bytearray.Endian; public class FeeFilterMessageInflater extends BitcoinProtocolMessageInflater { @Override public FeeFilterMessage fromBytes(final byte[] bytes) { final FeeFilterMessage feeFilterMessageMessage = new FeeFilterMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.FEE_FILTER); if (protocolMessageHeader == null) { return null; } feeFilterMessageMessage._minimumSatoshisPerByte = byteArrayReader.readLong(8, Endian.LITTLE); if (byteArrayReader.didOverflow()) { return null; } return feeFilterMessageMessage; } } <|start_filename|>www-shared/css/mobile-table.css<|end_filename|> @media only screen and (max-width: 768px) { table, thead, tbody, th, td, tr { display: block; } thead tr { position: absolute; top: -9999px; left: -9999px; } td { width: auto !important; border: none; border-bottom: 1px solid #B0B0B0; position: relative; padding-left: 50% !important; text-align: left !important; min-height: 1em; word-break: break-word; } td::before { position: absolute; top: 0; left: 0.5em; width: 45%; padding-right: 10px; white-space: nowrap; font-family: 'Bree Serif', serif; content: attr(data-label); } } <|start_filename|>src/main/java/com/softwareverde/network/time/ImmutableNetworkTime.java<|end_filename|> package com.softwareverde.network.time; import com.softwareverde.constable.Const; public class ImmutableNetworkTime implements NetworkTime, Const { public static ImmutableNetworkTime fromSeconds(final Long medianNetworkTimeInSeconds) { return new ImmutableNetworkTime(medianNetworkTimeInSeconds * 1000L); } public static ImmutableNetworkTime fromMilliseconds(final Long medianNetworkTimeInMilliseconds) { return new ImmutableNetworkTime(medianNetworkTimeInMilliseconds); } protected final Long _medianNetworkTimeInMilliseconds; protected ImmutableNetworkTime(final Long medianNetworkTimeInMilliseconds) { _medianNetworkTimeInMilliseconds = medianNetworkTimeInMilliseconds; } public ImmutableNetworkTime(final NetworkTime networkTime) { _medianNetworkTimeInMilliseconds = networkTime.getCurrentTimeInMilliSeconds(); } @Override public Long getCurrentTimeInSeconds() { return (_medianNetworkTimeInMilliseconds / 1000L); } @Override public Long getCurrentTimeInMilliSeconds() { return _medianNetworkTimeInMilliseconds; } @Override public ImmutableNetworkTime asConst() { return this; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/memory/MemoryStatus.java<|end_filename|> package com.softwareverde.bitcoin.server.memory; public interface MemoryStatus { Long getByteCountAvailable(); Long getByteCountUsed(); /** * Returns a value between 0 and 1 representing the percentage of memory used within the JVM. */ Float getMemoryUsedPercent(); void logCurrentMemoryUsage(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/rpc/handler/ThreadPoolInquisitor.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.rpc.handler; import com.softwareverde.bitcoin.server.module.node.rpc.NodeRpcHandler; import com.softwareverde.concurrent.pool.MainThreadPool; public class ThreadPoolInquisitor implements NodeRpcHandler.ThreadPoolInquisitor { protected final MainThreadPool _threadPool; public ThreadPoolInquisitor(final MainThreadPool threadPool) { _threadPool = threadPool; } @Override public Integer getQueueCount() { return _threadPool.getQueueCount(); } @Override public Integer getActiveThreadCount() { return _threadPool.getActiveThreadCount(); } @Override public Integer getMaxThreadCount() { return _threadPool.getMaxThreadCount(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/merkleroot/MutableMerkleTree.java<|end_filename|> package com.softwareverde.bitcoin.block.merkleroot; public interface MutableMerkleTree<T extends Hashable> extends MerkleTree<T> { void addItem(T item); void replaceItem(int index, T item); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/AbstractDatabase.java<|end_filename|> package com.softwareverde.bitcoin.server.database; import com.softwareverde.database.DatabaseException; import java.sql.Connection; public abstract class AbstractDatabase extends AbstractDatabaseConnectionFactory implements com.softwareverde.database.Database<Connection>, AutoCloseable { protected AbstractDatabase(final com.softwareverde.database.Database<Connection> core) { super(core); } @Override public abstract DatabaseConnection newConnection() throws DatabaseException; public abstract DatabaseConnectionFactory newConnectionFactory(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/core/TransactionValidatorContext.java<|end_filename|> package com.softwareverde.bitcoin.context.core; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.context.MedianBlockTimeContext; import com.softwareverde.bitcoin.context.UnspentTransactionOutputContext; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.validator.TransactionValidator; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.network.time.VolatileNetworkTime; public class TransactionValidatorContext implements TransactionValidator.Context { protected final TransactionInflaters _transactionInflaters; protected final VolatileNetworkTime _networkTime; protected final MedianBlockTimeContext _medianBlockTimeContext; protected final UnspentTransactionOutputContext _unspentTransactionOutputContext; public TransactionValidatorContext(final TransactionInflaters transactionInflaters, final VolatileNetworkTime networkTime, final MedianBlockTimeContext medianBlockTimeContext, final UnspentTransactionOutputContext unspentTransactionOutputContext) { _transactionInflaters = transactionInflaters; _networkTime = networkTime; _medianBlockTimeContext = medianBlockTimeContext; _unspentTransactionOutputContext = unspentTransactionOutputContext; } @Override public MedianBlockTime getMedianBlockTime(final Long blockHeight) { return _medianBlockTimeContext.getMedianBlockTime(blockHeight); } @Override public VolatileNetworkTime getNetworkTime() { return _networkTime; } @Override public TransactionOutput getTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { return _unspentTransactionOutputContext.getTransactionOutput(transactionOutputIdentifier); } @Override public Long getBlockHeight(final TransactionOutputIdentifier transactionOutputIdentifier) { return _unspentTransactionOutputContext.getBlockHeight(transactionOutputIdentifier); } @Override public Sha256Hash getBlockHash(final TransactionOutputIdentifier transactionOutputIdentifier) { return _unspentTransactionOutputContext.getBlockHash(transactionOutputIdentifier); } @Override public Boolean isCoinbaseTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { return _unspentTransactionOutputContext.isCoinbaseTransactionOutput(transactionOutputIdentifier); } @Override public TransactionInflater getTransactionInflater() { return _transactionInflaters.getTransactionInflater(); } @Override public TransactionDeflater getTransactionDeflater() { return _transactionInflaters.getTransactionDeflater(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/slp/SlpTransactionDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.slp; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.constable.list.List; import com.softwareverde.database.DatabaseException; import java.util.LinkedHashMap; public interface SlpTransactionDatabaseManager { /** * Returns the cached SLP validity of the TransactionId. * This function does run validation on the transaction and only queries its cached value. */ Boolean getSlpTransactionValidationResult(TransactionId transactionId) throws DatabaseException; void setSlpTransactionValidationResult(TransactionId transactionId, Boolean isValid) throws DatabaseException; /** * Returns a mapping of (SLP) TransactionIds that have not been validated yet, ordered by their respective block's height. * Unconfirmed transactions are not returned by this function. */ LinkedHashMap<BlockId, List<TransactionId>> getConfirmedPendingValidationSlpTransactions(Integer maxCount) throws DatabaseException; void setLastSlpValidatedBlockId(BlockId blockId) throws DatabaseException; /** * Returns a list of (SLP) TransactionIds that have not been validated yet that reside in the mempool. */ List<TransactionId> getUnconfirmedPendingValidationSlpTransactions(Integer maxCount) throws DatabaseException; } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/manager/health/NodeHealth.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager.health; import com.softwareverde.constable.Constable; import com.softwareverde.network.p2p.node.NodeId; import java.util.Comparator; public interface NodeHealth extends Constable<ImmutableNodeHealth> { interface Request { } Long FULL_HEALTH = 24L * 60L * 60L * 1000L; Float REGEN_TO_REQUEST_TIME_RATIO = 0.5F; Comparator<NodeHealth> HEALTH_ASCENDING_COMPARATOR = new Comparator<NodeHealth>() { @Override public int compare(final NodeHealth nodeHealth0, final NodeHealth nodeHealth1) { final Long nodeHealth0Value = nodeHealth0.getHealth(); final Long nodeHealth1Value = nodeHealth1.getHealth(); return (nodeHealth0Value.compareTo(nodeHealth1Value)); } }; NodeId getNodeId(); Long getHealth(); @Override ImmutableNodeHealth asConst(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/input/UnconfirmedTransactionInputId.java<|end_filename|> package com.softwareverde.bitcoin.transaction.input; import com.softwareverde.util.type.identifier.Identifier; public class UnconfirmedTransactionInputId extends Identifier { public static UnconfirmedTransactionInputId wrap(final Long value) { if (value == null) { return null; } return new UnconfirmedTransactionInputId(value); } protected UnconfirmedTransactionInputId(final Long value) { super(value); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/query/ParameterFactory.java<|end_filename|> package com.softwareverde.bitcoin.server.database.query; import com.softwareverde.bitcoin.server.message.type.node.feature.NodeFeatures; import com.softwareverde.database.query.ParameterFactoryCore; import com.softwareverde.database.query.parameter.TypedParameter; public class ParameterFactory extends ParameterFactoryCore { @Override public TypedParameter fromObject(final Object object) { if (object instanceof NodeFeatures.Feature) { return new TypedParameter(object.toString()); } return super.fromObject(object); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/ScriptType.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script; public enum ScriptType { UNKNOWN(1L), CUSTOM_SCRIPT(2L), PAY_TO_PUBLIC_KEY(3L), PAY_TO_PUBLIC_KEY_HASH(4L), PAY_TO_SCRIPT_HASH(5L), SLP_GENESIS_SCRIPT(6L), SLP_SEND_SCRIPT(7L), SLP_MINT_SCRIPT(8L), SLP_COMMIT_SCRIPT(9L); public static Boolean isSlpScriptType(final ScriptType scriptType) { if (scriptType == null) { return false; } switch (scriptType) { case SLP_GENESIS_SCRIPT: case SLP_SEND_SCRIPT: case SLP_MINT_SCRIPT: case SLP_COMMIT_SCRIPT: { return true; } default: { return false; } } } public static Boolean isAddressScriptType(final ScriptType scriptType) { if (scriptType == null) { return false; } switch (scriptType) { case PAY_TO_PUBLIC_KEY: case PAY_TO_PUBLIC_KEY_HASH: case PAY_TO_SCRIPT_HASH: { return true; } default: { return false; } } } protected final ScriptTypeId _scriptTypeId; ScriptType(final Long id) { _scriptTypeId = ScriptTypeId.wrap(id); } public ScriptTypeId getScriptTypeId() { return _scriptTypeId; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/constable/util/ConstUtil.java<|end_filename|> package com.softwareverde.bitcoin.constable.util; import com.softwareverde.constable.Const; import com.softwareverde.constable.Constable; import com.softwareverde.constable.list.mutable.MutableList; import java.util.Map; public class ConstUtil extends com.softwareverde.constable.util.ConstUtil { protected ConstUtil() { } public static <T extends Const> T asConstOrNull(final Constable<T> constable) { if (constable == null) { return null; } return constable.asConst(); } public static <Key, Item> void addToListMap(final Key key, final Item item, final Map<Key, MutableList<Item>> map) { MutableList<Item> items = map.get(key); if (items == null) { items = new MutableList<Item>(); map.put(key, items); } items.add(item); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/chain/time/MedianBlockTime.java<|end_filename|> package com.softwareverde.bitcoin.chain.time; import com.softwareverde.constable.Constable; import com.softwareverde.util.Util; import com.softwareverde.util.type.time.Time; public interface MedianBlockTime extends Time, Constable<ImmutableMedianBlockTime> { Integer BLOCK_COUNT = 11; Long GENESIS_BLOCK_TIMESTAMP = 1231006505L; // In seconds. ImmutableMedianBlockTime MAX_VALUE = new ImmutableMedianBlockTime(Long.MAX_VALUE); static MedianBlockTime fromSeconds(final Long medianBlockTimeInSeconds) { return ImmutableMedianBlockTime.fromSeconds(medianBlockTimeInSeconds); } static MedianBlockTime fromMilliseconds(final Long medianBlockTimeInMilliseconds) { return ImmutableMedianBlockTime.fromMilliseconds(medianBlockTimeInMilliseconds); } @Override ImmutableMedianBlockTime asConst(); } abstract class MedianBlockTimeCore implements MedianBlockTime { @Override public String toString() { final Long currentTimeInSeconds = this.getCurrentTimeInSeconds(); return Util.coalesce(currentTimeInSeconds).toString(); } @Override public int hashCode() { final Long timeInSeconds = this.getCurrentTimeInSeconds(); if (timeInSeconds == null) { return 0; } return timeInSeconds.hashCode(); } @Override public boolean equals(final Object object) { if (! (object instanceof MedianBlockTime)) { return false; } final MedianBlockTime medianBlockTime = (MedianBlockTime) object; final Long timeInSeconds0 = this.getCurrentTimeInSeconds(); final Long timeInSeconds1 = medianBlockTime.getCurrentTimeInSeconds(); return Util.areEqual(timeInSeconds0, timeInSeconds1); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/validator/thread/ParalleledTaskSpawner.java<|end_filename|> package com.softwareverde.bitcoin.block.validator.thread; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; public class ParalleledTaskSpawner<T, S> { protected final String _name; protected final ThreadPool _threadPool; protected List<ValidationTask<T, S>> _validationTasks = null; protected TaskHandlerFactory<T, S> _taskHandlerFactory; public void setTaskHandlerFactory(final TaskHandlerFactory<T, S> taskHandlerFactory) { _taskHandlerFactory = taskHandlerFactory; } public ParalleledTaskSpawner(final String name, final ThreadPool threadPool) { _name = name; _threadPool = threadPool; } public void executeTasks(final List<T> items, final int maxThreadCount) { final int totalItemCount = items.getCount(); final int threadCount = Math.min(maxThreadCount, Math.max(1, (totalItemCount / maxThreadCount))); final int itemsPerThread = (totalItemCount / threadCount); final ImmutableListBuilder<ValidationTask<T, S>> listBuilder = new ImmutableListBuilder<ValidationTask<T, S>>(threadCount); for (int i = 0; i < threadCount; ++i) { final int startIndex = i * itemsPerThread; final int remainingItems = (totalItemCount - startIndex); final int itemCount = ( (i < (threadCount - 1)) ? Math.min(itemsPerThread, remainingItems) : remainingItems); if (itemCount < 1) { break; } final ValidationTask<T, S> validationTask = new ValidationTask<T, S>(_name, items, _taskHandlerFactory.newInstance()); validationTask.setStartIndex(startIndex); validationTask.setItemCount(itemCount); validationTask.enqueueTo(_threadPool); listBuilder.add(validationTask); } _validationTasks = listBuilder.build(); } public List<S> waitForResults() { final ImmutableListBuilder<S> listBuilder = new ImmutableListBuilder<S>(); for (int i = 0; i < _validationTasks.getCount(); ++i) { final ValidationTask<T, S> validationTask = _validationTasks.get(i); final S result = validationTask.getResult(); if (result == null) { return null; } listBuilder.add(result); } return listBuilder.build(); } public void abort() { for (int i = 0; i < _validationTasks.getCount(); ++i) { final ValidationTask<T, S> validationTask = _validationTasks.get(i); validationTask.abort(); } } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/script/slp/SlpScriptTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.script.ScriptDeflater; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.slp.genesis.MutableSlpGenesisScript; import com.softwareverde.bitcoin.transaction.script.slp.genesis.SlpGenesisScript; import com.softwareverde.constable.bytearray.ByteArray; import org.junit.Assert; import org.junit.Test; public class SlpScriptTests { @Test public void should_generate_genesis_token() throws Exception { // Assert final ScriptDeflater scriptDeflater = new ScriptDeflater(); final SlpScriptBuilder slpScriptBuilder = new SlpScriptBuilder(); final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); final TransactionInflater transactionInflater = new TransactionInflater(); // Tx: 54856D53EE81C1EDF9C8AA0311F66FA4DC348213D47FB3E28D7873AC008F7E26 final Transaction slpGenesisTransaction = transactionInflater.fromBytes(ByteArray.fromHexString("0100000001ECFACC1990F40F68538E0072B6A579D372CF47FCE794B502C37578485AE73192000000006A473044022040177413F9C11C234584EA6FEF76F5978D259054C5935F03DD0B26D411295AFC02204B99B05F2B7E2F7E68CE1AAC54AA5F2F53C8102A88F16DC8AAE0B7D846E9B4864121030560CE41F8FF3875A60C17D58A2B2B532C41B53F7C885BB047AEFDCAF7997B39FEFFFFFF030000000000000000486A04534C500001010747454E4553495303534C5009534C5020546F6B656E1A68747470733A2F2F73696D706C656C65646765722E636173682F4C0001084C0008000775F05A07400022020000000000001976A9142B305BB7C3331464F20CE44AFE1D2485C44CD1CA88ACB2530000000000001976A9142B305BB7C3331464F20CE44AFE1D2485C44CD1CA88AC914F0800")); final LockingScript expectedLockingScript = slpGenesisTransaction.getTransactionOutputs().get(0).getLockingScript(); final MutableSlpGenesisScript slpGenesisScript = new MutableSlpGenesisScript(); slpGenesisScript.setTokenName("SLP Token"); slpGenesisScript.setTokenAbbreviation("SLP"); slpGenesisScript.setDocumentUrl("https://simpleledger.cash/"); slpGenesisScript.setDocumentHash(null); slpGenesisScript.setDecimalCount(8); slpGenesisScript.setBatonOutputIndex(null); slpGenesisScript.setTokenCount(21000000L * Transaction.SATOSHIS_PER_BITCOIN); // Action final LockingScript lockingScript = slpScriptBuilder.createGenesisScript(slpGenesisScript); final SlpScriptType slpScriptType = slpScriptInflater.getScriptType(lockingScript); // Assert Assert.assertEquals(scriptDeflater.toBytes(expectedLockingScript), scriptDeflater.toBytes(lockingScript)); Assert.assertEquals(slpScriptInflater.genesisScriptFromScript(expectedLockingScript), slpScriptInflater.genesisScriptFromScript(lockingScript)); Assert.assertEquals(SlpScriptType.GENESIS, slpScriptType); } @Test public void decimal_count_byte_length_must_be_1_byte_for_zero_decimals() { final MutableSlpGenesisScript slpGenesisScript = new MutableSlpGenesisScript(); slpGenesisScript.setTokenName("Bitcoin Cash"); slpGenesisScript.setTokenCount(0xFFFFFFFFFFFFFFFFL); slpGenesisScript.setBatonOutputIndex(null); slpGenesisScript.setTokenAbbreviation("BCH"); slpGenesisScript.setDocumentUrl(null); slpGenesisScript.setDocumentHash(null); slpGenesisScript.setDecimalCount(0); final SlpScriptBuilder slpScriptBuilder = new SlpScriptBuilder(); final LockingScript genesisLockingScript = slpScriptBuilder.createGenesisScript(slpGenesisScript); final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); final SlpGenesisScript inflatedSlpGenesisScript = slpScriptInflater.genesisScriptFromScript(genesisLockingScript); Assert.assertEquals(slpGenesisScript, inflatedSlpGenesisScript); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/slp/validator/TransactionAccumulator.java<|end_filename|> package com.softwareverde.bitcoin.slp.validator; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import java.util.Map; public interface TransactionAccumulator { Map<Sha256Hash, Transaction> getTransactions(List<Sha256Hash> transactionHashes, final Boolean allowUnconfirmedTransactions); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/MessageTypeInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; public class MessageTypeInflater { protected static final List<MessageType> MESSAGE_TYPES; static { final ImmutableListBuilder<MessageType> messageTypes = new ImmutableListBuilder<MessageType>(); messageTypes.add(MessageType.SYNCHRONIZE_VERSION); messageTypes.add(MessageType.ACKNOWLEDGE_VERSION); messageTypes.add(MessageType.PING); messageTypes.add(MessageType.PONG); messageTypes.add(MessageType.NODE_ADDRESSES); messageTypes.add(MessageType.QUERY_BLOCKS); messageTypes.add(MessageType.INVENTORY); messageTypes.add(MessageType.QUERY_UNCONFIRMED_TRANSACTIONS); messageTypes.add(MessageType.REQUEST_BLOCK_HEADERS); messageTypes.add(MessageType.BLOCK_HEADERS); messageTypes.add(MessageType.REQUEST_DATA); messageTypes.add(MessageType.BLOCK); messageTypes.add(MessageType.TRANSACTION); messageTypes.add(MessageType.MERKLE_BLOCK); messageTypes.add(MessageType.NOT_FOUND); messageTypes.add(MessageType.ERROR); messageTypes.add(MessageType.ENABLE_NEW_BLOCKS_VIA_HEADERS); messageTypes.add(MessageType.ENABLE_COMPACT_BLOCKS); messageTypes.add(MessageType.REQUEST_EXTRA_THIN_BLOCK); messageTypes.add(MessageType.EXTRA_THIN_BLOCK); messageTypes.add(MessageType.THIN_BLOCK); messageTypes.add(MessageType.REQUEST_EXTRA_THIN_TRANSACTIONS); messageTypes.add(MessageType.THIN_TRANSACTIONS); messageTypes.add(MessageType.FEE_FILTER); messageTypes.add(MessageType.REQUEST_PEERS); messageTypes.add(MessageType.SET_TRANSACTION_BLOOM_FILTER); messageTypes.add(MessageType.UPDATE_TRANSACTION_BLOOM_FILTER); messageTypes.add(MessageType.CLEAR_TRANSACTION_BLOOM_FILTER); // Bitcoin Verde Messages messageTypes.add(MessageType.QUERY_ADDRESS_BLOCKS); messageTypes.add(MessageType.ENABLE_SLP_TRANSACTIONS); messageTypes.add(MessageType.QUERY_SLP_STATUS); MESSAGE_TYPES = messageTypes.build(); } public MessageType fromBytes(final ByteArray byteArray) { for (final MessageType messageType : MESSAGE_TYPES) { if (ByteUtil.areEqual(messageType.getBytes(), byteArray)) { return messageType; } } return null; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/merkleroot/PartialMerkleTreeInflater.java<|end_filename|> package com.softwareverde.bitcoin.block.merkleroot; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import com.softwareverde.util.bytearray.Endian; public class PartialMerkleTreeInflater { public static final Integer MAX_HASHES_COUNT = (1 << 17); protected PartialMerkleTree _fromBytes(final ByteArrayReader byteArrayReader) { final Integer transactionCount = byteArrayReader.readInteger(4, Endian.LITTLE); final Integer hashesCount = byteArrayReader.readVariableSizedInteger().intValue(); if (hashesCount > MAX_HASHES_COUNT) { Logger.debug("MerkleBlock exceeded maximum hashes count: " + hashesCount); return null; } final ImmutableListBuilder<Sha256Hash> hashesBuilder = new ImmutableListBuilder<Sha256Hash>(hashesCount); for (int i = 0; i < hashesCount; ++i) { final Sha256Hash hash = MutableSha256Hash.wrap(byteArrayReader.readBytes(Sha256Hash.BYTE_COUNT, Endian.LITTLE)); hashesBuilder.add(hash); } final Integer flagsByteCount = byteArrayReader.readVariableSizedInteger().intValue(); if (flagsByteCount > MAX_HASHES_COUNT) { Logger.debug("MerkleBlock exceeded maximum flag-bytes count: " + flagsByteCount); return null; } final MutableByteArray flags = MutableByteArray.wrap(byteArrayReader.readBytes(flagsByteCount)); for (int i = 0; i < flagsByteCount; ++i) { flags.setByte(i, ByteUtil.reverseBits(flags.getByte(i))); } if (byteArrayReader.didOverflow()) { return null; } return PartialMerkleTree.build(transactionCount, hashesBuilder.build(), flags); } public PartialMerkleTree fromBytes(final byte[] bytes) { final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); return _fromBytes(byteArrayReader); } public PartialMerkleTree fromBytes(final ByteArray bytes) { final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); return _fromBytes(byteArrayReader); } public PartialMerkleTree fromBytes(final ByteArrayReader byteArrayReader) { return _fromBytes(byteArrayReader); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/socket/StratumServerSocket.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.socket; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.logging.Logger; import com.softwareverde.network.socket.JsonSocket; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class StratumServerSocket { public interface SocketEventCallback { void onConnect(JsonSocket socketConnection); void onDisconnect(JsonSocket socketConnection); } protected final Integer _port; protected java.net.ServerSocket _socket; protected final List<JsonSocket> _connections = new ArrayList<JsonSocket>(); protected Long _nextConnectionId = 0L; protected volatile Boolean _shouldContinue = true; protected Thread _serverThread = null; protected SocketEventCallback _socketEventCallback = null; protected final ThreadPool _threadPool; protected static final Long _purgeEveryCount = 20L; protected void _purgeDisconnectedConnections() { synchronized (_connections) { final Iterator<JsonSocket> iterator = _connections.iterator(); while (iterator.hasNext()) { final JsonSocket connection = iterator.next(); if (connection == null) { continue; } if (! connection.isConnected()) { iterator.remove(); Logger.debug("Purging disconnected stratum socket: " + connection.getIp() + ":" + connection.getPort()); _onDisconnect(connection); } } } } protected void _onConnect(final JsonSocket socketConnection) { final SocketEventCallback socketEventCallback = _socketEventCallback; if (socketEventCallback != null) { _threadPool.execute(new Runnable() { @Override public void run() { socketEventCallback.onConnect(socketConnection); } }); } } protected void _onDisconnect(final JsonSocket socketConnection) { final SocketEventCallback socketEventCallback = _socketEventCallback; if (socketEventCallback != null) { _threadPool.execute(new Runnable() { @Override public void run() { socketEventCallback.onDisconnect(socketConnection); } }); } } public StratumServerSocket(final Integer port, final ThreadPool threadPool) { _port = port; _threadPool = threadPool; } public void setSocketEventCallback(final SocketEventCallback socketEventCallback) { _socketEventCallback = socketEventCallback; } public void start() { _shouldContinue = true; try { _socket = new java.net.ServerSocket(_port); _serverThread = new Thread(new Runnable() { @Override public void run() { try { while (_shouldContinue) { if (_socket == null) { return; } final JsonSocket connection = new JsonSocket(_socket.accept(), _threadPool); final Boolean shouldPurgeConnections = (_nextConnectionId % _purgeEveryCount == 0L); if (shouldPurgeConnections) { _purgeDisconnectedConnections(); } synchronized (_connections) { _connections.add(connection); _nextConnectionId += 1L; } _onConnect(connection); } } catch (final IOException exception) { } } }); _serverThread.start(); } catch (final Exception exception) { Logger.warn(exception); } } public void stop() { _shouldContinue = false; if (_socket != null) { try { _socket.close(); } catch (final IOException e) { } } _socket = null; try { if (_serverThread != null) { _serverThread.join(30000L); } } catch (final Exception exception) { } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/slp/validator/SlpTransactionValidationCache.java<|end_filename|> package com.softwareverde.bitcoin.slp.validator; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface SlpTransactionValidationCache { /** * Returns null if validity of the associated transaction has not been cached. * Returns true if validity of the associated transaction has been cached and is valid. * Returns false if validity of the associated transaction has been cached and is invalid. */ Boolean isValid(Sha256Hash transactionHash); /** * Marks the transaction as valid for subsequent calls to ::isValid. * Failing to mark a transaction as valid/invalid may result in [sum(txInputCount)]^[validationDepth]. */ void setIsValid(Sha256Hash transactionHash, Boolean isValid); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/spv/SpvModule.java<|end_filename|> package com.softwareverde.bitcoin.server.module.spv; import com.softwareverde.bitcoin.CoreInflater; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.MerkleBlock; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.context.core.BlockHeaderDownloaderContext; import com.softwareverde.bitcoin.inflater.MasterInflater; import com.softwareverde.bitcoin.server.Environment; import com.softwareverde.bitcoin.server.State; import com.softwareverde.bitcoin.server.configuration.CheckpointConfiguration; import com.softwareverde.bitcoin.server.configuration.SeedNodeProperties; import com.softwareverde.bitcoin.server.database.Database; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.node.address.BitcoinNodeIpAddress; import com.softwareverde.bitcoin.server.message.type.node.feature.LocalNodeFeatures; import com.softwareverde.bitcoin.server.message.type.node.feature.NodeFeatures; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.BlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.spv.SpvBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.spv.SpvDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.spv.SpvDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.transaction.spv.SlpValidity; import com.softwareverde.bitcoin.server.module.node.database.transaction.spv.SpvTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.handler.block.RequestBlockHeadersHandler; import com.softwareverde.bitcoin.server.module.node.manager.BitcoinNodeManager; import com.softwareverde.bitcoin.server.module.node.manager.NodeInitializer; import com.softwareverde.bitcoin.server.module.node.manager.banfilter.BanFilter; import com.softwareverde.bitcoin.server.module.node.manager.banfilter.BanFilterCore; import com.softwareverde.bitcoin.server.module.node.sync.BlockHeaderDownloader; import com.softwareverde.bitcoin.server.module.node.sync.SpvSlpTransactionValidator; import com.softwareverde.bitcoin.server.module.spv.handler.MerkleBlockDownloader; import com.softwareverde.bitcoin.server.module.spv.handler.SpvRequestDataHandler; import com.softwareverde.bitcoin.server.module.spv.handler.SynchronizationStatusHandler; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.bitcoin.server.node.BitcoinNodeFactory; import com.softwareverde.bitcoin.server.node.RequestId; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionBloomFilterMatcher; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.wallet.Wallet; import com.softwareverde.bloomfilter.BloomFilter; import com.softwareverde.bloomfilter.MutableBloomFilter; import com.softwareverde.concurrent.pool.MainThreadPool; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.concurrent.pool.ThreadPoolFactory; import com.softwareverde.concurrent.pool.ThreadPoolThrottle; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.util.TransactionUtil; import com.softwareverde.logging.Logger; import com.softwareverde.network.ip.Ip; import com.softwareverde.network.p2p.node.address.NodeIpAddress; import com.softwareverde.network.time.MutableNetworkTime; import com.softwareverde.util.Tuple; import com.softwareverde.util.Util; import com.softwareverde.util.type.time.SystemTime; import java.util.HashSet; public class SpvModule { public interface MerkleBlockSyncUpdateCallback { void onMerkleBlockHeightUpdated(Long currentBlockHeight, Boolean isSynchronizing); } public interface NewTransactionCallback { void onNewTransactionReceived(Transaction transaction); } public interface TransactionValidityChangedCallback { void onTransactionValidityChanged(Sha256Hash transactionHash, SlpValidity slpValidity); } public enum Status { INITIALIZING ("Initializing"), LOADING ("Loading"), ONLINE ("Online"), SHUTTING_DOWN ("Shutting Down"), OFFLINE ("Offline"); private final String value; Status(final String value) { this.value = value; } public String getValue() { return this.value; } } protected static final TransactionValidityChangedCallback IGNORE_TRANSACTION_VALIDITY_CHANGED_CALLBACK = new TransactionValidityChangedCallback() { @Override public void onTransactionValidityChanged(final Sha256Hash transactionHash, final SlpValidity slpValidity) { } }; protected final Object _initPin = new Object(); protected final Integer _maxPeerCount; protected Boolean _isInitialized = false; protected final SeedNodeProperties[] _seedNodes; protected final Environment _environment; protected final CheckpointConfiguration _checkpointConfiguration; protected final MasterInflater _masterInflater; protected final Wallet _wallet; protected final SpvRequestDataHandler _spvRequestDataHandler = new SpvRequestDataHandler(); protected BitcoinNodeManager _bitcoinNodeManager; protected BlockHeaderDownloader _blockHeaderDownloader; protected SpvSlpTransactionValidator _spvSlpTransactionValidator; protected Boolean _shouldOnlyConnectToSeedNodes = false; protected final SystemTime _systemTime = new SystemTime(); protected final MutableNetworkTime _mutableNetworkTime = new MutableNetworkTime(); protected final DatabaseConnectionFactory _databaseConnectionFactory; protected final SpvDatabaseManagerFactory _databaseManagerFactory; protected final MainThreadPool _mainThreadPool; protected final BanFilter _banFilter; protected MerkleBlockDownloader _merkleBlockDownloader; protected BitcoinNodeFactory _bitcoinNodeFactory; protected Long _minimumMerkleBlockHeight = 575000L; protected volatile Status _status = Status.OFFLINE; protected Runnable _onStatusUpdatedCallback = null; protected NewTransactionCallback _newTransactionCallback = null; protected TransactionValidityChangedCallback _transactionValidityChangedCallback = null; protected Runnable _newBlockHeaderAvailableCallback = null; protected Sha256Hash _currentMerkleBlockHash = null; protected MerkleBlockSyncUpdateCallback _merkleBlockSyncUpdateCallback = null; protected void _setStatus(final Status status) { final Status previousStatus = _status; _status = status; if (previousStatus != status) { final Runnable callback = _onStatusUpdatedCallback; if (callback != null) { callback.run(); } } } protected void _waitForInit() { if (_isInitialized) { return; } synchronized (_initPin) { if (_isInitialized) { return; } try { _initPin.wait(); } catch (final Exception exception) { } } } protected void _connectToSeedNodes() { for (final SeedNodeProperties seedNodeProperties : _seedNodes) { final NodeIpAddress nodeIpAddress = SeedNodeProperties.toNodeIpAddress(seedNodeProperties); if (nodeIpAddress == null) { continue; } final boolean isAlreadyConnectedToNode = _bitcoinNodeManager.isConnectedToNode(nodeIpAddress); if (isAlreadyConnectedToNode) { continue; } final Ip ip = nodeIpAddress.getIp(); final Integer port = nodeIpAddress.getPort(); final BitcoinNode node = _bitcoinNodeFactory.newNode(String.valueOf(ip), port); _bitcoinNodeManager.addNode(node); } } protected void _synchronizeSlpValidity() { _spvSlpTransactionValidator.wakeUp(); } protected void _executeMerkleBlockSyncUpdateCallback() { final MerkleBlockSyncUpdateCallback merkleBlockSyncUpdateCallback = _merkleBlockSyncUpdateCallback; if (merkleBlockSyncUpdateCallback == null) { return; } _mainThreadPool.execute(new Runnable() { @Override public void run() { final Database database = _environment.getDatabase(); try (final DatabaseConnection databaseConnection = database.newConnection()) { final SpvDatabaseManager databaseManager = new SpvDatabaseManager(databaseConnection, database.getMaxQueryBatchSize(), _checkpointConfiguration); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final Long blockHeight; { final BlockId blockId; final Sha256Hash currentMerkleBlockHash = _currentMerkleBlockHash; if (currentMerkleBlockHash != null) { blockId = blockHeaderDatabaseManager.getBlockHeaderId(_currentMerkleBlockHash); } else { blockId = blockDatabaseManager.getHeadBlockId(); } blockHeight = blockHeaderDatabaseManager.getBlockHeight(blockId); } final Boolean isSynchronizingMerkleBlocks = _merkleBlockDownloader.isRunning(); merkleBlockSyncUpdateCallback.onMerkleBlockHeightUpdated(blockHeight, isSynchronizingMerkleBlocks); } catch (final DatabaseException exception) { Logger.warn(exception); } } }); } protected void _synchronizeMerkleBlocks() { if (! _bitcoinNodeManager.hasBloomFilter()) { Logger.warn("Unable to synchronize merkle blocks. Bloom filter not set.", new Exception()); return; } _merkleBlockDownloader.start(); } protected void _shutdown() { _setStatus(Status.SHUTTING_DOWN); if (_merkleBlockDownloader != null) { Logger.info("[Stopping MerkleBlock Downloader]"); _merkleBlockDownloader.shutdown(); } if (_blockHeaderDownloader != null) { Logger.info("[Stopping Header Downloader]"); _blockHeaderDownloader.stop(); } if (_spvSlpTransactionValidator != null) { Logger.info("[Stopping SPV SLP Validator]"); _spvSlpTransactionValidator.stop(); } if (_bitcoinNodeManager != null) { Logger.info("[Stopping Node Manager]"); _bitcoinNodeManager.shutdown(); } Logger.info("[Shutting Down Thread Server]"); _mainThreadPool.stop(); Logger.flush(); _setStatus(Status.OFFLINE); } protected void _loadDownloadedTransactionsIntoWallet() { final Database database = _environment.getDatabase(); try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { final SpvDatabaseManager databaseManager = new SpvDatabaseManager(databaseConnection, database.getMaxQueryBatchSize(), _checkpointConfiguration); final SpvBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final SpvTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); final HashSet<TransactionId> confirmedTransactionIds = new HashSet<TransactionId>(); { // load known valid/invalid SLP transaction hashes (unknowns will be handed automatically) final List<Sha256Hash> validSlpTransactions = transactionDatabaseManager.getSlpTransactionsWithSlpStatus(SlpValidity.VALID); for (final Sha256Hash transactionHash : validSlpTransactions) { _wallet.markSlpTransactionAsValid(transactionHash); } final List<Sha256Hash> invalidSlpTransactions = transactionDatabaseManager.getSlpTransactionsWithSlpStatus(SlpValidity.INVALID); for (final Sha256Hash transactionHash : invalidSlpTransactions) { _wallet.markSlpTransactionAsInvalid(transactionHash); } } { // Load confirmed Transactions from database... int loadedConfirmedTransactionCount = 0; final List<BlockId> blockIds = blockDatabaseManager.getBlockIdsWithTransactions(); for (final BlockId blockId : blockIds) { final List<TransactionId> transactionIds = blockDatabaseManager.getTransactionIds(blockId); for (final TransactionId transactionId : transactionIds) { final Transaction transaction = transactionDatabaseManager.getTransaction(transactionId); if (transaction == null) { Logger.warn("Unable to inflate Transaction: " + transactionId); continue; } confirmedTransactionIds.add(transactionId); _wallet.addTransaction(transaction); loadedConfirmedTransactionCount += 1; } } Logger.debug("Loaded " + loadedConfirmedTransactionCount + " confirmed transactions."); } { // Load remaining Transactions as unconfirmed Transactions from database... int loadedUnconfirmedTransactionCount = 0; final List<TransactionId> transactionIds = transactionDatabaseManager.getTransactionIds(); for (final TransactionId transactionId : transactionIds) { final boolean isUniqueTransactionId = confirmedTransactionIds.add(transactionId); if (! isUniqueTransactionId) { continue; } final Transaction transaction = transactionDatabaseManager.getTransaction(transactionId); if (transaction == null) { Logger.warn("Unable to inflate Transaction: " + transactionId); continue; } _wallet.addUnconfirmedTransaction(transaction); loadedUnconfirmedTransactionCount += 1; } Logger.debug("Loaded " + loadedUnconfirmedTransactionCount + " unconfirmed transactions."); } } catch (final DatabaseException exception) { Logger.warn(exception); } } public SpvModule(final Environment environment, final SeedNodeProperties[] seedNodes, final Integer maxPeerCount, final Wallet wallet) { _masterInflater = new CoreInflater(); _seedNodes = seedNodes; _wallet = wallet; _mainThreadPool = new MainThreadPool(Math.min(maxPeerCount * 8, 256), 5000L); _maxPeerCount = maxPeerCount; _mainThreadPool.setShutdownCallback(new Runnable() { @Override public void run() { try { _shutdown(); } catch (final Throwable ignored) { } } }); _environment = environment; _checkpointConfiguration = new CheckpointConfiguration(); final Database database = _environment.getDatabase(); _databaseConnectionFactory = database.newConnectionFactory(); _databaseManagerFactory = new SpvDatabaseManagerFactory(_databaseConnectionFactory, database.getMaxQueryBatchSize(), _checkpointConfiguration); _banFilter = new BanFilterCore(_databaseManagerFactory); } public Boolean isInitialized() { return _isInitialized; } public void initialize() { final Thread mainThread = Thread.currentThread(); _setStatus(Status.INITIALIZING); final Integer maxQueryBatchSize; { final Database database = _environment.getDatabase(); maxQueryBatchSize = database.getMaxQueryBatchSize(); } mainThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread thread, final Throwable throwable) { try { Logger.error(throwable); _shutdown(); } catch (final Throwable ignored) { } } }); _setStatus(Status.LOADING); final SynchronizationStatusHandler synchronizationStatusHandler = new SynchronizationStatusHandler(_databaseManagerFactory); final ThreadPoolFactory threadPoolFactory = new ThreadPoolFactory() { @Override public ThreadPool newThreadPool() { final ThreadPoolThrottle threadPoolThrottle = new ThreadPoolThrottle(64, _mainThreadPool); threadPoolThrottle.start(); return threadPoolThrottle; } }; final SpvDatabaseManagerFactory databaseManagerFactory = new SpvDatabaseManagerFactory(_databaseConnectionFactory, maxQueryBatchSize, _checkpointConfiguration); _merkleBlockDownloader = new MerkleBlockDownloader(databaseManagerFactory, new MerkleBlockDownloader.Downloader() { @Override public Tuple<RequestId, BitcoinNode> requestMerkleBlock(final Sha256Hash blockHash, final BitcoinNode.DownloadMerkleBlockCallback callback) { if (! _bitcoinNodeManager.hasBloomFilter()) { if (callback != null) { callback.onFailure(null, null, blockHash); } return new Tuple<>(); } final List<BitcoinNode> bitcoinNodes = _bitcoinNodeManager.getPreferredNodes(); if (bitcoinNodes.isEmpty()) { return new Tuple<>(); } final int index = (int) (Math.random() * bitcoinNodes.getCount()); final BitcoinNode bitcoinNode = bitcoinNodes.get(index); final RequestId requestId = bitcoinNode.requestMerkleBlock(blockHash, callback); return new Tuple<>(requestId, bitcoinNode); } }); _merkleBlockDownloader.setMinimumMerkleBlockHeight(_minimumMerkleBlockHeight); _merkleBlockDownloader.setDownloadCompleteCallback(new MerkleBlockDownloader.DownloadCompleteCallback() { @Override public void newMerkleBlockDownloaded(final MerkleBlock merkleBlock, final List<Transaction> transactions) { final BloomFilter walletBloomFilter = _wallet.getBloomFilter(); final AddressInflater addressInflater = _masterInflater.getAddressInflater(); final TransactionBloomFilterMatcher transactionBloomFilterMatcher = new TransactionBloomFilterMatcher(walletBloomFilter, addressInflater); try (final SpvDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final DatabaseConnection databaseConnection = databaseManager.getDatabaseConnection(); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final SpvBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final SpvTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); TransactionUtil.startTransaction(databaseConnection); final Sha256Hash previousBlockHash = merkleBlock.getPreviousBlockHash(); if (! Util.areEqual(previousBlockHash, Sha256Hash.EMPTY_HASH)) { // Check for Genesis Block... final BlockId previousBlockId = blockHeaderDatabaseManager.getBlockHeaderId(merkleBlock.getPreviousBlockHash()); if (previousBlockId == null) { Logger.debug("Out of order MerkleBlock received. Discarding. " + merkleBlock.getHash()); return; } } synchronized (BlockHeaderDatabaseManager.MUTEX) { final BlockId blockId = blockHeaderDatabaseManager.storeBlockHeader(merkleBlock); blockDatabaseManager.storePartialMerkleTree(blockId, merkleBlock.getPartialMerkleTree()); for (final Transaction transaction : transactions) { if (transactionBloomFilterMatcher.shouldInclude(transaction)) { final TransactionId transactionId = transactionDatabaseManager.storeTransaction(transaction); blockDatabaseManager.addTransactionToBlock(blockId, transactionId); _wallet.addTransaction(transaction); } } _synchronizeSlpValidity(); } TransactionUtil.commitTransaction(databaseConnection); } catch (final DatabaseException exception) { Logger.warn(exception); return; } final NewTransactionCallback newTransactionCallback = _newTransactionCallback; if (newTransactionCallback != null) { _mainThreadPool.execute(new Runnable() { @Override public void run() { for (final Transaction transaction : transactions) { newTransactionCallback.onNewTransactionReceived(transaction); } } }); } } }); _merkleBlockDownloader.setMerkleBlockProcessedCallback(new Runnable() { @Override public void run() { _executeMerkleBlockSyncUpdateCallback(); } }); final LocalNodeFeatures localNodeFeatures = new LocalNodeFeatures() { @Override public NodeFeatures getNodeFeatures() { final NodeFeatures nodeFeatures = new NodeFeatures(); nodeFeatures.enableFeature(NodeFeatures.Feature.BITCOIN_CASH_ENABLED); nodeFeatures.enableFeature(NodeFeatures.Feature.BLOOM_CONNECTIONS_ENABLED); return nodeFeatures; } }; final NodeInitializer nodeInitializer; { // Initialize NodeInitializer... final NodeInitializer.TransactionsAnnouncementHandlerFactory transactionsAnnouncementHandlerFactory = new NodeInitializer.TransactionsAnnouncementHandlerFactory() { protected final BitcoinNode.DownloadTransactionCallback _downloadTransactionsCallback = new BitcoinNode.DownloadTransactionCallback() { @Override public void onResult(final RequestId requestId, final BitcoinNode bitcoinNode, final Transaction transaction) { final Sha256Hash transactionHash = transaction.getHash(); Logger.debug("Received Transaction: " + transactionHash); final BloomFilter walletBloomFilter = _wallet.getBloomFilter(); final AddressInflater addressInflater = _masterInflater.getAddressInflater(); final TransactionBloomFilterMatcher transactionBloomFilterMatcher = new TransactionBloomFilterMatcher(walletBloomFilter, addressInflater); if (! transactionBloomFilterMatcher.shouldInclude(transaction)) { Logger.debug("Skipping Transaction that does not match filter: " + transactionHash); return; } try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { final SpvDatabaseManager databaseManager = new SpvDatabaseManager(databaseConnection, maxQueryBatchSize, _checkpointConfiguration); final SpvTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); TransactionUtil.startTransaction(databaseConnection); transactionDatabaseManager.storeTransaction(transaction); TransactionUtil.commitTransaction(databaseConnection); } catch (final DatabaseException exception) { Logger.warn(exception); } _wallet.addUnconfirmedTransaction(transaction); final NewTransactionCallback newTransactionCallback = _newTransactionCallback; if (newTransactionCallback != null) { _mainThreadPool.execute(new Runnable() { @Override public void run() { newTransactionCallback.onNewTransactionReceived(transaction); } }); } if (Transaction.isSlpTransaction(transaction)) { _synchronizeSlpValidity(); } } }; @Override public BitcoinNode.TransactionInventoryAnnouncementHandler createTransactionsAnnouncementHandler(final BitcoinNode bitcoinNode) { return new BitcoinNode.TransactionInventoryAnnouncementHandler() { @Override public void onResult(final BitcoinNode bitcoinNode, final List<Sha256Hash> transactions) { Logger.debug("Received " + transactions.getCount() + " transaction inventories."); final MutableList<Sha256Hash> unseenTransactions = new MutableList<Sha256Hash>(transactions.getCount()); try (final SpvDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final SpvTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); for (final Sha256Hash transactionHash : transactions) { final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); if (transactionId == null) { unseenTransactions.add(transactionHash); } } } catch (final DatabaseException exception) { Logger.warn(exception); } Logger.debug(unseenTransactions.getCount() + " transactions were new."); if (! unseenTransactions.isEmpty()) { bitcoinNode.requestTransactions(unseenTransactions, _downloadTransactionsCallback); } } @Override public void onResult(final BitcoinNode bitcoinNode, final List<Sha256Hash> transactionHashes, final Boolean isValid) { this.onResult(bitcoinNode, transactionHashes); try (final SpvDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final SpvTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); final DatabaseConnection databaseConnection = databaseManager.getDatabaseConnection(); final TransactionValidityChangedCallback transactionValidityChangedCallback = Util.coalesce(_transactionValidityChangedCallback, IGNORE_TRANSACTION_VALIDITY_CHANGED_CALLBACK); TransactionUtil.startTransaction(databaseConnection); Logger.info("Marking " + transactionHashes.getCount() + " SLP transactions as " + (isValid ? "valid" : "invalid")); for (final Sha256Hash transactionHash : transactionHashes) { if (isValid) { _wallet.markSlpTransactionAsValid(transactionHash); } else { _wallet.markSlpTransactionAsInvalid(transactionHash); } final SlpValidity slpValidity = (isValid ? SlpValidity.VALID : SlpValidity.INVALID); final TransactionId transactionId = transactionDatabaseManager.getTransactionId(transactionHash); if (transactionId != null) { final SlpValidity currentSlpValidity = transactionDatabaseManager.getSlpValidity(transactionId); if (currentSlpValidity != slpValidity) { transactionDatabaseManager.setSlpValidity(transactionId, slpValidity); transactionValidityChangedCallback.onTransactionValidityChanged(transactionHash, slpValidity); } } } TransactionUtil.commitTransaction(databaseConnection); } catch (final DatabaseException exception) { Logger.warn("Problem tracking SLP validity", exception); } } }; } }; final RequestBlockHeadersHandler requestBlockHeadersHandler = new RequestBlockHeadersHandler(databaseManagerFactory); final BitcoinNode.RequestPeersHandler requestPeersHandler = new BitcoinNode.RequestPeersHandler() { @Override public List<BitcoinNodeIpAddress> getConnectedPeers() { final List<BitcoinNode> connectedNodes = _bitcoinNodeManager.getNodes(); final ImmutableListBuilder<BitcoinNodeIpAddress> nodeIpAddresses = new ImmutableListBuilder<BitcoinNodeIpAddress>(connectedNodes.getCount()); for (final BitcoinNode bitcoinNode : connectedNodes) { final NodeIpAddress nodeIpAddress = bitcoinNode.getRemoteNodeIpAddress(); final BitcoinNodeIpAddress bitcoinNodeIpAddress = new BitcoinNodeIpAddress(nodeIpAddress); bitcoinNodeIpAddress.setNodeFeatures(bitcoinNode.getNodeFeatures()); nodeIpAddresses.add(bitcoinNodeIpAddress); } return nodeIpAddresses.build(); } }; final NodeInitializer.Context nodeInitializerContext = new NodeInitializer.Context(); nodeInitializerContext.synchronizationStatus = synchronizationStatusHandler; nodeInitializerContext.blockInventoryMessageHandler = new BitcoinNode.BlockInventoryAnnouncementHandler() { @Override public void onNewInventory(final BitcoinNode bitcoinNode, final List<Sha256Hash> blockHashes) { if (! _bitcoinNodeManager.hasBloomFilter()) { return; } // Only restart the synchronization process if it has already successfully completed. _merkleBlockDownloader.wakeUp(); } @Override public void onNewHeaders(final BitcoinNode bitcoinNode, final List<BlockHeader> blockHeaders) { final MutableList<Sha256Hash> blockHashes = new MutableList<Sha256Hash>(blockHeaders.getCount()); for (final BlockHeader blockHeader : blockHeaders) { final Sha256Hash blockHash = blockHeader.getHash(); blockHashes.add(blockHash); } this.onNewInventory(bitcoinNode, blockHashes); } }; nodeInitializerContext.threadPoolFactory = threadPoolFactory; nodeInitializerContext.localNodeFeatures = localNodeFeatures; nodeInitializerContext._transactionsAnnouncementHandlerFactory = transactionsAnnouncementHandlerFactory; nodeInitializerContext.requestBlockHashesHandler = null; nodeInitializerContext.requestBlockHeadersHandler = requestBlockHeadersHandler; nodeInitializerContext.requestDataHandler = _spvRequestDataHandler; nodeInitializerContext.requestPeersHandler = requestPeersHandler; nodeInitializerContext.requestUnconfirmedTransactionsHandler = null; nodeInitializerContext.spvBlockInventoryAnnouncementHandler = _merkleBlockDownloader; nodeInitializerContext.requestPeersHandler = new BitcoinNode.RequestPeersHandler() { @Override public List<BitcoinNodeIpAddress> getConnectedPeers() { final List<BitcoinNode> connectedNodes = _bitcoinNodeManager.getNodes(); final ImmutableListBuilder<BitcoinNodeIpAddress> nodeIpAddresses = new ImmutableListBuilder<BitcoinNodeIpAddress>(connectedNodes.getCount()); for (final BitcoinNode bitcoinNode : connectedNodes) { final NodeIpAddress nodeIpAddress = bitcoinNode.getRemoteNodeIpAddress(); final BitcoinNodeIpAddress bitcoinNodeIpAddress = new BitcoinNodeIpAddress(nodeIpAddress); bitcoinNodeIpAddress.setNodeFeatures(bitcoinNode.getNodeFeatures()); nodeIpAddresses.add(bitcoinNodeIpAddress); } return nodeIpAddresses.build(); } }; nodeInitializerContext.binaryPacketFormat = BitcoinProtocolMessage.BINARY_PACKET_FORMAT; _bitcoinNodeFactory = new BitcoinNodeFactory(nodeInitializerContext.binaryPacketFormat, threadPoolFactory, localNodeFeatures); nodeInitializer = new NodeInitializer(nodeInitializerContext); } { // Initialize NodeManager... final BitcoinNodeManager.Context context = new BitcoinNodeManager.Context(); { context.systemTime = _systemTime; context.databaseManagerFactory = databaseManagerFactory; context.nodeFactory = new BitcoinNodeFactory(BitcoinProtocolMessage.BINARY_PACKET_FORMAT, threadPoolFactory, localNodeFeatures); context.maxNodeCount = _maxPeerCount; context.networkTime = _mutableNetworkTime; context.nodeInitializer = nodeInitializer; context.banFilter = _banFilter; context.memoryPoolEnquirer = null; context.synchronizationStatusHandler = synchronizationStatusHandler; context.threadPool = _mainThreadPool; } _bitcoinNodeManager = new BitcoinNodeManager(context); _bitcoinNodeManager.enableTransactionRelay(false); _bitcoinNodeManager.enableSlpValidityChecking(true); _bitcoinNodeManager.setShouldOnlyConnectToSeedNodes(_shouldOnlyConnectToSeedNodes); for (final SeedNodeProperties seedNodeProperties : _seedNodes) { final NodeIpAddress nodeIpAddress = SeedNodeProperties.toNodeIpAddress(seedNodeProperties); if (nodeIpAddress == null) { continue; } _bitcoinNodeManager.defineSeedNode(nodeIpAddress); } } { // Initialize BlockHeaderDownloader... final BlockHeaderDownloaderContext blockHeaderDownloaderContext = new BlockHeaderDownloaderContext(_bitcoinNodeManager, databaseManagerFactory, _mutableNetworkTime, _systemTime, _mainThreadPool); _blockHeaderDownloader = new BlockHeaderDownloader(blockHeaderDownloaderContext, null); _blockHeaderDownloader.setMinBlockTimestamp(_systemTime.getCurrentTimeInSeconds()); } { // Initialize SpvSlpValidator _spvSlpTransactionValidator = new SpvSlpTransactionValidator(databaseManagerFactory, _bitcoinNodeManager); } try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { final DatabaseManager databaseManager = new SpvDatabaseManager(databaseConnection, maxQueryBatchSize, _checkpointConfiguration); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockId headBlockHeaderId = blockHeaderDatabaseManager.getHeadBlockHeaderId(); final Long headBlockHeaderTimestamp = (headBlockHeaderId != null ? blockHeaderDatabaseManager.getBlockTimestamp(headBlockHeaderId) : 0L); final Long currentTimestamp = _systemTime.getCurrentTimeInSeconds(); final long behindThreshold = (60L * 60L); // 1 Hour if ((currentTimestamp - headBlockHeaderTimestamp) > behindThreshold) { synchronizationStatusHandler.setState(State.SYNCHRONIZING); } else { synchronizationStatusHandler.setState(State.ONLINE); } } catch (final DatabaseException exception) { Logger.warn(exception); } _blockHeaderDownloader.setNewBlockHeaderAvailableCallback(new BlockHeaderDownloader.NewBlockHeadersAvailableCallback() { @Override public void onNewHeadersReceived(final BitcoinNode bitcoinNode, final List<BlockHeader> blockHeaders) { final Runnable newBlockHeaderAvailableCallback = _newBlockHeaderAvailableCallback; if (newBlockHeaderAvailableCallback != null) { newBlockHeaderAvailableCallback.run(); } } }); if (_wallet.hasPrivateKeys()) { // Avoid sending an empty bloom filter since Bitcoin Unlimited nodes will ignore it. final MutableBloomFilter bloomFilter = _wallet.generateBloomFilter(); _bitcoinNodeManager.setBloomFilter(bloomFilter); } _loadDownloadedTransactionsIntoWallet(); _isInitialized = true; synchronized (_initPin) { _initPin.notifyAll(); } } public void setNewBlockHeaderAvailableCallback(final Runnable newBlockHeaderAvailableCallback) { _newBlockHeaderAvailableCallback = newBlockHeaderAvailableCallback; } public Long getBlockHeight() { return _blockHeaderDownloader.getBlockHeight(); } public void loop() { _waitForInit(); _setStatus(Status.ONLINE); if ( (! _bitcoinNodeManager.hasBloomFilter()) && (_wallet.hasPrivateKeys()) ) { final MutableBloomFilter bloomFilter = _wallet.generateBloomFilter(); _bitcoinNodeManager.setBloomFilter(bloomFilter); _merkleBlockDownloader.wakeUp(); } Logger.info("[Starting Node Manager]"); _bitcoinNodeManager.start(); _connectToSeedNodes(); Logger.info("[Starting SPV SLP Validator]"); _spvSlpTransactionValidator.start(); Logger.info("[Starting Header Downloader]"); _blockHeaderDownloader.start(); while (! Thread.interrupted()) { // NOTE: Clears the isInterrupted flag for subsequent checks... try { Thread.sleep(50000); } catch (final Exception exception) { break; } } Logger.info("[SPV Module Exiting]"); _shutdown(); } public void setOnStatusUpdatedCallback(final Runnable callback) { _onStatusUpdatedCallback = callback; } public void setNewTransactionCallback(final NewTransactionCallback newTransactionCallback) { _newTransactionCallback = newTransactionCallback; } public void setTransactionValidityChangedCallback(final TransactionValidityChangedCallback transactionValidityChangedCallback) { _transactionValidityChangedCallback = transactionValidityChangedCallback; } public Status getStatus() { return _status; } public BitcoinNodeManager getBitcoinNodeManager() { return _bitcoinNodeManager; } public void connectToSeedNodes() { _connectToSeedNodes(); } public void storeTransaction(final Transaction transaction) throws DatabaseException { try (final SpvDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final SpvTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); transactionDatabaseManager.storeTransaction(transaction); } _wallet.addTransaction(transaction); } public void broadcastTransaction(final Transaction transaction) { _spvRequestDataHandler.addSpvTransaction(transaction); final MutableList<Sha256Hash> transactionHashes = new MutableList<Sha256Hash>(1); transactionHashes.add(transaction.getHash()); for (final BitcoinNode bitcoinNode : _bitcoinNodeManager.getNodes()) { Logger.info("Sending Tx Hash " + transaction.getHash() + " to " + bitcoinNode.getConnectionString()); bitcoinNode.transmitTransactionHashes(transactionHashes); } _synchronizeSlpValidity(); } public void setMerkleBlockSyncUpdateCallback(final MerkleBlockSyncUpdateCallback merkleBlockSyncUpdateCallback) { _merkleBlockSyncUpdateCallback = merkleBlockSyncUpdateCallback; } public void synchronizeMerkleBlocks() { _synchronizeMerkleBlocks(); } public void synchronizeSlpValidity() { _synchronizeSlpValidity(); } /** * Sets the merkleBlock height to begin syncing at. * This value is inclusive. * MerkleBlocks before this height will not be queried for transactions. */ public void setMinimumMerkleBlockHeight(final Long minimumMerkleBlockHeight) { _minimumMerkleBlockHeight = minimumMerkleBlockHeight; _merkleBlockDownloader.setMinimumMerkleBlockHeight(minimumMerkleBlockHeight); _merkleBlockDownloader.resetQueue(); } public void setShouldOnlyConnectToSeedNodes(final Boolean shouldOnlyConnectToSeedNodes) { _shouldOnlyConnectToSeedNodes = shouldOnlyConnectToSeedNodes; if (_bitcoinNodeManager != null) { _bitcoinNodeManager.setShouldOnlyConnectToSeedNodes(shouldOnlyConnectToSeedNodes); } } /** * Should be called whenever an external addition/removal to the internal wallet's keys occurs. * This function updates the node connections' bloom dilter. */ public void onWalletKeysUpdated() { final MutableBloomFilter bloomFilter = _wallet.generateBloomFilter(); _bitcoinNodeManager.setBloomFilter(bloomFilter); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/UnconfirmedTransactionId.java<|end_filename|> package com.softwareverde.bitcoin.transaction; import com.softwareverde.util.type.identifier.Identifier; public class UnconfirmedTransactionId extends Identifier { public static UnconfirmedTransactionId wrap(final Long value) { if (value == null) { return null; } return new UnconfirmedTransactionId(value); } protected UnconfirmedTransactionId(final Long value) { super(value); } } <|start_filename|>stratum/www/js/main.js<|end_filename|> $(document).ready(function() { Api.search = function(parameters, callback) { const defaultParameters = { query: null }; const apiParameters = $.extend({ }, defaultParameters, parameters); const query = apiParameters.query; const searchInput = $("#search"); searchInput.val(query); const queryParams = new URLSearchParams(window.location.search); window.location.assign("//bitcoinverde.org/?search=" + window.encodeURIComponent(query)); }; const searchInput = $("#search"); const loadingImage = $("#search-loading-image"); searchInput.on("focus", function() { searchInput.select(); }); searchInput.on("keyup", function(event) { const value = searchInput.val(); searchInput.css("text-transform", (value.length == 64 ? "uppercase" : "none")); }); searchInput.on("keypress", function(event) { const value = searchInput.val(); if (value.length == 0) { return true; } const key = event.which; if (key != KeyCodes.ENTER) { return true; } loadingImage.css("visibility", "visible"); Api.search({ query: value }); searchInput.blur(); return false; }); Api.getPrototypeBlock({ }, function(data) { loadingImage.css("visibility", "hidden"); const wasSuccess = data.wasSuccess; const errorMessage = data.errorMessage; const object = data.block; if (wasSuccess) { Ui.renderBlock(object); $("#main .block .transaction:first-child").trigger("click"); } else { console.log(errorMessage); } }); Api.getPoolHashRate({ }, function(data) { loadingImage.css("visibility", "hidden"); const wasSuccess = data.wasSuccess; const errorMessage = data.errorMessage; const hashesPerSecond = parseInt(data.hashesPerSecond); const prefixes = ["kilo", "mega", "giga", "tera", "peta", "exa"]; if (wasSuccess) { let prefix = ""; let factor = 1; if (hashesPerSecond < 1000000) { prefix = "kilo"; factor = 1000; } else if (hashesPerSecond < 1000000000) { prefix = "mega"; factor = 1000000; } else if (hashesPerSecond < 1000000000000) { prefix = "giga"; factor = 1000000000; } else if (hashesPerSecond < 1000000000000000) { prefix = "tera"; factor = 1000000000000; } else if (hashesPerSecond < 1000000000000000000) { prefix = "peta"; factor = 1000000000000000; } else { prefix = "exa"; factor = 1000000000000000000; } const hashRateElement = $("#pool-hash-rate"); for (let i = 0; i < prefixes.length; i += 1) { hashRateElement.toggleClass(prefixes[i], false); } hashRateElement.toggleClass(prefix, true); hashRateElement.text((hashesPerSecond / factor).toFixed(2)); } else { console.log(errorMessage); } }); }); <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/pool/ReadUncommittedDatabaseConnectionPoolWrapper.java<|end_filename|> package com.softwareverde.bitcoin.server.database.pool; import com.softwareverde.bitcoin.server.database.ReadUncommittedDatabaseConnectionConfigurer; import com.softwareverde.bitcoin.server.database.ReadUncommittedDatabaseConnectionFactoryWrapper; public class ReadUncommittedDatabaseConnectionPoolWrapper extends ReadUncommittedDatabaseConnectionFactoryWrapper implements DatabaseConnectionPool { public ReadUncommittedDatabaseConnectionPoolWrapper(final DatabaseConnectionPool core) { super(core); } public ReadUncommittedDatabaseConnectionPoolWrapper(final DatabaseConnectionPool core, final ReadUncommittedDatabaseConnectionConfigurer readUncommittedDatabaseConnectionConfigurer) { super(core, readUncommittedDatabaseConnectionConfigurer); } @Override public Integer getInUseConnectionCount() { return ((DatabaseConnectionPool) _core).getInUseConnectionCount(); } @Override public Integer getAliveConnectionCount() { return ((DatabaseConnectionPool) _core).getAliveConnectionCount(); } @Override public Integer getMaxConnectionCount() { return ((DatabaseConnectionPool) _core).getMaxConnectionCount(); } @Override public Integer getCurrentPoolSize() { return ((DatabaseConnectionPool) _core).getCurrentPoolSize(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/fullnode/input/UnconfirmedTransactionInputDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.input; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.query.BatchedInsertQuery; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.TransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.output.UnconfirmedTransactionOutputDatabaseManager; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.input.MutableTransactionInput; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.input.UnconfirmedTransactionInputId; import com.softwareverde.bitcoin.transaction.locktime.ImmutableSequenceNumber; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; import com.softwareverde.bitcoin.transaction.output.UnconfirmedTransactionOutputId; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.script.unlocking.ImmutableUnlockingScript; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.row.Row; import java.util.Map; public class UnconfirmedTransactionInputDatabaseManager { protected final FullNodeDatabaseManager _databaseManager; public UnconfirmedTransactionInputDatabaseManager(final FullNodeDatabaseManager databaseManager) { _databaseManager = databaseManager; } public UnconfirmedTransactionInputId getUnconfirmedTransactionInputId(final TransactionId transactionId, final TransactionInput transactionInput) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id FROM unconfirmed_transaction_inputs WHERE transaction_id = ? AND previous_transaction_hash = ? AND previous_transaction_output_index = ?") .setParameter(transactionId) .setParameter(transactionInput.getPreviousOutputTransactionHash()) .setParameter(transactionInput.getPreviousOutputIndex()) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); return UnconfirmedTransactionInputId.wrap(row.getLong("id")); } public UnconfirmedTransactionInputId insertUnconfirmedTransactionInput(final TransactionId transactionId, final TransactionInput transactionInput) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final Integer index; { final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT COUNT(*) AS `index` FROM unconfirmed_transaction_inputs WHERE transaction_id = ?") .setParameter(transactionId) ); final Row row = rows.get(0); index = row.getInteger("index"); } final Long transactionInputId = databaseConnection.executeSql( new Query("INSERT INTO unconfirmed_transaction_inputs (transaction_id, `index`, previous_transaction_hash, previous_transaction_output_index, sequence_number, unlocking_script) VALUES (?, ?, ?, ?, ?, ?)") .setParameter(transactionId) .setParameter(index) .setParameter(transactionInput.getPreviousOutputTransactionHash()) .setParameter(transactionInput.getPreviousOutputIndex()) .setParameter(transactionInput.getSequenceNumber()) .setParameter(transactionInput.getUnlockingScript().getBytes()) ); return UnconfirmedTransactionInputId.wrap(transactionInputId); } public List<UnconfirmedTransactionInputId> insertUnconfirmedTransactionInputs(final Map<Sha256Hash, TransactionId> transactionIds, final List<Transaction> transactions) throws DatabaseException { final BatchedInsertQuery batchedInsertQuery = new BatchedInsertQuery("INSERT INTO unconfirmed_transaction_inputs (transaction_id, `index`, previous_transaction_hash, previous_transaction_output_index, sequence_number, unlocking_script) VALUES (?, ?, ?, ?, ?, ?)"); for (final Transaction transaction : transactions) { final Sha256Hash transactionHash = transaction.getHash(); final TransactionId transactionId = transactionIds.get(transactionHash); int index = 0; for (final TransactionInput transactionInput : transaction.getTransactionInputs()) { batchedInsertQuery.setParameter(transactionId); batchedInsertQuery.setParameter(index); batchedInsertQuery.setParameter(transactionInput.getPreviousOutputTransactionHash()); batchedInsertQuery.setParameter(transactionInput.getPreviousOutputIndex()); batchedInsertQuery.setParameter(transactionInput.getSequenceNumber()); batchedInsertQuery.setParameter(transactionInput.getUnlockingScript().getBytes()); index += 1; } } final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final Long firstTransactionInputId = databaseConnection.executeSql(batchedInsertQuery); final Integer insertCount = databaseConnection.getRowsAffectedCount(); final MutableList<UnconfirmedTransactionInputId> transactionInputIds = new MutableList<UnconfirmedTransactionInputId>(insertCount); for (int i = 0; i < insertCount; ++i) { final UnconfirmedTransactionInputId transactionInputId = UnconfirmedTransactionInputId.wrap(firstTransactionInputId + i); transactionInputIds.add(transactionInputId); } return transactionInputIds; } public TransactionInput getUnconfirmedTransactionInput(final UnconfirmedTransactionInputId transactionInputId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT * FROM unconfirmed_transaction_inputs WHERE id = ?") .setParameter(transactionInputId) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); final Sha256Hash previousTransactionHash = Sha256Hash.copyOf(row.getBytes("previous_transaction_hash")); final Integer previousTransactionOutputIndex = row.getInteger("previous_transaction_output_index"); final SequenceNumber sequenceNumber = new ImmutableSequenceNumber(row.getLong("sequence_number")); final UnlockingScript unlockingScript = new ImmutableUnlockingScript(MutableByteArray.wrap(row.getBytes("unlocking_script"))); final MutableTransactionInput transactionInput = new MutableTransactionInput(); transactionInput.setPreviousOutputTransactionHash(previousTransactionHash); transactionInput.setPreviousOutputIndex(previousTransactionOutputIndex); transactionInput.setSequenceNumber(sequenceNumber); transactionInput.setUnlockingScript(unlockingScript); return transactionInput; } public UnconfirmedTransactionOutputId getPreviousTransactionOutputId(final UnconfirmedTransactionInputId transactionInputId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id, previous_transaction_hash, previous_transaction_output_index FROM unconfirmed_transaction_inputs WHERE id = ?") .setParameter(transactionInputId) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); final Sha256Hash previousTransactionHash = Sha256Hash.copyOf(row.getBytes("previous_transaction_hash")); final Integer previousTransactionOutputIndex = row.getInteger("previous_transaction_output_index"); final UnconfirmedTransactionOutputDatabaseManager transactionOutputDatabaseManager = _databaseManager.getUnconfirmedTransactionOutputDatabaseManager(); return transactionOutputDatabaseManager.getUnconfirmedTransactionOutputId(new TransactionOutputIdentifier(previousTransactionHash, previousTransactionOutputIndex)); } public List<UnconfirmedTransactionInputId> getUnconfirmedTransactionInputIds(final TransactionId transactionId) throws DatabaseException { final TransactionDatabaseManager transactionDatabaseManager = _databaseManager.getTransactionDatabaseManager(); final Sha256Hash transactionHash = transactionDatabaseManager.getTransactionHash(transactionId); if (transactionHash == null) { return null; } final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id FROM unconfirmed_transaction_inputs WHERE transaction_id = ?") .setParameter(transactionId) ); if (rows.isEmpty()) { return null; } final MutableList<UnconfirmedTransactionInputId> transactionInputIds = new MutableList<UnconfirmedTransactionInputId>(rows.size()); for (final Row row : rows) { final UnconfirmedTransactionInputId transactionInputId = UnconfirmedTransactionInputId.wrap(row.getLong("id")); transactionInputIds.add(transactionInputId); } return transactionInputIds; } public TransactionId getUnconfirmedPreviousTransactionId(final UnconfirmedTransactionInputId transactionInputId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id, previous_transaction_hash FROM unconfirmed_transaction_inputs WHERE id = ?") .setParameter(transactionInputId) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); final Sha256Hash previousTransactionHash = Sha256Hash.copyOf(row.getBytes("previous_transaction_hash")); final TransactionDatabaseManager transactionDatabaseManager = _databaseManager.getTransactionDatabaseManager(); return transactionDatabaseManager.getTransactionId(previousTransactionHash); } public void deleteTransactionInput(final UnconfirmedTransactionInputId transactionInputId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); databaseConnection.executeSql( new Query("DELETE FROM unconfirmed_transaction_inputs WHERE id = ?") .setParameter(transactionInputId) ); } public TransactionId getTransactionId(final UnconfirmedTransactionInputId unconfirmedTransactionInputId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id, transaction_id FROM unconfirmed_transaction_inputs WHERE id = ?") .setParameter(unconfirmedTransactionInputId) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); return TransactionId.wrap(row.getLong("transaction_id")); } public List<UnconfirmedTransactionInputId> getUnconfirmedTransactionInputIdsSpendingTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id FROM unconfirmed_transaction_inputs WHERE previous_transaction_hash = ? AND previous_transaction_output_index = ?") .setParameter(transactionOutputIdentifier.getTransactionHash()) .setParameter(transactionOutputIdentifier.getOutputIndex()) ); final MutableList<UnconfirmedTransactionInputId> unconfirmedTransactionInputIds = new MutableList<UnconfirmedTransactionInputId>(rows.size()); for (final Row row : rows) { final UnconfirmedTransactionInputId unconfirmedTransactionInputId = UnconfirmedTransactionInputId.wrap(row.getLong("id")); unconfirmedTransactionInputIds.add(unconfirmedTransactionInputId); } return unconfirmedTransactionInputIds; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/block/header/MedianBlockTimeDatabaseManagerUtil.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.block.header; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.chain.time.MutableMedianBlockTime; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; public class MedianBlockTimeDatabaseManagerUtil { public static MutableMedianBlockTime calculateMedianBlockTime(final BlockHeaderDatabaseManager blockHeaderDatabaseManager, final BlockId headBlockId) throws DatabaseException { return MedianBlockTimeDatabaseManagerUtil.calculateMedianBlockTime(blockHeaderDatabaseManager, headBlockId, null); } public static MutableMedianBlockTime calculateMedianBlockTime(final BlockHeaderDatabaseManager blockHeaderDatabaseManager, final Sha256Hash headBlockHash) throws DatabaseException { return MedianBlockTimeDatabaseManagerUtil.calculateMedianBlockTime(blockHeaderDatabaseManager, null, headBlockHash); } /** * Initializes a MedianBlockTime from the database. * NOTE: The blockId/blockHash is included within the MedianBlockTime. * To create the MedianTimePast for a block, provide the previousBlockId/previousBlockHash. */ public static MutableMedianBlockTime calculateMedianBlockTime(final BlockHeaderDatabaseManager blockHeaderDatabaseManager, final BlockId nullableBlockId, final Sha256Hash nullableBlockHash) throws DatabaseException { final BlockId firstBlockIdInclusive; final Sha256Hash firstBlockHashInclusive; { if ( (nullableBlockId == null) && (nullableBlockHash == null) ) { return null; } if (nullableBlockId == null) { firstBlockHashInclusive = nullableBlockHash; firstBlockIdInclusive = blockHeaderDatabaseManager.getBlockHeaderId(firstBlockHashInclusive); } else { firstBlockIdInclusive = nullableBlockId; if (nullableBlockHash != null) { firstBlockHashInclusive = nullableBlockHash; } else { firstBlockHashInclusive = blockHeaderDatabaseManager.getBlockHash(firstBlockIdInclusive); } } } final MutableMedianBlockTime medianBlockTime = new MutableMedianBlockTime(); if (firstBlockIdInclusive == null) { return medianBlockTime; } // Special case for the Genesis Block... final MutableList<BlockHeader> blockHeadersInDescendingOrder = new MutableList<BlockHeader>(MedianBlockTime.BLOCK_COUNT); Sha256Hash blockHash = firstBlockHashInclusive; for (int i = 0; i < MedianBlockTime.BLOCK_COUNT; ++i) { final BlockId blockId = (i == 0 ? firstBlockIdInclusive : blockHeaderDatabaseManager.getBlockHeaderId(blockHash)); if (blockId == null) { break; } final BlockHeader blockHeader = blockHeaderDatabaseManager.getBlockHeader(blockId); if (blockHeader == null) { break; } // Should never happen, but facilitates tests. blockHeadersInDescendingOrder.add(blockHeader); blockHash = blockHeader.getPreviousBlockHash(); } // Add the blocks to the MedianBlockTime in ascending order (lowest block-height is added first)... final int blockHeaderCount = blockHeadersInDescendingOrder.getCount(); for (int i = 0; i < blockHeaderCount; ++i) { final BlockHeader blockHeader = blockHeadersInDescendingOrder.get(blockHeaderCount - i - 1); medianBlockTime.addBlock(blockHeader); } return medianBlockTime; } protected MedianBlockTimeDatabaseManagerUtil() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/ChainWorkContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.block.header.difficulty.work.ChainWork; public interface ChainWorkContext { ChainWork getChainWork(Long blockHeight); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/BlockStoreContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.server.module.node.store.BlockStore; public interface BlockStoreContext { BlockStore getBlockStore(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/commit/SlpCommitScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp.commit; import com.softwareverde.bitcoin.merkleroot.MerkleRoot; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.transaction.script.slp.SlpScript; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptType; import com.softwareverde.constable.Constable; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface SlpCommitScript extends SlpScript, Constable<ImmutableSlpCommitScript> { SlpTokenId getTokenId(); Sha256Hash getBlockHash(); Long getBlockHeight(); MerkleRoot getMerkleRoot(); String getMerkleTreeUrl(); @Override ImmutableSlpCommitScript asConst(); } abstract class SlpCommitScriptCore implements SlpCommitScript { protected SlpTokenId _tokenId; protected Sha256Hash _blockHash; protected Long _blockHeight; protected MerkleRoot _merkleRoot; protected String _merkleTreeUrl; public SlpCommitScriptCore() { } public SlpCommitScriptCore(final SlpCommitScript slpCommitScript) { _tokenId = slpCommitScript.getTokenId().asConst(); _blockHash = slpCommitScript.getBlockHash(); _blockHeight = slpCommitScript.getBlockHeight(); _merkleRoot = slpCommitScript.getMerkleRoot(); _merkleTreeUrl = slpCommitScript.getMerkleTreeUrl(); } @Override public SlpScriptType getType() { return SlpScriptType.COMMIT; } @Override public Integer getMinimumTransactionOutputCount() { return 1; // Requires at only the Script Output... } @Override public SlpTokenId getTokenId() { return _tokenId; } @Override public Sha256Hash getBlockHash() { return _blockHash; } @Override public Long getBlockHeight() { return _blockHeight; } @Override public MerkleRoot getMerkleRoot() { return _merkleRoot; } @Override public String getMerkleTreeUrl() { return _merkleTreeUrl; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/header/BlockHeaderWithTransactionCountInflater.java<|end_filename|> package com.softwareverde.bitcoin.block.header; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.constable.bytearray.ByteArray; public class BlockHeaderWithTransactionCountInflater extends BlockHeaderInflater { @Override protected MutableBlockHeaderWithTransactionCount _fromByteArrayReader(final ByteArrayReader byteArrayReader) { final MutableBlockHeader blockHeader = super._fromByteArrayReader(byteArrayReader); final Integer transactionCount = byteArrayReader.readVariableSizedInteger().intValue(); return new MutableBlockHeaderWithTransactionCount(blockHeader, transactionCount); } @Override public MutableBlockHeaderWithTransactionCount fromBytes(final ByteArrayReader byteArrayReader) { return _fromByteArrayReader(byteArrayReader); } @Override public MutableBlockHeaderWithTransactionCount fromBytes(final ByteArray byteArray) { final ByteArrayReader byteArrayReader = new ByteArrayReader(byteArray.getBytes()); return _fromByteArrayReader(byteArrayReader); } @Override public MutableBlockHeaderWithTransactionCount fromBytes(final byte[] bytes) { final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); return _fromByteArrayReader(byteArrayReader); } } <|start_filename|>src/main/java/com/softwareverde/network/socket/Socket.java<|end_filename|> package com.softwareverde.network.socket; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.logging.Logger; import com.softwareverde.network.ip.Ip; import com.softwareverde.network.p2p.message.ProtocolMessage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.util.concurrent.ConcurrentLinkedQueue; public abstract class Socket { private static final Object _nextIdMutex = new Object(); private static Long _nextId = 0L; protected interface ReadThread { interface Callback { void onNewMessage(ProtocolMessage protocolMessage); void onExit(); } void setInputStream(InputStream inputStream); void setCallback(Callback callback); void interrupt(); void join() throws InterruptedException; void join(long timeout) throws InterruptedException; void start(); Long getTotalBytesReceived(); } protected final Long _id; protected final java.net.Socket _socket; protected final ConcurrentLinkedQueue<ProtocolMessage> _messages = new ConcurrentLinkedQueue<ProtocolMessage>(); protected Boolean _isClosed = false; protected Runnable _messageReceivedCallback; protected Runnable _socketClosedCallback; protected Boolean _isListening = false; protected final ReadThread _readThread; protected Long _totalBytesSent = 0L; protected String _cachedHost = null; protected final OutputStream _rawOutputStream; protected final InputStream _rawInputStream; protected final ThreadPool _threadPool; protected final Object _rawOutputStreamWriteMutex = new Object(); protected String _getHost() { if (_cachedHost == null) { Logger.info("INFO: Performing ip lookup for: " + _socket.getRemoteSocketAddress()); final InetAddress inetAddress = _socket.getInetAddress(); _cachedHost = (inetAddress != null ? inetAddress.getHostName() : null); } return _cachedHost; } protected Integer _getPort() { return _socket.getPort(); } /** * Internal callback that is executed when a message is received by the client. * Is executed before any external callbacks are received. * Intended for subclass extension. */ protected void _onMessageReceived(final ProtocolMessage message) { final Runnable messageReceivedCallback = _messageReceivedCallback; if (messageReceivedCallback != null) { _threadPool.execute(messageReceivedCallback); } } /** * Internal callback that is executed when the connection is closed by either the client or server, * or if the connection is terminated. * Intended for subclass extension. */ protected void _onSocketClosed() { // Nothing. } protected void _closeSocket() { Logger.debug("Closing socket. Thread Id: " + Thread.currentThread().getId() + " " + _socket.getRemoteSocketAddress()); final Boolean wasClosed = _isClosed; _isClosed = true; _readThread.interrupt(); try { _rawInputStream.close(); } catch (final Exception exception) { } try { _rawOutputStream.close(); } catch (final Exception exception) { } try { _readThread.join(5000L); } catch (final Exception exception) { } try { _socket.close(); } catch (final Exception exception) { } final Runnable onCloseCallback = _socketClosedCallback; _socketClosedCallback = null; if (onCloseCallback != null) { _threadPool.execute(onCloseCallback); } if (! wasClosed) { _onSocketClosed(); } } protected Socket(final java.net.Socket socket, final ReadThread readThread, final ThreadPool threadPool) { synchronized (_nextIdMutex) { _id = _nextId; _nextId += 1; } _socket = socket; InputStream inputStream = null; OutputStream outputStream = null; { // Initialize the input and output streams... try { outputStream = socket.getOutputStream(); inputStream = socket.getInputStream(); } catch (final IOException exception) { } } _rawOutputStream = outputStream; _rawInputStream = inputStream; _readThread = readThread; _readThread.setInputStream(_rawInputStream); _readThread.setCallback(new ReadThread.Callback() { @Override public void onNewMessage(final ProtocolMessage message) { _messages.offer(message); _onMessageReceived(message); } @Override public void onExit() { if (! _isClosed) { _closeSocket(); } } }); _threadPool = threadPool; } public synchronized void beginListening() { if (_isListening) { return; } _isListening = true; _readThread.start(); } public void setMessageReceivedCallback(final Runnable callback) { _messageReceivedCallback = callback; } public void setOnClosedCallback(final Runnable callback) { _socketClosedCallback = callback; } public Boolean write(final ProtocolMessage outboundMessage) { final ByteArray bytes = outboundMessage.getBytes(); _totalBytesSent += bytes.getByteCount(); try { synchronized (_rawOutputStreamWriteMutex) { _rawOutputStream.write(bytes.getBytes()); _rawOutputStream.flush(); return true; } } catch (final Exception exception) { Logger.debug(exception); _closeSocket(); } return false; } /** * Retrieves the oldest message from the inbound queue and returns it. * Returns null if there are no pending messages. */ public ProtocolMessage popMessage() { return _messages.poll(); } /** * Attempts to return the DNS lookup of the connection or null if the lookup fails. */ public String getHost() { return _getHost(); } public Ip getIp() { return Ip.fromSocket(_socket); } public Integer getPort() { return _getPort(); } /** * Ceases all reads, and closes the socket. * Invoking any write functions after this call throws a runtime exception. */ public void close() { _closeSocket(); } /** * Returns false if this instance has had its close() function invoked or the socket is no longer connected. */ public Boolean isConnected() { return ( (! _isClosed) && (! _socket.isClosed()) ); } public Long getTotalBytesSentCount() { return _totalBytesSent; } public Long getTotalBytesReceivedCount() { return _readThread.getTotalBytesReceived(); } @Override public int hashCode() { return (BinarySocket.class.getSimpleName().hashCode() + _id.hashCode()); } @Override public boolean equals(final Object object) { if (object == null) { return false; } if (! (object instanceof BinarySocket)) { return false; } final BinarySocket socketConnectionObject = (BinarySocket) object; return _id.equals(socketConnectionObject._id); } @Override public String toString() { return (Ip.fromSocket(_socket) + ":" + _getPort()); } } <|start_filename|>src/test/java/com/softwareverde/bloomfilter/MutableBloomFilterTests.java<|end_filename|> package com.softwareverde.bloomfilter; import com.softwareverde.async.lock.IndexLock; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.util.timer.MilliTimer; import org.junit.Assert; import org.junit.Test; public class MutableBloomFilterTests { protected static boolean isLocked(final IndexLock indexLock, final int index) { final MilliTimer milliTimer = new MilliTimer(); milliTimer.start(); try { indexLock.lock(index); } finally { indexLock.unlock(index); } milliTimer.stop(); return (milliTimer.getMillisecondsElapsed() > 5); } @Test public void should_release_all_locks_after_clear() throws Exception { // Setup final MutableBloomFilter mutableBloomFilter = new MutableBloomFilter(new MutableByteArray(512), 1, 0L); final int indexLockCount = mutableBloomFilter._indexLockSegmentCount; final IndexLock indexLock = mutableBloomFilter._indexLock; for (int i = 0; i < indexLockCount; ++i) { Assert.assertFalse(MutableBloomFilterTests.isLocked(indexLock, i)); } // Action final Thread thread = (new Thread(new Runnable() { @Override public void run() { mutableBloomFilter.clear(); } })); thread.start(); thread.join(5000L); // Assert for (int i = 0; i < indexLockCount; ++i) { Assert.assertFalse(MutableBloomFilterTests.isLocked(indexLock, i)); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/ScriptDeflater.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.opcode.Operation; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.json.Json; import com.softwareverde.util.bytearray.ByteArrayBuilder; public class ScriptDeflater { public MutableByteArray toBytes(final Script script) { final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); for (final Operation operation : script.getOperations()) { byteArrayBuilder.appendBytes(operation.getBytes()); } return MutableByteArray.wrap(byteArrayBuilder.build()); } public String toString(final Script script) { final List<Operation> scriptOperations = script.getOperations(); if (scriptOperations == null) { return null; } final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < scriptOperations.getCount(); ++i) { final Operation operation = scriptOperations.get(i); stringBuilder.append("("); stringBuilder.append(operation.toString()); stringBuilder.append(")"); if (i + 1 < scriptOperations.getCount()) { stringBuilder.append(" "); } } return stringBuilder.toString(); } /** * Serializes the script in a format the is commonly used by other applications. * This format is a more terse version of ScriptDeflater.toString(); Operations are merely their hex opcodes. */ public String toStandardString(final Script script) { final List<Operation> scriptOperations = script.getOperations(); if (scriptOperations == null) { return null; } final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < scriptOperations.getCount(); ++i) { final Operation operation = scriptOperations.get(i); stringBuilder.append(operation.toStandardString()); if (i + 1 < scriptOperations.getCount()) { stringBuilder.append(" "); } } return stringBuilder.toString(); } public Json toJson(final Script script) { final ByteArray scriptByteArray = script.getBytes(); final Json json = new Json(); json.put("bytes", scriptByteArray); final ScriptType scriptType; { if (script instanceof LockingScript) { final ScriptPatternMatcher scriptPatternMatcher = new ScriptPatternMatcher(); scriptType = scriptPatternMatcher.getScriptType((LockingScript) script); } else { scriptType = ScriptType.CUSTOM_SCRIPT; } } json.put("scriptType", scriptType); final Json operationsJson; final List<Operation> operations = script.getOperations(); if (operations != null) { operationsJson = new Json(); for (final Operation operation : operations) { operationsJson.add(operation); } } else { operationsJson = null; } json.put("operations", operationsJson); return json; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/wallet/slp/ImmutableSlpToken.java<|end_filename|> package com.softwareverde.bitcoin.wallet.slp; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.wallet.utxo.ImmutableSpendableTransactionOutput; import com.softwareverde.bitcoin.wallet.utxo.SpendableTransactionOutput; public class ImmutableSlpToken extends ImmutableSpendableTransactionOutput implements SlpToken { protected final SlpTokenId _tokenId; protected final Long _tokenAmount; protected final Boolean _isBatonHolder; public ImmutableSlpToken(final SlpTokenId tokenId, final Long tokenAmount, final SpendableTransactionOutput spendableTransactionOutput) { super(spendableTransactionOutput); _tokenId = tokenId; _tokenAmount = tokenAmount; _isBatonHolder = false; } public ImmutableSlpToken(final SlpTokenId tokenId, final Long tokenAmount, final SpendableTransactionOutput spendableTransactionOutput, final Boolean isBatonHolder) { super(spendableTransactionOutput); _tokenId = tokenId; _tokenAmount = tokenAmount; _isBatonHolder = isBatonHolder; } @Override public SlpTokenId getTokenId() { return _tokenId; } @Override public Long getTokenAmount() { return _tokenAmount; } @Override public Boolean isBatonHolder() { return _isBatonHolder; } @Override public ImmutableSlpToken asConst() { return this; } } <|start_filename|>explorer/www/css/toggle.css<|end_filename|> .toggle { display: inline-block; margin: 0.5em; vertical-align: middle; } .toggle > label { color: #CCCCCC; font-size: 0.5em; display: inline-block; margin-right: 4em; } .toggle > .toggle-bar { height: 1em; border-radius: 1em; width: 2.5em; background-color: #19B325; display: inline-block; text-align: left; } .toggle.off > .toggle-bar { background-color: #7B7B7B; text-align: right; } .toggle > .toggle-bar > .toggle-knob { display: inline-block; background-color: #FFFFFF; height: calc(1em - 2px); width: calc(1em - 2px); margin-top: 1px; margin-left: 2px; margin-right: 2px; box-sizing: border-box; border-radius: 1em; } .toggle > .toggle-label { color: #FFFFFF; font-size: 0.75em; } .toggle:not(.off) > .toggle-label > *:nth-child(2) { display: none; } .toggle.off > .toggle-label > *:nth-child(1) { display: none; } <|start_filename|>src/main/java/com/softwareverde/bitcoin/slp/validator/SlpTransactionValidator.java<|end_filename|> package com.softwareverde.bitcoin.slp.validator; import com.softwareverde.bitcoin.constable.util.ConstUtil; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.slp.SlpScript; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptInflater; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptType; import com.softwareverde.bitcoin.transaction.script.slp.commit.SlpCommitScript; import com.softwareverde.bitcoin.transaction.script.slp.genesis.SlpGenesisScript; import com.softwareverde.bitcoin.transaction.script.slp.mint.SlpMintScript; import com.softwareverde.bitcoin.transaction.script.slp.send.SlpSendScript; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import com.softwareverde.util.Util; import java.util.HashMap; import java.util.Map; public class SlpTransactionValidator { protected final Integer _maxRecursionDepth = 1024; protected final SlpTransactionValidationCache _validationCache; protected final TransactionAccumulator _transactionAccumulator; protected Boolean _allowUnconfirmedTransactions = true; protected SlpScript _getSlpScript(final Transaction transaction) { final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final TransactionOutput transactionOutput = transactionOutputs.get(0); final LockingScript slpLockingScript = transactionOutput.getLockingScript(); final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); return slpScriptInflater.fromLockingScript(slpLockingScript); } protected Map<Sha256Hash, Transaction> _getTransactions(final List<TransactionInput> transactionInputs, final Boolean allowUnconfirmedTransactions) { final ImmutableListBuilder<Sha256Hash> transactionHashes = new ImmutableListBuilder<Sha256Hash>(transactionInputs.getCount()); for (final TransactionInput transactionInput : transactionInputs) { final Sha256Hash transactionHash = transactionInput.getPreviousOutputTransactionHash(); transactionHashes.add(transactionHash); } return _transactionAccumulator.getTransactions(transactionHashes.build(), allowUnconfirmedTransactions); } protected Boolean _validateRecursiveTransactions(final Map<SlpScriptType, ? extends List<Transaction>> recursiveTransactionsToValidate, final Integer recursionDepth) { if (recursionDepth >= _maxRecursionDepth) { if (Logger.isDebugEnabled()) { Logger.debug("Max SLP validation recursion depth reached. (" + recursionDepth + ")"); for (final SlpScriptType slpScriptType : recursiveTransactionsToValidate.keySet()) { for (final Transaction transaction : recursiveTransactionsToValidate.get(slpScriptType)) { Logger.debug(slpScriptType + " " + transaction.getHash() + " assumed valid."); } } } return true; } for (final SlpScriptType slpScriptType : recursiveTransactionsToValidate.keySet()) { final List<Transaction> transactions = recursiveTransactionsToValidate.get(slpScriptType); switch (slpScriptType) { case GENESIS: { for (final Transaction transaction : transactions) { final Boolean isCachedAsValid = _validationCache.isValid(transaction.getHash()); if (isCachedAsValid != null) { if (isCachedAsValid) { continue; } else { return false; } } final Boolean isValid = _validateSlpGenesisTransaction(transaction); if (! isValid) { return false; } } } break; case MINT: { for (final Transaction transaction : transactions) { final Boolean isCachedAsValid = _validationCache.isValid(transaction.getHash()); if (isCachedAsValid != null) { if (isCachedAsValid) { continue; } else { return false; } } final Boolean isValid = _validateSlpMintTransaction(transaction, null, (recursionDepth + 1)); if (! isValid) { return false; } } } break; case SEND: { for (final Transaction transaction : transactions) { final Boolean isCachedAsValid = _validationCache.isValid(transaction.getHash()); if (isCachedAsValid != null) { if (isCachedAsValid) { continue; } else { return false; } } final Boolean isValid = _validateSlpSendTransaction(transaction, null, (recursionDepth + 1)); if (! isValid) { return false; } } } break; case COMMIT: { for (final Transaction transaction : transactions) { final Boolean isCachedAsValid = _validationCache.isValid(transaction.getHash()); if (isCachedAsValid != null) { if (isCachedAsValid) { continue; } else { return false; } } final Boolean isValid = _validateSlpCommitTransaction(transaction); if (! isValid) { return false; } } } break; } } return true; } protected Boolean _validateSlpGenesisScript(final SlpGenesisScript slpGenesisScript) { return (slpGenesisScript != null); } protected Boolean _validateSlpGenesisTransaction(final Transaction transaction) { final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final TransactionOutput transactionOutput = transactionOutputs.get(0); final LockingScript slpLockingScript = transactionOutput.getLockingScript(); if (! SlpScriptInflater.matchesSlpFormat(slpLockingScript)) { return null; } final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); final SlpScript slpScript = slpScriptInflater.fromLockingScript(slpLockingScript); if (slpScript == null) { return false; } return (slpScript instanceof SlpGenesisScript); } protected Boolean _validateSlpCommitScript(final SlpCommitScript slpCommitScript) { return (slpCommitScript != null); } protected Boolean _validateSlpCommitTransaction(final Transaction transaction) { final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final TransactionOutput transactionOutput = transactionOutputs.get(0); final LockingScript slpLockingScript = transactionOutput.getLockingScript(); if (! SlpScriptInflater.matchesSlpFormat(slpLockingScript)) { return null; } final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); final SlpScript slpScript = slpScriptInflater.fromLockingScript(slpLockingScript); if (slpScript == null) { return false; } return (slpScript instanceof SlpCommitScript); } protected Boolean _validateSlpMintTransaction(final Transaction transaction, final SlpMintScript nullableSlpMintScript, final Integer recursionDepth) { final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); final SlpMintScript slpMintScript = ((nullableSlpMintScript != null) ? nullableSlpMintScript : ((SlpMintScript) _getSlpScript(transaction))); final SlpTokenId slpTokenId = slpMintScript.getTokenId(); final Map<Sha256Hash, Transaction> previousTransactions = _getTransactions(transactionInputs, _allowUnconfirmedTransactions); if (previousTransactions == null) { return false; } final HashMap<SlpScriptType, MutableList<Transaction>> recursiveTransactionsToValidate = new HashMap<SlpScriptType, MutableList<Transaction>>(); boolean hasBaton = false; for (final TransactionInput transactionInput : transactionInputs) { final Integer previousTransactionOutputIndex = transactionInput.getPreviousOutputIndex(); final Sha256Hash previousTransactionHash = transactionInput.getPreviousOutputTransactionHash(); final Transaction previousTransaction = previousTransactions.get(previousTransactionHash); if (previousTransaction == null) { Logger.debug("Could not find previous Transaction: " + previousTransactionHash); return false; } final SlpScript previousTransactionSlpScript = _getSlpScript(previousTransaction); final boolean isSlpTransaction = (previousTransactionSlpScript != null); if (! isSlpTransaction) { continue; } final SlpScriptType slpScriptType = previousTransactionSlpScript.getType(); if (slpScriptType == SlpScriptType.GENESIS) { if (! Util.areEqual(slpTokenId, SlpTokenId.wrap(previousTransactionHash))) { continue; } final SlpGenesisScript slpGenesisScript = (SlpGenesisScript) previousTransactionSlpScript; if (Util.areEqual(previousTransactionOutputIndex, slpGenesisScript.getBatonOutputIndex())) { hasBaton = true; ConstUtil.addToListMap(SlpScriptType.GENESIS, previousTransaction, recursiveTransactionsToValidate); break; } } else if (slpScriptType == SlpScriptType.MINT) { final SlpMintScript previousSlpMintScript = (SlpMintScript) previousTransactionSlpScript; if (! Util.areEqual(slpTokenId, previousSlpMintScript.getTokenId())) { continue; } if (Util.areEqual(previousTransactionOutputIndex, previousSlpMintScript.getBatonOutputIndex())) { hasBaton = true; ConstUtil.addToListMap(SlpScriptType.MINT, previousTransaction, recursiveTransactionsToValidate); break; } } else if (slpScriptType == SlpScriptType.SEND) { // Nothing. } else if (slpScriptType == SlpScriptType.COMMIT) { // Nothing. } } if (! hasBaton) { return false; } return _validateRecursiveTransactions(recursiveTransactionsToValidate, recursionDepth); } protected Boolean _validateSlpSendTransaction(final Transaction transaction, final SlpSendScript nullableSlpSendScript, final Integer recursionDepth) { final List<TransactionInput> transactionInputs = transaction.getTransactionInputs(); final SlpSendScript slpSendScript = ((nullableSlpSendScript != null) ? nullableSlpSendScript : ((SlpSendScript) _getSlpScript(transaction))); final SlpTokenId slpTokenId = slpSendScript.getTokenId(); final Long totalSendAmount = slpSendScript.getTotalAmount(); final Map<Sha256Hash, Transaction> previousTransactions = _getTransactions(transactionInputs, _allowUnconfirmedTransactions); if (previousTransactions == null) { return false; } long totalSlpAmountReceived = 0L; for (final TransactionInput transactionInput : transactionInputs) { final Integer previousTransactionOutputIndex = transactionInput.getPreviousOutputIndex(); final Sha256Hash previousTransactionHash = transactionInput.getPreviousOutputTransactionHash(); final Transaction previousTransaction = previousTransactions.get(previousTransactionHash); if (previousTransaction == null) { Logger.debug("Could not find previous Transaction: " + previousTransactionHash); return false; } final SlpScript previousTransactionSlpScript = _getSlpScript(previousTransaction); final boolean isSlpTransaction = (previousTransactionSlpScript != null); if (! isSlpTransaction) { continue; } final SlpScriptType slpScriptType = previousTransactionSlpScript.getType(); if (slpScriptType == SlpScriptType.GENESIS) { if (! Util.areEqual(slpTokenId, SlpTokenId.wrap(previousTransactionHash))) { continue; } final SlpGenesisScript slpGenesisScript = (SlpGenesisScript) previousTransactionSlpScript; if (Util.areEqual(previousTransactionOutputIndex, SlpGenesisScript.RECEIVER_TRANSACTION_OUTPUT_INDEX)) { final Boolean isValid; { final HashMap<SlpScriptType, MutableList<Transaction>> recursiveTransactionsToValidate = new HashMap<SlpScriptType, MutableList<Transaction>>(); ConstUtil.addToListMap(SlpScriptType.GENESIS, previousTransaction, recursiveTransactionsToValidate); isValid = _validateRecursiveTransactions(recursiveTransactionsToValidate, (recursionDepth + 1)); recursiveTransactionsToValidate.clear(); } if (isValid) { totalSlpAmountReceived += slpGenesisScript.getTokenCount(); } } } else if (slpScriptType == SlpScriptType.MINT) { final SlpMintScript slpMintScript = (SlpMintScript) previousTransactionSlpScript; if (! Util.areEqual(slpTokenId, slpMintScript.getTokenId())) { continue; } if (Util.areEqual(previousTransactionOutputIndex, SlpMintScript.RECEIVER_TRANSACTION_OUTPUT_INDEX)) { final Boolean isValid; { final HashMap<SlpScriptType, MutableList<Transaction>> recursiveTransactionsToValidate = new HashMap<SlpScriptType, MutableList<Transaction>>(); ConstUtil.addToListMap(SlpScriptType.MINT, previousTransaction, recursiveTransactionsToValidate); isValid = _validateRecursiveTransactions(recursiveTransactionsToValidate, (recursionDepth + 1)); recursiveTransactionsToValidate.clear(); } if (isValid) { totalSlpAmountReceived += slpMintScript.getTokenCount(); } } } else if (slpScriptType == SlpScriptType.SEND) { final SlpSendScript previousTransactionSlpSendScript = (SlpSendScript) previousTransactionSlpScript; if (! Util.areEqual(slpTokenId, previousTransactionSlpSendScript.getTokenId())) { continue; } final Boolean isValid; { final HashMap<SlpScriptType, MutableList<Transaction>> recursiveTransactionsToValidate = new HashMap<SlpScriptType, MutableList<Transaction>>(); ConstUtil.addToListMap(SlpScriptType.SEND, previousTransaction, recursiveTransactionsToValidate); isValid = _validateRecursiveTransactions(recursiveTransactionsToValidate, (recursionDepth + 1)); recursiveTransactionsToValidate.clear(); } if (isValid) { totalSlpAmountReceived += Util.coalesce(previousTransactionSlpSendScript.getAmount(previousTransactionOutputIndex)); } } else if (slpScriptType == SlpScriptType.COMMIT) { // Nothing. } } final boolean isValid = (totalSlpAmountReceived >= totalSendAmount); _validationCache.setIsValid(transaction.getHash(), isValid); return isValid; } public SlpTransactionValidator(final TransactionAccumulator transactionAccumulator) { _transactionAccumulator = transactionAccumulator; _validationCache = new HashMapSlpTransactionValidationCache(); } public SlpTransactionValidator(final TransactionAccumulator transactionAccumulator, final SlpTransactionValidationCache validationCache) { _transactionAccumulator = transactionAccumulator; _validationCache = (validationCache != null ? validationCache : new HashMapSlpTransactionValidationCache()); } public Boolean validateTransaction(final Transaction transaction) { final Boolean isCachedAsValid = _validationCache.isValid(transaction.getHash()); if (isCachedAsValid != null) { return isCachedAsValid; } final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final TransactionOutput transactionOutput = transactionOutputs.get(0); final LockingScript slpLockingScript = transactionOutput.getLockingScript(); if (! SlpScriptInflater.matchesSlpFormat(slpLockingScript)) { return null; } final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); final SlpScript slpScript = slpScriptInflater.fromLockingScript(slpLockingScript); if (slpScript == null) { return false; } switch (slpScript.getType()) { case GENESIS: { final SlpGenesisScript slpGenesisScript = (SlpGenesisScript) slpScript; return _validateSlpGenesisScript(slpGenesisScript); } case MINT: { final SlpMintScript slpMintScript = (SlpMintScript) slpScript; return _validateSlpMintTransaction(transaction, slpMintScript, 0); } case COMMIT: { final SlpCommitScript slpCommitScript = (SlpCommitScript) slpScript; return _validateSlpCommitScript(slpCommitScript); } case SEND: { final SlpSendScript slpSendScript = (SlpSendScript) slpScript; return _validateSlpSendTransaction(transaction, slpSendScript, 0); } default: { return false; } } } public void setAllowUnconfirmedTransactions(final Boolean allowUnconfirmedTransactions) { _allowUnconfirmedTransactions = allowUnconfirmedTransactions; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/address/QueryAddressBlocksMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.address; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.inflater.AddressInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.util.bytearray.Endian; public class QueryAddressBlocksMessageInflater extends BitcoinProtocolMessageInflater { protected final AddressInflaters _addressInflaters; public QueryAddressBlocksMessageInflater(final AddressInflaters addressInflaters) { _addressInflaters = addressInflaters; } @Override public QueryAddressBlocksMessage fromBytes(final byte[] bytes) { final QueryAddressBlocksMessage queryAddressBlocksMessage = new QueryAddressBlocksMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.QUERY_ADDRESS_BLOCKS); if (protocolMessageHeader == null) { return null; } final int addressCount = byteArrayReader.readVariableSizedInteger().intValue(); if ( (addressCount < 0) || (addressCount >= QueryAddressBlocksMessage.MAX_ADDRESS_COUNT) ) { return null; } final Integer bytesRequired = (Address.BYTE_COUNT * addressCount); if (byteArrayReader.remainingByteCount() < bytesRequired) { return null; } for (int i = 0; i < addressCount; ++i) { final AddressInflater addressInflater = _addressInflaters.getAddressInflater(); final Address address = addressInflater.fromBytes(MutableByteArray.wrap(byteArrayReader.readBytes(Address.BYTE_COUNT, Endian.LITTLE))); if (address == null) { return null; } queryAddressBlocksMessage._addresses.add(address); } if (byteArrayReader.didOverflow()) { return null; } return queryAddressBlocksMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/header/BlockHeaderWithTransactionCount.java<|end_filename|> package com.softwareverde.bitcoin.block.header; import com.softwareverde.json.Json; import com.softwareverde.util.Util; public interface BlockHeaderWithTransactionCount extends BlockHeader { Integer getTransactionCount(); } class BlockHeaderWithTransactionCountCore { public static void toJson(final Json json, final Integer transactionCount) { json.put("transactionCount", transactionCount); } public static boolean equals(final BlockHeaderWithTransactionCount blockHeaderWithTransactionCount, final Object object) { if (! (object instanceof BlockHeaderWithTransactionCount)) { return false; } final BlockHeaderWithTransactionCount blockHeaderWithTransactionCountObject = ((BlockHeaderWithTransactionCount) object); return (Util.areEqual(blockHeaderWithTransactionCount.getTransactionCount(), blockHeaderWithTransactionCountObject.getTransactionCount())); } } <|start_filename|>www-shared/js/cookie.js<|end_filename|> window.Cookies = { }; window.Cookies.set = function(key, value) { let date = new Date(); date.setFullYear(date.getFullYear() + 1); document.cookie = key + "=" + value + "; expires=" + date.toUTCString() + "; samesite=strict; path=/"; }; window.Cookies.get = function(key) { const value = ("; " + document.cookie); const parts = value.split("; " + key + "="); if (parts.length == 2) { return parts.pop().split(";").shift(); } return null; }; <|start_filename|>src/main/java/com/softwareverde/bitcoin/inflater/AddressInflaters.java<|end_filename|> package com.softwareverde.bitcoin.inflater; import com.softwareverde.bitcoin.address.AddressInflater; public interface AddressInflaters extends Inflater { AddressInflater getAddressInflater(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/output/identifier/TransactionOutputIdentifier.java<|end_filename|> package com.softwareverde.bitcoin.transaction.output.identifier; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.constable.Const; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.Util; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class TransactionOutputIdentifier implements Const, Comparable<TransactionOutputIdentifier> { public static final TransactionOutputIdentifier COINBASE = new TransactionOutputIdentifier(Sha256Hash.EMPTY_HASH, -1); public static TransactionOutputIdentifier fromTransactionInput(final TransactionInput transactionInput) { return new TransactionOutputIdentifier(transactionInput.getPreviousOutputTransactionHash(), transactionInput.getPreviousOutputIndex()); } public static MutableList<TransactionOutputIdentifier> fromTransactionOutputs(final Transaction transaction) { final Sha256Hash transactionHash = transaction.getHash(); final Sha256Hash constTransactionHash = transactionHash.asConst(); final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final int outputCount = transactionOutputs.getCount(); final MutableList<TransactionOutputIdentifier> transactionOutputIdentifiers = new MutableList<TransactionOutputIdentifier>(outputCount); for (int outputIndex = 0; outputIndex < outputCount; ++outputIndex) { final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(constTransactionHash, outputIndex); transactionOutputIdentifiers.add(transactionOutputIdentifier); } return transactionOutputIdentifiers; } protected final Sha256Hash _transactionHash; protected final Integer _outputIndex; public TransactionOutputIdentifier(final Sha256Hash transactionHash, final Integer outputIndex) { _transactionHash = transactionHash.asConst(); _outputIndex = outputIndex; } public Sha256Hash getTransactionHash() { return _transactionHash; } public Integer getOutputIndex() { return _outputIndex; } @Override public boolean equals(final Object object) { if (object == this) { return true; } if (! (object instanceof TransactionOutputIdentifier)) { return false; } final TransactionOutputIdentifier transactionOutputIdentifier = (TransactionOutputIdentifier) object; if (! Util.areEqual(_transactionHash, transactionOutputIdentifier._transactionHash)) { return false; } if (! Util.areEqual(_outputIndex, transactionOutputIdentifier._outputIndex)) { return false; } return true; } @Override public int hashCode() { return (_transactionHash.hashCode() + _outputIndex.hashCode()); } @Override public String toString() { return (_transactionHash + ":" + _outputIndex); } /** * Serializes the TransactionOutputIdentifier as (TransactionHash | OutputIndex), as LittleEndian. The reference client refers to this as a COutPoint. */ public ByteArray toBytes() { final ByteArrayBuilder cOutPointBuilder = new ByteArrayBuilder(); cOutPointBuilder.appendBytes(_transactionHash.getBytes(), Endian.LITTLE); cOutPointBuilder.appendBytes(ByteUtil.integerToBytes(_outputIndex), Endian.LITTLE); return MutableByteArray.wrap(cOutPointBuilder.build()); } @Override public int compareTo(final TransactionOutputIdentifier transactionOutputIdentifier) { final int hashComparison = _transactionHash.compareTo(transactionOutputIdentifier.getTransactionHash()); if (hashComparison != 0) { return hashComparison; } return _outputIndex.compareTo(transactionOutputIdentifier.getOutputIndex()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/node/RequestId.java<|end_filename|> package com.softwareverde.bitcoin.server.node; import com.softwareverde.util.type.identifier.Identifier; public class RequestId extends Identifier { public static RequestId wrap(final Long value) { if (value == null) { return null; } return new RequestId(value); } protected RequestId(final Long value) { super(value); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/VolatileNetworkTimeWrapper.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.network.time.ImmutableNetworkTime; import com.softwareverde.network.time.NetworkTime; import com.softwareverde.network.time.VolatileNetworkTime; public class VolatileNetworkTimeWrapper implements VolatileNetworkTime { public static VolatileNetworkTimeWrapper wrap(final NetworkTime networkTime) { if (networkTime instanceof VolatileNetworkTimeWrapper) { return (VolatileNetworkTimeWrapper) networkTime; } return new VolatileNetworkTimeWrapper(networkTime); } protected final NetworkTime _networkTime; public VolatileNetworkTimeWrapper(final NetworkTime networkTime) { _networkTime = networkTime; } @Override public ImmutableNetworkTime asConst() { return _networkTime.asConst(); } @Override public Long getCurrentTimeInSeconds() { return _networkTime.getCurrentTimeInSeconds(); } @Override public Long getCurrentTimeInMilliSeconds() { return _networkTime.getCurrentTimeInMilliSeconds(); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/TestBlockDataStratumMiner.java<|end_filename|> package com.softwareverde.bitcoin.test; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.BlockHeaderDeflater; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.server.configuration.Configuration; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.main.BitcoinConstants; import com.softwareverde.bitcoin.server.stratum.message.RequestMessage; import com.softwareverde.bitcoin.server.stratum.message.ResponseMessage; import com.softwareverde.bitcoin.server.stratum.message.server.MinerSubmitBlockResult; import com.softwareverde.bitcoin.server.stratum.socket.StratumServerSocket; import com.softwareverde.bitcoin.server.stratum.task.StratumMineBlockTask; import com.softwareverde.bitcoin.server.stratum.task.StratumMineBlockTaskBuilderCore; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.TransactionWithFee; import com.softwareverde.bitcoin.util.BitcoinUtil; import com.softwareverde.concurrent.pool.MainThreadPool; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.json.Json; import com.softwareverde.logging.Logger; import com.softwareverde.network.socket.JsonProtocolMessage; import com.softwareverde.network.socket.JsonSocket; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.HexUtil; import java.io.File; /** * Generates TestBlock Data via Stratum. * NOTE: Stratum Mining always modifies the coinbase's ExtraNonce, which may be undesirable. */ public class TestBlockDataStratumMiner { // @Test public void run() { final String coinbaseMessage = BitcoinConstants.getCoinbaseMessage(); final TransactionInflater transactionInflater = new TransactionInflater(); final AddressInflater addressInflater = new AddressInflater(); final PrivateKey coinbasePrivateKey = PrivateKey.createNewKey(); Logger.info("Private Key: " + coinbasePrivateKey); Logger.info("Address: " + addressInflater.fromPrivateKey(coinbasePrivateKey, false).toBase58CheckEncoded()); final Address address = addressInflater.fromPrivateKey(coinbasePrivateKey, false); final Long blockHeight = 1L; // ??? final Sha256Hash previousBlockHash = BlockHeader.GENESIS_BLOCK_HASH; // ??? final Difficulty difficulty = Difficulty.BASE_DIFFICULTY; final Transaction coinbaseTransaction = transactionInflater.createCoinbaseTransactionWithExtraNonce(blockHeight, coinbaseMessage, StratumMiner.totalExtraNonceByteCount, address, BlockHeader.calculateBlockReward(blockHeight)); final MutableList<Transaction> transactions = new MutableList<Transaction>(); // { // final PrivateKey prevoutPrivateKey = ???; // // final MutableTransaction transaction = new MutableTransaction(); // transaction.setVersion(Transaction.VERSION); // transaction.setLockTime(LockTime.MIN_TIMESTAMP); // final TransactionOutput outputBeingSpent; // { // final Transaction transactionToSpend = ???; // outputBeingSpent = ???; // // final MutableTransactionInput transactionInput = new MutableTransactionInput(); // transactionInput.setPreviousOutputTransactionHash(transactionToSpend.getHash()); // transactionInput.setPreviousOutputIndex(0); // transactionInput.setSequenceNumber(SequenceNumber.MAX_SEQUENCE_NUMBER); // transactionInput.setUnlockingScript(UnlockingScript.EMPTY_SCRIPT); // transaction.addTransactionInput(transactionInput); // } // // final MutableTransactionOutput newTransactionOutput; // { // final PrivateKey newTransactionOutputPrivateKey = PrivateKey.createNewKey(); // final Address payToAddress = addressInflater.fromPrivateKey(newTransactionOutputPrivateKey); // System.out.println("Tx Private Key: " + newTransactionOutputPrivateKey); // newTransactionOutput = new MutableTransactionOutput(); // newTransactionOutput.setAmount(50L * Transaction.SATOSHIS_PER_BITCOIN); // newTransactionOutput.setIndex(0); // newTransactionOutput.setLockingScript(ScriptBuilder.payToAddress(payToAddress)); // } // transaction.addTransactionOutput(newTransactionOutput); // // final SignatureContext signatureContext = new SignatureContext(transaction, new HashType(Mode.SIGNATURE_HASH_ALL, true, false), Long.MAX_VALUE); // signatureContext.setShouldSignInputScript(0, true, outputBeingSpent); // final TransactionSigner transactionSigner = new TransactionSigner(); // final Transaction signedTransaction = transactionSigner.signTransaction(signatureContext, prevoutPrivateKey); // // final TransactionInput transactionInput = signedTransaction.getTransactionInputs().get(0); // final MutableContext context = new MutableContext(); // context.setCurrentScript(null); // context.setTransactionInputIndex(0); // context.setTransactionInput(transactionInput); // context.setTransaction(signedTransaction); // context.setBlockHeight(blockHeight); // context.setTransactionOutputBeingSpent(outputBeingSpent); // context.setCurrentScriptLastCodeSeparatorIndex(0); // final ScriptRunner scriptRunner = new ScriptRunner(); // final Boolean outputIsUnlocked = scriptRunner.runScript(outputBeingSpent.getLockingScript(), transactionInput.getUnlockingScript(), context); // Assert.assertTrue(outputIsUnlocked); // // transactions.add(signedTransaction); // } final StratumMiner.BlockConfiguration blockConfiguration = new StratumMiner.BlockConfiguration(); blockConfiguration.blockVersion = BlockHeader.VERSION; blockConfiguration.coinbaseTransaction = coinbaseTransaction; blockConfiguration.difficulty = difficulty; blockConfiguration.previousBlockHash = previousBlockHash; blockConfiguration.transactions = transactions; final StratumMiner stratumMiner = new StratumMiner(blockConfiguration); stratumMiner.loop(); } } class StratumMiner { public static final Integer extraNonceByteCount = 4; public static final Integer extraNonce2ByteCount = 4; public static final Integer totalExtraNonceByteCount = (extraNonceByteCount + extraNonce2ByteCount); protected final StratumServerSocket _stratumServerSocket; protected final MainThreadPool _threadPool = new MainThreadPool(256, 60000L); protected final ByteArray _extraNonce; protected StratumMineBlockTaskBuilderCore _stratumMineBlockTaskBuilder; protected StratumMineBlockTask _currentMineBlockTask = null; protected Integer _shareDifficulty = 1; protected Thread _mainThread; public static class BlockConfiguration { Long blockVersion; Sha256Hash previousBlockHash; Difficulty difficulty; Transaction coinbaseTransaction; List<Transaction> transactions; } protected final BlockConfiguration _blockConfiguration; protected ByteArray _createRandomBytes(final int byteCount) { int i = 0; final MutableByteArray mutableByteArray = new MutableByteArray(byteCount); while (i < byteCount) { final byte[] randomBytes = ByteUtil.integerToBytes((int) (Math.random() * Integer.MAX_VALUE)); for (byte b : randomBytes) { mutableByteArray.setByte(i, b); i += 1; if (i >= byteCount) { break; } } } return mutableByteArray; } protected void _buildMiningTask() { final StratumMineBlockTaskBuilderCore stratumMineBlockTaskBuilder = new StratumMineBlockTaskBuilderCore(totalExtraNonceByteCount, new TransactionDeflater()); stratumMineBlockTaskBuilder.setBlockVersion(_blockConfiguration.blockVersion); stratumMineBlockTaskBuilder.setPreviousBlockHash(_blockConfiguration.previousBlockHash); stratumMineBlockTaskBuilder.setDifficulty(_blockConfiguration.difficulty); stratumMineBlockTaskBuilder.setCoinbaseTransaction(_blockConfiguration.coinbaseTransaction); stratumMineBlockTaskBuilder.setExtraNonce(_extraNonce); for (final Transaction transaction : _blockConfiguration.transactions) { stratumMineBlockTaskBuilder.addTransaction(new TransactionWithFee(transaction, 0L)); } _stratumMineBlockTaskBuilder = stratumMineBlockTaskBuilder; _currentMineBlockTask = stratumMineBlockTaskBuilder.buildMineBlockTask(); } protected void _sendWork(final JsonSocket socketConnection, final Boolean abandonOldJobs) { _setDifficulty(socketConnection); final RequestMessage mineBlockRequest = _currentMineBlockTask.createRequest(abandonOldJobs); Logger.info("Sent: "+ mineBlockRequest.toString()); socketConnection.write(new JsonProtocolMessage(mineBlockRequest)); } protected void _setDifficulty(final JsonSocket socketConnection) { final RequestMessage mineBlockMessage = new RequestMessage(RequestMessage.ServerCommand.SET_DIFFICULTY.getValue()); final Json parametersJson = new Json(true); parametersJson.add(_shareDifficulty); // Difficulty::getDifficultyRatio mineBlockMessage.setParameters(parametersJson); Logger.info("Sent: "+ mineBlockMessage.toString()); socketConnection.write(new JsonProtocolMessage(mineBlockMessage)); } protected void _handleSubscribeMessage(final RequestMessage requestMessage, final JsonSocket socketConnection) { final String subscriptionId = HexUtil.toHexString(_createRandomBytes(8).getBytes()); final Json resultJson = new Json(true); { final Json setDifficulty = new Json(true); { setDifficulty.add("mining.set_difficulty"); setDifficulty.add(subscriptionId); } final Json notify = new Json(true); { notify.add("mining.notify"); notify.add(subscriptionId); } final Json subscriptions = new Json(true); { subscriptions.add(setDifficulty); subscriptions.add(notify); } resultJson.add(subscriptions); resultJson.add(_currentMineBlockTask.getExtraNonce()); resultJson.add(extraNonce2ByteCount); } final ResponseMessage responseMessage = new ResponseMessage(requestMessage.getId()); responseMessage.setResult(resultJson); Logger.info("Sent: "+ responseMessage); socketConnection.write(new JsonProtocolMessage(responseMessage)); } protected void _handleAuthorizeMessage(final RequestMessage requestMessage, final JsonSocket socketConnection) { { // Respond with successful authorization... final ResponseMessage responseMessage = new ResponseMessage(requestMessage.getId()); responseMessage.setResult(ResponseMessage.RESULT_TRUE); Logger.info("Sent: "+ responseMessage.toString()); socketConnection.write(new JsonProtocolMessage(responseMessage)); } _sendWork(socketConnection, true); } protected void _handleSubmitMessage(final RequestMessage requestMessage, final JsonSocket socketConnection) { // mining.submit("username", "job id", "ExtraNonce2", "nTime", "nOnce") final Json messageParameters = requestMessage.getParameters(); final String workerName = messageParameters.getString(0); final ByteArray taskId = MutableByteArray.wrap(HexUtil.hexStringToByteArray(messageParameters.getString(1))); final String stratumNonce = messageParameters.getString(4); final String stratumExtraNonce2 = messageParameters.getString(2); final String stratumTimestamp = messageParameters.getString(3); Boolean submissionWasAccepted = true; final Long taskIdLong = ByteUtil.bytesToLong(taskId.getBytes()); final StratumMineBlockTask mineBlockTask = _currentMineBlockTask; if (mineBlockTask == null) { submissionWasAccepted = false; } Boolean shouldExit = false; if (mineBlockTask != null) { final Difficulty shareDifficulty = Difficulty.BASE_DIFFICULTY.divideBy(_shareDifficulty); final BlockHeader blockHeader = mineBlockTask.assembleBlockHeader(stratumNonce, stratumExtraNonce2, stratumTimestamp); final Sha256Hash hash = blockHeader.getHash(); Logger.info(mineBlockTask.getDifficulty().getBytes()); Logger.info(hash); Logger.info(shareDifficulty.getBytes()); if (! shareDifficulty.isSatisfiedBy(hash)) { submissionWasAccepted = false; Logger.info("NOTICE: Share Difficulty not satisfied."); final RequestMessage newRequestMessage = mineBlockTask.createRequest(false); Logger.info("Resending Task: "+ newRequestMessage.toString()); socketConnection.write(new JsonProtocolMessage(newRequestMessage)); } else if (blockHeader.isValid()) { final BlockHeaderDeflater blockHeaderDeflater = new BlockHeaderDeflater(); Logger.info("Valid Block: " + blockHeaderDeflater.toBytes(blockHeader)); final BlockDeflater blockDeflater = new BlockDeflater(); final Block block = mineBlockTask.assembleBlock(stratumNonce, stratumExtraNonce2, stratumTimestamp); Logger.info(blockDeflater.toBytes(block)); shouldExit = true; BitcoinUtil.exitSuccess(); } } final ResponseMessage blockAcceptedMessage = new MinerSubmitBlockResult(requestMessage.getId(), submissionWasAccepted); Logger.info("Sent: "+ blockAcceptedMessage.toString()); socketConnection.write(new JsonProtocolMessage(blockAcceptedMessage)); if (shouldExit) { socketConnection.close(); _mainThread.interrupt(); } } public StratumMiner(final BlockConfiguration blockConfiguration) { _extraNonce = _createRandomBytes(extraNonceByteCount); _blockConfiguration = blockConfiguration; File TEMP_FILE = null; try { TEMP_FILE = File.createTempFile("tmp", ".dat"); TEMP_FILE.deleteOnExit(); } catch (final Exception exception) { exception.printStackTrace(); } final Configuration configuration = new Configuration(TEMP_FILE); final StratumProperties stratumProperties = configuration.getStratumProperties(); _stratumServerSocket = new StratumServerSocket(stratumProperties.getPort(), _threadPool); _stratumServerSocket.setSocketEventCallback(new StratumServerSocket.SocketEventCallback() { @Override public void onConnect(final JsonSocket socketConnection) { Logger.info("Node connected: " + socketConnection.getIp() + ":" + socketConnection.getPort()); socketConnection.setMessageReceivedCallback(new Runnable() { @Override public void run() { final JsonProtocolMessage jsonProtocolMessage = socketConnection.popMessage(); final Json message = jsonProtocolMessage.getMessage(); { // Handle Request Messages... final RequestMessage requestMessage = RequestMessage.parse(message); if (requestMessage != null) { Logger.info("Received: " + requestMessage); if (requestMessage.isCommand(RequestMessage.ClientCommand.SUBSCRIBE)) { _handleSubscribeMessage(requestMessage, socketConnection); } else if (requestMessage.isCommand(RequestMessage.ClientCommand.AUTHORIZE)) { _handleAuthorizeMessage(requestMessage, socketConnection); } else if (requestMessage.isCommand(RequestMessage.ClientCommand.SUBMIT)) { _handleSubmitMessage(requestMessage, socketConnection); } else { Logger.info("Unrecognized Message: " + requestMessage.getCommand()); } } } { // Handle Response Messages... final ResponseMessage responseMessage = ResponseMessage.parse(message); if (responseMessage != null) { System.out.println(responseMessage); } } } }); socketConnection.beginListening(); } @Override public void onDisconnect(final JsonSocket disconnectedSocket) { Logger.info("Node disconnected: " + disconnectedSocket.getIp() + ":" + disconnectedSocket.getPort()); } }); } public void loop() { _mainThread = Thread.currentThread(); _buildMiningTask(); _stratumServerSocket.start(); Logger.info("[Server Online]"); while (true) { try { Thread.sleep(60000); } catch (final Exception exception) { break; } } _stratumServerSocket.stop(); } } <|start_filename|>src/server/java/com/softwareverde/servlet/AuthenticatedServlet.java<|end_filename|> package com.softwareverde.servlet; import com.softwareverde.bitcoin.miner.pool.AccountId; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiEndpoint; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.json.Json; import com.softwareverde.servlet.session.Session; public abstract class AuthenticatedServlet extends StratumApiEndpoint { public AuthenticatedServlet(final StratumProperties stratumProperties) { super(stratumProperties); } @Override protected final Response _onRequest(final Request request) { final Session session = _sessionManager.getSession(request); if (session == null) { return new JsonResponse(Response.Codes.OK, new StratumApiResult(false, "Not authenticated.")); } final Json sessionData = session.getMutableData(); final AccountId accountId = AccountId.wrap(sessionData.getLong("accountId")); if (accountId == null) { return new JsonResponse(Response.Codes.OK, new StratumApiResult(false, "Not authenticated.")); } return _onAuthenticatedRequest(accountId, request); } protected abstract Response _onAuthenticatedRequest(final AccountId accountId, final Request request); } <|start_filename|>src/test/java/com/softwareverde/util/BitcoinReflectionUtil.java<|end_filename|> package com.softwareverde.util; import com.softwareverde.logging.Logger; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class BitcoinReflectionUtil extends ReflectionUtil { protected BitcoinReflectionUtil() { } public static void setStaticValue(final Class<?> objectClass, final String memberName, final Object value) { RuntimeException lastException = null; Class<?> clazz = objectClass; do { try { final Field field = clazz.getDeclaredField(memberName); field.setAccessible(true); try { final Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, value); } catch (final IllegalAccessException exception) { throw exception; } catch (final Exception exception) { // Java 12+ does not allow for overwriting final members; // however, this can still be achieved via Unsafe black magic. // NOTE: This requires that the `--release` flag be disabled on the compiler within intelliJ. // (Preferences -> Build -> Compiler -> Java Compiler -> Disable "use --release") // final sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe(); final Field unsafeField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); unsafeField.setAccessible(true); final sun.misc.Unsafe unsafe = (sun.misc.Unsafe) unsafeField.get(null); final Object staticFieldBase = unsafe.staticFieldBase(field); final long staticFieldOffset = unsafe.staticFieldOffset(field); unsafe.putObject(staticFieldBase, staticFieldOffset, value); } return; } catch (final NoSuchFieldException exception) { Logger.debug(exception); lastException = new RuntimeException("Invalid member name found: " + objectClass.getSimpleName() + "." + memberName); } catch (final IllegalAccessException exception) { lastException = new RuntimeException("Unable to access member: " + objectClass.getSimpleName() + "." + memberName); } } while ((clazz = clazz.getSuperclass()) != null); throw lastException; } public static void setVolatile(final Class<?> objectClass, final String memberName, final Boolean isVolatile) { RuntimeException lastException = null; Class<?> clazz = objectClass; do { try { final Field field = clazz.getDeclaredField(memberName); field.setAccessible(true); final Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); if (isVolatile) { modifiersField.setInt(field, ((modifiersField.getModifiers() | Modifier.TRANSIENT) & (~Modifier.FINAL)) ); } else { modifiersField.setInt(field, (modifiersField.getModifiers() & (~Modifier.TRANSIENT))); } return; } catch (final NoSuchFieldException exception) { lastException = new RuntimeException("Invalid member name found: " + objectClass.getSimpleName() + "." + memberName); } catch (final IllegalAccessException exception) { lastException = new RuntimeException("Unable to access member: " + objectClass.getSimpleName() + "." + memberName); } } while ((clazz = clazz.getSuperclass()) != null); throw lastException; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/UnitTest.java<|end_filename|> package com.softwareverde.bitcoin.test; import com.softwareverde.logging.LineNumberAnnotatedLog; import com.softwareverde.logging.LogLevel; import com.softwareverde.logging.Logger; public class UnitTest { static { Logger.setLog(LineNumberAnnotatedLog.getInstance()); Logger.setLogLevel(LogLevel.ON); Logger.setLogLevel("com.softwareverde.async.lock.IndexLock", LogLevel.ERROR); } public void before() throws Exception { } public void after() throws Exception { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/spv/SpvDatabaseManagerFactory.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.spv; import com.softwareverde.bitcoin.server.configuration.CheckpointConfiguration; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManagerFactory; import com.softwareverde.database.DatabaseException; public class SpvDatabaseManagerFactory implements DatabaseManagerFactory { protected final DatabaseConnectionFactory _databaseConnectionFactory; protected final Integer _maxQueryBatchSize; protected final CheckpointConfiguration _checkpointConfiguration; public SpvDatabaseManagerFactory(final DatabaseConnectionFactory databaseConnectionFactory, final Integer maxQueryBatchSize, final CheckpointConfiguration checkpointConfiguration) { _databaseConnectionFactory = databaseConnectionFactory; _maxQueryBatchSize = maxQueryBatchSize; _checkpointConfiguration = checkpointConfiguration; } @Override public SpvDatabaseManager newDatabaseManager() throws DatabaseException { final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection(); return new SpvDatabaseManager(databaseConnection, _maxQueryBatchSize, _checkpointConfiguration); } @Override public DatabaseConnectionFactory getDatabaseConnectionFactory() { return _databaseConnectionFactory; } @Override public DatabaseManagerFactory newDatabaseManagerFactory(final DatabaseConnectionFactory databaseConnectionFactory) { return new SpvDatabaseManagerFactory(databaseConnectionFactory, _maxQueryBatchSize, _checkpointConfiguration); } @Override public Integer getMaxQueryBatchSize() { return _maxQueryBatchSize; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/task/ViaBtcStratumMineBlockTaskBuilder.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.task; import com.softwareverde.bitcoin.block.CanonicalMutableBlock; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.transaction.MutableTransaction; import com.softwareverde.bitcoin.util.BitcoinUtil; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.HexUtil; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ViaBtcStratumMineBlockTaskBuilder implements RelayedStratumMineBlockTaskBuilder { protected List<String> _merkleTreeBranches; // Little-endian merkle tree (intermediary) branch hashes... protected final MutableBlock _prototypeBlock = new CanonicalMutableBlock(); protected String _extraNonce1; protected String _coinbaseTransactionHead; protected String _coinbaseTransactionTail; protected final ReentrantReadWriteLock.ReadLock _prototypeBlockReadLock; protected final ReentrantReadWriteLock.WriteLock _prototypeBlockWriteLock; public ViaBtcStratumMineBlockTaskBuilder(final Integer totalExtraNonceByteCount) { _prototypeBlock.addTransaction(new MutableTransaction()); // NOTE: Actual nonce and timestamp are updated later within the MineBlockTask... _prototypeBlock.setTimestamp(0L); _prototypeBlock.setNonce(0L); final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); _prototypeBlockReadLock = readWriteLock.readLock(); _prototypeBlockWriteLock = readWriteLock.writeLock(); } @Override public void setBlockVersion(final String stratumBlockVersion) { try { _prototypeBlockWriteLock.lock(); final Long blockVersion = ByteUtil.bytesToLong(HexUtil.hexStringToByteArray(stratumBlockVersion)); _prototypeBlock.setVersion(blockVersion); } finally { _prototypeBlockWriteLock.unlock(); } } @Override public void setPreviousBlockHash(final String stratumPreviousBlockHash) { try { _prototypeBlockWriteLock.lock(); final Sha256Hash previousBlockHash = Sha256Hash.fromHexString(BitcoinUtil.reverseEndianString(StratumUtil.swabHexString(stratumPreviousBlockHash))); _prototypeBlock.setPreviousBlockHash(previousBlockHash); } finally { _prototypeBlockWriteLock.unlock(); } } @Override public void setExtraNonce(final String stratumExtraNonce) { _extraNonce1 = stratumExtraNonce; } @Override public void setDifficulty(final String stratumDifficulty) { try { _prototypeBlockWriteLock.lock(); final Difficulty difficulty = Difficulty.decode(ByteArray.fromHexString(stratumDifficulty)); if (difficulty == null) { return; } _prototypeBlock.setDifficulty(difficulty); } finally { _prototypeBlockWriteLock.unlock(); } } @Override public void setMerkleTreeBranches(final List<String> merkleTreeBranches) { try { _prototypeBlockWriteLock.lock(); _merkleTreeBranches = merkleTreeBranches.asConst(); } finally { _prototypeBlockWriteLock.unlock(); } } @Override public void setCoinbaseTransaction(final String stratumCoinbaseTransactionHead, final String stratumCoinbaseTransactionTail) { try { _prototypeBlockWriteLock.lock(); _coinbaseTransactionHead = stratumCoinbaseTransactionHead; _coinbaseTransactionTail = stratumCoinbaseTransactionTail; } finally { _prototypeBlockWriteLock.unlock(); } } @Override public StratumMineBlockTask buildMineBlockTask() { try { _prototypeBlockReadLock.lock(); final ByteArray id = MutableByteArray.wrap(ByteUtil.integerToBytes(StratumMineBlockTaskBuilderCore.getNextId())); return new StratumMineBlockTask(id, _prototypeBlock, _coinbaseTransactionHead, _coinbaseTransactionTail, _extraNonce1); } finally { _prototypeBlockReadLock.unlock(); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/block/QueryBlocksMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.block; import com.softwareverde.bitcoin.server.main.BitcoinConstants; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class QueryBlocksMessage extends BitcoinProtocolMessage { public static Integer MAX_BLOCK_HASH_COUNT = 500; protected Integer _version; protected final MutableList<Sha256Hash> _blockHashes = new MutableList<Sha256Hash>(); protected final MutableSha256Hash _stopBeforeBlockHash = new MutableSha256Hash(); public QueryBlocksMessage() { super(MessageType.QUERY_BLOCKS); _version = BitcoinConstants.getProtocolVersion(); } public Integer getVersion() { return _version; } /** * NOTE: Block Hashes should be added in descending order by block height (i.e. head Block first)... */ public void addBlockHash(final Sha256Hash blockHash) { if (_blockHashes.getCount() >= MAX_BLOCK_HASH_COUNT) { return; } if (blockHash == null) { return; } _blockHashes.add(blockHash.asConst()); } public void clearBlockHashes() { _blockHashes.clear(); } /** * NOTE: Block Hashes are sorted in descending order by block height (i.e. head Block first)... */ public List<Sha256Hash> getBlockHashes() { return _blockHashes; } public Sha256Hash getStopBeforeBlockHash() { return _stopBeforeBlockHash; } public void setStopBeforeBlockHash(final Sha256Hash blockHash) { if (blockHash == null) { _stopBeforeBlockHash.setBytes(Sha256Hash.EMPTY_HASH); return; } _stopBeforeBlockHash.setBytes(blockHash); } @Override protected ByteArray _getPayload() { final int blockHeaderCount = _blockHashes.getCount(); final int blockHashByteCount = Sha256Hash.BYTE_COUNT; final byte[] versionBytes = ByteUtil.integerToBytes(_version); final byte[] blockHeaderCountBytes = ByteUtil.variableLengthIntegerToBytes(blockHeaderCount); final byte[] blockHashesBytes = new byte[blockHashByteCount * blockHeaderCount]; for (int i = 0; i < blockHeaderCount; ++i) { final Sha256Hash blockHash = _blockHashes.get(i); final int startIndex = (blockHashByteCount * i); final ByteArray littleEndianBlockHash = blockHash.toReversedEndian(); ByteUtil.setBytes(blockHashesBytes, littleEndianBlockHash.getBytes(), startIndex); } final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(versionBytes, Endian.LITTLE); byteArrayBuilder.appendBytes(blockHeaderCountBytes, Endian.BIG); byteArrayBuilder.appendBytes(blockHashesBytes, Endian.BIG); byteArrayBuilder.appendBytes(_stopBeforeBlockHash, Endian.LITTLE); return byteArrayBuilder; } @Override protected Integer _getPayloadByteCount() { final int blockHeaderCount = _blockHashes.getCount(); final byte[] blockHeaderCountBytes = ByteUtil.variableLengthIntegerToBytes(blockHeaderCount); return (4 + blockHeaderCountBytes.length + (Sha256Hash.BYTE_COUNT * (blockHeaderCount + 1))); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/address/QueryAddressBlocksMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.address; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; // BitcoinVerde 2019-04-22 public class QueryAddressBlocksMessage extends BitcoinProtocolMessage { public static final Integer MAX_ADDRESS_COUNT = 1024; protected final MutableList<Address> _addresses = new MutableList<Address>(); public QueryAddressBlocksMessage() { super(MessageType.QUERY_ADDRESS_BLOCKS); } public void addAddress(final Address address) { if (_addresses.getCount() >= MAX_ADDRESS_COUNT) { return; } _addresses.add(address); } public List<Address> getAddresses() { return _addresses; } @Override protected ByteArray _getPayload() { final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(_addresses.getCount())); for (final Address address : _addresses) { byteArrayBuilder.appendBytes(address.getBytes(), Endian.LITTLE); } return byteArrayBuilder; } @Override protected Integer _getPayloadByteCount() { final int addressCount = _addresses.getCount(); final byte[] addressCountBytes = ByteUtil.variableLengthIntegerToBytes(_addresses.getCount()); return (addressCountBytes.length + (addressCount * AddressInflater.BYTE_COUNT)); } } <|start_filename|>explorer/www/js/blockchain.js<|end_filename|> class BlockchainUi { static search(objectHash) { document.location.href = "/?search=" + window.encodeURIComponent(objectHash); } static renderBlockchainMetadata(blockchainMetadata) { const blockchainSegments = {}; const sortedBlockCounts = []; const nodes = []; for (let i in blockchainMetadata) { const metadata = blockchainMetadata[i]; nodes.push({ id: metadata.blockchainSegmentId, shape: "dot", label: (metadata.minBlockHeight + " - " + metadata.maxBlockHeight), value: metadata.blockCount, title: ("Id " + metadata.blockchainSegmentId + ": " + metadata.blockCount + " blocks") }); sortedBlockCounts.push(metadata.blockCount); blockchainSegments[metadata.blockchainSegmentId] = metadata; } { // Sort the blockCounts and make them unique... sortedBlockCounts.sort(function(a, b){ return (a - b); }); // const medianBlockCount = (sortedBlockCounts.length > 0 ? sortedBlockCounts[sortedBlockCounts.length / 2] : 0); const copiedArray = sortedBlockCounts.slice(); sortedBlockCounts.length = 0; let previousBlockCountValue = null; for (let i in copiedArray) { const blockCountValue = copiedArray[i]; if (previousBlockCountValue != blockCountValue) { sortedBlockCounts.push(blockCountValue); } previousBlockCountValue = blockCountValue; } } const buckets = []; { // Create scaling buckets for the custom scaling function... const bucketCount = 10; const itemsPerBucket = Math.ceil(sortedBlockCounts.length / bucketCount); for (let i = 0; i < bucketCount; i += 1) { buckets.push({ min: Number.MAX_VALUE, max: 0 }); } for (let i in sortedBlockCounts) { const bucket = buckets[Math.floor(i / itemsPerBucket)]; const blockCount = sortedBlockCounts[i]; bucket.min = (blockCount < bucket.min ? blockCount : bucket.min); bucket.max = (blockCount > bucket.max ? blockCount : bucket.max); } } const edges = []; for (let i in blockchainMetadata) { const metadata = blockchainMetadata[i]; if (metadata.parentBlockchainSegmentId) { edges.push({ from: metadata.parentBlockchainSegmentId, to: metadata.blockchainSegmentId, title: (metadata.blockCount + " blocks") }); } } const data = { nodes: nodes, edges: edges }; const container = document.getElementById("blockchain-metadata"); const options = { layout: { hierarchical: { direction: (window.innerWidth > window.innerHeight ? "LR" : "DU"), sortMethod: "directed" } }, nodes: { borderWidth: 2, scaling: { min: 8, max: 56, label: { min: 10, max: 10 }, customScalingFunction: function(min, max, total, value) { for (let i = 0; i < buckets.length; i += 1) { const bucket = buckets[i]; if (value <= bucket.max && value >= bucket.min) { const bucketScale = (bucket.max == bucket.min ? 1.0 : ((value - bucket.min) / (bucket.max - bucket.min))); return ((1.0 / buckets.length) * (bucketScale + i)); } } return 0.5; } }, color: { border: "#313131", background: "#F99500", hover: { border: "#424242", background: "#FFA010", } }, font: { color:"#202020" }, chosen: { node: function(values, id, selected, hovering) { } }, fixed: { x: true, y: true } }, edges: { color: "#AAAAAA" }, interaction: { hover: true, hoverConnectedEdges: false } }; const network = new vis.Network(container, data, options); let sticky = false; const hideBlockchainSegmentDetails = function(data) { const isClickEvent = (data.nodes ? true : false); if (isClickEvent) { sticky = false; } else if (sticky) { return; } const detailsElement = $("#blockchain-metadata-details"); $(".blockchain-segment-id", detailsElement).text("").toggleClass("empty", true); $(".blockchain-segment-block-count", detailsElement).text("").toggleClass("empty", true); $(".blockchain-segment-min-height", detailsElement).text("").toggleClass("empty", true); $(".blockchain-segment-max-height", detailsElement).text("").toggleClass("empty", true); }; const displayBlockchainSegmentDetails = function(data) { const isClickEvent = (data.nodes ? true : false); const nodeId = (isClickEvent ? data.nodes[0] : data.node); if (isClickEvent) { sticky = nodeId; } else if (sticky) { return; } const blockchainSegment = blockchainSegments[nodeId]; if (! blockchainSegment) { return; } const detailsElement = $("#blockchain-metadata-details"); $(".blockchain-segment-id", detailsElement).text(blockchainSegment.blockchainSegmentId).toggleClass("empty", false); $(".blockchain-segment-block-count", detailsElement).text(blockchainSegment.blockCount.toLocaleString()).toggleClass("empty", false); $(".blockchain-segment-min-height", detailsElement).text(blockchainSegment.minBlockHeight.toLocaleString()).toggleClass("empty", false); $(".blockchain-segment-max-height", detailsElement).text(blockchainSegment.maxBlockHeight.toLocaleString()).toggleClass("empty", false); }; network.on("selectNode", displayBlockchainSegmentDetails); network.on("hoverNode", displayBlockchainSegmentDetails); // network.on("hoverEdge", displayBlockchainSegmentDetails); network.on("deselectNode", hideBlockchainSegmentDetails); network.on("blurNode", hideBlockchainSegmentDetails); network.on("blurEdge", hideBlockchainSegmentDetails); } } $(document).ready(function() { const searchInput = $("#search"); const loadingImage = $("#search-loading-image"); searchInput.keypress(function(event) { const key = event.which; if (key == KeyCodes.ENTER) { loadingImage.css("visibility", "visible"); const hash = searchInput.val(); BlockchainUi.search(hash); return false; } }); Api.getBlockchainMetadata({ }, function(data) { if (! data.wasSuccess) { console.log(data.errorMessage); return; } const blockchainMetadata = data.blockchainMetadata; BlockchainUi.renderBlockchainMetadata(blockchainMetadata); }); const detailsElement = $("#blockchain-metadata-details"); $(".blockchain-segment-min-height, .blockchain-segment-max-height", detailsElement).on("click", function() { searchInput.val($(this).text()); searchInput.trigger($.Event( "keypress", { which: KeyCodes.ENTER } )); }); }); <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/database/TransactionDatabaseManagerTests.java<|end_filename|> package com.softwareverde.bitcoin.server.database; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.FullNodeTransactionDatabaseManager; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TransactionDatabaseManagerTests extends IntegrationTest { @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } @Test public void storing_the_same_transaction_should_return_the_same_id() throws Exception { // Setup try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final TransactionInflater transactionInflater = new TransactionInflater(); final Transaction transaction = transactionInflater.fromBytes(ByteArray.fromHexString("01000000010000000000000000000000000000000000000000000000000000000000000000FFFFFFFF0704FFFF001D0104FFFFFFFF0100F2052A0100000043410496B538E853519C726A2C91E61EC11600AE1390813A627C66FB8BE7947BE63C52DA7589379515D4E0A604F8141781E62294721166BF621E73A82CBF2342C858EEAC00000000")); final FullNodeTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); // Action final TransactionId transactionId0 = transactionDatabaseManager.storeTransactionHash(transaction); final TransactionId transactionId1 = transactionDatabaseManager.storeTransactionHash(transaction); final List<TransactionId> transactionIds = transactionDatabaseManager.storeTransactionHashes(new ImmutableList<Transaction>(transaction, transaction)); // Assert Assert.assertEquals(transactionId0, transactionId1); Assert.assertEquals(2, transactionIds.getCount()); Assert.assertEquals(transactionId0, transactionIds.get(0)); Assert.assertEquals(transactionId0, transactionIds.get(1)); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/coinbase/ImmutableCoinbaseTransaction.java<|end_filename|> package com.softwareverde.bitcoin.transaction.coinbase; import com.softwareverde.bitcoin.transaction.ImmutableTransaction; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; public class ImmutableCoinbaseTransaction extends ImmutableTransaction implements CoinbaseTransaction { public ImmutableCoinbaseTransaction(final Transaction transaction) { super(transaction); } @Override public UnlockingScript getCoinbaseScript() { if (_transactionInputs.getCount() < 1) { return null; } final TransactionInput transactionInput = _transactionInputs.get(0); return transactionInput.getUnlockingScript(); } @Override public Long getBlockReward() { if (_transactionOutputs.getCount() < 1) { return null; } final TransactionOutput transactionOutput = _transactionOutputs.get(0); return transactionOutput.getAmount(); } @Override public ImmutableCoinbaseTransaction asCoinbase() { return this; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/response/block/merkle/MerkleBlockMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response.block.merkle; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.block.header.ImmutableBlockHeaderWithTransactionCount; import com.softwareverde.bitcoin.block.merkleroot.PartialMerkleTree; import com.softwareverde.bitcoin.block.merkleroot.PartialMerkleTreeInflater; import com.softwareverde.bitcoin.inflater.BlockHeaderInflaters; import com.softwareverde.bitcoin.inflater.MerkleTreeInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; public class MerkleBlockMessageInflater extends BitcoinProtocolMessageInflater { protected final BlockHeaderInflaters _blockHeaderInflaters; protected final MerkleTreeInflaters _merkleTreeInflaters; public MerkleBlockMessageInflater(final BlockHeaderInflaters blockHeaderInflaters, final MerkleTreeInflaters merkleTreeInflaters) { _blockHeaderInflaters = blockHeaderInflaters; _merkleTreeInflaters = merkleTreeInflaters; } @Override public MerkleBlockMessage fromBytes(final byte[] bytes) { final MerkleBlockMessage merkleBlockMessage = new MerkleBlockMessage(_blockHeaderInflaters, _merkleTreeInflaters); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.MERKLE_BLOCK); if (protocolMessageHeader == null) { return null; } final BlockHeaderInflater blockHeaderInflater = _blockHeaderInflaters.getBlockHeaderInflater(); final BlockHeader blockHeader = blockHeaderInflater.fromBytes(byteArrayReader); if (blockHeader == null) { return null; } final PartialMerkleTreeInflater partialMerkleTreeInflater = _merkleTreeInflaters.getPartialMerkleTreeInflater(); final PartialMerkleTree partialMerkleTree = partialMerkleTreeInflater.fromBytes(byteArrayReader); if (partialMerkleTree == null) { return null; } merkleBlockMessage.setBlockHeader(new ImmutableBlockHeaderWithTransactionCount(blockHeader, partialMerkleTree.getItemCount())); merkleBlockMessage.setPartialMerkleTree(partialMerkleTree); return merkleBlockMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/HF20201115.java<|end_filename|> package com.softwareverde.bitcoin.bip; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; public class HF20201115 { public static final Long ACTIVATION_BLOCK_TIME = 1605441600L; // Bitcoin Cash: 2020-11-15 Hard Fork: https://gitlab.com/bitcoin-cash-node/bchn-sw/bitcoincash-upgrade-specifications/-/blob/master/spec/2020-11-15-upgrade.md public static Boolean isEnabled(final MedianBlockTime medianBlockTime) { if (medianBlockTime == null) { return true; } final long currentTimestamp = medianBlockTime.getCurrentTimeInSeconds(); return (currentTimestamp >= ACTIVATION_BLOCK_TIME); } protected HF20201115() { } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/sync/BlockchainBuilderTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.context.core.BlockProcessorContext; import com.softwareverde.bitcoin.context.core.BlockchainBuilderContext; import com.softwareverde.bitcoin.context.core.PendingBlockLoaderContext; import com.softwareverde.bitcoin.context.core.TransactionValidatorContext; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.module.node.BlockProcessor; import com.softwareverde.bitcoin.server.module.node.database.block.fullnode.FullNodeBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.pending.fullnode.FullNodePendingBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.UnspentTransactionOutputDatabaseManager; import com.softwareverde.bitcoin.server.module.node.manager.BitcoinNodeManager; import com.softwareverde.bitcoin.server.module.node.sync.block.BlockDownloader; import com.softwareverde.bitcoin.server.module.node.sync.blockloader.PendingBlockLoader; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.bitcoin.test.BlockData; import com.softwareverde.bitcoin.test.FakeBlockStore; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.bitcoin.test.fake.FakeStaticMedianBlockTimeContext; import com.softwareverde.bitcoin.test.fake.FakeUnspentTransactionOutputContext; import com.softwareverde.bitcoin.test.util.BlockTestUtil; import com.softwareverde.bitcoin.test.util.TransactionTestUtil; import com.softwareverde.bitcoin.transaction.MutableTransaction; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.signer.TransactionOutputRepository; import com.softwareverde.bitcoin.transaction.validator.TransactionValidationResult; import com.softwareverde.bitcoin.transaction.validator.TransactionValidator; import com.softwareverde.bitcoin.transaction.validator.TransactionValidatorCore; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.concurrent.service.SleepyService; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.network.time.MutableNetworkTime; import com.softwareverde.util.HexUtil; import com.softwareverde.util.Util; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class BlockchainBuilderTests extends IntegrationTest { /** * A BlockDownloader StatusMonitor that is always in the `ACTIVE` state. */ public static final BlockDownloader.StatusMonitor FAKE_DOWNLOAD_STATUS_MONITOR = new SleepyService.StatusMonitor() { @Override public SleepyService.Status getStatus() { return SleepyService.Status.ACTIVE; } }; /** * A BlockInflater/Deflater that prevents the Block's hash from being evaluated. */ public static final BlockInflaters FAKE_BLOCK_INFLATERS = new BlockInflaters() { protected final BlockDeflater _blockDeflater = new BlockDeflater(); @Override public BlockInflater getBlockInflater() { return new BlockInflater() { @Override protected MutableBlock _fromByteArrayReader(final ByteArrayReader byteArrayReader) { final Block originalBlock = super._fromByteArrayReader(byteArrayReader); return new MutableBlock(originalBlock) { @Override public Boolean isValid() { return true; } }; } }; } @Override public BlockDeflater getBlockDeflater() { return _blockDeflater; } }; /** * A dummy BlockDownloadRequester that does nothing. */ public static final BlockDownloadRequester FAKE_BLOCK_DOWNLOAD_REQUESTER = new BlockDownloadRequester() { @Override public void requestBlock(final BlockHeader blockHeader) { } @Override public void requestBlock(final Sha256Hash blockHash, final Sha256Hash previousBlockHash) { } }; /** * FakeBitcoinNodeManager is a BitcoinNodeManager that prevents all network traffic. */ public static class FakeBitcoinNodeManager extends BitcoinNodeManager { protected static Context _createFakeContext() { final Context context = new Context(); context.maxNodeCount = 0; return context; } public FakeBitcoinNodeManager() { super(_createFakeContext()); } @Override public List<BitcoinNode> getNodes() { return new MutableList<BitcoinNode>(0); } } @Override @Before public void before() throws Exception { super.before(); } @After @Override public void after() throws Exception { super.after(); } @Test public void should_synchronize_pending_blocks() throws Exception { final FakeBlockStore blockStore = new FakeBlockStore(); final FakeBitcoinNodeManager bitcoinNodeManager = new FakeBitcoinNodeManager(); final BlockProcessorContext blockProcessorContext = new BlockProcessorContext(_masterInflater, _masterInflater, blockStore, _fullNodeDatabaseManagerFactory, new MutableNetworkTime(), _synchronizationStatus, _transactionValidatorFactory); final PendingBlockLoaderContext pendingBlockLoaderContext = new PendingBlockLoaderContext(_masterInflater, _fullNodeDatabaseManagerFactory, _threadPool); final BlockchainBuilderContext blockchainBuilderContext = new BlockchainBuilderContext(_masterInflater, _fullNodeDatabaseManagerFactory, bitcoinNodeManager, _threadPool); final BlockProcessor blockProcessor = new BlockProcessor(blockProcessorContext); final PendingBlockLoader pendingBlockLoader = new PendingBlockLoader(pendingBlockLoaderContext, 1); final BlockchainBuilder blockchainBuilder = new BlockchainBuilder(blockchainBuilderContext, blockProcessor, pendingBlockLoader, BlockchainBuilderTests.FAKE_DOWNLOAD_STATUS_MONITOR, null); final Block[] blocks; try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final FullNodePendingBlockDatabaseManager pendingBlockDatabaseManager = databaseManager.getPendingBlockDatabaseManager(); blocks = new Block[6]; int blockHeight = 0; for (final String blockData : new String[]{ BlockData.MainChain.GENESIS_BLOCK, BlockData.MainChain.BLOCK_1, BlockData.MainChain.BLOCK_2, BlockData.MainChain.BLOCK_3, BlockData.MainChain.BLOCK_4, BlockData.MainChain.BLOCK_5 }) { final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(blockData)); pendingBlockDatabaseManager.storeBlock(block); blocks[blockHeight] = block; blockHeight += 1; } } // Action blockchainBuilder.start(); Thread.sleep(1000L); blockchainBuilder.stop(); // Assert try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockchainSegmentId blockchainSegmentId = BlockchainSegmentId.wrap(1L); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(blockchainSegmentId, 0L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(blockchainSegmentId, 1L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(blockchainSegmentId, 2L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(blockchainSegmentId, 3L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(blockchainSegmentId, 4L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(blockchainSegmentId, 5L)); // Ensure the coinbase UTXOs were added to the UTXO set. final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = databaseManager.getUnspentTransactionOutputDatabaseManager(); for (int blockHeight = 1; blockHeight < 6L; ++blockHeight) { final Block block = blocks[blockHeight]; final Transaction transaction = block.getCoinbaseTransaction(); final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transaction.getHash(), 0); final TransactionOutput unspentTransactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(transactionOutputIdentifier); Assert.assertNotNull(unspentTransactionOutput); } } } @Test public void block_should_be_valid_if_output_is_spent_only_on_a_different_chain() throws Exception { // This test creates a (fake) Block03 with a spendable coinbase, then creates two contentious (fake) Block04s. // Both versions of Block04 spend the coinbase of Block03, and both chains should be valid. (Coinbase maturity must be disabled.) final TransactionInflaters transactionInflaters = _masterInflater; final AddressInflater addressInflater = new AddressInflater(); final FakeBlockStore blockStore = new FakeBlockStore(); final FakeBitcoinNodeManager bitcoinNodeManager = new FakeBitcoinNodeManager(); final BlockInflaters blockInflaters = BlockchainBuilderTests.FAKE_BLOCK_INFLATERS; final BlockProcessorContext blockProcessorContext = new BlockProcessorContext(blockInflaters, transactionInflaters, blockStore, _fullNodeDatabaseManagerFactory, new MutableNetworkTime(), _synchronizationStatus, _transactionValidatorFactory); final PendingBlockLoaderContext pendingBlockLoaderContext = new PendingBlockLoaderContext(blockInflaters, _fullNodeDatabaseManagerFactory, _threadPool); final BlockchainBuilderContext blockchainBuilderContext = new BlockchainBuilderContext(blockInflaters, _fullNodeDatabaseManagerFactory, bitcoinNodeManager, _threadPool); final BlockProcessor blockProcessor = new BlockProcessor(blockProcessorContext); final PendingBlockLoader pendingBlockLoader = new PendingBlockLoader(pendingBlockLoaderContext, 1); final Sha256Hash block02Hash; { final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(BlockData.MainChain.BLOCK_2)); block02Hash = block.getHash(); } final PrivateKey privateKey = PrivateKey.createNewKey(); final Block fakeBlock03; { final MutableBlock mutableBlock = BlockTestUtil.createBlock(); mutableBlock.setPreviousBlockHash(block02Hash); // Create a transaction that will be spent in the test's signed transaction. // This transaction will create an output that can be spent by the test's private key. final Transaction transactionToSpend = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(privateKey); mutableBlock.addTransaction(transactionToSpend); fakeBlock03 = mutableBlock; } final TransactionOutputIdentifier spentTransactionOutputIdentifier; final Transaction signedTransactionSpendingCoinbase; { final Transaction transactionToSpend = fakeBlock03.getCoinbaseTransaction(); // Create an unsigned transaction that spends the test's previous transaction, and send the test's payment to an irrelevant address. final Transaction unsignedTransaction; { spentTransactionOutputIdentifier = new TransactionOutputIdentifier(transactionToSpend.getHash(), 0); final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(spentTransactionOutputIdentifier); final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput( (50L * Transaction.SATOSHIS_PER_BITCOIN), addressInflater.fromPrivateKey(privateKey, true) ); final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); mutableTransaction.addTransactionInput(transactionInput); mutableTransaction.addTransactionOutput(transactionOutput); unsignedTransaction = mutableTransaction; } final TransactionOutputRepository transactionOutputRepository = TransactionTestUtil.createTransactionOutputRepository(transactionToSpend); signedTransactionSpendingCoinbase = TransactionTestUtil.signTransaction(transactionOutputRepository, unsignedTransaction, privateKey); { // Ensure the transaction would normally be valid on its own... final FakeUnspentTransactionOutputContext unspentTransactionOutputContext = new FakeUnspentTransactionOutputContext(); unspentTransactionOutputContext.addTransaction(transactionToSpend, null, 2L, false); final TransactionValidatorContext transactionValidatorContext = new TransactionValidatorContext(transactionInflaters, new MutableNetworkTime(), FakeStaticMedianBlockTimeContext.MAX_MEDIAN_BLOCK_TIME, unspentTransactionOutputContext); final TransactionValidator transactionValidator = new TransactionValidatorCore(transactionValidatorContext); final TransactionValidationResult transactionValidationResult = transactionValidator.validateTransaction(3L, signedTransactionSpendingCoinbase); Assert.assertTrue(transactionValidationResult.isValid); } } final Transaction chainedTransactionForBlock4b; // Since the signedTransactionSpendingCoinbase is duplicated between Block4a and Block4b, this transaction is unique to Block4b to test that its outputs are not added to the UTXO set. { final TransactionOutputIdentifier transactionOutputIdentifierToSpend = new TransactionOutputIdentifier(signedTransactionSpendingCoinbase.getHash(), 0); final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(transactionOutputIdentifierToSpend); final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput(addressInflater.fromPrivateKey(privateKey, true)); final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); mutableTransaction.addTransactionInput(transactionInput); mutableTransaction.addTransactionOutput(transactionOutput); final TransactionOutputRepository transactionOutputRepository = TransactionTestUtil.createTransactionOutputRepository(signedTransactionSpendingCoinbase); chainedTransactionForBlock4b = TransactionTestUtil.signTransaction(transactionOutputRepository, mutableTransaction, privateKey); } final Block fakeBlock04aSpendingBlock03Coinbase; { // Spend the coinbase in a block... final MutableBlock mutableBlock = BlockTestUtil.createBlock(); mutableBlock.setPreviousBlockHash(fakeBlock03.getHash()); final Transaction regularCoinbaseTransaction = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(PrivateKey.createNewKey()); mutableBlock.addTransaction(regularCoinbaseTransaction); mutableBlock.addTransaction(signedTransactionSpendingCoinbase); fakeBlock04aSpendingBlock03Coinbase = mutableBlock; } final Block fakeBlock04bSpendingBlock03Coinbase; { // Spend the coinbase on a separate chain by creating another modified block #3 ... final MutableBlock mutableBlock = BlockTestUtil.createBlock(); mutableBlock.setPreviousBlockHash(fakeBlock03.getHash()); final Transaction regularCoinbaseTransaction = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(PrivateKey.createNewKey()); mutableBlock.addTransaction(regularCoinbaseTransaction); mutableBlock.addTransaction(signedTransactionSpendingCoinbase); mutableBlock.addTransaction(chainedTransactionForBlock4b); fakeBlock04bSpendingBlock03Coinbase = mutableBlock; } final Block[] mainChainBlocks; try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final FullNodePendingBlockDatabaseManager pendingBlockDatabaseManager = databaseManager.getPendingBlockDatabaseManager(); int blockHeight = 0; mainChainBlocks = new Block[5]; for (final String blockData : new String[]{ BlockData.MainChain.GENESIS_BLOCK, BlockData.MainChain.BLOCK_1, BlockData.MainChain.BLOCK_2 }) { final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(blockData)); pendingBlockDatabaseManager.storeBlock(block); mainChainBlocks[blockHeight] = block; blockHeight += 1; } for (final Block block : new Block[] { fakeBlock03 }) { pendingBlockDatabaseManager.storeBlock(block); mainChainBlocks[blockHeight] = block; blockHeight += 1; } for (final Block block : new Block[] { fakeBlock04aSpendingBlock03Coinbase, fakeBlock04bSpendingBlock03Coinbase }) { pendingBlockDatabaseManager.storeBlock(block); } mainChainBlocks[blockHeight] = fakeBlock04aSpendingBlock03Coinbase; } // NOTE: The blockchainBuilder checks for the Genesis block upon instantiation. final BlockchainBuilder blockchainBuilder = new BlockchainBuilder(blockchainBuilderContext, blockProcessor, pendingBlockLoader, BlockchainBuilderTests.FAKE_DOWNLOAD_STATUS_MONITOR, BlockchainBuilderTests.FAKE_BLOCK_DOWNLOAD_REQUESTER); // Action blockchainBuilder.start(); Thread.sleep(1000L); blockchainBuilder.stop(); // Assert try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockchainDatabaseManager blockchainDatabaseManager = databaseManager.getBlockchainDatabaseManager(); final BlockchainSegmentId mainBlockchainSegmentId = blockchainDatabaseManager.getHeadBlockchainSegmentId(); { Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 0L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 1L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 2L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 3L)); final BlockId block4aId = blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 4L); Assert.assertNotNull(block4aId); final Sha256Hash block4aHash = blockHeaderDatabaseManager.getBlockHash(block4aId); Assert.assertEquals(fakeBlock04aSpendingBlock03Coinbase.getHash(), block4aHash); } { final BlockId block4bId = blockHeaderDatabaseManager.getBlockHeaderId(fakeBlock04bSpendingBlock03Coinbase.getHash()); Assert.assertNotNull(block4bId); final BlockchainSegmentId altBlockchainSegmentId = blockHeaderDatabaseManager.getBlockchainSegmentId(block4bId); Assert.assertNotEquals(mainBlockchainSegmentId, altBlockchainSegmentId); // The original blockHeader should not have been usurped by its contentious brother... Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(altBlockchainSegmentId, 0L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(altBlockchainSegmentId, 1L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(altBlockchainSegmentId, 2L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(altBlockchainSegmentId, 3L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(altBlockchainSegmentId, 4L)); } { // Ensure the UTXO set was maintained correctly... final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = databaseManager.getUnspentTransactionOutputDatabaseManager(); { // Should exclude genesis UTXO... final Block block = mainChainBlocks[0]; final Transaction transaction = block.getCoinbaseTransaction(); final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transaction.getHash(), 0); final TransactionOutput unspentTransactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(transactionOutputIdentifier); Assert.assertNull(unspentTransactionOutput); } for (int i = 1; i < mainChainBlocks.length; ++i) { final Block block = mainChainBlocks[i]; for (final Transaction transaction : block.getTransactions()) { final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transaction.getHash(), 0); final TransactionOutput unspentTransactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(transactionOutputIdentifier); if (Util.areEqual(spentTransactionOutputIdentifier, transactionOutputIdentifier)) { Assert.assertNull(unspentTransactionOutput); } else { Assert.assertNotNull(unspentTransactionOutput); } } } { // Ensure the transactionOutput unique to Block4b is not included in the UTXO set. // NOTE: `signedTransactionSpendingCoinbase` is shared between Block4a and Block4b, so therefore its UTXO should be included within the set. final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(chainedTransactionForBlock4b.getHash(), 0); final TransactionOutput unspentTransactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(transactionOutputIdentifier); Assert.assertNull(unspentTransactionOutput); } } } } @Test public void should_not_validate_transaction_when_transaction_output_is_only_found_on_separate_fork() throws Exception { // This test creates two (fake) Block03s, each with a spendable coinbase. // The second Block03 (`Block03b`) spends the first Block03 (`Block03a`)'s coinbase, which is invalid. // The insertion order is Genesis -> Block01 -> Block02 -> Block03a -> Block03b final FakeBlockStore blockStore = new FakeBlockStore(); final FakeBitcoinNodeManager bitcoinNodeManager = new FakeBitcoinNodeManager(); final BlockInflaters blockInflaters = BlockchainBuilderTests.FAKE_BLOCK_INFLATERS; final TransactionInflaters transactionInflaters = _masterInflater; final BlockProcessorContext blockProcessorContext = new BlockProcessorContext(blockInflaters, transactionInflaters, blockStore, _fullNodeDatabaseManagerFactory, new MutableNetworkTime(), _synchronizationStatus, _transactionValidatorFactory); final PendingBlockLoaderContext pendingBlockLoaderContext = new PendingBlockLoaderContext(blockInflaters, _fullNodeDatabaseManagerFactory, _threadPool); final BlockchainBuilderContext blockchainBuilderContext = new BlockchainBuilderContext(blockInflaters, _fullNodeDatabaseManagerFactory, bitcoinNodeManager, _threadPool); final BlockProcessor blockProcessor = new BlockProcessor(blockProcessorContext); final PendingBlockLoader pendingBlockLoader = new PendingBlockLoader(pendingBlockLoaderContext, 1); final Sha256Hash block02Hash; { final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(BlockData.MainChain.BLOCK_2)); block02Hash = block.getHash(); } final PrivateKey privateKey = PrivateKey.createNewKey(); final Block fakeBlock03a; { final MutableBlock mutableBlock = BlockTestUtil.createBlock(); mutableBlock.setPreviousBlockHash(block02Hash); // Create a transaction that will be spent in the test's signed transaction. // This transaction will create an output that can be spent by the test's private key. final Transaction transactionToSpend = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(privateKey); mutableBlock.addTransaction(transactionToSpend); fakeBlock03a = mutableBlock; } final Transaction signedTransactionSpendingFakeBlock3aCoinbase; { final AddressInflater addressInflater = new AddressInflater(); final Transaction transactionToSpend = fakeBlock03a.getCoinbaseTransaction(); // Create an unsigned transaction that spends the test's previous transaction, and send the test's payment to an irrelevant address. final Transaction unsignedTransaction; { final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); final TransactionOutputIdentifier transactionOutputIdentifierToSpend = new TransactionOutputIdentifier(transactionToSpend.getHash(), 0); final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(transactionOutputIdentifierToSpend); mutableTransaction.addTransactionInput(transactionInput); final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput( addressInflater.fromBase58Check("1HrXm9WZF7LBm3HCwCBgVS3siDbk5DYCuW") ); mutableTransaction.addTransactionOutput(transactionOutput); unsignedTransaction = mutableTransaction; } final TransactionOutputRepository transactionOutputRepository = TransactionTestUtil.createTransactionOutputRepository(transactionToSpend); signedTransactionSpendingFakeBlock3aCoinbase = TransactionTestUtil.signTransaction(transactionOutputRepository, unsignedTransaction, privateKey); { // Ensure the transaction would normally be valid on its own... final FakeUnspentTransactionOutputContext unspentTransactionOutputContext = new FakeUnspentTransactionOutputContext(); unspentTransactionOutputContext.addTransaction(transactionToSpend, null, 2L, false); final TransactionValidatorContext transactionValidatorContext = new TransactionValidatorContext(transactionInflaters, new MutableNetworkTime(), FakeStaticMedianBlockTimeContext.MAX_MEDIAN_BLOCK_TIME, unspentTransactionOutputContext); final TransactionValidator transactionValidator = new TransactionValidatorCore(transactionValidatorContext); final TransactionValidationResult transactionValidationResult = transactionValidator.validateTransaction(3L, signedTransactionSpendingFakeBlock3aCoinbase); Assert.assertTrue(transactionValidationResult.isValid); } } final Block fakeBlock03bSpendingBlock03aCoinbase; { // Spend the coinbase in a block... final MutableBlock mutableBlock = BlockTestUtil.createBlock(); mutableBlock.setPreviousBlockHash(block02Hash); final Transaction regularCoinbaseTransaction = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(PrivateKey.createNewKey()); mutableBlock.addTransaction(regularCoinbaseTransaction); mutableBlock.addTransaction(signedTransactionSpendingFakeBlock3aCoinbase); fakeBlock03bSpendingBlock03aCoinbase = mutableBlock; } try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final FullNodePendingBlockDatabaseManager pendingBlockDatabaseManager = databaseManager.getPendingBlockDatabaseManager(); for (final String blockData : new String[]{ BlockData.MainChain.GENESIS_BLOCK, BlockData.MainChain.BLOCK_1, BlockData.MainChain.BLOCK_2 }) { final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(blockData)); pendingBlockDatabaseManager.storeBlock(block); } for (final Block block : new Block[] { fakeBlock03a, fakeBlock03bSpendingBlock03aCoinbase }) { pendingBlockDatabaseManager.storeBlock(block); } } // NOTE: The blockchainBuilder checks for the Genesis block upon instantiation. final BlockchainBuilder blockchainBuilder = new BlockchainBuilder(blockchainBuilderContext, blockProcessor, pendingBlockLoader, BlockchainBuilderTests.FAKE_DOWNLOAD_STATUS_MONITOR, BlockchainBuilderTests.FAKE_BLOCK_DOWNLOAD_REQUESTER); // Action blockchainBuilder.start(); Thread.sleep(1000L); blockchainBuilder.stop(); // Assert try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockchainDatabaseManager blockchainDatabaseManager = databaseManager.getBlockchainDatabaseManager(); final BlockchainSegmentId mainBlockchainSegmentId = blockchainDatabaseManager.getHeadBlockchainSegmentId(); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 0L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 1L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 2L)); final BlockId block3aId = blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 3L); Assert.assertNotNull(block3aId); final Sha256Hash block4aHash = blockHeaderDatabaseManager.getBlockHash(block3aId); Assert.assertEquals(fakeBlock03a.getHash(), block4aHash); final BlockId block3bId = blockHeaderDatabaseManager.getBlockHeaderId(fakeBlock03bSpendingBlock03aCoinbase.getHash()); final FullNodeBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final Boolean block3bWasValid = blockDatabaseManager.hasTransactions(block3bId); Assert.assertFalse(block3bWasValid); } } @Test public void should_not_validate_block_that_has_two_transactions_spending_the_same_output() throws Exception { // This test creates a (fake) Block03, with a spendable coinbase, then creates a (fake) Block04 that spends the Block03's coinbase twice, which is invalid. final FakeBlockStore blockStore = new FakeBlockStore(); final FakeBitcoinNodeManager bitcoinNodeManager = new FakeBitcoinNodeManager(); final BlockInflaters blockInflaters = BlockchainBuilderTests.FAKE_BLOCK_INFLATERS; final TransactionInflaters transactionInflaters = _masterInflater; final BlockProcessorContext blockProcessorContext = new BlockProcessorContext(blockInflaters, transactionInflaters, blockStore, _fullNodeDatabaseManagerFactory, new MutableNetworkTime(), _synchronizationStatus, _transactionValidatorFactory); final PendingBlockLoaderContext pendingBlockLoaderContext = new PendingBlockLoaderContext(blockInflaters, _fullNodeDatabaseManagerFactory, _threadPool); final BlockchainBuilderContext blockchainBuilderContext = new BlockchainBuilderContext(blockInflaters, _fullNodeDatabaseManagerFactory, bitcoinNodeManager, _threadPool); final BlockProcessor blockProcessor = new BlockProcessor(blockProcessorContext); final PendingBlockLoader pendingBlockLoader = new PendingBlockLoader(pendingBlockLoaderContext, 1); final Sha256Hash block02Hash; { final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(BlockData.MainChain.BLOCK_2)); block02Hash = block.getHash(); } final PrivateKey privateKey = PrivateKey.createNewKey(); final Block fakeBlock03; { final MutableBlock mutableBlock = BlockTestUtil.createBlock(); mutableBlock.setPreviousBlockHash(block02Hash); // Create a transaction that will be spent in the test's signed transaction. // This transaction will create an output that can be spent by the test's private key. final Transaction transactionToSpend = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(privateKey); mutableBlock.addTransaction(transactionToSpend); fakeBlock03 = mutableBlock; } final Transaction signedTransactionSpendingBlock03CoinbaseA; final Transaction signedTransactionSpendingBlock03CoinbaseB; { final AddressInflater addressInflater = new AddressInflater(); final Transaction transactionToSpend = fakeBlock03.getCoinbaseTransaction(); // Create an unsigned transaction that spends the test's previous transaction, and send the test's payment to an irrelevant address. final Transaction unsignedTransactionA; { final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); final TransactionOutputIdentifier transactionOutputIdentifierToSpend = new TransactionOutputIdentifier(transactionToSpend.getHash(), 0); final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(transactionOutputIdentifierToSpend); mutableTransaction.addTransactionInput(transactionInput); final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput( addressInflater.fromPrivateKey(PrivateKey.createNewKey(), false) ); mutableTransaction.addTransactionOutput(transactionOutput); unsignedTransactionA = mutableTransaction; } // Create an unsigned transaction that spends the test's previous transaction, and send the test's payment to an irrelevant address. final Transaction unsignedTransactionB; { final MutableTransaction mutableTransaction = TransactionTestUtil.createTransaction(); final TransactionOutputIdentifier transactionOutputIdentifierToSpend = new TransactionOutputIdentifier(transactionToSpend.getHash(), 0); final TransactionInput transactionInput = TransactionTestUtil.createTransactionInput(transactionOutputIdentifierToSpend); mutableTransaction.addTransactionInput(transactionInput); final TransactionOutput transactionOutput = TransactionTestUtil.createTransactionOutput( addressInflater.fromPrivateKey(PrivateKey.createNewKey(), false) ); mutableTransaction.addTransactionOutput(transactionOutput); unsignedTransactionB = mutableTransaction; } { final TransactionOutputRepository transactionOutputRepository = TransactionTestUtil.createTransactionOutputRepository(transactionToSpend); signedTransactionSpendingBlock03CoinbaseA = TransactionTestUtil.signTransaction(transactionOutputRepository, unsignedTransactionA, privateKey); } { final TransactionOutputRepository transactionOutputRepository = TransactionTestUtil.createTransactionOutputRepository(transactionToSpend); signedTransactionSpendingBlock03CoinbaseB = TransactionTestUtil.signTransaction(transactionOutputRepository, unsignedTransactionB, privateKey); } Assert.assertNotEquals(signedTransactionSpendingBlock03CoinbaseA.getHash(), signedTransactionSpendingBlock03CoinbaseB.getHash()); // Sanity check to ensure they are different transactions... { // Ensure the transactions would normally be valid on their own... final FakeUnspentTransactionOutputContext unspentTransactionOutputContext = new FakeUnspentTransactionOutputContext(); unspentTransactionOutputContext.addTransaction(transactionToSpend, null, 4L, false); final TransactionValidatorContext transactionValidatorContext = new TransactionValidatorContext(transactionInflaters, new MutableNetworkTime(), FakeStaticMedianBlockTimeContext.MAX_MEDIAN_BLOCK_TIME, unspentTransactionOutputContext); final TransactionValidator transactionValidator = new TransactionValidatorCore(transactionValidatorContext); { final TransactionValidationResult transactionValidationResult = transactionValidator.validateTransaction(4L, signedTransactionSpendingBlock03CoinbaseA); Assert.assertTrue(transactionValidationResult.isValid); } { final TransactionValidationResult transactionValidationResult = transactionValidator.validateTransaction(4L, signedTransactionSpendingBlock03CoinbaseB); Assert.assertTrue(transactionValidationResult.isValid); } } } final Block fakeBlock04; { // Spend the coinbase twice from different transactions within the same block... final MutableBlock mutableBlock = BlockTestUtil.createBlock(); mutableBlock.setPreviousBlockHash(block02Hash); final Transaction regularCoinbaseTransaction = TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(PrivateKey.createNewKey()); mutableBlock.addTransaction(regularCoinbaseTransaction); mutableBlock.addTransaction(signedTransactionSpendingBlock03CoinbaseA); mutableBlock.addTransaction(signedTransactionSpendingBlock03CoinbaseB); fakeBlock04 = mutableBlock; } try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final FullNodePendingBlockDatabaseManager pendingBlockDatabaseManager = databaseManager.getPendingBlockDatabaseManager(); for (final String blockData : new String[]{ BlockData.MainChain.GENESIS_BLOCK, BlockData.MainChain.BLOCK_1, BlockData.MainChain.BLOCK_2 }) { final Block block = blockInflater.fromBytes(HexUtil.hexStringToByteArray(blockData)); pendingBlockDatabaseManager.storeBlock(block); } for (final Block block : new Block[] { fakeBlock03, fakeBlock04 }) { pendingBlockDatabaseManager.storeBlock(block); } } // NOTE: The blockchainBuilder checks for the Genesis block upon instantiation. final BlockchainBuilder blockchainBuilder = new BlockchainBuilder(blockchainBuilderContext, blockProcessor, pendingBlockLoader, BlockchainBuilderTests.FAKE_DOWNLOAD_STATUS_MONITOR, BlockchainBuilderTests.FAKE_BLOCK_DOWNLOAD_REQUESTER); // Action blockchainBuilder.start(); Thread.sleep(1000L); blockchainBuilder.stop(); // Assert try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockchainDatabaseManager blockchainDatabaseManager = databaseManager.getBlockchainDatabaseManager(); final BlockchainSegmentId mainBlockchainSegmentId = blockchainDatabaseManager.getHeadBlockchainSegmentId(); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 0L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 1L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 2L)); Assert.assertNotNull(blockHeaderDatabaseManager.getBlockIdAtHeight(mainBlockchainSegmentId, 3L)); final BlockId block04Id = blockHeaderDatabaseManager.getBlockHeaderId(fakeBlock04.getHash()); final FullNodeBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final Boolean block04WasValid = blockDatabaseManager.hasTransactions(block04Id); Assert.assertFalse(block04WasValid); { // Assert the Block03 coinbase is still in the UTXO set since Block04 was invalid. final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = databaseManager.getUnspentTransactionOutputDatabaseManager(); final Transaction transaction = fakeBlock03.getCoinbaseTransaction(); final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transaction.getHash(), 0); final TransactionOutput unspentTransactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(transactionOutputIdentifier); Assert.assertNotNull(unspentTransactionOutput); } } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/slp/validator/HashMapSlpTransactionValidationCache.java<|end_filename|> package com.softwareverde.bitcoin.slp.validator; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import java.util.HashMap; public class HashMapSlpTransactionValidationCache implements SlpTransactionValidationCache { protected final HashMap<Sha256Hash, Boolean> _validatedTransactions = new HashMap<Sha256Hash, Boolean>(); @Override public Boolean isValid(final Sha256Hash transactionHash) { return _validatedTransactions.get(transactionHash); } @Override public void setIsValid(final Sha256Hash transactionHash, final Boolean isValid) { _validatedTransactions.put(transactionHash, isValid); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/core/BlockHeaderDownloaderContext.java<|end_filename|> package com.softwareverde.bitcoin.context.core; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.manager.BitcoinNodeManager; import com.softwareverde.bitcoin.server.module.node.sync.BlockHeaderDownloader; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.network.time.VolatileNetworkTime; import com.softwareverde.util.type.time.SystemTime; public class BlockHeaderDownloaderContext implements BlockHeaderDownloader.Context { protected final BitcoinNodeManager _nodeManager; protected final DatabaseManagerFactory _databaseManagerFactory; protected final VolatileNetworkTime _networkTime; protected final SystemTime _systemTime; protected final ThreadPool _threadPool; public BlockHeaderDownloaderContext(final BitcoinNodeManager nodeManager, final DatabaseManagerFactory databaseManagerFactory, final VolatileNetworkTime networkTime, final SystemTime systemTime, final ThreadPool threadPool) { _nodeManager = nodeManager; _databaseManagerFactory = databaseManagerFactory; _networkTime = networkTime; _systemTime = systemTime; _threadPool = threadPool; } @Override public DatabaseManagerFactory getDatabaseManagerFactory() { return _databaseManagerFactory; } @Override public VolatileNetworkTime getNetworkTime() { return _networkTime; } @Override public BitcoinNodeManager getBitcoinNodeManager() { return _nodeManager; } @Override public SystemTime getSystemTime() { return _systemTime; } @Override public ThreadPool getThreadPool() { return _threadPool; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/inflater/BlockHeaderInflaters.java<|end_filename|> package com.softwareverde.bitcoin.inflater; import com.softwareverde.bitcoin.block.header.BlockHeaderDeflater; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; public interface BlockHeaderInflaters extends Inflater { BlockHeaderInflater getBlockHeaderInflater(); BlockHeaderDeflater getBlockHeaderDeflater(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/manager/FilterType.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager; public enum FilterType { KEEP_NODES_WITH_INVENTORY, KEEP_NODES_WITHOUT_INVENTORY } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/script/ScriptBuilderTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script; import com.softwareverde.bitcoin.test.util.TestUtil; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.opcode.Operation; import com.softwareverde.constable.list.List; import com.softwareverde.util.HexUtil; import org.junit.Assert; import org.junit.Test; public class ScriptBuilderTests { @Test public void should_recreate_pay_to_address_script() { // Setup final String address = "1ACFXTz7v92dK2ymZ5VDGQE5vZKhF82DVd"; final TransactionInflater transactionInflater = new TransactionInflater(); final byte[] expectedTransactionBytes = HexUtil.hexStringToByteArray("01000000019E4FC764B63B143FD65296E9163D193F4053459518939ECD608C0D1E29DC5F7F050000006B4830450221008D33C6CFA30A8F3DDA347CD307B7EB2BDBC8492057F377455DA70E298BE67ACB02203F5332199E677FC9646724C4A78C2A2A090B3732B848A0DD0995E5FBE0AC0B16012102D7C2342ED6EF6E9DB7FEC62E14358FFBDC661C42AE9EF34D7BD52413E89512B0FFFFFFFF010AD92800000000001976A91464D9D52CA7CE4D4B73919A7F078921A94ACDDBAB88AC00000000"); final Transaction expectedTransaction = transactionInflater.fromBytes(expectedTransactionBytes); final TransactionOutput expectedTransactionOutput = expectedTransaction.getTransactionOutputs().get(0); final Script expectedLockingScript = expectedTransactionOutput.getLockingScript(); final List<Operation> expectedOperations = expectedLockingScript.getOperations(); // Action final Script lockingScript = ScriptBuilder.payToAddress(address); // Assert final List<Operation> operations = lockingScript.getOperations(); for (int i = 0; i < operations.getCount(); ++i) { final Operation operation = operations.get(i); final Operation expectedOperation = expectedOperations.get(i); Assert.assertEquals(expectedOperation, operation); } TestUtil.assertEqual(expectedLockingScript.getBytes().getBytes(), lockingScript.getBytes().getBytes()); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/database/FakeBlockHeaderDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.test.fake.database; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.work.ChainWork; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.chain.time.MutableMedianBlockTime; import com.softwareverde.bitcoin.server.configuration.CheckpointConfiguration; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.BlockRelationship; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.MedianBlockTimeDatabaseManagerUtil; import com.softwareverde.bitcoin.server.module.node.database.block.header.fullnode.FullNodeBlockHeaderDatabaseManager; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import java.util.Map; public interface FakeBlockHeaderDatabaseManager extends BlockHeaderDatabaseManager { static MutableMedianBlockTime newInitializedMedianBlockTime(final BlockHeaderDatabaseManager blockDatabaseManager, final Sha256Hash headBlockHash) throws DatabaseException { return FakeFullNodeBlockHeaderDatabaseManager.newInitializedMedianBlockTime(blockDatabaseManager, headBlockHash); } @Override default BlockId insertBlockHeader(final BlockHeader blockHeader) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default void updateBlockHeader(final BlockId blockId, final BlockHeader blockHeader) throws DatabaseException { } @Override default BlockId storeBlockHeader(final BlockHeader blockHeader) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default List<BlockId> insertBlockHeaders(final List<BlockHeader> blockHeaders) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default void setBlockByteCount(final BlockId blockId, final Integer byteCount) throws DatabaseException { } @Override default Integer getBlockByteCount(final BlockId blockId) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default Sha256Hash getHeadBlockHeaderHash() throws DatabaseException { throw new UnsupportedOperationException(); } @Override default BlockId getHeadBlockHeaderId() throws DatabaseException { throw new UnsupportedOperationException(); } @Override default BlockId getBlockHeaderId(final Sha256Hash blockHash) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default BlockHeader getBlockHeader(final BlockId blockId) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default Boolean blockHeaderExists(final Sha256Hash blockHash) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default Integer getBlockDirectDescendantCount(final BlockId blockId) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default void setBlockchainSegmentId(final BlockId blockId, final BlockchainSegmentId blockchainSegmentId) throws DatabaseException { } @Override default BlockchainSegmentId getBlockchainSegmentId(final BlockId blockId) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default Long getBlockHeight(final BlockId blockId) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default Long getBlockTimestamp(final BlockId blockId) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default BlockId getChildBlockId(final BlockchainSegmentId blockchainSegmentId, final BlockId previousBlockId) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default Boolean hasChildBlock(final BlockId blockId) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default Boolean isBlockConnectedToChain(final BlockId blockId, final BlockchainSegmentId blockchainSegmentId, final BlockRelationship blockRelationship) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default Sha256Hash getBlockHash(final BlockId blockId) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default List<Sha256Hash> getBlockHashes(final List<BlockId> blockIds) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default BlockId getAncestorBlockId(final BlockId blockId, final Integer parentCount) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default MutableMedianBlockTime calculateMedianBlockHeaderTime() throws DatabaseException { throw new UnsupportedOperationException(); } @Override default MutableMedianBlockTime calculateMedianBlockTime(final BlockId blockId) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default ChainWork getChainWork(final BlockId blockId) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default BlockId getBlockIdAtHeight(final BlockchainSegmentId blockchainSegmentId, final Long blockHeight) throws DatabaseException { throw new UnsupportedOperationException(); } @Override default Map<BlockId, Long> getBlockHeights(List<BlockId> blockIds) throws DatabaseException { throw new UnsupportedOperationException(); } } class FakeFullNodeBlockHeaderDatabaseManager extends FullNodeBlockHeaderDatabaseManager { public static MutableMedianBlockTime newInitializedMedianBlockTime(final BlockHeaderDatabaseManager blockDatabaseManager, final Sha256Hash headBlockHash) throws DatabaseException { return MedianBlockTimeDatabaseManagerUtil.calculateMedianBlockTime(blockDatabaseManager, headBlockHash); } public FakeFullNodeBlockHeaderDatabaseManager(final DatabaseManager databaseManager, final CheckpointConfiguration checkpointConfiguration) { super(databaseManager, checkpointConfiguration); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/wallet/PaymentAmount.java<|end_filename|> package com.softwareverde.bitcoin.wallet; import com.softwareverde.bitcoin.address.Address; public class PaymentAmount { public final Address address; public final Long amount; public PaymentAmount(final Address address, final Long amount) { this.address = address; this.amount = amount; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/util/bytearray/ByteArrayReader.java<|end_filename|> package com.softwareverde.bitcoin.util.bytearray; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.bytearray.Endian; public class ByteArrayReader extends com.softwareverde.util.bytearray.ByteArrayReader { public static class VariableSizedInteger { public final long value; public final int bytesConsumedCount; public VariableSizedInteger(final long value, final int byteCount) { this.value = value; this.bytesConsumedCount = byteCount; } } protected VariableSizedInteger _peakVariableSizedInteger(final int index) { final int prefix = ByteUtil.byteToInteger(_getByte(index)); if (prefix < 0xFD) { return new VariableSizedInteger(prefix, 1); } if (prefix < 0xFE) { final long value = ByteUtil.bytesToLong(_getBytes(index+1, 2, Endian.LITTLE)); return new VariableSizedInteger(value, 3); } if (prefix < 0xFF) { final long value = ByteUtil.bytesToLong(_getBytes(index+1, 4, Endian.LITTLE)); return new VariableSizedInteger(value, 5); } final long value = ByteUtil.bytesToLong(_getBytes(index+1, 8, Endian.LITTLE)); return new VariableSizedInteger(value, 9); } public ByteArrayReader(final byte[] bytes) { super(bytes); } public ByteArrayReader(final ByteArray byteArray) { super(byteArray); } public Long readVariableSizedInteger() { final VariableSizedInteger variableSizedInteger = _peakVariableSizedInteger(_index); _index += variableSizedInteger.bytesConsumedCount; return variableSizedInteger.value; } public VariableSizedInteger peakVariableSizedInteger() { return _peakVariableSizedInteger(_index); } public String readVariableLengthString() { final VariableSizedInteger stringByteCount = _peakVariableSizedInteger(_index); _index += stringByteCount.bytesConsumedCount; if (stringByteCount.value > Integer.MAX_VALUE) { return ""; } final byte[] stringBytes = _consumeBytes((int) stringByteCount.value, Endian.BIG); return new String(stringBytes); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/block/BlockDeflaterTests.java<|end_filename|> package com.softwareverde.bitcoin.block; import com.softwareverde.bitcoin.test.util.TestUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.util.HexUtil; import com.softwareverde.util.IoUtil; import org.junit.Assert; import org.junit.Test; public class BlockDeflaterTests { @Test public void should_deflate_inflated_block_29664() { // Setup final BlockInflater blockInflater = new BlockInflater(); final BlockDeflater blockDeflater = new BlockDeflater(); final byte[] expectedBytes = HexUtil.hexStringToByteArray(IoUtil.getResource("/blocks/00000000AFE94C578B4DC327AA64E1203283C5FD5F152CE886341766298CF523")); final Block block = blockInflater.fromBytes(expectedBytes); // Action final ByteArray blockBytes = blockDeflater.toBytes(block); // Assert TestUtil.assertEqual(expectedBytes, blockBytes.getBytes()); } @Test public void should_calculate_correct_byte_count_for_block() { // Setup final BlockInflater blockInflater = new BlockInflater(); final BlockDeflater blockDeflater = new BlockDeflater(); final byte[] expectedBytes = HexUtil.hexStringToByteArray(IoUtil.getResource("/blocks/00000000000000000051CFB8C9B8191EC4EF14F8F44F3E2290D67A8A0A29DD05")); final Block block = blockInflater.fromBytes(expectedBytes); final Integer expectedByteCount = 999150; // Action final Integer toBytesByteCount = blockDeflater.toBytes(block).getByteCount(); final Integer getByteCountByteCount = blockDeflater.getByteCount(block); final Integer blockGetByteCount = block.getByteCount(); // Assert Assert.assertEquals(expectedByteCount, toBytesByteCount); Assert.assertEquals(expectedByteCount, getByteCountByteCount); Assert.assertEquals(expectedByteCount, blockGetByteCount); } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/pool/PoolWorkerApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint.pool; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiEndpoint; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumDataHandler; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.json.Json; public class PoolWorkerApi extends StratumApiEndpoint { protected final StratumDataHandler _stratumDataHandler; public PoolWorkerApi(final StratumProperties stratumProperties, final StratumDataHandler stratumDataHandler) { super(stratumProperties); _stratumDataHandler = stratumDataHandler; } @Override protected Response _onRequest(final Request request) { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); { // GET PROTOTYPE BLOCK // Requires GET: // Requires POST: final Block prototypeBlock = _stratumDataHandler.getPrototypeBlock(); final Json prototypeBlockJson = prototypeBlock.toJson(); final StratumApiResult prototypeBlockResult = new StratumApiResult(); prototypeBlockResult.setWasSuccess(true); prototypeBlockResult.put("block", prototypeBlockJson); return new JsonResponse(Response.Codes.OK, prototypeBlockResult); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/ThreadPoolContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.concurrent.pool.ThreadPool; public interface ThreadPoolContext { ThreadPool getThreadPool(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/jni/NativeSecp256k1.java<|end_filename|> /* * Copyright 2013 Google Inc. * Copyright 2014-2016 the libsecp256k1 contributors * Copyright 2018 Software Verde, LLC <<EMAIL>> * * 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.softwareverde.bitcoin.jni; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.logging.Logger; import com.softwareverde.util.SystemUtil; import com.softwareverde.util.jni.NativeUtil; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import static org.bitcoin.NativeSecp256k1.secp256k1_destroy_context; import static org.bitcoin.NativeSecp256k1.secp256k1_ecdsa_verify; import static org.bitcoin.Secp256k1Context.secp256k1_init_context; // NOTE: The last time this message was updated, the included secp256k1 library was built from git hash: 452d8e4 /** * <p>This class holds native methods to handle ECDSA verification.</p> * * <p>You can find an example library that can be used for this at https://github.com/bitcoin/secp256k1</p> * * <p>To recompile libsecp256k1 for use with java, ensure JAVA_HOME is set, run * `./autogen.sh` * `./configure --enable-jni --enable-experimental --enable-module-ecdh` * and `make`. * Then, copy `.libs/libsecp256k1.*` to `src/main/resources/lib`. * </p> */ public class NativeSecp256k1 { private static final boolean _libraryLoadedCorrectly; private static final long _context; private static final ReentrantReadWriteLock _reentrantReadWriteLock = new ReentrantReadWriteLock(); private static final Lock _readLock = _reentrantReadWriteLock.readLock(); private static final Lock _writeLock = _reentrantReadWriteLock.writeLock(); private static final ThreadLocal<ByteBuffer> _nativeECDSABuffer = new ThreadLocal<ByteBuffer>(); static { boolean isEnabled = true; long contextRef = -1; try { final String extension; { if (SystemUtil.isWindowsOperatingSystem()) { extension = "dll"; } else if (SystemUtil.isMacOperatingSystem()) { extension = "dylib"; } else { extension = "so"; } } NativeUtil.loadLibraryFromJar("/lib/libsecp256k1." + extension); contextRef = secp256k1_init_context(); } catch (final Throwable exception) { Logger.debug("NOTICE: libsecp256k1 failed to load.", exception); isEnabled = false; } _libraryLoadedCorrectly = isEnabled; _context = contextRef; } protected static ByteBuffer _getByteBuffer() { ByteBuffer byteBuff = _nativeECDSABuffer.get(); if ((byteBuff == null) || (byteBuff.capacity() < 520)) { byteBuff = ByteBuffer.allocateDirect(520); byteBuff.order(ByteOrder.nativeOrder()); _nativeECDSABuffer.set(byteBuff); } return byteBuff; } public static boolean isEnabled() { return _libraryLoadedCorrectly; } public static long getContext() { return _context; } /** * Verifies the given secp256k1 signature in native code. * * @param data The data which was signed, must be exactly 32 bytes * @param signatureBytes The signature * @param publicKeyBytes The public key which did the signing */ public static boolean verifySignature(final ByteArray data, final ByteArray signatureBytes, final ByteArray publicKeyBytes) { final int dataByteCount = data.getByteCount(); final int signatureByteCount = signatureBytes.getByteCount(); final int publicKeyByteCount = publicKeyBytes.getByteCount(); if (dataByteCount != 32) { throw new RuntimeException("Invalid data length. Required 32 bytes; found "+ dataByteCount + " bytes."); } if (! _libraryLoadedCorrectly) { throw new RuntimeException("Cannot run NativeSecp256k1. Library failed to load."); } final ByteBuffer byteBuffer = _getByteBuffer(); byteBuffer.rewind(); int writeIndex = 0; for (int i = 0; i < dataByteCount; ++i) { byteBuffer.put(writeIndex, data.getByte(i)); writeIndex += 1; } for (int i = 0; i < signatureByteCount; ++i) { byteBuffer.put(writeIndex, signatureBytes.getByte(i)); writeIndex += 1; } for (int i = 0; i < publicKeyByteCount; ++i) { byteBuffer.put(writeIndex, publicKeyBytes.getByte(i)); writeIndex += 1; } _readLock.lock(); try { return (secp256k1_ecdsa_verify(byteBuffer, _context, signatureByteCount, publicKeyByteCount) == 1); } finally { _readLock.unlock(); } } public static boolean verifySignature(final byte[] data, final byte[] signature, final byte[] publicKey) { return NativeSecp256k1.verifySignature(ByteArray.wrap(data), ByteArray.wrap(signature), ByteArray.wrap(publicKey)); } /** * libsecp256k1 Cleanup - This destroys the secp256k1 context object. * This should be called at the end of the program for proper cleanup of the context. */ public static synchronized void shutdown() { _writeLock.lock(); try { secp256k1_destroy_context(_context); } finally { _writeLock.unlock(); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/error/ErrorMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.error; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.util.bytearray.Endian; public class ErrorMessageInflater extends BitcoinProtocolMessageInflater { @Override public ErrorMessage fromBytes(final byte[] bytes) { final ErrorMessage errorMessage = new ErrorMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.ERROR); if (protocolMessageHeader == null) { return null; } final ErrorMessage.RejectMessageType rejectMessageType = ErrorMessage.RejectMessageType.fromString(byteArrayReader.readVariableLengthString()); final byte rejectCode = byteArrayReader.readByte(); errorMessage._rejectCode = ErrorMessage.RejectCode.fromData(rejectMessageType, rejectCode); errorMessage._rejectDescription = byteArrayReader.readVariableLengthString(); errorMessage._extraData = byteArrayReader.readBytes(byteArrayReader.remainingByteCount(), Endian.LITTLE); // if (byteArrayReader.didOverflow()) { return null; } return errorMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/sync/blockloader/PreloadedPendingBlock.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync.blockloader; import com.softwareverde.bitcoin.context.core.MutableUnspentTransactionOutputSet; import com.softwareverde.bitcoin.server.module.node.sync.block.pending.PendingBlock; public interface PreloadedPendingBlock { PendingBlock getPendingBlock(); MutableUnspentTransactionOutputSet getUnspentTransactionOutputSet(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/indexer/BlockchainIndexerDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.indexer; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.constable.list.List; import com.softwareverde.database.DatabaseException; public interface BlockchainIndexerDatabaseManager { List<TransactionId> getTransactionIds(BlockchainSegmentId blockchainSegmentId, Address address, Boolean includeUnconfirmedTransactions) throws DatabaseException; Long getAddressBalance(BlockchainSegmentId blockchainSegmentId, Address address) throws DatabaseException; SlpTokenId getSlpTokenId(TransactionId transactionId) throws DatabaseException; List<TransactionId> getSlpTransactionIds(SlpTokenId slpTokenId) throws DatabaseException; void queueTransactionsForProcessing(List<TransactionId> transactionIds) throws DatabaseException; List<TransactionId> getUnprocessedTransactions(Integer batchSize) throws DatabaseException; void dequeueTransactionsForProcessing(List<TransactionId> transactionIds) throws DatabaseException; void indexTransactionOutputs(List<TransactionId> transactionIds, List<Integer> outputIndexes, List<Long> amounts, List<ScriptType> scriptTypes, List<Address> addresses, List<TransactionId> slpTransactionIds) throws DatabaseException; void indexTransactionInputs(List<TransactionId> transactionIds, List<Integer> inputIndexes, List<TransactionOutputId> transactionOutputIds) throws DatabaseException; } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/handler/BlockInventoryMessageHandlerUtil.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.handler; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; public class BlockInventoryMessageHandlerUtil { public interface BlockIdStore { BlockId getBlockId(Sha256Hash blockHash) throws Exception; } public static class NodeInventory { public final Long blockHeight; public final Sha256Hash blockHash; public NodeInventory(final Long blockHeight, final Sha256Hash blockHash) { this.blockHeight = blockHeight; this.blockHash = blockHash; } } public static NodeInventory getHeadBlockInventory(final Long blockHeightOfFirstBlockHash, final List<Sha256Hash> blockHashes, final BlockIdStore blockIdStore) throws Exception { final int blockHashCount = blockHashes.getCount(); int lookupCount = 0; int i = (blockHashCount / 2); int maxPivotIndex = (blockHashCount - 1); int minPivotIndex = 0; final int indexOfFirstUnknown; while (true) { lookupCount += 1; final int index = i; final Sha256Hash blockHash = blockHashes.get(index); final BlockId blockId = blockIdStore.getBlockId(blockHash); boolean indexIsGreaterThanOrEqualToCorrectIndex = (blockId == null); Logger.trace(minPivotIndex + " <= " + index + " <= " + maxPivotIndex + " (" + indexIsGreaterThanOrEqualToCorrectIndex + ")"); if (indexIsGreaterThanOrEqualToCorrectIndex) { maxPivotIndex = index; } else { minPivotIndex = index; } if ((maxPivotIndex - minPivotIndex) <= 1) { final Sha256Hash minIndexBlockHash = blockHashes.get(minPivotIndex); final BlockId minIndexBlockId = blockIdStore.getBlockId(minIndexBlockHash); final boolean minIndexIsCorrectIndex = (minIndexBlockId == null); if (minIndexIsCorrectIndex) { indexOfFirstUnknown = minPivotIndex; } else { indexOfFirstUnknown = (indexIsGreaterThanOrEqualToCorrectIndex ? index : maxPivotIndex); } break; } i = ((minPivotIndex + maxPivotIndex) / 2); } Logger.trace("Lookup Count: " + lookupCount); final Long blockHeight = (blockHeightOfFirstBlockHash + indexOfFirstUnknown); final Sha256Hash blockHash = blockHashes.get(indexOfFirstUnknown); return new NodeInventory(blockHeight, blockHash); } protected BlockInventoryMessageHandlerUtil() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/node/ExtraThinBlockParameters.java<|end_filename|> package com.softwareverde.bitcoin.server.node; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; public class ExtraThinBlockParameters { public final BlockHeader blockHeader; public final List<ByteArray> transactionHashes; public final List<Transaction> transactions; public ExtraThinBlockParameters(final BlockHeader blockHeader, final List<ByteArray> transactionHashes, final List<Transaction> transactions) { this.blockHeader = blockHeader; this.transactionHashes = transactionHashes; this.transactions = transactions; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/lazy/CachingMedianBlockTimeContext.java<|end_filename|> package com.softwareverde.bitcoin.context.lazy; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.context.MedianBlockTimeContext; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; import java.util.HashMap; public class CachingMedianBlockTimeContext implements MedianBlockTimeContext { protected final BlockchainSegmentId _blockchainSegmentId; protected final DatabaseManager _databaseManager; protected final HashMap<Long, BlockId> _blockIds = new HashMap<Long, BlockId>(); protected final HashMap<Long, MedianBlockTime> _medianBlockTimes = new HashMap<Long, MedianBlockTime>(); protected BlockId _getBlockId(final Long blockHeight) throws DatabaseException { { // Check for a cached BlockId... final BlockId blockId = _blockIds.get(blockHeight); if (blockId != null) { return blockId; } } final BlockHeaderDatabaseManager blockHeaderDatabaseManager = _databaseManager.getBlockHeaderDatabaseManager(); final BlockId blockId = blockHeaderDatabaseManager.getBlockIdAtHeight(_blockchainSegmentId, blockHeight); if (blockId != null) { _blockIds.put(blockHeight, blockId); } return blockId; } public CachingMedianBlockTimeContext(final BlockchainSegmentId blockchainSegmentId, final DatabaseManager databaseManager) { _blockchainSegmentId = blockchainSegmentId; _databaseManager = databaseManager; } @Override public MedianBlockTime getMedianBlockTime(final Long blockHeight) { { // Check for a cached value... final MedianBlockTime medianBlockTime = _medianBlockTimes.get(blockHeight); if (medianBlockTime != null) { return medianBlockTime; } } try { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = _databaseManager.getBlockHeaderDatabaseManager(); final BlockId blockId = _getBlockId(blockHeight); if (blockId == null) { return null; } final MedianBlockTime medianBlockTime = blockHeaderDatabaseManager.getMedianBlockTime(blockId); _medianBlockTimes.put(blockHeight, medianBlockTime); return medianBlockTime; } catch (final DatabaseException exception) { Logger.debug(exception); return null; } } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/pool/PoolHashRateApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint.pool; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiEndpoint; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumDataHandler; import com.softwareverde.http.HttpMethod; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; public class PoolHashRateApi extends StratumApiEndpoint { protected final StratumDataHandler _stratumDataHandler; public PoolHashRateApi(final StratumProperties stratumProperties, final StratumDataHandler stratumDataHandler) { super(stratumProperties); _stratumDataHandler = stratumDataHandler; } @Override protected Response _onRequest(final Request request) { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); if (request.getMethod() != HttpMethod.GET) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid method.")); } { // GET POOL HASH RATE // Requires GET: // Requires POST: final Long hashesPerSecond = _stratumDataHandler.getHashesPerSecond(); final StratumApiResult apiResult = new StratumApiResult(); apiResult.setWasSuccess(true); apiResult.put("hashesPerSecond", hashesPerSecond); return new JsonResponse(Response.Codes.OK, apiResult); } } } <|start_filename|>src/main/java/com/softwareverde/network/socket/JsonProtocolMessage.java<|end_filename|> package com.softwareverde.network.socket; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.json.Json; import com.softwareverde.json.Jsonable; import com.softwareverde.network.p2p.message.ProtocolMessage; import com.softwareverde.util.StringUtil; public class JsonProtocolMessage implements ProtocolMessage { protected final Json _message; public JsonProtocolMessage(final Json json) { _message = json; } public JsonProtocolMessage(final Jsonable jsonable) { _message = jsonable.toJson(); } public Json getMessage() { return _message; } @Override public ByteArray getBytes() { final String messageWithNewline; { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(_message); stringBuilder.append("\n"); messageWithNewline = stringBuilder.toString(); } return MutableByteArray.wrap(StringUtil.stringToBytes(messageWithNewline)); } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/v1/post/SubmitTransactionHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.v1.post; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.bitcoin.server.module.explorer.api.endpoint.TransactionsApi; import com.softwareverde.bitcoin.server.module.node.rpc.NodeJsonRpcConnection; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.http.server.servlet.routed.RequestHandler; import com.softwareverde.json.Json; import com.softwareverde.util.HexUtil; import java.util.Map; public class SubmitTransactionHandler implements RequestHandler<Environment> { /** * SUBMIT TRANSACTION TO NETWORK * Requires GET: * Requires POST: transactionData */ @Override public Response handleRequest(final Request request, final Environment environment, final Map<String, String> parameters) throws Exception { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); final ByteArray transactionData = (postParameters.containsKey("transactionData") ? MutableByteArray.wrap(HexUtil.hexStringToByteArray(postParameters.get("transactionData"))) : null); if (transactionData == null) { final TransactionsApi.SubmitTransactionResult result = new TransactionsApi.SubmitTransactionResult(); result.setWasSuccess(false); result.setErrorMessage("Invalid transaction data."); return new JsonResponse(Response.Codes.BAD_REQUEST, result); } final TransactionInflater transactionInflater = new TransactionInflater(); final Transaction transaction = transactionInflater.fromBytes(transactionData); if (transaction == null) { final TransactionsApi.SubmitTransactionResult result = new TransactionsApi.SubmitTransactionResult(); result.setWasSuccess(false); result.setErrorMessage("Invalid transaction."); return new JsonResponse(Response.Codes.BAD_REQUEST, result); } final Json rpcResponseJson; try (final NodeJsonRpcConnection nodeJsonRpcConnection = environment.getNodeJsonRpcConnection()) { if (nodeJsonRpcConnection == null) { final TransactionsApi.SubmitTransactionResult result = new TransactionsApi.SubmitTransactionResult(); result.setWasSuccess(false); result.setErrorMessage("Unable to connect to node."); return new JsonResponse(Response.Codes.SERVER_ERROR, result); } rpcResponseJson = nodeJsonRpcConnection.submitTransaction(transaction); if (rpcResponseJson == null) { return new JsonResponse(Response.Codes.SERVER_ERROR, new ApiResult(false, "Request timed out.")); } } if (! rpcResponseJson.getBoolean("wasSuccess")) { final String errorMessage = rpcResponseJson.getString("errorMessage"); return new JsonResponse(Response.Codes.SERVER_ERROR, new ApiResult(false, errorMessage)); } final TransactionsApi.SubmitTransactionResult submitTransactionResult = new TransactionsApi.SubmitTransactionResult(); submitTransactionResult.setWasSuccess(true); return new JsonResponse(Response.Codes.OK, submitTransactionResult); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/task/StratumMineBlockTaskBuilderCore.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.task; import com.softwareverde.bitcoin.block.CanonicalMutableBlock; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.bytearray.FragmentedBytes; import com.softwareverde.bitcoin.transaction.MutableTransaction; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionWithFee; import com.softwareverde.bitcoin.transaction.coinbase.CoinbaseTransaction; import com.softwareverde.bitcoin.transaction.coinbase.MutableCoinbaseTransaction; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import com.softwareverde.util.HexUtil; import com.softwareverde.util.type.time.SystemTime; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; public class StratumMineBlockTaskBuilderCore implements ConfigurableStratumMineBlockTaskBuilder { final static Object _mutex = new Object(); private static Long _nextId = 1L; protected static Long getNextId() { synchronized (_mutex) { final Long id = _nextId; _nextId += 1; return id; } } protected final SystemTime _systemTime = new SystemTime(); protected final TransactionDeflater _transactionDeflater; protected final ConcurrentHashMap<Sha256Hash, TransactionWithFee> _transactionsWithFee = new ConcurrentHashMap<Sha256Hash, TransactionWithFee>(); protected final CanonicalMutableBlock _prototypeBlock = new CanonicalMutableBlock(); protected final Integer _totalExtraNonceByteCount; protected String _extraNonce1; protected String _coinbaseTransactionHead; protected String _coinbaseTransactionTail; protected Long _blockHeight; protected final ReentrantReadWriteLock.ReadLock _prototypeBlockReadLock; protected final ReentrantReadWriteLock.WriteLock _prototypeBlockWriteLock; protected void _setCoinbaseTransaction(final Transaction coinbaseTransaction) { try { _prototypeBlockWriteLock.lock(); final FragmentedBytes coinbaseTransactionParts; coinbaseTransactionParts = _transactionDeflater.fragmentTransaction(coinbaseTransaction); // NOTE: _coinbaseTransactionHead contains the unlocking script. This script contains two items: // 1. The Coinbase Message (ex: "/Mined via Bitcoin-Verde v0.0.1/") // 2. The extraNonce (which itself is composed of two components: extraNonce1 and extraNonce2...) // extraNonce1 is usually defined by the Mining Pool, not the Miner. The Miner is sent (by the Pool) the number // of bytes it should use when generating the extraNonce2 during the Pool's response to the Miner's SUBSCRIBE message. // Despite extraNonce just being random data, it still needs to be pushed like regular data within the unlocking script. // Thus, the unlocking script is generated by pushing N bytes (0x00), where N is the byteCount of the extraNonce // (extraNonceByteCount = extraNonce1ByteCount + extraNonce2ByteCount). This results in appropriate operation code // being prepended to the script. These 0x00 bytes are omitted when stored within _coinbaseTransactionHead, // otherwise, the Miner would appending the extraNonce after the 0x00 bytes instead of replacing them... // // Therefore, assuming N is 8, the 2nd part of the unlocking script would originally look something like: // // OPCODE | EXTRA NONCE 1 | EXTRA NONCE 2 // ----------------------------------------------------- // 0x08 | 0x00 0x00 0x00 0x00 | 0x00 0x00 0x00 0x00 // // Then, stored within _coinbaseTransactionHead (to be sent to the Miner) simply as: // 0x08 | | // final Integer headByteCountExcludingExtraNonces = (coinbaseTransactionParts.headBytes.length - _totalExtraNonceByteCount); _coinbaseTransactionHead = HexUtil.toHexString(ByteUtil.copyBytes(coinbaseTransactionParts.headBytes, 0, headByteCountExcludingExtraNonces)); _coinbaseTransactionTail = HexUtil.toHexString(coinbaseTransactionParts.tailBytes); _prototypeBlock.replaceTransaction(0, coinbaseTransaction); } finally { _prototypeBlockWriteLock.unlock(); } } protected void _initPrototypeBlock() { _prototypeBlock.addTransaction(new MutableTransaction()); // NOTE: Actual nonce and timestamp are updated later within the MineBlockTask... _prototypeBlock.setTimestamp(0L); _prototypeBlock.setNonce(0L); } public StratumMineBlockTaskBuilderCore(final Integer totalExtraNonceByteCount, final TransactionDeflater transactionDeflater) { _totalExtraNonceByteCount = totalExtraNonceByteCount; _transactionDeflater = transactionDeflater; final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); _prototypeBlockReadLock = readWriteLock.readLock(); _prototypeBlockWriteLock = readWriteLock.writeLock(); _initPrototypeBlock(); } @Override public void setBlockVersion(final Long blockVersion) { try { _prototypeBlockWriteLock.lock(); _prototypeBlock.setVersion(blockVersion); } finally { _prototypeBlockWriteLock.unlock(); } } @Override public void setPreviousBlockHash(final Sha256Hash previousBlockHash) { try { _prototypeBlockWriteLock.lock(); _prototypeBlock.setPreviousBlockHash(previousBlockHash); } finally { _prototypeBlockWriteLock.unlock(); } } @Override public void setExtraNonce(final ByteArray extraNonce) { _extraNonce1 = HexUtil.toHexString(extraNonce.getBytes()); } @Override public void setDifficulty(final Difficulty difficulty) { try { _prototypeBlockWriteLock.lock(); _prototypeBlock.setDifficulty(difficulty); } finally { _prototypeBlockWriteLock.unlock(); } } @Override public void addTransaction(final TransactionWithFee transactionWithFee) { try { _prototypeBlockWriteLock.lock(); final Transaction transaction = transactionWithFee.transaction; final Long transactionFee = transactionWithFee.transactionFee; _prototypeBlock.addTransaction(transaction); _transactionsWithFee.put(transaction.getHash(), transactionWithFee); final CoinbaseTransaction coinbaseTransaction = _prototypeBlock.getCoinbaseTransaction(); final MutableCoinbaseTransaction mutableCoinbaseTransaction = new MutableCoinbaseTransaction(coinbaseTransaction); final Long currentBlockReward = coinbaseTransaction.getBlockReward(); mutableCoinbaseTransaction.setBlockReward(currentBlockReward + transactionFee); _setCoinbaseTransaction(mutableCoinbaseTransaction); } finally { _prototypeBlockWriteLock.unlock(); } } @Override public CoinbaseTransaction getCoinbaseTransaction() { return _prototypeBlock.getCoinbaseTransaction(); } @Override public void removeTransaction(final Sha256Hash transactionHash) { try { _prototypeBlockWriteLock.lock(); _prototypeBlock.removeTransaction(transactionHash); final TransactionWithFee transactionWithFee = _transactionsWithFee.get(transactionHash); if (transactionWithFee == null) { Logger.warn("Unable to remove transaction from prototype block: " + transactionHash); return; } final Long transactionFee = transactionWithFee.transactionFee; final CoinbaseTransaction coinbaseTransaction = _prototypeBlock.getCoinbaseTransaction(); final MutableCoinbaseTransaction mutableCoinbaseTransaction = new MutableCoinbaseTransaction(coinbaseTransaction); final Long currentBlockReward = coinbaseTransaction.getBlockReward(); mutableCoinbaseTransaction.setBlockReward(currentBlockReward - transactionFee); _setCoinbaseTransaction(mutableCoinbaseTransaction); } finally { _prototypeBlockWriteLock.unlock(); } } @Override public void clearTransactions() { try { _prototypeBlockWriteLock.lock(); final Transaction coinbaseTransaction = _prototypeBlock.getCoinbaseTransaction(); _prototypeBlock.clearTransactions(); _prototypeBlock.addTransaction(coinbaseTransaction); } finally { _prototypeBlockWriteLock.unlock(); } } @Override public void setCoinbaseTransaction(final Transaction coinbaseTransaction) { _setCoinbaseTransaction(coinbaseTransaction); } @Override public StratumMineBlockTask buildMineBlockTask() { try { _prototypeBlockReadLock.lock(); final ByteArray id = MutableByteArray.wrap(ByteUtil.integerToBytes(StratumMineBlockTaskBuilderCore.getNextId())); return new StratumMineBlockTask(id, _prototypeBlock, _coinbaseTransactionHead, _coinbaseTransactionTail, _extraNonce1); } finally { _prototypeBlockReadLock.unlock(); } } @Override public void setBlockHeight(final Long blockHeight) { try { _prototypeBlockWriteLock.lock(); _blockHeight = blockHeight; } finally { _prototypeBlockWriteLock.unlock(); } } @Override public Long getBlockHeight() { try { _prototypeBlockReadLock.lock(); return _blockHeight; } finally { _prototypeBlockReadLock.unlock(); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/node/ThinBlockParameters.java<|end_filename|> package com.softwareverde.bitcoin.server.node; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public class ThinBlockParameters { public final BlockHeader blockHeader; public final List<Sha256Hash> transactionHashes; public final List<Transaction> transactions; public ThinBlockParameters(final BlockHeader blockHeader, final List<Sha256Hash> transactionHashes, final List<Transaction> transactions) { this.blockHeader = blockHeader; this.transactionHashes = transactionHashes; this.transactions = transactions; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/fullnode/utxo/jvm/JvmSpentState.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.jvm; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.UnspentTransactionOutputDatabaseManager; public class JvmSpentState implements UnspentTransactionOutputDatabaseManager.SpentState { public static final int IS_SPENT_FLAG = 0x01; public static final int IS_FLUSHED_FLAG = 0x01 << 1; public static final int FORCE_FLUSH_FLAG = 0x01 << 2; public static Boolean isSpent(final int bitfield) { return ((bitfield & IS_SPENT_FLAG) != 0x00); } public static Boolean isFlushedToDisk(final int bitfield) { return ((bitfield & IS_FLUSHED_FLAG) != 0x00); } public static Boolean isFlushMandatory(final int bitfield) { return ((bitfield & FORCE_FLUSH_FLAG) != 0x00); } protected int _bitField; public JvmSpentState() { _bitField = 0x00; } public JvmSpentState(final int intValue) { _bitField = intValue; } public void initialize(final int intValue) { _bitField = intValue; } public void setIsSpent(final Boolean isSpent) { if (isSpent) { _bitField |= IS_SPENT_FLAG; } else { _bitField &= (~IS_SPENT_FLAG); } } public void setIsFlushedToDisk(final Boolean isFlushedToDisk) { if (isFlushedToDisk) { _bitField |= IS_FLUSHED_FLAG; } else { _bitField &= (~IS_FLUSHED_FLAG); } } public void setIsFlushMandatory(final Boolean isFlushedMandatory) { if (isFlushedMandatory) { _bitField |= FORCE_FLUSH_FLAG; } else { _bitField &= (~FORCE_FLUSH_FLAG); } } @Override public Boolean isSpent() { return JvmSpentState.isSpent(_bitField); } @Override public Boolean isFlushedToDisk() { return JvmSpentState.isFlushedToDisk(_bitField); } public Boolean isFlushMandatory() { return JvmSpentState.isFlushMandatory(_bitField); } public int intValue() { return _bitField; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/store/BlockStore.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.store; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.block.header.MutableBlockHeader; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface BlockStore { Boolean storeBlock(Block block, Long blockHeight); void removeBlock(Sha256Hash blockHash, Long blockHeight); MutableBlockHeader getBlockHeader(Sha256Hash blockHash, Long blockHeight); MutableBlock getBlock(Sha256Hash blockHash, Long blockHeight); ByteArray readFromBlock(Sha256Hash blockHash, Long blockHeight, Long diskOffset, Integer byteCount); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/sync/blockloader/PreloadedBlock.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync.blockloader; import com.softwareverde.bitcoin.block.Block; public interface PreloadedBlock { Long getBlockHeight(); Block getBlock(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/TransactionValidatorFactory.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.transaction.validator.BlockOutputs; import com.softwareverde.bitcoin.transaction.validator.TransactionValidator; public interface TransactionValidatorFactory { TransactionValidator getTransactionValidator(BlockOutputs blockOutputs, TransactionValidator.Context transactionValidatorContext); default TransactionValidator getUnconfirmedTransactionValidator(final TransactionValidator.Context transactionValidatorContext) { return this.getTransactionValidator(null, transactionValidatorContext); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/slp/SlpUtil.java<|end_filename|> package com.softwareverde.bitcoin.slp; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptInflater; import com.softwareverde.bitcoin.transaction.script.slp.SlpScriptType; import com.softwareverde.bitcoin.transaction.script.slp.genesis.SlpGenesisScript; import com.softwareverde.bitcoin.transaction.script.slp.mint.SlpMintScript; import com.softwareverde.bitcoin.transaction.script.slp.send.SlpSendScript; import com.softwareverde.constable.list.List; import com.softwareverde.util.Util; public class SlpUtil { /** * Returns true iff transactionOutputIdentifier points to an output containing SLP tokens. * This only includes Genesis Receiver, Baton Receiver, and Send outputs. */ public static Boolean outputContainsSpendableSlpTokens(final Transaction transaction, final Integer transactionOutputIndex) { final Long tokenAmount = SlpUtil.getOutputTokenAmount(transaction, transactionOutputIndex); return (tokenAmount > 0); } /** * Returns true iff transactionOutputIdentifier points to an output associated to SLP tokens. * This includes Batons, Commits, Genesis, and Send outputs. */ public static Boolean isSlpTokenOutput(final Transaction transaction, final Integer transactionOutputIndex) { final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final TransactionOutput transactionOutput = transactionOutputs.get(0); final LockingScript lockingScript = transactionOutput.getLockingScript(); final SlpScriptType slpScriptType = SlpScriptInflater.getScriptType(lockingScript); if (slpScriptType == null) { return false; } // Transaction is not an SLP transaction. final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); switch (slpScriptType) { case GENESIS: { // Check for the output containing genesis tokens... final Boolean isGenesisReceiver = Util.areEqual(transactionOutputIndex, SlpGenesisScript.RECEIVER_TRANSACTION_OUTPUT_INDEX); if (isGenesisReceiver) { return true; } // Check for the output being the baton... final SlpGenesisScript slpGenesisScript = slpScriptInflater.genesisScriptFromScript(lockingScript); if (slpGenesisScript == null) { return false; } final Boolean isBaton = Util.areEqual(transactionOutputIndex, slpGenesisScript.getBatonOutputIndex()); if (isBaton) { return true; } } break; case MINT: { // Check for the output containing mint tokens... final Boolean isMintReceiver = Util.areEqual(transactionOutputIndex, SlpMintScript.RECEIVER_TRANSACTION_OUTPUT_INDEX); if (isMintReceiver) { return true; } // Check for the output being the baton... final SlpMintScript slpMintScript = slpScriptInflater.mintScriptFromScript(lockingScript); if (slpMintScript == null) { return false; } final Boolean isBaton = Util.areEqual(transactionOutputIndex, slpMintScript.getBatonOutputIndex()); if (isBaton) { return true; } } break; case SEND: { // Check for the output containing tokens sent from another output... final SlpSendScript slpSendScript = slpScriptInflater.sendScriptFromScript(lockingScript); if (slpSendScript == null) { return false; } final Long tokenAmount = Util.coalesce(slpSendScript.getAmount(transactionOutputIndex)); if (tokenAmount > 0) { return true; } } break; } return false; } public static Long getOutputTokenAmount(final Transaction transaction, final Integer transactionOutputIndex) { final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final TransactionOutput transactionOutput = transactionOutputs.get(0); final LockingScript lockingScript = transactionOutput.getLockingScript(); final SlpScriptType slpScriptType = SlpScriptInflater.getScriptType(lockingScript); if (slpScriptType == null) { return 0L; } // Transaction is not an SLP transaction. final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); switch (slpScriptType) { case GENESIS: { // Check for the output containing genesis tokens... final Boolean isGenesisReceiver = Util.areEqual(transactionOutputIndex, SlpGenesisScript.RECEIVER_TRANSACTION_OUTPUT_INDEX); if (! isGenesisReceiver) { return 0L; } final SlpGenesisScript slpGenesisScript = slpScriptInflater.genesisScriptFromScript(lockingScript); if (slpGenesisScript == null) { return 0L; } return slpGenesisScript.getTokenCount(); } case MINT: { // Check for the output containing mint tokens... final Boolean isMintReceiver = Util.areEqual(transactionOutputIndex, SlpMintScript.RECEIVER_TRANSACTION_OUTPUT_INDEX); if (! isMintReceiver) { return 0L; } final SlpMintScript slpMintScript = slpScriptInflater.mintScriptFromScript(lockingScript); if (slpMintScript == null) { return 0L; } return slpMintScript.getTokenCount(); } case SEND: { // Check for the output containing tokens sent from another output... final SlpSendScript slpSendScript = slpScriptInflater.sendScriptFromScript(lockingScript); if (slpSendScript == null) { return 0L; } return Util.coalesce(slpSendScript.getAmount(transactionOutputIndex)); } } return 0L; } public static Boolean isSlpTokenBatonHolder(final Transaction transaction, final Integer transactionOutputIndex) { final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final TransactionOutput transactionOutput = transactionOutputs.get(0); final LockingScript lockingScript = transactionOutput.getLockingScript(); final SlpScriptType slpScriptType = SlpScriptInflater.getScriptType(lockingScript); if (slpScriptType == null) { return false; } // Transaction is not an SLP transaction. final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); switch (slpScriptType) { case GENESIS: { final SlpGenesisScript slpGenesisScript = slpScriptInflater.genesisScriptFromScript(lockingScript); if (slpGenesisScript == null) { return false; } return Util.areEqual(slpGenesisScript.getBatonOutputIndex(), transactionOutputIndex); } case MINT: { final SlpMintScript slpMintScript = slpScriptInflater.mintScriptFromScript(lockingScript); if (slpMintScript == null) { return false; } return Util.areEqual(slpMintScript.getBatonOutputIndex(), transactionOutputIndex); } } return false; } public static SlpTokenId getTokenId(final Transaction transaction) { final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final TransactionOutput transactionOutput = transactionOutputs.get(0); final LockingScript lockingScript = transactionOutput.getLockingScript(); final SlpScriptType slpScriptType = SlpScriptInflater.getScriptType(lockingScript); if (slpScriptType == null) { return null; } // Transaction is not an SLP transaction. final SlpScriptInflater slpScriptInflater = new SlpScriptInflater(); switch (slpScriptType) { case GENESIS: { return SlpTokenId.wrap(transaction.getHash()); } case MINT: { final SlpMintScript slpMintScript = slpScriptInflater.mintScriptFromScript(lockingScript); if (slpMintScript == null) { return null; } return slpMintScript.getTokenId(); } case SEND: { final SlpSendScript slpSendScript = slpScriptInflater.sendScriptFromScript(lockingScript); if (slpSendScript == null) { return null; } return slpSendScript.getTokenId(); } } return null; } protected SlpUtil() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/lazy/LazyReferenceBlockLoaderContext.java<|end_filename|> package com.softwareverde.bitcoin.context.lazy; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.context.ContextException; import com.softwareverde.bitcoin.context.core.AsertReferenceBlockLoader; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManager; import com.softwareverde.database.DatabaseException; public class LazyReferenceBlockLoaderContext implements AsertReferenceBlockLoader.ReferenceBlockLoaderContext { protected final BlockchainDatabaseManager _blockchainDatabaseManager; protected final BlockHeaderDatabaseManager _blockHeaderDatabaseManager; public LazyReferenceBlockLoaderContext(final DatabaseManager databaseManager) { _blockchainDatabaseManager = databaseManager.getBlockchainDatabaseManager(); _blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); } @Override public BlockId getHeadBlockIdOfBlockchainSegment(final BlockchainSegmentId blockchainSegmentId) throws ContextException { try { return _blockchainDatabaseManager.getHeadBlockIdOfBlockchainSegment(blockchainSegmentId); } catch (final DatabaseException exception) { throw new ContextException(exception); } } @Override public MedianBlockTime getMedianBlockTime(final BlockId blockId) throws ContextException { try { return _blockHeaderDatabaseManager.getMedianBlockTime(blockId); } catch (final DatabaseException exception) { throw new ContextException(exception); } } @Override public Long getBlockTimestamp(final BlockId blockId) throws ContextException { try { return _blockHeaderDatabaseManager.getBlockTimestamp(blockId); } catch (final DatabaseException exception) { throw new ContextException(exception); } } @Override public Long getBlockHeight(final BlockId blockId) throws ContextException { try { return _blockHeaderDatabaseManager.getBlockHeight(blockId); } catch (final DatabaseException exception) { throw new ContextException(exception); } } @Override public BlockId getBlockIdAtHeight(final BlockchainSegmentId blockchainSegmentId, final Long blockHeight) throws ContextException { try { return _blockHeaderDatabaseManager.getBlockIdAtHeight(blockchainSegmentId, blockHeight); } catch (final DatabaseException exception) { throw new ContextException(exception); } } @Override public Difficulty getDifficulty(final BlockId blockId) throws ContextException { try { final BlockHeader blockHeader = _blockHeaderDatabaseManager.getBlockHeader(blockId); if (blockHeader == null) { return null; } return blockHeader.getDifficulty(); } catch (final DatabaseException exception) { throw new ContextException(exception); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/locking/MutableLockingScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.locking; import com.softwareverde.bitcoin.transaction.script.MutableScript; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.bitcoin.transaction.script.ScriptPatternMatcher; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.constable.bytearray.ByteArray; public class MutableLockingScript extends MutableScript implements LockingScript { public MutableLockingScript() { super(); } public MutableLockingScript(final ByteArray bytes) { super(bytes); } public MutableLockingScript(final Script script) { super(script); } @Override public ScriptType getScriptType() { final ScriptPatternMatcher scriptPatternMatcher = new ScriptPatternMatcher(); return scriptPatternMatcher.getScriptType(this); } @Override public ImmutableLockingScript asConst() { return new ImmutableLockingScript(this); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/locking/LockingScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.locking; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.bitcoin.transaction.script.ScriptType; public interface LockingScript extends Script { LockingScript EMPTY_SCRIPT = new ImmutableLockingScript(); static LockingScript castFrom(final Script script) { return new ImmutableLockingScript(script); } ScriptType getScriptType(); @Override ImmutableLockingScript asConst(); } <|start_filename|>stratum/www/css/account.css<|end_filename|> #main .navigation { background-color: #F99400; border: solid 2px #313131; box-sizing: border-box; } #main .navigation ul { padding-inline-start: 0; } #main .navigation ul li { color: #222222; flex-grow: 1; font-size: 0.75em; line-height: 1.1em; } #main .navigation ul li i { display: block; margin-bottom: 0.25em; font-size: 2.5em; } #view-container { text-align: center; padding: 2em; background-color: #424242; } #view-container .title { text-align: center; font-size: 2em; font-weight: bold; color: #222222; margin-top: 2em; margin-bottom: 1em; } #view-container .results { font-size: 0.75em; padding: 0.25em; color: #222222; display: block; border-radius: 0.25em; /* background-color: #EEEEEE; */ margin: 2em; margin-bottom: -2em; width: calc(100% - 4em); box-sizing: border-box; text-align: center; min-height: 2.5em; padding-top: 0.75em; } #view-container .container { display: inline-block; background: #FFFFFF; padding: 2em; border-radius: 0.5em; max-width: 35em; width: calc(100% - 4em); box-shadow: 0px 2px 10px #696969; border: solid 1px #868686; } #view-container .container input { font-size: 1.5em; padding: 0.5em; color: #222222; background-color: #EEEEEE; border: solid 1px #DCDCDC; display: block; border-radius: 0.25em; margin: 2em; width: calc(100% - 4em); box-sizing: border-box; text-align: center; } #view-container .container .button { line-height: 2em; border: solid 1px #DCDCDC; background-color: #EEEEEE; font-weight: bold; font-size: 1.25em; color: #222222; width: 50%; margin: auto; margin-bottom: 1em; cursor: pointer; border-radius: 0.25em; } #view-container .container.set-address-container input.address { font-size: 1.0em; padding: 0.75em; margin-top: 3em; margin-bottom: 3em; line-height: 1.5em; } #view-container .manage-workers-container table.workers { width: 100%; border: 0; border-collapse: collapse; } #view-container .manage-workers-container table.workers th, #view-container .manage-workers-container table.workers td { border-bottom: solid 1px #EEEEEE; } #view-container .manage-workers-container table.workers tr:nth-child(even) td { background-color: #FAFAFA; } #view-container .manage-workers-container table.workers td.delete { cursor: pointer; } <|start_filename|>src/test/java/com/softwareverde/bitcoin/transaction/script/opcode/OperationTests.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode; import org.junit.Assert; import org.junit.Test; public class OperationTests { @Test public void should_not_consider_negative_2147483648_as_within_integer_range() { // Setup final Long value = -2147483648L; // Action final Boolean isWithinIntegerRange = Operation.isWithinIntegerRange(value); // Assert Assert.assertFalse(isWithinIntegerRange); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeSocket.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class FakeSocket extends Socket { public final ByteArrayInputStream inputStream; public final ByteArrayOutputStream outputStream; public FakeSocket() { inputStream = new ByteArrayInputStream(new byte[0]); outputStream = new ByteArrayOutputStream(); } public FakeSocket(final byte[] inputBytes) { inputStream = new ByteArrayInputStream(inputBytes); outputStream = new ByteArrayOutputStream(); } @Override public InputStream getInputStream() { return this.inputStream; } @Override public OutputStream getOutputStream() { return this.outputStream; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/validator/SpentOutputsTracker.java<|end_filename|> package com.softwareverde.bitcoin.transaction.validator; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.util.Util; import java.util.concurrent.ConcurrentHashMap; public class SpentOutputsTracker { protected final ConcurrentHashMap<TransactionOutputIdentifier, Boolean> _spentOutputs; public SpentOutputsTracker() { _spentOutputs = new ConcurrentHashMap<TransactionOutputIdentifier, Boolean>(256, 0.75F, 4); } /** * Instantiates a tracker to be used for determining if an output has been spent multiple times within the same block. * This tracker is thread-safe. * `threadCount` may be used to optimize concurrent threads read/writes. */ public SpentOutputsTracker(final Integer estimatedOutputCount, final Integer threadCount) { _spentOutputs = new ConcurrentHashMap<TransactionOutputIdentifier, Boolean>(estimatedOutputCount, 0.75F, threadCount); } /** * Marks the TransactionOutputIdentifier as spent. * Returns true iff the output has been spent already, otherwise returns false. */ public Boolean markOutputAsSpent(final TransactionOutputIdentifier transactionOutputIdentifier) { final Boolean wasSpent = _spentOutputs.put(transactionOutputIdentifier, true); return Util.coalesce(wasSpent, false); } public List<TransactionOutputIdentifier> getSpentOutputs() { return new ImmutableList<TransactionOutputIdentifier>(_spentOutputs.keySet()); } } <|start_filename|>src/test/java/com/softwareverde/network/p2p/node/manager/FakeThreadPool.java<|end_filename|> package com.softwareverde.network.p2p.node.manager; import com.softwareverde.concurrent.pool.MainThreadPool; public class FakeThreadPool extends MainThreadPool { public FakeThreadPool() { super(0, 0L); } @Override public void execute(final Runnable runnable) { if (runnable.toString().contains("TimeoutRunnable")) { return; // Skip running any timeout runnables... } runnable.run(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/spv/handler/MerkleBlockDownloader.java<|end_filename|> package com.softwareverde.bitcoin.server.module.spv.handler; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.block.MerkleBlock; import com.softwareverde.bitcoin.block.merkleroot.PartialMerkleTree; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.BlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.spv.SpvBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.spv.SpvDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.spv.SpvDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.transaction.spv.SpvTransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.manager.RequestBabysitter; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.bitcoin.server.node.MerkleBlockParameters; import com.softwareverde.bitcoin.server.node.RequestId; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.util.TransactionUtil; import com.softwareverde.logging.Logger; import com.softwareverde.util.Tuple; import com.softwareverde.util.Util; import com.softwareverde.util.type.time.SystemTime; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; /** * Sequentially downloads merkleBlocks received via SpvBlockInventoryMessageCallback::onResult. * Failed blocks are retried 3 times immediately, and up to 21 times total. */ public class MerkleBlockDownloader implements BitcoinNode.SpvBlockInventoryAnnouncementHandler { public interface Downloader { Tuple<RequestId, BitcoinNode> requestMerkleBlock(Sha256Hash blockHash, BitcoinNode.DownloadMerkleBlockCallback callback); } public interface DownloadCompleteCallback { void newMerkleBlockDownloaded(MerkleBlock merkleBlock, List<Transaction> transactions); } protected final SystemTime _systemTime = new SystemTime(); protected final SpvDatabaseManagerFactory _databaseManagerFactory; protected final Downloader _merkleBlockDownloader; protected final ConcurrentLinkedQueue<Sha256Hash> _queuedBlockHashes = new ConcurrentLinkedQueue<Sha256Hash>(); protected final AtomicBoolean _blockIsInFlight = new AtomicBoolean(false); protected final RequestBabysitter _requestBabysitter = new RequestBabysitter(); protected Runnable _merkleBlockProcessedCallback = null; protected DownloadCompleteCallback _downloadCompleteCallback = null; protected Long _minimumMerkleBlockHeight = 0L; protected final AtomicBoolean _isPaused = new AtomicBoolean(true); protected final BitcoinNode.DownloadMerkleBlockCallback _onMerkleBlockDownloaded = new BitcoinNode.DownloadMerkleBlockCallback() { private final ConcurrentHashMap<Sha256Hash, ConcurrentLinkedDeque<Long>> _failedDownloadTimes = new ConcurrentHashMap<Sha256Hash, ConcurrentLinkedDeque<Long>>(); protected synchronized Boolean _processMerkleBlock(final MerkleBlockParameters merkleBlockParameters) { if (merkleBlockParameters == null) { return false; } final MerkleBlock merkleBlock = merkleBlockParameters.getMerkleBlock(); if (merkleBlock == null) { return false; } final PartialMerkleTree partialMerkleTree = merkleBlock.getPartialMerkleTree(); if (partialMerkleTree == null) { return false; } final List<Transaction> transactions = merkleBlockParameters.getTransactions(); if (transactions == null) { return false; } if (! merkleBlock.isValid()) { Logger.debug("Invalid MerkleBlock received. Discarding. " + merkleBlock.getHash()); return false; } for (final Transaction transaction : transactions) { final Sha256Hash transactionHash = transaction.getHash(); if (! merkleBlock.containsTransaction(transactionHash)) { Logger.debug("MerkleBlock did not contain transaction. Block: " + merkleBlock.getHash() + " Tx: " + transactionHash); return false; } } // final UpdateBloomFilterMode updateBloomFilterMode = Util.coalesce(UpdateBloomFilterMode.valueOf(bloomFilter.getUpdateMode()), UpdateBloomFilterMode.READ_ONLY); // final TransactionBloomFilterMatcher transactionBloomFilterMatcher = new TransactionBloomFilterMatcher(bloomFilter, updateBloomFilterMode); // return transactionBloomFilterMatcher.shouldInclude(transaction); try (final SpvDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final DatabaseConnection databaseConnection = databaseManager.getDatabaseConnection(); final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final SpvBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final SpvTransactionDatabaseManager transactionDatabaseManager = databaseManager.getTransactionDatabaseManager(); TransactionUtil.startTransaction(databaseConnection); final Sha256Hash previousBlockHash = merkleBlock.getPreviousBlockHash(); if (! Util.areEqual(previousBlockHash, Sha256Hash.EMPTY_HASH)) { // Check for Genesis Block... final BlockId previousBlockId = blockHeaderDatabaseManager.getBlockHeaderId(merkleBlock.getPreviousBlockHash()); if (previousBlockId == null) { Logger.debug("NOTICE: Out of order MerkleBlock received. Discarding. " + merkleBlock.getHash()); return false; } } synchronized (BlockHeaderDatabaseManager.MUTEX) { final BlockId blockId = blockHeaderDatabaseManager.storeBlockHeader(merkleBlock); blockDatabaseManager.storePartialMerkleTree(blockId, partialMerkleTree); for (final Transaction transaction : transactions) { final TransactionId transactionId = transactionDatabaseManager.storeTransaction(transaction); blockDatabaseManager.addTransactionToBlock(blockId, transactionId); } } TransactionUtil.commitTransaction(databaseConnection); } catch (final DatabaseException exception) { Logger.warn(exception); return false; } final DownloadCompleteCallback downloadCompleteCallback = _downloadCompleteCallback; if (downloadCompleteCallback != null) { downloadCompleteCallback.newMerkleBlockDownloaded(merkleBlock, transactions); } return true; } /** * Returns true if the block download should continue from the normal download mechanism. */ protected synchronized Boolean _onFailure(final Sha256Hash merkleBlockHash) { try { Thread.sleep(5000L); } catch (final InterruptedException exception) { return false; } final Long now = _systemTime.getCurrentTimeInMilliSeconds(); ConcurrentLinkedDeque<Long> failedDownloadTimestamps = _failedDownloadTimes.get(merkleBlockHash); if (failedDownloadTimestamps == null) { failedDownloadTimestamps = new ConcurrentLinkedDeque<Long>(); _failedDownloadTimes.put(merkleBlockHash, failedDownloadTimestamps); } failedDownloadTimestamps.add(now); int totalFailureCount = 0; int recentFailureCount = 0; for (final Long failedTimestamp : failedDownloadTimestamps) { if (now - failedTimestamp > 30000L) { recentFailureCount += 1; } totalFailureCount += 1; } if (recentFailureCount <= 3) { Logger.debug("Retrying Merkle: " + merkleBlockHash); _requestMerkleBlock(merkleBlockHash); return false; } if (totalFailureCount <= 21) { // TODO: Does sequential-ness matter? // Add the block to the back of the stack and try again later... Logger.debug("Re-Queueing Merkle for Download: " + merkleBlockHash); _queuedBlockHashes.add(merkleBlockHash); } return true; } @Override public void onResult(final RequestId requestId, final BitcoinNode bitcoinNode, final MerkleBlockParameters merkleBlockParameters) { _processMerkleBlock(merkleBlockParameters); _blockIsInFlight.set(false); final Runnable merkleBlockProcessedCallback = _merkleBlockProcessedCallback; if (merkleBlockProcessedCallback != null) { merkleBlockProcessedCallback.run(); } _downloadNextMerkleBlock(); } @Override public void onFailure(final RequestId requestId, final BitcoinNode bitcoinNode, final Sha256Hash merkleBlockHash) { final Boolean shouldDownloadNextBlock = _onFailure(merkleBlockHash); if (! shouldDownloadNextBlock) { return; } // Retrying current block... _blockIsInFlight.set(false); final Runnable merkleBlockProcessedCallback = _merkleBlockProcessedCallback; if (merkleBlockProcessedCallback != null) { merkleBlockProcessedCallback.run(); } _downloadNextMerkleBlock(); } }; protected synchronized void _refillBlockHashQueue() { try (final SpvDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final SpvBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final List<BlockId> nextBlockIds = blockDatabaseManager.selectNextIncompleteBlocks(_minimumMerkleBlockHeight, 256); if (nextBlockIds.isEmpty()) { return; } final List<Sha256Hash> blockHashes = blockHeaderDatabaseManager.getBlockHashes(nextBlockIds); for (final Sha256Hash blockHash : blockHashes) { if (blockHash == null) { continue; } _queuedBlockHashes.add(blockHash); } } catch (final DatabaseException exception) { Logger.warn(exception); } } public static class WatchedRequest extends RequestBabysitter.WatchedRequest implements BitcoinNode.DownloadMerkleBlockCallback { protected RequestId _requestId; protected BitcoinNode _bitcoinNode; protected final Sha256Hash _blockHash; protected final BitcoinNode.DownloadMerkleBlockCallback _callback; public WatchedRequest(final Sha256Hash blockHash, final BitcoinNode.DownloadMerkleBlockCallback downloadMerkleBlockCallback) { _blockHash = blockHash; _callback = downloadMerkleBlockCallback; } public void setRequestInformation(final RequestId requestId, final BitcoinNode bitcoinNode) { _requestId = requestId; _bitcoinNode = bitcoinNode; } @Override public void onResult(final RequestId requestId, final BitcoinNode bitcoinNode, final MerkleBlockParameters result) { if (! this.onWatchEnded()) { return; } _callback.onResult(requestId, bitcoinNode, result); } @Override protected void onExpiration() { _callback.onFailure(_requestId, _bitcoinNode, _blockHash); } @Override public void onFailure(final RequestId requestId, final BitcoinNode bitcoinNode, final Sha256Hash blockHash) { if (! this.onWatchEnded()) { return; } _callback.onFailure(requestId, bitcoinNode, blockHash); } } protected void _requestMerkleBlock(final Sha256Hash blockHash) { Logger.debug("Downloading Merkle Block: " + blockHash); final WatchedRequest watchedRequest = new WatchedRequest(blockHash, _onMerkleBlockDownloaded); final Tuple<RequestId, BitcoinNode> requestInformation = _merkleBlockDownloader.requestMerkleBlock(blockHash, watchedRequest); watchedRequest.setRequestInformation(requestInformation.first, requestInformation.second); _requestBabysitter.watch(watchedRequest, 15L); } protected synchronized void _downloadNextMerkleBlock() { if (_isPaused.get()) { return; } if (! _blockIsInFlight.compareAndSet(false, true)) { return; } try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); while (true) { final Sha256Hash blockHash = _queuedBlockHashes.poll(); if (blockHash == null) { _refillBlockHashQueue(); if (_queuedBlockHashes.isEmpty()) { break; } else { continue; } } if (! blockDatabaseManager.hasTransactions(blockHash)) { _requestMerkleBlock(blockHash); return; } else { Logger.debug("Skipping MerkleBlock. Block already downloaded: " + blockHash); } } } catch (final DatabaseException exception) { Logger.warn(exception); } // No block ended up being requested... _blockIsInFlight.set(false); } public MerkleBlockDownloader(final SpvDatabaseManagerFactory databaseManagerFactory, final Downloader downloader) { _databaseManagerFactory = databaseManagerFactory; _merkleBlockDownloader = downloader; } public void setMinimumMerkleBlockHeight(final Long minimumMerkleBlockHeight) { _minimumMerkleBlockHeight = minimumMerkleBlockHeight; } public void resetQueue() { _queuedBlockHashes.clear(); _refillBlockHashQueue(); } public void pause() { _isPaused.set(true); } public void start() { // if (! _isPaused.compareAndSet(true, false)) { return; } _requestBabysitter.start(); _isPaused.set(false); _downloadNextMerkleBlock(); } public void setDownloadCompleteCallback(final DownloadCompleteCallback downloadCompleteCallback) { _downloadCompleteCallback = downloadCompleteCallback; } public void setMerkleBlockProcessedCallback(final Runnable merkleBlockProcessedCallback) { _merkleBlockProcessedCallback = merkleBlockProcessedCallback; } @Override public void onResult(final BitcoinNode bitcoinNode, final List<Sha256Hash> blockHashes) { for (final Sha256Hash blockHash : blockHashes) { Logger.debug("Queuing Merkle Block for download: " + blockHash); _queuedBlockHashes.add(blockHash); } _downloadNextMerkleBlock(); } public void wakeUp() { _downloadNextMerkleBlock(); } public Boolean isRunning() { return _blockIsInFlight.get(); } public void shutdown() { _requestBabysitter.stop(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/State.java<|end_filename|> package com.softwareverde.bitcoin.server; public enum State { ONLINE, SYNCHRONIZING, SHUTTING_DOWN } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/handler/SynchronizationStatusHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.handler; import com.softwareverde.bitcoin.block.BlockId; import com.softwareverde.bitcoin.server.State; import com.softwareverde.bitcoin.server.SynchronizationStatus; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.block.BlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; import com.softwareverde.util.Util; import com.softwareverde.util.type.time.SystemTime; public class SynchronizationStatusHandler implements SynchronizationStatus { protected final SystemTime _systemTime = new SystemTime(); protected final DatabaseManagerFactory _databaseManagerFactory; protected State _state = State.ONLINE; public SynchronizationStatusHandler(final DatabaseManagerFactory databaseManagerFactory) { _databaseManagerFactory = databaseManagerFactory; } public void setState(final State state) { if (! Util.areEqual(_state, state)) { Logger.info("Synchronization State: " + state); } _state = state; } @Override public State getState() { return _state; } @Override public Boolean isBlockchainSynchronized() { return (_state == State.ONLINE); } @Override public Boolean isReadyForTransactions() { return (_state == State.ONLINE); } @Override public Boolean isShuttingDown() { return (_state == State.SHUTTING_DOWN); } @Override public Long getCurrentBlockHeight() { try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BlockHeaderDatabaseManager blockHeaderDatabaseManager = databaseManager.getBlockHeaderDatabaseManager(); final BlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final BlockId blockId = blockDatabaseManager.getHeadBlockId(); if (blockId == null) { return 0L; } return blockHeaderDatabaseManager.getBlockHeight(blockId); } catch (final DatabaseException exception) { Logger.warn(exception); return 0L; } } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/endpoint/TransactionsApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.endpoint; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.bitcoin.server.module.explorer.api.v1.post.SubmitTransactionHandler; import com.softwareverde.http.HttpMethod; public class TransactionsApi extends ExplorerApiEndpoint { public static class SubmitTransactionResult extends ApiResult { } public TransactionsApi(final String apiPrePath, final Environment environment) { super(environment); _defineEndpoint((apiPrePath + "/transactions"), HttpMethod.POST, new SubmitTransactionHandler()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/util/StringUtil.java<|end_filename|> package com.softwareverde.bitcoin.util; public class StringUtil extends com.softwareverde.util.StringUtil { public static String formatNumberString(final Long value) { if (value == null) { return null; } return _numberFormatter.format(value); } protected StringUtil() { super(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/BlockHasher.java<|end_filename|> package com.softwareverde.bitcoin.block; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.BlockHeaderDeflater; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.hash.sha256.MutableSha256Hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.util.HashUtil; import org.bouncycastle.crypto.digests.SHA256Digest; public class BlockHasher { protected final BlockHeaderDeflater _blockHeaderDeflater = new BlockHeaderDeflater(); /** * BouncyCastle is about half as fast as JVM's native implementation, however, it can perform better at high concurrency. */ protected static MutableSha256Hash doubleSha256ViaBouncyCastle(final ByteArray data) { final SHA256Digest digest = new SHA256Digest(); final byte[] dataBytes = data.getBytes(); digest.update(dataBytes, 0, dataBytes.length); digest.doFinal(dataBytes, 0); digest.update(dataBytes, 0, Sha256Hash.BYTE_COUNT); digest.doFinal(dataBytes, 0); return MutableSha256Hash.wrap(ByteUtil.copyBytes(dataBytes, 0, Sha256Hash.BYTE_COUNT)); } protected Sha256Hash _calculateBlockHash(final ByteArray serializedByteData, final Boolean useBouncyCastle) { final MutableSha256Hash sha256Hash; if (useBouncyCastle) { sha256Hash = BlockHasher.doubleSha256ViaBouncyCastle(serializedByteData); } else { sha256Hash = HashUtil.doubleSha256(serializedByteData); } return sha256Hash.toReversedEndian(); } protected Sha256Hash _calculateBlockHash(final BlockHeader blockHeader, final Boolean useBouncyCastle) { final ByteArray serializedByteData = _blockHeaderDeflater.toBytes(blockHeader); return _calculateBlockHash(serializedByteData, useBouncyCastle); } public Sha256Hash calculateBlockHash(final BlockHeader blockHeader, final Boolean useBouncyCastle) { return _calculateBlockHash(blockHeader, useBouncyCastle); } public Sha256Hash calculateBlockHash(final BlockHeader blockHeader) { return _calculateBlockHash(blockHeader, false); } public BlockHeaderDeflater getBlockHeaderDeflater() { return _blockHeaderDeflater; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/wallet/utxo/MutableSpendableTransactionOutput.java<|end_filename|> package com.softwareverde.bitcoin.wallet.utxo; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; public class MutableSpendableTransactionOutput extends SpendableTransactionOutputCore implements SpendableTransactionOutput { protected final Address _address; protected final TransactionOutputIdentifier _transactionOutputIdentifier; protected final TransactionOutput _transactionOutput; protected Boolean _isSpent; public MutableSpendableTransactionOutput(final Address address, final TransactionOutputIdentifier transactionOutputIdentifier, final TransactionOutput transactionOutput) { _address = (address != null ? address.asConst() : null); _transactionOutputIdentifier = transactionOutputIdentifier; _transactionOutput = transactionOutput.asConst(); _isSpent = false; } public MutableSpendableTransactionOutput(final Address address, final TransactionOutputIdentifier transactionOutputIdentifier, final TransactionOutput transactionOutput, final Boolean isSpent) { _address = (address != null ? address.asConst() : null); _transactionOutputIdentifier = transactionOutputIdentifier; _transactionOutput = transactionOutput.asConst(); _isSpent = isSpent; } public MutableSpendableTransactionOutput(final SpendableTransactionOutput spendableTransactionOutput) { _address = spendableTransactionOutput.getAddress(); _transactionOutputIdentifier = spendableTransactionOutput.getIdentifier(); _transactionOutput = spendableTransactionOutput.getTransactionOutput().asConst(); _isSpent = spendableTransactionOutput.isSpent(); } @Override public Address getAddress() { return _address; } @Override public TransactionOutputIdentifier getIdentifier() { return _transactionOutputIdentifier; } @Override public TransactionOutput getTransactionOutput() { return _transactionOutput; } public void setIsSpent(final Boolean isSpent) { _isSpent = isSpent; } @Override public Boolean isSpent() { return _isSpent; } @Override public ImmutableSpendableTransactionOutput asConst() { return new ImmutableSpendableTransactionOutput(this); } } <|start_filename|>www-shared/css/blocks.css<|end_filename|> .block { background-color: #FFFFFF; } .transaction, .block { border: solid 1px rgba(0, 0, 0, 0.05); box-sizing: border-box; margin-top: 2em; margin-left: 2em; margin-right: 2em; padding-left: 2em; padding-right: 2em; padding-bottom: 2em; } #main > .block .block-header > div { transition: all 500ms ease; box-sizing: border-box; height: 3.5em; flex-basis: 50%; } #main > .block .block-header > div:nth-child(2n+3) { padding-left: 15%; text-align: left; } #main > .block .block-header > div:nth-child(2n+4) { padding-right: 15%; text-align: right; } #main > .block .block-header > div.height { font-size: 2em; text-align: center; height: auto; margin-bottom: 0.25em; flex-grow: 2; flex-basis: 100%; } #main > .block .block-header > div.height > label { color: #303030; } #main > .block .block-header > div.height > .value { display: inline-block; margin-left: 0.25em; } #main > .block .block-header > div.hash { margin-bottom: 1em; flex-grow: 2; flex-basis: 100%; } #main > .block .block-header > div.hash > label { display: none; } #main > .block .block-header > div.hash > .value { font-size: 2em; margin: auto; } #main > .block .block-header > div.difficulty > .mask { display: none; } #main > .block .block-header > div.difficulty > .ratio > label { display: none !important; } #main > .block .block-header > div.byte-count { } #main > .block .block-header > div.previous-block-hash { flex-grow: 2; flex-basis: 100%; padding: 0; text-align: center; } #main > .block .block-header > div.previous-block-hash > .value { margin: auto; } #main > .block .block-header > div.double { height: calc(7em + 0.5em); } .transaction .io .transaction-inputs::before, .transaction .io .transaction-outputs::before, .transaction::before, .block::before { /* content: 'Block'; */ color: #404040; font-weight: bold; font-size: 1.0em; margin-left: -1em; position: relative; top: 0.25em; } .transaction::before { content: none; color: #404040; transition: all 500ms ease; } .transaction .io .transaction-inputs::before { content: 'Transaction Inputs'; margin-left: 0px; transition: all 500ms ease; } .transaction .io .transaction-outputs::before { content: 'Transaction Outputs'; margin-left: 0px; transition: all 500ms ease; } .transaction .io { clear: both; width: calc(100% - 0.5em); position: relative; padding-bottom: 0.5em; margin-bottom: 0.5em; } .transaction .io .transaction-inputs, .transaction .io .transaction-outputs { margin-top: 0.25em; overflow: auto; float: left; width: calc(48.5% - 0.5em); cursor: default; } .transaction .io .transaction-outputs { margin-left: calc(5% - 2em); } .transaction .io img.tx-arrow { width: 1.75em; opacity: 0.75; position: absolute; top: calc(50% + 0.875em); left: calc(50% - 0.25em); transform: translate(-50%, -50%); } .transaction .io .transaction-inputs > div, .transaction .io .transaction-outputs > div { margin-top: 0.5em; margin-left: 1em; border: solid 1px rgba(0, 0, 0, 0.05); background-color: rgba(0, 0, 0, 0.025); box-sizing: border-box; transition: all 500ms ease; } .transaction .io .transaction-input > .label, .transaction .io .transaction-output > .label { border: solid 1px rgba(0, 0, 0, 0.2); background-color: #EEEEEE; overflow: auto; padding: 0.5em; line-height: 2em; padding-left: 1em; padding-right: 1em; margin: 0.5em; font-size: 0.75em; cursor: pointer; } .transaction .io .transaction-input > div:not(:first-child), .transaction .io .transaction-output> div:not(:first-child) { display: none; margin-bottom: 0.25em; margin-top: 0.25em; margin-left: 1em; margin-right: 0.5em; border: solid 1px rgba(0, 0, 0, 0.05); background-color: rgba(255, 255, 255, 0.1); padding: 0.5em; } .transaction .io .transaction-input > div:last-child:not(:first-child), .transaction .io .transaction-output > div:last-child:not(:first-child) { margin-bottom: 1em; } .transaction .io .transaction-input .unlocking-script .script .script-operation > .value, .transaction .io .transaction-output .locking-script .script .script-operation > .value { font-size: 0.8em; word-wrap: break-word; margin-left: 0.5em; border: solid 1px rgba(0, 0, 0, 0.05); background-color: rgba(255, 255, 255, 0.25); padding: 0.5em; margin-right: 0.5em; padding-left: 1.5em; text-indent: -0.75em; display: block; word-break: break-word; } .transaction .io .transaction-input > .label .address, .transaction .io .transaction-output > .label .address { color: #262626; font-size: 1.0em; } .transaction .io .transaction-input > .label .amount, .transaction .io .transaction-output > .label .amount { float: right; color: #505050; font-weight: bold; padding-right: 0.5em; } .transaction .io .transaction-input > .label .token-amount, .transaction .io .transaction-output > .label .token-amount { background-color: #1AB325; border: solid 1px #0F6115; padding-left: 0.5em; padding-right: 0.5em; clear: both; float: right; color: #FFFFFF; font-weight: bold; border-radius: 5px; display: none; } .transaction .io .transaction-input.slp > .label .token-amount, .transaction .io .transaction-output.slp > .label .token-amount { display: block; } .transaction .io .transaction-input > .label .token-amount > .token-name, .transaction .io .transaction-output > .label .token-amount > .token-name { padding-left: 0.25em; } .transaction > div, .block .block-header { box-sizing: border-box; overflow: auto; margin: auto; background-color: #FFFFFF; padding: 1em; } #announcements .transaction > div:not(.hash) { display: none; } #announcements .transaction > div.hash, #announcements .block .block-header { padding: 0; margin-top: 0.5em; box-shadow: none; display: block; } .block .block-header { box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.25); display: flex; flex-direction: row; flex-wrap: wrap; } .transaction .hash > label, .transaction .block-hashes > label { font-weight: bold; } .transaction .hash > label.slp-transaction { color: #1AB326; } .transaction .hash > label.slp-transaction.invalid { color: #F7931D; } .transaction div > label, .block .block-header div label { display: inline-block; box-sizing: border-box; font-size: 0.75em; color: #AAAAAA; } .transaction > div > div .value, .block .block-header div .value { display: block; box-sizing: border-box; margin-top: 0.25em; } .value.fixed { /* Formerly block; table facilitates hash-resizing while still on a newline from its label. */ display: table !important; } .block .block-header div.timestamp .value::after { /* content: '(UTC)'; */ font-size: 0.75em; color: rgba(0, 0, 0, 0.4); margin-left: 0.5em; font-style: italic; } .block .block-header div.reward .value::after { content: '(bitcoin)'; font-size: 0.75em; color: rgba(0, 0, 0, 0.4); margin-left: 0.5em; font-style: italic; } .transaction .hash .value { display: inline-block !important; margin-left: 1em; vertical-align: text-bottom; } .transaction div div.fee .value::after, .transaction div div.byte-count .value::after, .block .block-header div.byte-count .value::after { content: '\A(bytes)'; color: rgba(0, 0, 0, 0.4); font-style: italic; font-size: 25%; display: block; } .transaction div div.fee .value::after { content: '\A(satoshis)'; } .transaction div div.block-hashes div.value span { display: block; } .block .block-header div.difficulty { float: right; } .script > .value { margin-left: 0 !important; margin-right: 0 !important; padding-left: 0 !important; padding-right: 0 !important; } .transaction .io .transaction-input .unlocking-script > div > label, .transaction .io .transaction-output .locking-script > div > label, .transaction-input div.unlocking-script div label, .transaction-input div.sequence-number div label, .transaction div div.lock-time div label, .block .block-header div.difficulty div label { margin-left: 0.5em; color: rgba(0, 0, 0, 0.5); margin-top: 0.2em; } .block .block-header div.transaction-count { /* display: none; */ } .transaction .io .unlocking-script > div > .value, .transaction .io .locking-script > div > .value { margin-left: 0.5em; } .is-disabled span.value, .type span.value { font-style: italic; font-weight: bold; font-size: 0.75em; } .transaction { transition: all 500ms ease; transition: opacity 500ms ease; background-color: #FFFFFF; border: solid 1px #AAAAAA; padding-top: 0.5em; padding-bottom: 2.5em; position: relative; } .transaction.collapsed { padding-bottom: 0px; cursor: pointer; border: solid 1px #EEEEEE; } .transaction.collapsed > .hash { margin-bottom: 0; padding: 0; padding-left: 1em; } .transaction.collapsed .hash .value { font-size: 1em; } .transaction.collapsed .io { padding-top: 0; margin-top: 1em; } .transaction.collapsed .io img.tx-arrow { display: none; } .transaction.collapsed .io .transaction-outputs::before, .transaction.collapsed .io .transaction-inputs::before, .transaction.collapsed::before { opacity: 0; position: absolute; } .transaction.collapsed > div > div { width: calc(100% - 0.5em); } .transaction .floating-properties-container { position: absolute; top: 0; right: 0; text-align: right; vertical-align: top; } .transaction .floating-property { width: 90px; height: 90px; border-radius: 5em; padding: 0.5em; border: solid 1px #F0F0F0; text-align: center; margin-left: 10px; float: right; background-color: #FAFAFA; position: relative; box-sizing: border-box; } .transaction .floating-property label { font-weight: normal; } .transaction .floating-property .value { display: block; font-size: 150%; } .transaction .slp.floating-property .value { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin-top: 0; line-height: 90px; font-size: 250%; } .transaction .slp.floating-property.oversized label { float: left; width: 100%; } .transaction .slp.floating-property.oversized .value { font-size: 150%; } .transaction .slp.floating-property { border-color: #0F6115; background-color: #1AB325; cursor: pointer; overflow: hidden; } .transaction .slp.floating-property.invalid { border-color: #962727; background-color: #FF3030; cursor: not-allowed; } .slp.floating-property.invalid::after { content: '\2215'; top: 0; bottom: 0; left: 0; right: 0; position: absolute; font-size: 150px; line-height: 95px; color: rgba(0, 0, 0, 0.5); transform: rotate(22deg); } .transaction .slp.floating-property > label { color: #303030; } .transaction.collapsed .slp-genesis { display: none; } .transaction .slp-genesis { background-color: #F9F9F9; border: solid 1px #ECECEC; margin-bottom: 1em; display: flex; flex-direction: row; flex-wrap: wrap; position: relative; } .transaction .slp-genesis > div { flex-basis: 50%; flex-grow: 1; box-sizing: border-box; } .transaction .slp-genesis > div.token-name > label, .transaction .slp-genesis > div.token-id > label { display: none; } .transaction .slp-genesis > div.token-name, .transaction .slp-genesis > div.token-id { flex-grow: 2; flex-basis: 100%; text-align: center; font-size: 133%; } .transaction .slp-genesis > div.token-id > .value { margin: auto; } .transaction .slp-genesis > div.token-name object, .transaction .slp-genesis > div.token-name img { height: 32px; position: absolute; top: 1px; left: 1px; border-radius: 4px; } .transaction .slp-genesis > div:nth-child(2) { margin-top: 0.5em; margin-bottom: 1em; } .transaction .slp-genesis > div:nth-child(2n+3) { padding-left: 15%; text-align: left; } .transaction .slp-genesis > div:nth-child(2n+4) { padding-right: 15%; text-align: right; } .transaction > .lock-time.floating-property { display: inline-block; border: solid 2px #F0F0F0; padding: 0.5em; position: absolute; right: 0; bottom: 0; margin: 0.25em; color: #BBBBBB; border-radius: 5px; width: auto; height: auto; } .transaction > .lock-time > label { display: none; } .transaction > .lock-time > .img { color: #C0C0C0; margin-right: 0.25em; display: inline-block; } .transaction > .lock-time > .value { display: inline-block; font-size: 0.75em; } .transaction.collapsed > div > div { border: none; background-color: initial; } .transaction.collapsed .io .transaction-inputs, .transaction.collapsed .io .transaction-outputs, .transaction.collapsed .io .transaction-inputs > div, .transaction.collapsed .io .transaction-outputs > div { margin-top: 0px; } .transaction.collapsed .io { margin-top: 0.5em; } .transaction.collapsed > div > div { padding: 0px; margin: 0px; } #main > .block .transactions-nav { display: block; } .block .transactions-nav { font-size: 1.25em; padding-top: 0.5em; text-align: center; margin-bottom: -1em; color: #00B512; display: none; } .block .transactions-nav .page-navigation { margin-left: 0.5em; margin-right: 0.5em; } .block .transactions-nav .page-navigation > a:hover { cursor: pointer; } .block .transactions-nav .page-navigation > * { border: solid 1px; border-color: #CCCCCC; width: 1.5em; display: inline-block; height: 1.5em; line-height: 1.5em; margin-left: -1px; color: #858585; position: relative; z-index: 1; } .block .transactions-nav .page-navigation > *:first-child { border-top-left-radius: 5px; border-bottom-left-radius: 5px; } .block .transactions-nav .page-navigation > *:last-child { border-top-right-radius: 5px; border-bottom-right-radius: 5px; } .block .transactions-nav .page-navigation > *:hover { background-color: #C7FFD5; } .block .transactions-nav .page-navigation > a.current { font-size: 1.1em; font-weight: bold; border: solid 2px #606060; z-index: 2; } .block .transactions-nav .page-navigation { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .block .transactions .transaction:hover { box-shadow: 0px 0px 2px #00B512; } .transaction-output > .label.highlight { border-color: #1BAB1B !important; } .transaction-output .address.highlight { color: #1BAB1B !important; } .transaction-input > .label.highlight { border-color: #AB1B1B !important; } .transaction-input .address.highlight { color: #AB1B1B !important; } .address .address-metadata { margin-top: 1em; padding: 1em; padding-left: 3em; padding-right: 3em; border: solid 1px #AAA; margin: 1em; background-color: #FFFFFF; } .address-metadata .address { font-size: 125%; font-weight: bold; display: block; } .address-metadata .address-balance { margin-top: 0.5em; display: block; } .address-metadata .address-balance::before { content: 'Balance:'; color: #BBBBBB; font-size: 0.95em; margin-right: 0.5em; display: inline-block; font-weight: bold; } .address-metadata .address-balance::after { content: '(satoshis)'; font-size: 0.75em; color: #BBBBBB; margin-left: 0.5em; font-style: italic; } .address-metadata .qr-code { float: right; } .recent-transactions .transaction > .hash > label { display: none; } .block > .block-header div.merkle-root:nth-child(2n) .value.fixed, .transaction .slp-genesis > div.document-hash:nth-child(2n) .value.fixed { margin-left: auto; } @media only screen and (max-width: 1100px) { .block, .transaction { margin-left: 0; margin-right: 0; padding-left: 0; padding-right: 0; } .transaction .io .transaction-inputs::before, .transaction .io .transaction-outputs::before, .transaction::before, .block::before { margin-left: 0; } } @media only screen and (max-width: 960px) { .block .block-header > div { width: calc(100% - 0.5em); } .transaction .floating-properties-container { position: relative; display: flex; } .transaction .floating-properties-container .floating-property { flex-grow: 1; border-radius: 5px; margin-right: 10px; } } @media only screen and (max-width: 800px) { .transaction .io { text-align: center; } .transaction .io img.tx-arrow { position: initial; transform: initial; top: initial; margin: auto; margin-top: 0.5em; margin-bottom: 0.5em; float: initial; transform: rotateZ(90deg); } .transaction.collapsed .io img.tx-arrow { display: inline-block; } .transaction .io .transaction-inputs, .transaction .io .transaction-outputs { float: none; margin: 0; width: 100%; box-sizing: border-box; } .transaction .io .transaction-inputs .transaction-input, .transaction .io .transaction-outputs .transaction-output { margin-bottom: 1px; } } @media only screen and (max-width: 700px) { .address .address-metadata { text-align: center; padding: 0; padding-top: 1em; padding-bottom: 1em; } .address .address-metadata .address { font-size: 100%; } .address-metadata .qr-code { float: none; margin-bottom: 1em; } } @media only screen and (max-width: 600px) { .transaction > div > div .value, .block .block-header div .value { margin: auto; } .transaction > div > div, .block .block-header > div { width: auto; float: none !important; overflow-x: hidden; } #main > .block .block-header > div:nth-child(n+3) { flex-basis: 100%; padding: 0px; text-align: left; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/inflater/InventoryItemInflaters.java<|end_filename|> package com.softwareverde.bitcoin.inflater; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItemInflater; public interface InventoryItemInflaters extends Inflater { InventoryItemInflater getInventoryItemInflater(); } <|start_filename|>src/main/java/com/softwareverde/network/p2p/message/ProtocolMessage.java<|end_filename|> package com.softwareverde.network.p2p.message; import com.softwareverde.constable.bytearray.ByteArray; public interface ProtocolMessage { ByteArray getBytes(); } <|start_filename|>src/test/java/com/softwareverde/network/p2p/node/manager/FakeNodeFactory.java<|end_filename|> package com.softwareverde.network.p2p.node.manager; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.bitcoin.server.node.BitcoinNodeFactory; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.network.socket.BinarySocket; public class FakeNodeFactory extends BitcoinNodeFactory { protected final ThreadPool _threadPool; public FakeNodeFactory(final ThreadPool threadPool) { super(null, null, null); _threadPool = threadPool; } @Override public FakeNode newNode(final String host, final Integer port) { return new FakeNode(host, _threadPool); } @Override public BitcoinNode newNode(final BinarySocket binarySocket) { return new FakeNode(binarySocket.getHost(), _threadPool); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/validator/TransactionValidationResult.java<|end_filename|> package com.softwareverde.bitcoin.transaction.validator; import com.softwareverde.bitcoin.block.validator.ValidationResult; import com.softwareverde.json.Json; public class TransactionValidationResult extends ValidationResult { protected final Integer _signatureOperationCount; public static TransactionValidationResult valid(final Integer signatureOperationCount) { return new TransactionValidationResult(true, null, signatureOperationCount); } public static TransactionValidationResult invalid(final String errorMessage) { return new TransactionValidationResult(false, errorMessage, null); } public static TransactionValidationResult invalid(final Json errorMessage) { return new TransactionValidationResult(false, ((errorMessage != null) ? errorMessage.toString() : null), null); } public TransactionValidationResult(final Boolean isValid, final String errorMessage, final Integer signatureOperationCount) { super(isValid, errorMessage); _signatureOperationCount = signatureOperationCount; } /** * Returns the number of signature operations executed by this Transaction, or null if validation failed. */ public Integer getSignatureOperationCount() { return _signatureOperationCount; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/commit/ImmutableSlpCommitScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp.commit; import com.softwareverde.constable.Const; public class ImmutableSlpCommitScript extends SlpCommitScriptCore implements Const { public ImmutableSlpCommitScript(final SlpCommitScript slpCommitScript) { super(slpCommitScript); } @Override public ImmutableSlpCommitScript asConst() { return this; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/BatchRunner.java<|end_filename|> package com.softwareverde.bitcoin.server.database; import com.softwareverde.concurrent.Pin; import com.softwareverde.concurrent.pool.MainThreadPool; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.database.DatabaseException; import com.softwareverde.util.Container; import com.softwareverde.util.Util; public class BatchRunner<T> { public interface Batch<T> { void run(List<T> batchItems) throws Exception; } protected final Boolean _asynchronousExecutionIsEnabled; protected final Integer _maxItemCountPerBatch; protected final Integer _maxConcurrentThreadCount; protected void _executeAsynchronously(final Runnable[] runnables, final Container<Exception> exceptionContainer) throws DatabaseException { final int batchCount = runnables.length; final int threadCount = Math.min(runnables.length, _maxConcurrentThreadCount); final MainThreadPool threadPool = new MainThreadPool(threadCount, 0L); try { final Pin[] pins = new Pin[batchCount]; for (int i = 0; i < batchCount; ++i) { final Runnable runnable = runnables[i]; final Pin pin = new Pin(); pins[i] = pin; threadPool.execute(new Runnable() { @Override public void run() { try { runnable.run(); } catch (final Exception exception) { exceptionContainer.value = exception; } finally { pin.release(); } } }); } for (int i = 0; i < batchCount; ++i) { final Pin pin = pins[i]; pin.waitForRelease(Long.MAX_VALUE); } } catch (final InterruptedException exception) { throw new DatabaseException(exception); } finally { threadPool.stop(); } } public BatchRunner(final Integer maxItemCountPerBatch) { this(maxItemCountPerBatch, false); } public BatchRunner(final Integer maxItemCountPerBatch, final Boolean executeAsynchronously) { this(maxItemCountPerBatch, executeAsynchronously, null); } public BatchRunner(final Integer maxItemCountPerBatch, final Boolean executeAsynchronously, final Integer maxConcurrentThreadCount) { _maxItemCountPerBatch = maxItemCountPerBatch; _asynchronousExecutionIsEnabled = executeAsynchronously; _maxConcurrentThreadCount = Util.coalesce(maxConcurrentThreadCount, Integer.MAX_VALUE); } public void run(final List<T> totalCollection, final Batch<T> batch) throws DatabaseException { final int totalItemCount = totalCollection.getCount(); final int itemCountPerBatch; final int batchCount; if (totalItemCount <= _maxItemCountPerBatch) { itemCountPerBatch = totalItemCount; batchCount = 1; } else { itemCountPerBatch = _maxItemCountPerBatch; batchCount = (int) Math.ceil(totalItemCount / (double) itemCountPerBatch); } final Runnable[] runnables = new Runnable[batchCount]; final Container<Exception> exceptionContainer = new Container<Exception>(); for (int i = 0; i < batchCount; ++i) { final int batchId = i; final Runnable runnable = new Runnable() { @Override public void run() { final MutableList<T> bathedItems = new MutableList<T>(itemCountPerBatch); for (int j = 0; j < itemCountPerBatch; ++j) { final int index = ((batchId * itemCountPerBatch) + j); if (index >= totalItemCount) { break; } final T item = totalCollection.get(index); bathedItems.add(item); } if (bathedItems.isEmpty()) { return; } try { batch.run(bathedItems); } catch (final Exception exception) { exceptionContainer.value = exception; } } }; runnables[i] = runnable; } if (_asynchronousExecutionIsEnabled) { _executeAsynchronously(runnables, exceptionContainer); } else { for (final Runnable runnable : runnables) { if (exceptionContainer.value != null) { break; } runnable.run(); } } if (exceptionContainer.value != null) { if (exceptionContainer.value instanceof DatabaseException) { throw ((DatabaseException) exceptionContainer.value); } else { throw new DatabaseException(exceptionContainer.value); } } } public Integer getItemCountPerBatch() { return _maxItemCountPerBatch; } public Boolean asynchronousExecutionIsEnabled() { return _asynchronousExecutionIsEnabled; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/message/RequestMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.message; import com.softwareverde.json.Json; import com.softwareverde.json.Jsonable; public class RequestMessage implements Jsonable { private static int _nextId = 1; private static final Object _mutex = new Object(); private static int createId() { synchronized (_mutex) { final int id = _nextId; _nextId += 1; return id; } } private static void synchronizeNextId(final Integer id) { if (id == null) { return; } synchronized (_mutex) { if (_nextId < id) { _nextId = (id + 1); } } } public enum ClientCommand { AUTHORIZE("mining.authorize"), CAPABILITIES("mining.capabilities"), EXTRA_NONCE("mining.extranonce.subscribe"), GET_TRANSACTIONS("mining.get_transactions"), SUBMIT("mining.submit"), SUBSCRIBE("mining.subscribe"), SUGGEST_DIFFICULTY("mining.suggest_difficulty"), SUGGEST_TARGET("mining.suggest_target"); private final String _value; ClientCommand(final String value) { _value = value; } public String getValue() { return _value; } } public enum ServerCommand { GET_VERSION("client.get_version"), RECONNECT("client.reconnect"), SHOW_MESSAGES("client.show_messages"), NOTIFY("mining.notify"), SET_DIFFICULTY("mining.set_difficulty"), SET_EXTRA_NONCE("mining.set_extranonce"), SET_GOAL("mining.set_goal"); private final String _value; ServerCommand(final String value) { _value = value; } public String getValue() { return _value; } } public static RequestMessage parse(final String input) { final Json json = Json.parse(input); return RequestMessage.parse(json); } public static RequestMessage parse(final Json json) { if (json.isArray()) { return null; } if (! json.hasKey("method")) { return null; } final Integer id = json.getInteger("id"); final String command = json.getString("method"); final RequestMessage requestMessage = new RequestMessage(id, command); requestMessage._parameters = json.get("params"); return requestMessage; } protected final Integer _id; protected final String _command; protected Json _parameters = new Json(true); protected RequestMessage(final Integer id, final String command) { synchronizeNextId(id); _id = id; _command = command; } public RequestMessage(final String command) { _id = createId(); _command = command; } public void setParameters(final Json parameters) { _parameters = parameters; } public Json getParameters() { return _parameters; } public Integer getId() { return _id; } public String getCommand() { return _command; } public Boolean isCommand(final ClientCommand clientCommand) { if (clientCommand == null) { return false; } return clientCommand.getValue().equals(_command); } public Boolean isCommand(final ServerCommand serverCommand) { if (serverCommand == null) { return false; } return serverCommand.getValue().equals(_command); } @Override public Json toJson() { final Json message = new Json(); message.put("id", _id); message.put("method", _command); message.put("params", _parameters); return message; } @Override public String toString() { final Json json = this.toJson(); return json.toString(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/store/BlockStoreCore.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.store; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.block.header.MutableBlockHeader; import com.softwareverde.bitcoin.inflater.BlockHeaderInflaters; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.util.ByteBuffer; import com.softwareverde.bitcoin.util.IoUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import java.io.File; import java.io.RandomAccessFile; public class BlockStoreCore implements BlockStore { protected final BlockHeaderInflaters _blockHeaderInflaters; protected final BlockInflaters _blockInflaters; protected final String _blockDataDirectory; protected final Integer _blocksPerDirectoryCount = 2016; // About 2 weeks... protected final ByteBuffer _byteBuffer = new ByteBuffer(); protected String _getBlockDataDirectory(final Long blockHeight) { final String blockDataDirectory = _blockDataDirectory; if (blockDataDirectory == null) { return null; } final long blockHeightDirectory = (blockHeight / _blocksPerDirectoryCount); return (blockDataDirectory + "/" + blockHeightDirectory); } protected String _getBlockDataPath(final Sha256Hash blockHash, final Long blockHeight) { if (_blockDataDirectory == null) { return null; } final String blockHeightDirectory = _getBlockDataDirectory(blockHeight); return (blockHeightDirectory + "/" + blockHash); } protected ByteArray _readFromBlock(final Sha256Hash blockHash, final Long blockHeight, final Long diskOffset, final Integer byteCount) { if (_blockDataDirectory == null) { return null; } final String blockPath = _getBlockDataPath(blockHash, blockHeight); if (blockPath == null) { return null; } if (! IoUtil.fileExists(blockPath)) { return null; } try { final MutableByteArray byteArray = new MutableByteArray(byteCount); try (final RandomAccessFile file = new RandomAccessFile(new File(blockPath), "r")) { file.seek(diskOffset); final byte[] buffer; synchronized (_byteBuffer) { buffer = _byteBuffer.getRecycledBuffer(); } int totalBytesRead = 0; while (totalBytesRead < byteCount) { final int byteCountRead = file.read(buffer); if (byteCountRead < 0) { break; } byteArray.setBytes(totalBytesRead, buffer); totalBytesRead += byteCountRead; } synchronized (_byteBuffer) { _byteBuffer.recycleBuffer(buffer); } if (totalBytesRead < byteCount) { return null; } } return byteArray; } catch (final Exception exception) { Logger.warn(exception); return null; } } public BlockStoreCore(final String blockDataDirectory, final BlockHeaderInflaters blockHeaderInflaters, final BlockInflaters blockInflaters) { _blockDataDirectory = blockDataDirectory; _blockInflaters = blockInflaters; _blockHeaderInflaters = blockHeaderInflaters; } @Override public Boolean storeBlock(final Block block, final Long blockHeight) { if (_blockDataDirectory == null) { return false; } if (block == null) { return false; } final Sha256Hash blockHash = block.getHash(); final String blockPath = _getBlockDataPath(blockHash, blockHeight); if (blockPath == null) { return false; } if (! IoUtil.isEmpty(blockPath)) { return true; } { // Create the directory, if necessary... final String dataDirectory = _getBlockDataDirectory(blockHeight); final File directory = new File(dataDirectory); if (! directory.exists()) { final boolean mkdirSuccessful = directory.mkdirs(); if (! mkdirSuccessful) { Logger.warn("Unable to create block data directory: " + dataDirectory); return false; } } } final BlockDeflater blockDeflater = _blockInflaters.getBlockDeflater(); final ByteArray byteArray = blockDeflater.toBytes(block); return IoUtil.putFileContents(blockPath, byteArray); } @Override public void removeBlock(final Sha256Hash blockHash, final Long blockHeight) { if (_blockDataDirectory == null) { return; } final String blockPath = _getBlockDataPath(blockHash, blockHeight); if (blockPath == null) { return; } if (! IoUtil.fileExists(blockPath)) { return; } final File file = new File(blockPath); file.delete(); } @Override public MutableBlockHeader getBlockHeader(final Sha256Hash blockHash, final Long blockHeight) { if (_blockDataDirectory == null) { return null; } final String blockPath = _getBlockDataPath(blockHash, blockHeight); if (blockPath == null) { return null; } if (! IoUtil.fileExists(blockPath)) { return null; } final ByteArray blockBytes = _readFromBlock(blockHash, blockHeight, 0L, BlockHeaderInflater.BLOCK_HEADER_BYTE_COUNT); if (blockBytes == null) { return null; } final BlockHeaderInflater blockHeaderInflater = _blockHeaderInflaters.getBlockHeaderInflater(); return blockHeaderInflater.fromBytes(blockBytes); } @Override public MutableBlock getBlock(final Sha256Hash blockHash, final Long blockHeight) { if (_blockDataDirectory == null) { return null; } final String blockPath = _getBlockDataPath(blockHash, blockHeight); if (blockPath == null) { return null; } if (! IoUtil.fileExists(blockPath)) { return null; } final ByteArray blockBytes = MutableByteArray.wrap(IoUtil.getFileContents(blockPath)); if (blockBytes == null) { return null; } final BlockInflater blockInflater = _blockInflaters.getBlockInflater(); return blockInflater.fromBytes(blockBytes); } @Override public ByteArray readFromBlock(final Sha256Hash blockHash, final Long blockHeight, final Long diskOffset, final Integer byteCount) { return _readFromBlock(blockHash, blockHeight, diskOffset, byteCount); } public String getBlockDataDirectory() { return _blockDataDirectory; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/core/BlockProcessorContext.java<|end_filename|> package com.softwareverde.bitcoin.context.core; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.context.TransactionValidatorFactory; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.SynchronizationStatus; import com.softwareverde.bitcoin.server.module.node.BlockProcessor; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.store.BlockStore; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.transaction.validator.BlockOutputs; import com.softwareverde.bitcoin.transaction.validator.TransactionValidator; import com.softwareverde.network.time.VolatileNetworkTime; public class BlockProcessorContext implements BlockProcessor.Context { protected final BlockInflaters _blockInflaters; protected final TransactionInflaters _transactionInflaters; protected final BlockStore _blockStore; protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; protected final VolatileNetworkTime _networkTime; protected final SynchronizationStatus _synchronizationStatus; protected final TransactionValidatorFactory _transactionValidatorFactory; public BlockProcessorContext(final BlockInflaters blockInflaters, final TransactionInflaters transactionInflaters, final BlockStore blockStore, final FullNodeDatabaseManagerFactory databaseManagerFactory, final VolatileNetworkTime networkTime, final SynchronizationStatus synchronizationStatus, final TransactionValidatorFactory transactionValidatorFactory) { _blockInflaters = blockInflaters; _transactionInflaters = transactionInflaters; _blockStore = blockStore; _databaseManagerFactory = databaseManagerFactory; _networkTime = networkTime; _synchronizationStatus = synchronizationStatus; _transactionValidatorFactory = transactionValidatorFactory; } @Override public BlockStore getBlockStore() { return _blockStore; } @Override public FullNodeDatabaseManagerFactory getDatabaseManagerFactory() { return _databaseManagerFactory; } @Override public VolatileNetworkTime getNetworkTime() { return _networkTime; } @Override public SynchronizationStatus getSynchronizationStatus() { return _synchronizationStatus; } @Override public BlockInflater getBlockInflater() { return _blockInflaters.getBlockInflater(); } @Override public BlockDeflater getBlockDeflater() { return _blockInflaters.getBlockDeflater(); } @Override public TransactionValidator getTransactionValidator(final BlockOutputs blockOutputs, final TransactionValidator.Context transactionValidatorContext) { return _transactionValidatorFactory.getTransactionValidator(blockOutputs, transactionValidatorContext); } @Override public TransactionInflater getTransactionInflater() { return _transactionInflaters.getTransactionInflater(); } @Override public TransactionDeflater getTransactionDeflater() { return _transactionInflaters.getTransactionDeflater(); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/module/node/database/transaction/fullnode/utxo/UnspentTransactionOutputManagerTests.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.server.module.node.database.block.fullnode.FullNodeBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.BlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.test.BlockData; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.bitcoin.transaction.MutableTransaction; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.coinbase.CoinbaseTransaction; import com.softwareverde.bitcoin.transaction.input.MutableTransactionInput; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.locktime.LockTime; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class UnspentTransactionOutputManagerTests extends IntegrationTest { @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } @Test public void should_remove_created_utxos_and_restore_spent_outputs_when_removing_block_from_utxo_set() throws Exception { // Setup final AddressInflater addressInflater = _masterInflater.getAddressInflater(); try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final FullNodeBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = databaseManager.getUnspentTransactionOutputDatabaseManager(); final UnspentTransactionOutputManager unspentTransactionOutputManager = new UnspentTransactionOutputManager(databaseManager, 2016L); final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final Block block0 = blockInflater.fromBytes(ByteArray.fromHexString(BlockData.MainChain.GENESIS_BLOCK)); synchronized (BlockHeaderDatabaseManager.MUTEX) { blockDatabaseManager.storeBlock(block0); } final Address address0 = addressInflater.fromPrivateKey(PrivateKey.createNewKey()); final Address address1 = addressInflater.fromPrivateKey(PrivateKey.createNewKey()); final Address address2 = addressInflater.fromPrivateKey(PrivateKey.createNewKey()); final Block block1; final Block block2; final CoinbaseTransaction block1CoinbaseTransaction; final Transaction block1Transaction1; final Transaction block2CoinbaseTransaction; final Transaction block2Transaction1; final Transaction block2Transaction2; { final MutableBlock mutableBlock = new MutableBlock(); { // Init Block Template... mutableBlock.setVersion(Block.VERSION); mutableBlock.setPreviousBlockHash(BlockHeader.GENESIS_BLOCK_HASH); mutableBlock.setDifficulty(Difficulty.BASE_DIFFICULTY); mutableBlock.setTimestamp(MedianBlockTime.GENESIS_BLOCK_TIMESTAMP); mutableBlock.setNonce(0L); } { final MutableTransactionInput mutableTransactionInput = new MutableTransactionInput(); { // Init Transaction Input Template... mutableTransactionInput.setSequenceNumber(SequenceNumber.MAX_SEQUENCE_NUMBER); mutableTransactionInput.setUnlockingScript(UnlockingScript.EMPTY_SCRIPT); } final MutableTransaction mutableTransaction = new MutableTransaction(); { // Init Transaction Template... mutableTransaction.setVersion(Transaction.VERSION); mutableTransaction.setLockTime(LockTime.MIN_TIMESTAMP); } { // Create Block1's CoinbaseTransaction; generates 50 BCH. mutableTransaction.addTransactionInput(TransactionInput.createCoinbaseTransactionInput(1L, "")); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address0, 50L * Transaction.SATOSHIS_PER_BITCOIN)); block1CoinbaseTransaction = mutableTransaction.asCoinbase(); } { // Create Block1's second Transaction that spends Block1's Coinbase and creates two 25BCH outputs. mutableTransaction.clearTransactionInputs(); mutableTransaction.clearTransactionOutputs(); { // Configure TransactionInput to spent Block1's Coinbase Transaction. mutableTransactionInput.setPreviousOutputTransactionHash(block1CoinbaseTransaction.getHash()); mutableTransactionInput.setPreviousOutputIndex(0); } mutableTransaction.addTransactionInput(mutableTransactionInput.asConst()); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address1, 25L * Transaction.SATOSHIS_PER_BITCOIN)); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address2, 25L * Transaction.SATOSHIS_PER_BITCOIN)); block1Transaction1 = mutableTransaction.asConst(); } { // Create Block2's CoinbaseTransaction; generates 50 BCH. mutableTransaction.clearTransactionInputs(); mutableTransaction.clearTransactionOutputs(); mutableTransaction.addTransactionInput(TransactionInput.createCoinbaseTransactionInput(2L, "")); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address1, 50L * Transaction.SATOSHIS_PER_BITCOIN)); block2CoinbaseTransaction = mutableTransaction.asCoinbase(); } { // Create Block2's second Transaction that spends Block1's second Transaction first TransactionOutput... mutableTransaction.clearTransactionInputs(); mutableTransaction.clearTransactionOutputs(); { // Configure TransactionInput to spent Block1's Coinbase Transaction. mutableTransactionInput.setPreviousOutputTransactionHash(block1Transaction1.getHash()); mutableTransactionInput.setPreviousOutputIndex(0); } mutableTransaction.addTransactionInput(mutableTransactionInput.asConst()); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address1, 12L * Transaction.SATOSHIS_PER_BITCOIN)); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address2, 13L * Transaction.SATOSHIS_PER_BITCOIN)); block2Transaction1 = mutableTransaction.asConst(); } { // Create Block2's third Transaction that spends Block2's second Transaction second TransactionOutput... mutableTransaction.clearTransactionInputs(); mutableTransaction.clearTransactionOutputs(); { // Configure TransactionInput to spent Block1's Coinbase Transaction. mutableTransactionInput.setPreviousOutputTransactionHash(block2Transaction1.getHash()); mutableTransactionInput.setPreviousOutputIndex(1); } mutableTransaction.addTransactionInput(mutableTransactionInput.asConst()); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address1, 10L * Transaction.SATOSHIS_PER_BITCOIN)); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address2, 3L * Transaction.SATOSHIS_PER_BITCOIN)); block2Transaction2 = mutableTransaction.asConst(); } } { // Assemble Block 1... mutableBlock.addTransaction(block1CoinbaseTransaction); mutableBlock.addTransaction(block1Transaction1); block1 = mutableBlock.asConst(); } { // Assemble Block 2... mutableBlock.clearTransactions(); mutableBlock.addTransaction(block2CoinbaseTransaction); mutableBlock.addTransaction(block2Transaction1); mutableBlock.addTransaction(block2Transaction2); block2 = mutableBlock.asConst(); } } { // Store and sanity-check Block1 state... synchronized (BlockHeaderDatabaseManager.MUTEX) { blockDatabaseManager.storeBlock(block1); } unspentTransactionOutputManager.applyBlockToUtxoSet(block1, 1L, _fullNodeDatabaseManagerFactory); final TransactionOutput coinbaseTransactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1CoinbaseTransaction.getHash(), 0)); Assert.assertNull(coinbaseTransactionOutput); // Spent by Block1 Transaction1... final TransactionOutput transactionOutput0 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 0)); Assert.assertNotNull(transactionOutput0); final TransactionOutput transactionOutput1 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 1)); Assert.assertNotNull(transactionOutput1); } { // Store and sanity-check Block2 state... synchronized (BlockHeaderDatabaseManager.MUTEX) { blockDatabaseManager.storeBlock(block2); } unspentTransactionOutputManager.applyBlockToUtxoSet(block2, 2L, _fullNodeDatabaseManagerFactory); final TransactionOutput coinbaseTransactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1CoinbaseTransaction.getHash(), 0)); Assert.assertNull(coinbaseTransactionOutput); // Spent by Block1's Transaction1... final TransactionOutput transactionOutput0 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 0)); Assert.assertNull(transactionOutput0); // Spent by Block2's Transaction1... final TransactionOutput transactionOutput1 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 1)); Assert.assertNotNull(transactionOutput1); final TransactionOutput transactionOutput2 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block2Transaction1.getHash(), 0)); Assert.assertNotNull(transactionOutput2); final TransactionOutput transactionOutput3 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block2Transaction1.getHash(), 1)); Assert.assertNull(transactionOutput3); final TransactionOutput transactionOutput4 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block2Transaction2.getHash(), 0)); Assert.assertNotNull(transactionOutput4); final TransactionOutput transactionOutput5 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block2Transaction2.getHash(), 1)); Assert.assertNotNull(transactionOutput5); } // Action unspentTransactionOutputManager.removeBlockFromUtxoSet(block2, 2L); // Assert // Should be exactly the same as before Block2 was applied... final TransactionOutput coinbaseTransactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1CoinbaseTransaction.getHash(), 0)); Assert.assertNull(coinbaseTransactionOutput); // Spent by Block1 Transaction1... final TransactionOutput transactionOutput0 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 0)); Assert.assertNotNull(transactionOutput0); final TransactionOutput transactionOutput1 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 1)); Assert.assertNotNull(transactionOutput1); } } @Test public void should_remove_created_utxos_and_restore_spent_outputs_when_removing_block_from_utxo_set_after_utxo_commit() throws Exception { // Setup final AddressInflater addressInflater = _masterInflater.getAddressInflater(); try (final FullNodeDatabaseManager databaseManager = _fullNodeDatabaseManagerFactory.newDatabaseManager()) { final FullNodeBlockDatabaseManager blockDatabaseManager = databaseManager.getBlockDatabaseManager(); final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = databaseManager.getUnspentTransactionOutputDatabaseManager(); final UnspentTransactionOutputManager unspentTransactionOutputManager = new UnspentTransactionOutputManager(databaseManager, 2016L); final BlockInflater blockInflater = _masterInflater.getBlockInflater(); final Block block0 = blockInflater.fromBytes(ByteArray.fromHexString(BlockData.MainChain.GENESIS_BLOCK)); synchronized (BlockHeaderDatabaseManager.MUTEX) { blockDatabaseManager.storeBlock(block0); } final Address address0 = addressInflater.fromPrivateKey(PrivateKey.createNewKey()); final Address address1 = addressInflater.fromPrivateKey(PrivateKey.createNewKey()); final Address address2 = addressInflater.fromPrivateKey(PrivateKey.createNewKey()); final Block block1; final Block block2; final CoinbaseTransaction block1CoinbaseTransaction; final Transaction block1Transaction1; final Transaction block2CoinbaseTransaction; final Transaction block2Transaction1; final Transaction block2Transaction2; { final MutableBlock mutableBlock = new MutableBlock(); { // Init Block Template... mutableBlock.setVersion(Block.VERSION); mutableBlock.setPreviousBlockHash(BlockHeader.GENESIS_BLOCK_HASH); mutableBlock.setDifficulty(Difficulty.BASE_DIFFICULTY); mutableBlock.setTimestamp(MedianBlockTime.GENESIS_BLOCK_TIMESTAMP); mutableBlock.setNonce(0L); } { final MutableTransactionInput mutableTransactionInput = new MutableTransactionInput(); { // Init Transaction Input Template... mutableTransactionInput.setSequenceNumber(SequenceNumber.MAX_SEQUENCE_NUMBER); mutableTransactionInput.setUnlockingScript(UnlockingScript.EMPTY_SCRIPT); } final MutableTransaction mutableTransaction = new MutableTransaction(); { // Init Transaction Template... mutableTransaction.setVersion(Transaction.VERSION); mutableTransaction.setLockTime(LockTime.MIN_TIMESTAMP); } { // Create Block1's CoinbaseTransaction; generates 50 BCH. mutableTransaction.addTransactionInput(TransactionInput.createCoinbaseTransactionInput(1L, "")); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address0, 50L * Transaction.SATOSHIS_PER_BITCOIN)); block1CoinbaseTransaction = mutableTransaction.asCoinbase(); } { // Create Block1's second Transaction that spends Block1's Coinbase and creates two 25BCH outputs. mutableTransaction.clearTransactionInputs(); mutableTransaction.clearTransactionOutputs(); { // Configure TransactionInput to spent Block1's Coinbase Transaction. mutableTransactionInput.setPreviousOutputTransactionHash(block1CoinbaseTransaction.getHash()); mutableTransactionInput.setPreviousOutputIndex(0); } mutableTransaction.addTransactionInput(mutableTransactionInput.asConst()); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address1, 25L * Transaction.SATOSHIS_PER_BITCOIN)); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address2, 25L * Transaction.SATOSHIS_PER_BITCOIN)); block1Transaction1 = mutableTransaction.asConst(); } { // Create Block2's CoinbaseTransaction; generates 50 BCH. mutableTransaction.clearTransactionInputs(); mutableTransaction.clearTransactionOutputs(); mutableTransaction.addTransactionInput(TransactionInput.createCoinbaseTransactionInput(2L, "")); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address1, 50L * Transaction.SATOSHIS_PER_BITCOIN)); block2CoinbaseTransaction = mutableTransaction.asCoinbase(); } { // Create Block2's second Transaction that spends Block1's second Transaction first TransactionOutput... mutableTransaction.clearTransactionInputs(); mutableTransaction.clearTransactionOutputs(); { // Configure TransactionInput to spent Block1's Coinbase Transaction. mutableTransactionInput.setPreviousOutputTransactionHash(block1Transaction1.getHash()); mutableTransactionInput.setPreviousOutputIndex(0); } mutableTransaction.addTransactionInput(mutableTransactionInput.asConst()); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address1, 12L * Transaction.SATOSHIS_PER_BITCOIN)); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address2, 13L * Transaction.SATOSHIS_PER_BITCOIN)); block2Transaction1 = mutableTransaction.asConst(); } { // Create Block2's third Transaction that spends Block2's second Transaction second TransactionOutput... mutableTransaction.clearTransactionInputs(); mutableTransaction.clearTransactionOutputs(); { // Configure TransactionInput to spent Block1's Coinbase Transaction. mutableTransactionInput.setPreviousOutputTransactionHash(block2Transaction1.getHash()); mutableTransactionInput.setPreviousOutputIndex(1); } mutableTransaction.addTransactionInput(mutableTransactionInput.asConst()); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address1, 10L * Transaction.SATOSHIS_PER_BITCOIN)); mutableTransaction.addTransactionOutput(TransactionOutput.createPayToAddressTransactionOutput(address2, 3L * Transaction.SATOSHIS_PER_BITCOIN)); block2Transaction2 = mutableTransaction.asConst(); } } { // Assemble Block 1... mutableBlock.addTransaction(block1CoinbaseTransaction); mutableBlock.addTransaction(block1Transaction1); block1 = mutableBlock.asConst(); } { // Assemble Block 2... mutableBlock.clearTransactions(); mutableBlock.addTransaction(block2CoinbaseTransaction); mutableBlock.addTransaction(block2Transaction1); mutableBlock.addTransaction(block2Transaction2); block2 = mutableBlock.asConst(); } } { // Store and sanity-check Block1 state... synchronized (BlockHeaderDatabaseManager.MUTEX) { blockDatabaseManager.storeBlock(block1); } unspentTransactionOutputManager.applyBlockToUtxoSet(block1, 1L, _fullNodeDatabaseManagerFactory); final TransactionOutput coinbaseTransactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1CoinbaseTransaction.getHash(), 0)); Assert.assertNull(coinbaseTransactionOutput); // Spent by Block1 Transaction1... final TransactionOutput transactionOutput0 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 0)); Assert.assertNotNull(transactionOutput0); final TransactionOutput transactionOutput1 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 1)); Assert.assertNotNull(transactionOutput1); } unspentTransactionOutputDatabaseManager.commitUnspentTransactionOutputs(_fullNodeDatabaseManagerFactory, true); // Commit the UTXO set... { // Store and sanity-check Block2 state... synchronized (BlockHeaderDatabaseManager.MUTEX) { blockDatabaseManager.storeBlock(block2); } unspentTransactionOutputManager.applyBlockToUtxoSet(block2, 2L, _fullNodeDatabaseManagerFactory); final TransactionOutput coinbaseTransactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1CoinbaseTransaction.getHash(), 0)); Assert.assertNull(coinbaseTransactionOutput); // Spent by Block1's Transaction1... final TransactionOutput transactionOutput0 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 0)); Assert.assertNull(transactionOutput0); // Spent by Block2's Transaction1... final TransactionOutput transactionOutput1 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 1)); Assert.assertNotNull(transactionOutput1); final TransactionOutput transactionOutput2 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block2Transaction1.getHash(), 0)); Assert.assertNotNull(transactionOutput2); final TransactionOutput transactionOutput3 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block2Transaction1.getHash(), 1)); Assert.assertNull(transactionOutput3); final TransactionOutput transactionOutput4 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block2Transaction2.getHash(), 0)); Assert.assertNotNull(transactionOutput4); final TransactionOutput transactionOutput5 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block2Transaction2.getHash(), 1)); Assert.assertNotNull(transactionOutput5); } unspentTransactionOutputDatabaseManager.commitUnspentTransactionOutputs(_fullNodeDatabaseManagerFactory, true); // Commit the UTXO set... // Action unspentTransactionOutputManager.removeBlockFromUtxoSet(block2, 2L); unspentTransactionOutputDatabaseManager.commitUnspentTransactionOutputs(_fullNodeDatabaseManagerFactory, true); // Commit the UTXO set... unspentTransactionOutputDatabaseManager.clearUncommittedUtxoSet(); // Assert // Should be exactly the same as before Block2 was applied... final TransactionOutput coinbaseTransactionOutput = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1CoinbaseTransaction.getHash(), 0)); Assert.assertNull(coinbaseTransactionOutput); // Spent by Block1 Transaction1... final TransactionOutput transactionOutput0 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 0)); Assert.assertNotNull(transactionOutput0); final TransactionOutput transactionOutput1 = unspentTransactionOutputDatabaseManager.getUnspentTransactionOutput(new TransactionOutputIdentifier(block1Transaction1.getHash(), 1)); Assert.assertNotNull(transactionOutput1); final Long committedBlockHeight = unspentTransactionOutputDatabaseManager.getCommittedUnspentTransactionOutputBlockHeight(); Assert.assertEquals(Long.valueOf(1L), committedBlockHeight); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/genesis/MutableSlpGenesisScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp.genesis; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public class MutableSlpGenesisScript extends SlpGenesisScriptCore { public void setTokenAbbreviation(final String tokenAbbreviation) { _tokenAbbreviation = tokenAbbreviation; } public void setTokenName(final String tokenName) { _tokenName = tokenName; } public void setDocumentUrl(final String documentUrl) { _documentUrl = documentUrl; } public void setDocumentHash(final Sha256Hash documentHash) { _documentHash = documentHash; } public void setDecimalCount(final Integer decimalCount) { _decimalCount = decimalCount; } public void setBatonOutputIndex(final Integer batonOutputIndex) { _batonOutputIndex = batonOutputIndex; } /** * Sets the number of tokens created. * The tokenCount is the equivalent to the number of "satoshis" created, not the number of "bitcoin". */ public void setTokenCount(final Long tokenCount) { _tokenCount = tokenCount; } @Override public ImmutableSlpGenesisScript asConst() { return new ImmutableSlpGenesisScript(this); } } <|start_filename|>src/main/java/com/softwareverde/network/p2p/message/ProtocolMessageFactory.java<|end_filename|> package com.softwareverde.network.p2p.message; public interface ProtocolMessageFactory<T extends ProtocolMessage> { T fromBytes(byte[] bytes); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/manager/RequestBabysitter.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager; import com.softwareverde.concurrent.service.SleepyService; import com.softwareverde.util.type.time.SystemTime; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantReadWriteLock; public class RequestBabysitter extends SleepyService { public static abstract class WatchedRequest { private final AtomicBoolean _watchHasCompleted = new AtomicBoolean(false); protected final Boolean onWatchEnded() { return _watchHasCompleted.compareAndSet(false, true); } protected final Boolean watchHasEnded() { return (! _watchHasCompleted.compareAndSet(false, true)); } protected abstract void onExpiration(); } protected final SystemTime _systemTime = new SystemTime(); protected final TreeMap<Long, List<WatchedRequest>> _requests = new TreeMap<Long, List<WatchedRequest>>(); protected final ReentrantReadWriteLock.ReadLock _readLock; protected final ReentrantReadWriteLock.WriteLock _writeLock; @Override protected void _onStart() { } @Override protected Boolean _run() { final List<WatchedRequest> removedWatchedRequests; final List<Long> itemsToRemove = new ArrayList<Long>(); _readLock.lock(); try { final Long now = _systemTime.getCurrentTimeInSeconds(); for (final Long expirationTime : _requests.keySet()) { if (expirationTime > now) { break; } itemsToRemove.add(expirationTime); } } finally { _readLock.unlock(); } if (! itemsToRemove.isEmpty()) { removedWatchedRequests = new ArrayList<WatchedRequest>(); _writeLock.lock(); try { for (final Long expirationTime : itemsToRemove) { final List<WatchedRequest> watchedRequests = _requests.remove(expirationTime); if (watchedRequests == null) { continue; } removedWatchedRequests.addAll(watchedRequests); } } finally { _writeLock.unlock(); } } else { removedWatchedRequests = null; } if (removedWatchedRequests != null) { for (final WatchedRequest watchedRequest : removedWatchedRequests) { if (! watchedRequest.watchHasEnded()) { watchedRequest.onExpiration(); } } } try { Thread.sleep(1000L); } catch (final InterruptedException exception) { final Thread currentThread = Thread.currentThread(); currentThread.interrupt(); return false; } _readLock.lock(); try { return (! _requests.isEmpty()); } finally { _readLock.unlock(); } } @Override protected void _onSleep() { } public RequestBabysitter() { final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(true); _readLock = readWriteLock.readLock(); _writeLock = readWriteLock.writeLock(); } public void watch(final WatchedRequest watchedRequest, final Long timeoutSeconds) { final long expireAfter = (_systemTime.getCurrentTimeInSeconds() + timeoutSeconds); List<WatchedRequest> list; _readLock.lock(); try { list = _requests.get(expireAfter); if (list != null) { list.add(watchedRequest); } } finally { _readLock.unlock(); } if (list == null) { _writeLock.lock(); try { list = _requests.get(expireAfter); if (list == null) { list = new ArrayList<WatchedRequest>(); _requests.put(expireAfter, list); } list.add(watchedRequest); } finally { _writeLock.unlock(); } } this.wakeUp(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/SlpScriptBuilder.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.locking.MutableLockingScript; import com.softwareverde.bitcoin.transaction.script.opcode.ControlOperation; import com.softwareverde.bitcoin.transaction.script.opcode.PushOperation; import com.softwareverde.bitcoin.transaction.script.slp.genesis.SlpGenesisScript; import com.softwareverde.bitcoin.transaction.script.slp.mint.SlpMintScript; import com.softwareverde.bitcoin.transaction.script.slp.send.SlpSendScript; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.bitcoin.util.StringUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.ImmutableByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.util.Util; public class SlpScriptBuilder { protected static final ByteArray EMPTY_BYTE_ARRAY = new ImmutableByteArray(new byte[0]); // All SLP integer values are unsigned and use big-endian encoding. protected static ByteArray longToBytes(final Long value) { // if (value == 0L) { return new MutableByteArray(0); } if (value == 0L) { return new MutableByteArray(1); } // SLP uses non-minimally encoded values for zero. final MutableByteArray longBytes = MutableByteArray.wrap(ByteUtil.longToBytes(value)); final int trimByteCount = (Long.numberOfLeadingZeros(value) / 8); return MutableByteArray.wrap(longBytes.getBytes(trimByteCount, (8 - trimByteCount))); } protected static ByteArray longToFixedBytes(final Long value, final Integer byteCount) { final MutableByteArray fixedLengthBytes = new MutableByteArray(byteCount); final ByteArray longBytes = MutableByteArray.wrap(ByteUtil.longToBytes(value)); for (int i = 0; i < byteCount; ++i) { int index = (byteCount - i - 1); final byte b = longBytes.getByte(index); fixedLengthBytes.setByte(index, b); } return fixedLengthBytes; } public LockingScript createGenesisScript(final SlpGenesisScript slpGenesisScript) { // Allowed Non-Return Opcodes: // PUSH_DATA (0x01, 0x4B), // PUSH_DATA_BYTE (0x4C), // PUSH_DATA_SHORT (0x4D), // PUSH_DATA_INTEGER (0x4E) final ByteArray tokenAbbreviationBytes = MutableByteArray.wrap(StringUtil.stringToBytes(slpGenesisScript.getTokenAbbreviation())); final ByteArray tokenFullNameBytes = MutableByteArray.wrap(StringUtil.stringToBytes(slpGenesisScript.getTokenName())); final ByteArray documentUrlBytes = MutableByteArray.wrap(StringUtil.stringToBytes(Util.coalesce(slpGenesisScript.getDocumentUrl(), ""))); final ByteArray documentHashBytes = Util.coalesce(slpGenesisScript.getDocumentHash(), EMPTY_BYTE_ARRAY); final Integer batonOutputIndex = slpGenesisScript.getBatonOutputIndex(); final ByteArray tokenDecimalBytes = SlpScriptBuilder.longToBytes(Util.coalesce(slpGenesisScript.getDecimalCount()).longValue()); final ByteArray batonOutputIndexBytes = (batonOutputIndex == null ? EMPTY_BYTE_ARRAY : SlpScriptBuilder.longToBytes(batonOutputIndex.longValue())); final ByteArray totalCountCountBytes = SlpScriptBuilder.longToFixedBytes(Util.coalesce(slpGenesisScript.getTokenCount()), 8); final MutableLockingScript lockingScript = new MutableLockingScript(); lockingScript.addOperation(ControlOperation.RETURN); lockingScript.addOperation(PushOperation.pushBytes(SlpScriptType.LOKAD_ID)); // Lokad Id (Static Value) lockingScript.addOperation(PushOperation.pushBytes(SlpScriptType.TOKEN_TYPE)); // Token Type (Static Value) lockingScript.addOperation(PushOperation.pushBytes(SlpScriptType.GENESIS.getBytes())); // Script Type (Static Value) lockingScript.addOperation(PushOperation.pushBytes(tokenAbbreviationBytes)); // Token Abbreviation lockingScript.addOperation(PushOperation.pushBytes(tokenFullNameBytes)); // Token Full Name lockingScript.addOperation(PushOperation.pushBytes(documentUrlBytes)); // Token Document Url lockingScript.addOperation(PushOperation.pushBytes(documentHashBytes)); // Document Hash lockingScript.addOperation(PushOperation.pushBytes(tokenDecimalBytes)); // Decimal Count lockingScript.addOperation(PushOperation.pushBytes(batonOutputIndexBytes)); // Baton Output lockingScript.addOperation(PushOperation.pushBytes(totalCountCountBytes)); // Mint Quantity return lockingScript; } public LockingScript createMintScript(final SlpMintScript slpMintScript) { final Integer batonOutputIndex = slpMintScript.getBatonOutputIndex(); final ByteArray batonOutputIndexBytes = (batonOutputIndex == null ? EMPTY_BYTE_ARRAY : SlpScriptBuilder.longToBytes(batonOutputIndex.longValue())); final ByteArray totalCountCountBytes = SlpScriptBuilder.longToFixedBytes(Util.coalesce(slpMintScript.getTokenCount()), 8); final MutableLockingScript lockingScript = new MutableLockingScript(); lockingScript.addOperation(ControlOperation.RETURN); lockingScript.addOperation(PushOperation.pushBytes(SlpScriptType.LOKAD_ID)); // Lokad Id (Static Value) lockingScript.addOperation(PushOperation.pushBytes(SlpScriptType.TOKEN_TYPE)); // Token Type (Static Value) lockingScript.addOperation(PushOperation.pushBytes(SlpScriptType.MINT.getBytes())); // Script Type (Static Value) lockingScript.addOperation(PushOperation.pushBytes(slpMintScript.getTokenId())); // Token id lockingScript.addOperation(PushOperation.pushBytes(batonOutputIndexBytes)); // Baton Output lockingScript.addOperation(PushOperation.pushBytes(totalCountCountBytes)); // Mint Quantity return lockingScript; } public LockingScript createSendScript(final SlpSendScript slpSendScript) { final MutableLockingScript lockingScript = new MutableLockingScript(); lockingScript.addOperation(ControlOperation.RETURN); lockingScript.addOperation(PushOperation.pushBytes(SlpScriptType.LOKAD_ID)); // Lokad Id (Static Value) lockingScript.addOperation(PushOperation.pushBytes(SlpScriptType.TOKEN_TYPE)); // Token Type (Static Value) lockingScript.addOperation(PushOperation.pushBytes(SlpScriptType.SEND.getBytes())); // Script Type (Static Value) lockingScript.addOperation(PushOperation.pushBytes(slpSendScript.getTokenId())); // Token id for (int i = 1; i < SlpSendScript.MAX_OUTPUT_COUNT; ++i) { final Long amount = slpSendScript.getAmount(i); if (amount == null) { break; } final ByteArray spendAmountBytes = SlpScriptBuilder.longToFixedBytes(amount, 8); lockingScript.addOperation(PushOperation.pushBytes(spendAmountBytes)); } return lockingScript; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/node/MessageRouter.java<|end_filename|> package com.softwareverde.bitcoin.server.node; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.logging.Logger; import com.softwareverde.network.p2p.message.ProtocolMessage; import java.util.HashMap; public class MessageRouter { public interface MessageHandler { void run(ProtocolMessage message, BitcoinNode bitcoinNode); } public interface UnknownRouteHandler { void run(MessageType messageType, ProtocolMessage message, BitcoinNode bitcoinNode); } protected final HashMap<MessageType, MessageHandler> _routingTable = new HashMap<MessageType, MessageHandler>(); protected UnknownRouteHandler _unknownRouteHandler; public void addRoute(final MessageType messageType, final MessageHandler messageHandler) { _routingTable.put(messageType, messageHandler); } public void removeRoute(final MessageType messageType) { _routingTable.remove(messageType); } public void route(final MessageType messageType, final ProtocolMessage message, final BitcoinNode bitcoinNode) { final MessageHandler messageHandler = _routingTable.get(messageType); if (messageHandler == null) { if (_unknownRouteHandler != null) { _unknownRouteHandler.run(messageType, message, bitcoinNode); } return; } try { messageHandler.run(message, bitcoinNode); } catch (final Exception exception) { Logger.warn(exception); } } public void setUnknownRouteHandler(final UnknownRouteHandler unknownRouteHandler) { _unknownRouteHandler = unknownRouteHandler; } } <|start_filename|>src/main/java/com/softwareverde/network/p2p/message/type/PingMessage.java<|end_filename|> package com.softwareverde.network.p2p.message.type; import com.softwareverde.network.p2p.message.ProtocolMessage; public interface PingMessage extends ProtocolMessage { Long getNonce(); } <|start_filename|>src/main/java/com/softwareverde/concurrent/Pin.java<|end_filename|> package com.softwareverde.concurrent; import com.softwareverde.util.timer.NanoTimer; import java.util.concurrent.atomic.AtomicBoolean; public class Pin { protected final AtomicBoolean _pin = new AtomicBoolean(false); protected Boolean _waitForRelease(final Long timeout) throws InterruptedException { synchronized (_pin) { final NanoTimer nanoTimer = new NanoTimer(); nanoTimer.start(); if (_pin.get()) { return true; } _pin.wait(timeout); nanoTimer.stop(); final Double msElapsed = nanoTimer.getMillisecondsElapsed(); // Timeout reached... if (msElapsed >= timeout) { return false; } return true; } } public Boolean wasReleased() { synchronized (_pin) { return _pin.get(); } } public void release() { synchronized (_pin) { _pin.set(true); _pin.notifyAll(); } } public void waitForRelease() { try { _waitForRelease(0L); } catch (final InterruptedException exception) { throw new RuntimeException(exception); } } public Boolean waitForRelease(final Long timeout) throws InterruptedException { return _waitForRelease(timeout); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/IndexedOutput.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.script.ScriptType; public class IndexedOutput { public final TransactionId transactionId; public final Integer outputIndex; public final Long amount; public final ScriptType scriptType; public final Address address; public final TransactionId slpTransactionId; public IndexedOutput(final TransactionId transactionId, final Integer outputIndex, final Long amount, final ScriptType scriptType, final Address address, final TransactionId slpTransactionId) { this.transactionId = transactionId; this.outputIndex = outputIndex; this.amount = amount; this.scriptType = scriptType; this.address = address; this.slpTransactionId = slpTransactionId; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeMedianBlockTime.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.chain.time.ImmutableMedianBlockTime; import com.softwareverde.bitcoin.chain.time.MutableMedianBlockTime; public class FakeMedianBlockTime extends MutableMedianBlockTime { protected Long _medianBlockTime; public FakeMedianBlockTime() { _medianBlockTime = Long.MAX_VALUE; } public FakeMedianBlockTime(final Long medianBlockTime) { _medianBlockTime = medianBlockTime; } @Override public ImmutableMedianBlockTime asConst() { return ImmutableMedianBlockTime.fromSeconds(_medianBlockTime); } @Override public Long getCurrentTimeInSeconds() { return _medianBlockTime; } @Override public Long getCurrentTimeInMilliSeconds() { return (_medianBlockTime * 1000L); } public void setMedianBlockTime(final Long medianBlockTime) { _medianBlockTime = medianBlockTime; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/endpoint/NodesApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.endpoint; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.bitcoin.server.module.explorer.api.v1.get.GetNodesHandler; import com.softwareverde.http.HttpMethod; import com.softwareverde.json.Json; public class NodesApi extends ExplorerApiEndpoint { public static class NodesResult extends ApiResult { private Json _nodes = new Json(true); public void setNodes(final Json nodes) { _nodes = nodes; } @Override public Json toJson() { final Json json = super.toJson(); json.put("nodes", _nodes); return json; } } public NodesApi(final String apiPrePath, final Environment environment) { super(environment); _defineEndpoint((apiPrePath + "/nodes"), HttpMethod.GET, new GetNodesHandler()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/address/PayToScriptHashAddress.java<|end_filename|> package com.softwareverde.bitcoin.address; public class PayToScriptHashAddress extends Address { public static final byte PREFIX = (byte) 0x05; public static final byte BASE_32_PREFIX = (byte) (0x08); @Override protected byte _getPrefix() { return PREFIX; } @Override protected byte _getBase32Prefix() { return BASE_32_PREFIX; } protected PayToScriptHashAddress(final byte[] bytes) { super(bytes); } @Override public Boolean isCompressed() { return true; } @Override public PayToScriptHashAddress asConst() { return this; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/response/error/NotFoundResponseMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response.error; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItem; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItemInflater; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class NotFoundResponseMessage extends BitcoinProtocolMessage { private final MutableList<InventoryItem> _inventoryItems = new MutableList<InventoryItem>(); public NotFoundResponseMessage() { super(MessageType.NOT_FOUND); } public List<InventoryItem> getInventoryItems() { return _inventoryItems; } public void addItem(final InventoryItem inventoryItem) { _inventoryItems.add(inventoryItem); } public void clearItems() { _inventoryItems.clear(); } @Override protected ByteArray _getPayload() { final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(_inventoryItems.getCount()), Endian.BIG); for (final InventoryItem inventoryItem : _inventoryItems) { byteArrayBuilder.appendBytes(inventoryItem.getBytes(), Endian.BIG); } return byteArrayBuilder; } @Override protected Integer _getPayloadByteCount() { final int inventoryItemCount = _inventoryItems.getCount(); final byte[] itemCountBytes = ByteUtil.variableLengthIntegerToBytes(inventoryItemCount); return (itemCountBytes.length + (inventoryItemCount * InventoryItemInflater.BYTE_COUNT)); } } <|start_filename|>src/main/java/com/softwareverde/network/socket/BinarySocket.java<|end_filename|> package com.softwareverde.network.socket; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.util.ByteUtil; public class BinarySocket extends Socket { public static Integer DEFAULT_BUFFER_PAGE_BYTE_COUNT = (1024 * 2); public static Integer DEFAULT_MAX_BUFFER_BYTE_COUNT = (int) (128L * ByteUtil.Unit.Binary.MEBIBYTES); protected final BinaryPacketFormat _binaryPacketFormat; public BinarySocket(final java.net.Socket socket, final BinaryPacketFormat binaryPacketFormat, final ThreadPool threadPool) { super(socket, new BinarySocketReadThread(DEFAULT_BUFFER_PAGE_BYTE_COUNT, DEFAULT_MAX_BUFFER_BYTE_COUNT, binaryPacketFormat), threadPool); _binaryPacketFormat = binaryPacketFormat; } public void setBufferPageByteCount(final Integer bufferSize) { ((BinarySocketReadThread) _readThread).setBufferPageByteCount(bufferSize); } public void setBufferMaxByteCount(final Integer totalMaxBufferSize) { ((BinarySocketReadThread) _readThread).setBufferMaxByteCount(totalMaxBufferSize); } public Integer getBufferPageByteCount() { final PacketBuffer packetBuffer = ((BinarySocketReadThread) _readThread).getProtocolMessageBuffer(); return packetBuffer.getPageByteCount(); } public Integer getBufferMaxByteCount() { final PacketBuffer packetBuffer = ((BinarySocketReadThread) _readThread).getProtocolMessageBuffer(); return packetBuffer.getMaxByteCount(); } public BinaryPacketFormat getBinaryPacketFormat() { return _binaryPacketFormat; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/signer/TransactionOutputRepository.java<|end_filename|> package com.softwareverde.bitcoin.transaction.signer; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; public interface TransactionOutputRepository { TransactionOutput get(TransactionOutputIdentifier transactionOutputIdentifier); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/memory/LowMemoryMonitor.java<|end_filename|> package com.softwareverde.bitcoin.server.memory; import javax.management.Notification; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.util.List; public class LowMemoryMonitor { protected final Float _memoryThresholdPercent; protected final Runnable _memoryThresholdReachedCallback; protected void _registerCallback() { final MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); final NotificationEmitter notificationEmitter = (NotificationEmitter) memoryBean; notificationEmitter.addNotificationListener(new NotificationListener() { @Override public void handleNotification(final Notification notification, final Object handback) { _memoryThresholdReachedCallback.run(); } }, null, null); final List<MemoryPoolMXBean> memoryPoolBeans = ManagementFactory.getMemoryPoolMXBeans(); for (final MemoryPoolMXBean memoryPoolBean : memoryPoolBeans) { if (memoryPoolBean.isUsageThresholdSupported()) { final MemoryUsage memoryUsage = memoryPoolBean.getUsage(); final long memoryUsageMax = memoryUsage.getMax(); memoryPoolBean.setUsageThreshold((long) (memoryUsageMax * _memoryThresholdPercent)); } } } public LowMemoryMonitor(final Float memoryThresholdPercent, final Runnable memoryThresholdReachedCallback) { _memoryThresholdPercent = memoryThresholdPercent; _memoryThresholdReachedCallback = memoryThresholdReachedCallback; _registerCallback(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/DatabaseMaintainer.java<|end_filename|> package com.softwareverde.bitcoin.server.database; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; public class DatabaseMaintainer { protected final DatabaseConnectionFactory _databaseConnectionFactory; protected static final List<String> TABLES; static { final ImmutableListBuilder<String> listBuilder = new ImmutableListBuilder<String>(); listBuilder.add("properties"); listBuilder.add("script_types"); listBuilder.add("pending_blocks"); listBuilder.add("invalid_blocks"); listBuilder.add("pending_transactions"); listBuilder.add("pending_transaction_data"); listBuilder.add("pending_transactions_dependent_transactions"); listBuilder.add("addresses"); listBuilder.add("blocks"); listBuilder.add("blockchain_segments"); listBuilder.add("transactions"); listBuilder.add("block_transactions"); listBuilder.add("committed_unspent_transaction_outputs"); listBuilder.add("unconfirmed_transactions"); listBuilder.add("unconfirmed_transaction_outputs"); listBuilder.add("unconfirmed_transaction_inputs"); listBuilder.add("indexed_transaction_outputs"); listBuilder.add("indexed_transaction_inputs"); listBuilder.add("validated_slp_transactions"); listBuilder.add("hosts"); listBuilder.add("nodes"); listBuilder.add("node_features"); listBuilder.add("node_transactions_inventory"); TABLES = listBuilder.build(); } public DatabaseMaintainer(final DatabaseConnectionFactory databaseConnectionFactory) { _databaseConnectionFactory = databaseConnectionFactory; } public void analyzeTables() { try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { for (final String tableName : TABLES) { databaseConnection.executeSql(new Query("ANALYZE TABLE " + tableName)); } } catch (final DatabaseException exception) { Logger.warn(exception); } } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/v1/get/SearchHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.v1.get; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.bitcoin.server.module.explorer.api.endpoint.SearchApi; import com.softwareverde.bitcoin.server.module.node.rpc.NodeJsonRpcConnection; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.http.server.servlet.routed.RequestHandler; import com.softwareverde.json.Json; import com.softwareverde.json.Jsonable; import com.softwareverde.util.StringUtil; import com.softwareverde.util.Util; import java.util.Map; public class SearchHandler implements RequestHandler<Environment> { /** * SEARCH * Requires GET: query, [rawFormat=0] * Requires POST: **/ @Override public Response handleRequest(final Request request, final Environment environment, final Map<String, String> parameters) throws Exception { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); final String queryParam = getParameters.get("query").trim(); if (queryParam.isEmpty()) { return new JsonResponse(Response.Codes.BAD_REQUEST, (new ApiResult(false, "Missing Parameter: query"))); } final Boolean rawFormat = (getParameters.containsKey("rawFormat") ? Util.parseBool(getParameters.get("rawFormat")) : null); try (final NodeJsonRpcConnection nodeJsonRpcConnection = environment.getNodeJsonRpcConnection()) { if (nodeJsonRpcConnection == null) { final SearchApi.SearchResult result = new SearchApi.SearchResult(); result.setWasSuccess(false); result.setErrorMessage("Unable to connect to node."); return new JsonResponse(Response.Codes.SERVER_ERROR, result); } SearchApi.SearchResult.ObjectType objectType = null; Jsonable object = null; { final int hashCharacterLength = 64; final AddressInflater addressInflater = new AddressInflater(); final Address address; { final Address base58Address = addressInflater.fromBase58Check(queryParam); if (base58Address != null) { address = base58Address; } else { address = addressInflater.fromBase32Check(queryParam); } } if (address != null) { final Json responseJson = nodeJsonRpcConnection.getAddressTransactions(address); if (responseJson == null) { return new JsonResponse(Response.Codes.SERVER_ERROR, new ApiResult(false, "Request timed out.")); } if (responseJson.getBoolean("wasSuccess")) { final Json transactionsJson = responseJson.get("address"); object = transactionsJson; objectType = SearchApi.SearchResult.ObjectType.ADDRESS; } } else if ( (queryParam.startsWith("00000000")) || (queryParam.length() != hashCharacterLength) ) { final Json queryBlockResponseJson; if (queryParam.length() == hashCharacterLength) { final Sha256Hash blockHash = Sha256Hash.fromHexString(queryParam); queryBlockResponseJson = nodeJsonRpcConnection.getBlockHeader(blockHash, rawFormat); if ( (queryBlockResponseJson != null) && queryBlockResponseJson.hasKey("block") ) { final Json blockTransactionsJson; try (final NodeJsonRpcConnection secondNodeJsonRpcConnection = environment.getNodeJsonRpcConnection()) { if (secondNodeJsonRpcConnection == null) { final SearchApi.SearchResult result = new SearchApi.SearchResult(); result.setWasSuccess(false); result.setErrorMessage("Unable to connect to node."); return new JsonResponse(Response.Codes.SERVER_ERROR, result); } final Json queryBlockTransactionsJson = secondNodeJsonRpcConnection.getBlockTransactions(blockHash, 32, 0); blockTransactionsJson = queryBlockTransactionsJson.get("transactions"); } final Json blockJson = queryBlockResponseJson.get("block"); blockJson.put("transactions", blockTransactionsJson); queryBlockResponseJson.put("block", blockJson); } } else { final boolean queryParamContainsNonNumeric = (! StringUtil.pregMatch("([^0-9,. ])", queryParam).isEmpty()); if ( (! Util.isLong(queryParam)) || (queryParamContainsNonNumeric) ) { return new JsonResponse(Response.Codes.BAD_REQUEST, (new ApiResult(false, "Invalid Parameter Value: " + queryParam))); } final Long blockHeight = Util.parseLong(queryParam); queryBlockResponseJson = nodeJsonRpcConnection.getBlockHeader(blockHeight, rawFormat); if ( (queryBlockResponseJson != null) && queryBlockResponseJson.hasKey("block") ) { final Json blockTransactionsJson; try (final NodeJsonRpcConnection secondNodeJsonRpcConnection = environment.getNodeJsonRpcConnection()) { if (secondNodeJsonRpcConnection == null) { final SearchApi.SearchResult result = new SearchApi.SearchResult(); result.setWasSuccess(false); result.setErrorMessage("Unable to connect to node."); return new JsonResponse(Response.Codes.SERVER_ERROR, result); } final Json queryBlockTransactionsJson = secondNodeJsonRpcConnection.getBlockTransactions(blockHeight, 32, 0); blockTransactionsJson = queryBlockTransactionsJson.get("transactions"); } final Json blockJson = queryBlockResponseJson.get("block"); blockJson.put("transactions", blockTransactionsJson); queryBlockResponseJson.put("block", blockJson); } } if (queryBlockResponseJson == null) { return new JsonResponse(Response.Codes.SERVER_ERROR, new ApiResult(false, "Request timed out.")); } if (queryBlockResponseJson.getBoolean("wasSuccess")) { if (Util.coalesce(rawFormat)) { final String blockHex = queryBlockResponseJson.getString("block"); object = SearchApi.makeRawObjectJson(blockHex); objectType = SearchApi.SearchResult.ObjectType.BLOCK; } else { final Json blockJson = queryBlockResponseJson.get("block"); final boolean isFullBlock = (blockJson.get("transactions").length() > 0); object = blockJson; objectType = (isFullBlock ? SearchApi.SearchResult.ObjectType.BLOCK : SearchApi.SearchResult.ObjectType.BLOCK_HEADER); } } } if ( (objectType == null) && (queryParam.length() == hashCharacterLength) ) { final Sha256Hash blockHash = Sha256Hash.fromHexString(queryParam); final Json queryTransactionResponseJson = nodeJsonRpcConnection.getTransaction(blockHash, rawFormat); if (queryTransactionResponseJson == null) { return new JsonResponse(Response.Codes.SERVER_ERROR, new ApiResult(false, "Request timed out.")); } if (queryTransactionResponseJson.getBoolean("wasSuccess")) { if (Util.coalesce(rawFormat)) { final String transactionHex = queryTransactionResponseJson.getString("transaction"); object = SearchApi.makeRawObjectJson(transactionHex); objectType = SearchApi.SearchResult.ObjectType.TRANSACTION; } else { final Json transactionJson = queryTransactionResponseJson.get("transaction"); object = transactionJson; objectType = SearchApi.SearchResult.ObjectType.TRANSACTION; } } } } final Boolean wasSuccess = (objectType != null); final SearchApi.SearchResult searchResult = new SearchApi.SearchResult(); searchResult.setWasSuccess(wasSuccess); searchResult.setObjectType(objectType); searchResult.setObject(object); return new JsonResponse(Response.Codes.OK, searchResult); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/mempool/QueryUnconfirmedTransactionsMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.mempool; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; public class QueryUnconfirmedTransactionsMessageInflater extends BitcoinProtocolMessageInflater { @Override public QueryUnconfirmedTransactionsMessage fromBytes(final byte[] bytes) { final QueryUnconfirmedTransactionsMessage queryUnconfirmedTransactionsMessage = new QueryUnconfirmedTransactionsMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.QUERY_UNCONFIRMED_TRANSACTIONS); if (protocolMessageHeader == null) { return null; } return queryUnconfirmedTransactionsMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/rpc/handler/UtxoCacheHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.rpc.handler; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.utxo.UnspentTransactionOutputDatabaseManager; import com.softwareverde.bitcoin.server.module.node.rpc.NodeRpcHandler; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; public class UtxoCacheHandler implements NodeRpcHandler.UtxoCacheHandler { protected final FullNodeDatabaseManagerFactory _databaseManagerFactory; public UtxoCacheHandler(final FullNodeDatabaseManagerFactory databaseManagerFactory) { _databaseManagerFactory = databaseManagerFactory; } @Override public Long getCachedUtxoCount() { try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = databaseManager.getUnspentTransactionOutputDatabaseManager(); return unspentTransactionOutputDatabaseManager.getUncommittedUnspentTransactionOutputCount(true); } catch (final DatabaseException exception) { Logger.warn(exception); return null; } } @Override public Long getMaxCachedUtxoCount() { try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = databaseManager.getUnspentTransactionOutputDatabaseManager(); return unspentTransactionOutputDatabaseManager.getMaxUtxoCount(); } catch (final DatabaseException exception) { Logger.warn(exception); return null; } } @Override public Long getUncommittedUtxoCount() { try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = databaseManager.getUnspentTransactionOutputDatabaseManager(); return unspentTransactionOutputDatabaseManager.getUncommittedUnspentTransactionOutputCount(true); } catch (final DatabaseException exception) { Logger.warn(exception); return null; } } @Override public Long getCommittedUtxoBlockHeight() { try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = databaseManager.getUnspentTransactionOutputDatabaseManager(); return unspentTransactionOutputDatabaseManager.getCommittedUnspentTransactionOutputBlockHeight(true); } catch (final DatabaseException exception) { Logger.warn(exception); return null; } } @Override public void commitUtxoCache() { try (final FullNodeDatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final UnspentTransactionOutputDatabaseManager unspentTransactionOutputDatabaseManager = databaseManager.getUnspentTransactionOutputDatabaseManager(); Logger.info("Committing UTXO set."); unspentTransactionOutputDatabaseManager.commitUnspentTransactionOutputs(_databaseManagerFactory); } catch (final DatabaseException exception) { Logger.warn(exception); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/signer/HashMapTransactionOutputRepository.java<|end_filename|> package com.softwareverde.bitcoin.transaction.signer; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import java.util.HashMap; public class HashMapTransactionOutputRepository implements TransactionOutputRepository { protected final HashMap<TransactionOutputIdentifier, TransactionOutput> _data = new HashMap<TransactionOutputIdentifier, TransactionOutput>(); @Override public TransactionOutput get(final TransactionOutputIdentifier transactionOutputIdentifier) { return _data.get(transactionOutputIdentifier); } public void put(final TransactionOutputIdentifier transactionOutputIdentifier, final TransactionOutput transactionOutput) { _data.put(transactionOutputIdentifier, transactionOutput.asConst()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/response/block/BlockMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response.block; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; public class BlockMessageInflater extends BitcoinProtocolMessageInflater { protected final BlockInflaters _blockInflaters; public BlockMessageInflater(final BlockInflaters blockInflaters) { _blockInflaters = blockInflaters; } @Override public BlockMessage fromBytes(final byte[] bytes) { final BlockMessage blockMessage = new BlockMessage(_blockInflaters); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.BLOCK); if (protocolMessageHeader == null) { return null; } final BlockInflater blockInflater = _blockInflaters.getBlockInflater(); blockMessage._block = blockInflater.fromBytes(byteArrayReader); return blockMessage; } } <|start_filename|>www-shared/js/hash-resizer.js<|end_filename|> (function() { window.HashResizer = function(container) { if (container) { // If the container is specifically provided, do not use/reset the global timer... window.setTimeout(function() { window.HashResizer.update(container); }, 200); return; } window.clearTimeout(window.HashResizer.globalTimeout); window.HashResizer.globalTimeout = window.setTimeout(window.HashResizer.update, 200); } window.HashResizer.update = function(container) { const TEXT_NODE_TYPE = 3; container = (container || document); $(".hash, .transaction-hash, .block-hashes, .previous-block-hash, .difficulty .mask, .merkle-root", container).each(function() { const element = $(this); if (element.is(".no-resize")) { return; } window.setTimeout(function() { const valueElement = $(".value", element); const textNode = (valueElement.contents().filter(function() { return this.nodeType == TEXT_NODE_TYPE; })[0] || { }); const textNodeContent = textNode.nodeValue; const originalValue = (valueElement.data("hash-value") || textNodeContent || ""); if (originalValue.length != 64) { return; } // Sanity check... valueElement.data("hash-value", originalValue); textNode.nodeValue = originalValue; let isOverflowing = null; let truncatedValue = originalValue; do { isOverflowing = ( (element[0].offsetHeight < element[0].scrollHeight) || (element[0].offsetWidth < element[0].scrollWidth) ); if (isOverflowing) { const length = truncatedValue.length; if (length < 4) { break; } truncatedValue = truncatedValue.substr(0, ((length / 2) - 2)) + "..." + truncatedValue.substr((length / 2) + 2); textNode.nodeValue = truncatedValue; } } while (isOverflowing); }, 0); }); }; $(window).on("load resize", function() { window.HashResizer(); }); })(); <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/output/TransactionOutputInflater.java<|end_filename|> package com.softwareverde.bitcoin.transaction.output; import com.softwareverde.bitcoin.transaction.script.locking.ImmutableLockingScript; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.logging.Logger; import com.softwareverde.util.HexUtil; import com.softwareverde.util.bytearray.Endian; public class TransactionOutputInflater { protected MutableTransactionOutput _fromByteArrayReader(final Integer index, final ByteArrayReader byteArrayReader) { final MutableTransactionOutput transactionOutput = new MutableTransactionOutput(); transactionOutput._amount = byteArrayReader.readLong(8, Endian.LITTLE); transactionOutput._index = index; final Integer scriptByteCount = byteArrayReader.readVariableSizedInteger().intValue(); transactionOutput._lockingScript = new ImmutableLockingScript(MutableByteArray.wrap(byteArrayReader.readBytes(scriptByteCount, Endian.BIG))); if (byteArrayReader.didOverflow()) { return null; } return transactionOutput; } public void _debugBytes(final ByteArrayReader byteArrayReader) { Logger.debug("Tx Output: Amount: " + MutableByteArray.wrap(byteArrayReader.readBytes(8))); final ByteArrayReader.VariableSizedInteger variableSizedInteger = byteArrayReader.peakVariableSizedInteger(); Logger.debug("Tx Output: Script Byte Count: " + HexUtil.toHexString(byteArrayReader.readBytes(variableSizedInteger.bytesConsumedCount))); Logger.debug("Tx Output: Script: " + HexUtil.toHexString(byteArrayReader.readBytes((int) variableSizedInteger.value))); } public MutableTransactionOutput fromBytes(final Integer index, final ByteArrayReader byteArrayReader) { return _fromByteArrayReader(index, byteArrayReader); } public MutableTransactionOutput fromBytes(final Integer index, final byte[] bytes) { final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); return _fromByteArrayReader(index, byteArrayReader); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/server/database/pool/DatabaseConnectionPoolTests.java<|end_filename|> package com.softwareverde.bitcoin.server.database.pool; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.bitcoin.test.IntegrationTest; import com.softwareverde.database.row.Row; import org.junit.After; import org.junit.Assert; import org.junit.Before; import java.util.List; public class DatabaseConnectionPoolTests extends IntegrationTest { protected Integer _getCurrentConnectionCount(final DatabaseConnection databaseConnection) throws Exception { final List<Row> rows = databaseConnection.query(new Query("SHOW STATUS WHERE variable_name = 'Threads_connected'")); final Row row = rows.get(0); return row.getInteger("value"); } @Override @Before public void before() throws Exception { super.before(); } @Override @After public void after() throws Exception { super.after(); } /** * This test was originally designed specifically for the custom-written database connection pool. * After the Hikari replacement, this test has become obsolete and no longer represents the original intent. * Therefore, it has been disabled and deprecated, and will likely be removed in the future. */ public void should_not_surpass_max_connection_count() throws Exception { // Setup final DatabaseConnection databaseConnection = _database.newConnection(); final Integer baselineConnectionCount = _getCurrentConnectionCount(databaseConnection); final Integer maxConnectionCount = 10; final DatabaseConnectionPool databaseConnectionPool = _database.getDatabaseConnectionPool(); final DatabaseConnection[] pooledConnections = new DatabaseConnection[maxConnectionCount]; // Action for (int i = 0; i < maxConnectionCount; ++i) { final DatabaseConnection pooledConnection = databaseConnectionPool.newConnection(); pooledConnections[i] = pooledConnection; // Assert final Integer newConnectionCount = _getCurrentConnectionCount(pooledConnection); final Integer expectedConnectionCount = (Math.min(i + 1, maxConnectionCount) + baselineConnectionCount); Assert.assertEquals(expectedConnectionCount, newConnectionCount); } // Should not actually close any connections... just mark them as available. for (final DatabaseConnection pooledDatabaseConnection : pooledConnections) { pooledDatabaseConnection.close(); } { // Assert final Integer newConnectionCount = _getCurrentConnectionCount(databaseConnection); final Integer expectedConnectionCount = (maxConnectionCount + baselineConnectionCount); Assert.assertEquals(expectedConnectionCount, newConnectionCount); } // Action for (int i = 0; i < maxConnectionCount * 2; ++i) { try (final DatabaseConnection pooledConnection = databaseConnectionPool.newConnection()) { // Assert final Integer newConnectionCount = _getCurrentConnectionCount(pooledConnection); final Integer expectedConnectionCount = (maxConnectionCount + baselineConnectionCount); Assert.assertEquals(expectedConnectionCount, newConnectionCount); } } databaseConnectionPool.close(); // Assert final Integer newConnectionCount = _getCurrentConnectionCount(databaseConnection); Assert.assertEquals(baselineConnectionCount, newConnectionCount); Assert.assertEquals(0, databaseConnectionPool.getAliveConnectionCount().intValue()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/unlocking/ImmutableUnlockingScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.unlocking; import com.softwareverde.bitcoin.transaction.script.ImmutableScript; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.constable.bytearray.ByteArray; public class ImmutableUnlockingScript extends ImmutableScript implements UnlockingScript { protected ImmutableUnlockingScript() { super(); } public ImmutableUnlockingScript(final ByteArray bytes) { super(bytes); } public ImmutableUnlockingScript(final Script script) { super(script); } @Override public ImmutableUnlockingScript asConst() { return this; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/MultiConnectionDatabaseContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManagerFactory; public interface MultiConnectionDatabaseContext { DatabaseManagerFactory getDatabaseManagerFactory(); } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/StratumApiResult.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.json.Json; import java.util.HashMap; public class StratumApiResult extends ApiResult { private HashMap<String, Object> _values = new HashMap<String, Object>(); public void put(final String key, final Object object) { _values.put(key, object); } public StratumApiResult() { } public StratumApiResult(final Boolean wasSuccess, final String errorMessage) { super(wasSuccess, errorMessage); } @Override public Json toJson() { final Json json = super.toJson(); for (final String key : _values.keySet()) { final Object value = _values.get(key); json.put(key, value); } return json; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/node/fullnode/FullNodeBitcoinNodeDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.node.fullnode; import com.softwareverde.bitcoin.server.module.node.database.node.BitcoinNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.manager.FilterType; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.network.p2p.node.NodeId; public interface FullNodeBitcoinNodeDatabaseManager extends BitcoinNodeDatabaseManager { Boolean updateBlockInventory(BitcoinNode node, Long blockHeight, Sha256Hash blockHash) throws DatabaseException; void updateTransactionInventory(BitcoinNode node, List<Sha256Hash> transactionHashes) throws DatabaseException; List<NodeId> filterNodesViaTransactionInventory(List<NodeId> nodeIds, Sha256Hash transactionHash, FilterType filterType) throws DatabaseException; List<NodeId> filterNodesViaBlockInventory(List<NodeId> nodeIds, Sha256Hash blockHash, FilterType filterType) throws DatabaseException; } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/memory/JvmMemoryStatus.java<|end_filename|> package com.softwareverde.bitcoin.server.memory; import com.softwareverde.logging.Logger; public class JvmMemoryStatus implements MemoryStatus { protected final Runtime _runtime; protected Long _calculateUsedMemory() { // In Bytes... return (_runtime.totalMemory() - _runtime.freeMemory()); } protected Long _getMaxMemory() { // In Bytes... return _runtime.maxMemory(); } protected Long _calculateFreeMemory() { return (_getMaxMemory() - _calculateUsedMemory()); } public JvmMemoryStatus() { _runtime = Runtime.getRuntime(); } @Override public Long getByteCountAvailable() { return _calculateFreeMemory(); } @Override public Long getByteCountUsed() { return _calculateUsedMemory(); } /** * Returns a value between 0 and 1 representing the percentage of memory used within the JVM. */ @Override public Float getMemoryUsedPercent() { final Long maxMemory = _getMaxMemory(); final Long usedMemory = _calculateUsedMemory(); if (usedMemory == 0L) { return 1.0F; } return (usedMemory.floatValue() / maxMemory.floatValue()); } @Override public void logCurrentMemoryUsage() { Logger.info("Current JVM Memory Usage : " + (_calculateFreeMemory()) + " bytes | MAX=" + _getMaxMemory() + " TOTAL=" + _runtime.totalMemory() + " FREE=" + _runtime.freeMemory()); } } <|start_filename|>www-shared/css/dialog.css<|end_filename|> #dialog { display: none; position: fixed; height: 250px; width: 350px; z-index: 100; top: 50%; left: 50%; margin-left: -175px; margin-top: -125px; border: solid 1px #505050; background-color: rgba(255, 255, 255, 1); box-shadow: 0px 0px 10px #000000; border-radius: 10px; overflow: hidden; font-family: sans-serif; } #dialog #dialog_title { background-color: rgba(0, 0, 0, 0.1); border-bottom: solid 2px #151515; color: #000000; padding: 3px; padding-left: 10px; padding-bottom: 1px; box-sizing: border-box; height: 33px; font-weight: bold; font-size: 18px; padding-top: 6px; } #dialog #dialog_title .dialog_cancel_button { float: right; width: 20px; height: 20px; color: #000000; display: block; border: none; background-color: rgba(255, 255, 255, 0.3); text-align: center; border-radius: 6px; box-sizing: border-box; font-size: 13px; margin-top: -1px; font-family: monospace; font-weight: bold; } #dialog #dialog_title .dialog_cancel_button:hover { cursor: pointer; background-color: rgba(0, 0, 0, 0.25); color: #FF0000; } #dialog #dialog_body { color: #222222; font-size: 15px; font-weight: bold; padding: 8px; padding-top: 10px; } #dialog .dialog-button { border: solid 1px #CCCCCC; font-size: 110%; font-weight: bold; text-align: center; color: #222222; background-color: rgba(0, 0, 0, 0.2); border-radius: 5px; display: block; width: 90%; margin: auto; margin-top: 10px; } #dialog .dialog-button:hover { background-color: rgba(0, 0, 0, 0.3); cursor: pointer; } <|start_filename|>src/test/java/com/softwareverde/test/database/TestDatabase.java<|end_filename|> package com.softwareverde.test.database; import com.softwareverde.bitcoin.server.database.Database; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.database.pool.DatabaseConnectionPool; import com.softwareverde.bitcoin.server.database.wrapper.MysqlDatabaseConnectionFactoryWrapper; import com.softwareverde.bitcoin.server.database.wrapper.MysqlDatabaseConnectionWrapper; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.mysql.MysqlDatabaseConnectionFactory; import com.softwareverde.database.mysql.embedded.vorburger.DB; import com.softwareverde.database.properties.DatabaseCredentials; import com.softwareverde.util.Util; public class TestDatabase implements Database { protected final MysqlTestDatabase _core; protected DatabaseConnectionPool _databaseConnectionPool; protected MysqlDatabaseConnectionFactory _databaseConnectionFactory; public TestDatabase(final MysqlTestDatabase core) { _core = core; } @Override public DatabaseConnection newConnection() throws DatabaseException { return new MysqlDatabaseConnectionWrapper(_core.newConnection()); } @Override public DatabaseConnection getMaintenanceConnection() throws DatabaseException { return this.newConnection(); } @Override public DatabaseConnectionFactory newConnectionFactory() { return new MysqlDatabaseConnectionFactoryWrapper(Util.coalesce(_databaseConnectionFactory, _core.newConnectionFactory())); } @Override public Integer getMaxQueryBatchSize() { return 1024; } public void reset() throws DatabaseException { _core.reset(); } public DB getDatabaseInstance() { return _core.getDatabaseInstance(); } public DatabaseCredentials getCredentials() { return _core.getCredentials(); } public DatabaseConnectionFactory getDatabaseConnectionFactory() { return new MysqlDatabaseConnectionFactoryWrapper(Util.coalesce(_databaseConnectionFactory, _core.getDatabaseConnectionFactory())); } public MysqlDatabaseConnectionFactory getMysqlDatabaseConnectionFactory() { return Util.coalesce(_databaseConnectionFactory, _core.getDatabaseConnectionFactory()); } public DatabaseConnectionPool getDatabaseConnectionPool() { return Util.coalesce(_databaseConnectionPool, _core.getDatabaseConnectionPool()); } public MysqlTestDatabase getCore() { return _core; } public void setDatabaseConnectionPool(final DatabaseConnectionPool databaseConnectionPool) { _databaseConnectionPool = databaseConnectionPool; } public void setDatabaseConnectionFactory(final MysqlDatabaseConnectionFactory databaseConnectionFactory) { _databaseConnectionFactory = databaseConnectionFactory; } @Override public void close() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/opcode/SubTypedOperation.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.opcode; public abstract class SubTypedOperation extends Operation { protected final Opcode _opcode; protected SubTypedOperation(final byte value, final Type type, final Opcode opcode) { super(value, type); _opcode = opcode; } @Override public boolean equals(final Object object) { if (! (object instanceof SubTypedOperation)) { return false ;} if (! super.equals(object)) { return false; } final SubTypedOperation operation = (SubTypedOperation) object; if (operation._opcode != _opcode) { return false; } return true; } @Override public String toString() { return super.toString() + "-" + _opcode; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/api/ApiResult.java<|end_filename|> package com.softwareverde.bitcoin.server.module.api; import com.softwareverde.json.Json; import com.softwareverde.json.Jsonable; public class ApiResult implements Jsonable { private Boolean _wasSuccess; private String _errorMessage; public ApiResult() { } public ApiResult(final Boolean wasSuccess, final String errorMessage) { _wasSuccess = wasSuccess; _errorMessage = errorMessage; } public void setWasSuccess(final Boolean wasSuccess) { _wasSuccess = wasSuccess; } public void setErrorMessage(final String errorMessage) { _errorMessage = errorMessage; } @Override public Json toJson() { final Json json = new Json(); json.put("wasSuccess", (_wasSuccess ? 1 : 0)); json.put("errorMessage", _errorMessage); return json; } } <|start_filename|>src/main/java/com/softwareverde/concurrent/pool/ThreadPoolFactory.java<|end_filename|> package com.softwareverde.concurrent.pool; public interface ThreadPoolFactory { ThreadPool newThreadPool(); } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/FakeUnspentTransactionOutputContext.java<|end_filename|> package com.softwareverde.bitcoin.test.fake; import com.softwareverde.bitcoin.context.UnspentTransactionOutputContext; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.logging.Logger; import java.util.HashMap; public class FakeUnspentTransactionOutputContext implements UnspentTransactionOutputContext { protected final HashMap<TransactionOutputIdentifier, TransactionOutput> _transactionOutputs = new HashMap<TransactionOutputIdentifier, TransactionOutput>(); protected final HashMap<TransactionOutputIdentifier, Boolean> _transactionCoinbaseStatuses = new HashMap<TransactionOutputIdentifier, Boolean>(); protected final HashMap<TransactionOutputIdentifier, Sha256Hash> _transactionBlockHashes = new HashMap<TransactionOutputIdentifier, Sha256Hash>(); protected final HashMap<TransactionOutputIdentifier, Long> _transactionBlockHeights = new HashMap<TransactionOutputIdentifier, Long>(); @Override public TransactionOutput getTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { if (! _transactionOutputs.containsKey(transactionOutputIdentifier)) { Logger.debug("Requested non-existent output: " + transactionOutputIdentifier, new Exception()); } return _transactionOutputs.get(transactionOutputIdentifier); } @Override public Long getBlockHeight(final TransactionOutputIdentifier transactionOutputIdentifier) { if (! _transactionBlockHeights.containsKey(transactionOutputIdentifier)) { Logger.debug("Requested non-existent output blockHeight: " + transactionOutputIdentifier, new Exception()); } return _transactionBlockHeights.get(transactionOutputIdentifier); } @Override public Sha256Hash getBlockHash(final TransactionOutputIdentifier transactionOutputIdentifier) { if (! _transactionBlockHeights.containsKey(transactionOutputIdentifier)) { Logger.debug("Requested non-existent output Block hash: " + transactionOutputIdentifier, new Exception()); } return _transactionBlockHashes.get(transactionOutputIdentifier); } @Override public Boolean isCoinbaseTransactionOutput(final TransactionOutputIdentifier transactionOutputIdentifier) { if (! _transactionBlockHeights.containsKey(transactionOutputIdentifier)) { Logger.debug("Requested non-existent coinbase output: " + transactionOutputIdentifier, new Exception()); } return _transactionCoinbaseStatuses.get(transactionOutputIdentifier); } public void addTransaction(final Transaction transaction, final Sha256Hash blockHash, final Long blockHeight, final Boolean isCoinbaseTransaction) { final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); final Sha256Hash transactionHash = transaction.getHash(); int outputIndex = 0; for (final TransactionOutput transactionOutput : transactionOutputs) { final TransactionOutputIdentifier transactionOutputIdentifier = new TransactionOutputIdentifier(transactionHash, outputIndex); _transactionOutputs.put(transactionOutputIdentifier, transactionOutput); _transactionBlockHeights.put(transactionOutputIdentifier, blockHeight); _transactionCoinbaseStatuses.put(transactionOutputIdentifier, isCoinbaseTransaction); _transactionBlockHashes.put(transactionOutputIdentifier, blockHash); outputIndex += 1; } } public void clear() { _transactionOutputs.clear(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/inflater/BlockInflaters.java<|end_filename|> package com.softwareverde.bitcoin.inflater; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.BlockInflater; public interface BlockInflaters extends Inflater { BlockInflater getBlockInflater(); BlockDeflater getBlockDeflater(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/header/MutableBlockHeader.java<|end_filename|> package com.softwareverde.bitcoin.block.header; import com.softwareverde.bitcoin.block.BlockHasher; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.constable.util.ConstUtil; import com.softwareverde.bitcoin.merkleroot.MerkleRoot; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public class MutableBlockHeader extends BlockHeaderCore { protected Sha256Hash _cachedHash = null; protected Integer _cachedHashCode = null; public MutableBlockHeader() { } public MutableBlockHeader(final BlockHasher blockHasher) { super(blockHasher); } public MutableBlockHeader(final BlockHeader blockHeader) { super(blockHeader); } public void setVersion(final Long version) { _version = version; _cachedHashCode = null; _cachedHash = null; } public void setPreviousBlockHash(final Sha256Hash previousBlockHash) { _previousBlockHash = (Sha256Hash) ConstUtil.asConstOrNull(previousBlockHash); _cachedHashCode = null; _cachedHash = null; } public void setMerkleRoot(final MerkleRoot merkleRoot) { _merkleRoot = (MerkleRoot) ConstUtil.asConstOrNull(merkleRoot); _cachedHashCode = null; _cachedHash = null; } public void setTimestamp(final Long timestamp) { _timestamp = timestamp; _cachedHashCode = null; _cachedHash = null; } public void setDifficulty(final Difficulty difficulty) { _difficulty = ConstUtil.asConstOrNull(difficulty); _cachedHashCode = null; _cachedHash = null; } public void setNonce(final Long nonce) { _nonce = nonce; _cachedHashCode = null; _cachedHash = null; } @Override public Sha256Hash getHash() { final Sha256Hash cachedHash = _cachedHash; if (cachedHash != null) { return cachedHash; } final Sha256Hash hash = super.getHash(); _cachedHash = hash; return hash; } @Override public int hashCode() { final Integer cachedHashCode = _cachedHashCode; if (cachedHashCode != null) { return cachedHashCode; } final int hashCode = super.hashCode(); _cachedHashCode = hashCode; return hashCode; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/main/BitcoinVerdeDatabase.java<|end_filename|> package com.softwareverde.bitcoin.server.main; import com.softwareverde.bitcoin.server.configuration.BitcoinProperties; import com.softwareverde.bitcoin.server.configuration.DatabaseProperties; import com.softwareverde.bitcoin.server.database.Database; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.database.wrapper.MysqlDatabaseConnectionFactoryWrapper; import com.softwareverde.bitcoin.server.database.wrapper.MysqlDatabaseConnectionWrapper; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.DatabaseInitializer; import com.softwareverde.database.mysql.MysqlDatabase; import com.softwareverde.database.mysql.MysqlDatabaseConnection; import com.softwareverde.database.mysql.MysqlDatabaseConnectionFactory; import com.softwareverde.database.mysql.MysqlDatabaseInitializer; import com.softwareverde.database.mysql.embedded.DatabaseCommandLineArguments; import com.softwareverde.database.mysql.embedded.EmbeddedMysqlDatabase; import com.softwareverde.database.properties.DatabaseCredentials; import com.softwareverde.logging.Logger; import java.sql.Connection; public class BitcoinVerdeDatabase implements Database { public static class InitFile { public final String sqlInitFile; public final Integer databaseVersion; public InitFile(final String sqlInitFile, final Integer databaseVersion) { this.sqlInitFile = sqlInitFile; this.databaseVersion = databaseVersion; } } public static final InitFile BITCOIN = new InitFile("/sql/full_node/init_mysql.sql", BitcoinConstants.DATABASE_VERSION); public static final InitFile STRATUM = new InitFile("/sql/stratum/init_mysql.sql", BitcoinConstants.DATABASE_VERSION); public static final Integer MAX_DATABASE_CONNECTION_COUNT = 64; // Increasing too much may cause MySQL to use excessive memory... public static Database newInstance(final InitFile initFile, final DatabaseProperties databaseProperties) { return BitcoinVerdeDatabase.newInstance(initFile, databaseProperties, null); } public static Database newInstance(final InitFile initFile, final DatabaseProperties databaseProperties, final BitcoinProperties bitcoinProperties) { return BitcoinVerdeDatabase.newInstance(initFile, databaseProperties, bitcoinProperties, new Runnable() { @Override public void run() { // Nothing. } }); } public static final DatabaseInitializer.DatabaseUpgradeHandler<Connection> DATABASE_UPGRADE_HANDLER = new DatabaseInitializer.DatabaseUpgradeHandler<Connection>() { @Override public Boolean onUpgrade(final com.softwareverde.database.DatabaseConnection<Connection> maintenanceDatabaseConnection, final Integer currentVersion, final Integer requiredVersion) { if ( (currentVersion < 3) && (requiredVersion <= 3) ) { return false; // Upgrading from Verde v1 (DB v1-v2) is not supported. } return false; } }; public static Database newInstance(final InitFile sqlInitFile, final DatabaseProperties databaseProperties, final BitcoinProperties bitcoinProperties, final Runnable onShutdownCallback) { final DatabaseInitializer<Connection> databaseInitializer = new MysqlDatabaseInitializer(sqlInitFile.sqlInitFile, sqlInitFile.databaseVersion, BitcoinVerdeDatabase.DATABASE_UPGRADE_HANDLER); try { if (databaseProperties.useEmbeddedDatabase()) { // Initialize the embedded database... final DatabaseCommandLineArguments commandLineArguments = new DatabaseCommandLineArguments(); DatabaseConfigurer.configureCommandLineArguments(commandLineArguments, MAX_DATABASE_CONNECTION_COUNT, databaseProperties, bitcoinProperties); Logger.info("[Initializing Database]"); final EmbeddedMysqlDatabase embeddedMysqlDatabase = new EmbeddedMysqlDatabase(databaseProperties, databaseInitializer, commandLineArguments); if (onShutdownCallback != null) { embeddedMysqlDatabase.setShutdownCallback(onShutdownCallback); } final DatabaseCredentials maintenanceCredentials = databaseInitializer.getMaintenanceCredentials(databaseProperties); final MysqlDatabaseConnectionFactory maintenanceDatabaseConnectionFactory = new MysqlDatabaseConnectionFactory(databaseProperties, maintenanceCredentials); return new BitcoinVerdeDatabase(embeddedMysqlDatabase, maintenanceDatabaseConnectionFactory); } else { // Connect to the remote database... final DatabaseCredentials credentials = databaseProperties.getCredentials(); final DatabaseCredentials rootCredentials = databaseProperties.getRootCredentials(); final DatabaseCredentials maintenanceCredentials = databaseInitializer.getMaintenanceCredentials(databaseProperties); final MysqlDatabaseConnectionFactory rootDatabaseConnectionFactory = new MysqlDatabaseConnectionFactory(databaseProperties.getHostname(), databaseProperties.getPort(), "", rootCredentials.username, rootCredentials.password); final MysqlDatabaseConnectionFactory maintenanceDatabaseConnectionFactory = new MysqlDatabaseConnectionFactory(databaseProperties, maintenanceCredentials); // final MysqlDatabaseConnectionFactory databaseConnectionFactory = new MysqlDatabaseConnectionFactory(connectionUrl, credentials.username, credentials.password); try (final MysqlDatabaseConnection maintenanceDatabaseConnection = maintenanceDatabaseConnectionFactory.newConnection()) { final Integer databaseVersion = databaseInitializer.getDatabaseVersionNumber(maintenanceDatabaseConnection); if (databaseVersion < 0) { try (final MysqlDatabaseConnection rootDatabaseConnection = rootDatabaseConnectionFactory.newConnection()) { databaseInitializer.initializeSchema(rootDatabaseConnection, databaseProperties); } } } catch (final DatabaseException exception) { try (final MysqlDatabaseConnection rootDatabaseConnection = rootDatabaseConnectionFactory.newConnection()) { databaseInitializer.initializeSchema(rootDatabaseConnection, databaseProperties); } } try (final MysqlDatabaseConnection maintenanceDatabaseConnection = maintenanceDatabaseConnectionFactory.newConnection()) { databaseInitializer.initializeDatabase(maintenanceDatabaseConnection); } return new BitcoinVerdeDatabase(new MysqlDatabase(databaseProperties, credentials), maintenanceDatabaseConnectionFactory); } } catch (final DatabaseException exception) { Logger.error(exception); } return null; } public static DatabaseConnectionFactory getMaintenanceDatabaseConnectionFactory(final DatabaseProperties databaseProperties) { final DatabaseInitializer<Connection> databaseInitializer = new MysqlDatabaseInitializer(); final DatabaseCredentials maintenanceCredentials = databaseInitializer.getMaintenanceCredentials(databaseProperties); final MysqlDatabaseConnectionFactory databaseConnectionFactory = new MysqlDatabaseConnectionFactory(databaseProperties, maintenanceCredentials); return new MysqlDatabaseConnectionFactoryWrapper(databaseConnectionFactory); } protected final MysqlDatabase _core; protected final MysqlDatabaseConnectionFactory _maintenanceDatabaseConnectionFactory; protected BitcoinVerdeDatabase(final MysqlDatabase core, final MysqlDatabaseConnectionFactory maintenanceDatabaseConnectionFactory) { _core = core; _maintenanceDatabaseConnectionFactory = maintenanceDatabaseConnectionFactory; } @Override public DatabaseConnection newConnection() throws DatabaseException { return new MysqlDatabaseConnectionWrapper(_core.newConnection()); } @Override public DatabaseConnection getMaintenanceConnection() throws DatabaseException { if (_maintenanceDatabaseConnectionFactory == null) { return null; } final MysqlDatabaseConnection databaseConnection = _maintenanceDatabaseConnectionFactory.newConnection(); return new MysqlDatabaseConnectionWrapper(databaseConnection); } @Override public void close() { } @Override public DatabaseConnectionFactory newConnectionFactory() { return new MysqlDatabaseConnectionFactoryWrapper(_core.newConnectionFactory()); } @Override public Integer getMaxQueryBatchSize() { return 1024; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/runner/ControlState.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.runner; import com.softwareverde.bitcoin.transaction.script.opcode.controlstate.CodeBlock; import com.softwareverde.bitcoin.transaction.script.opcode.controlstate.CodeBlockType; import com.softwareverde.util.Util; public class ControlState { // protected final LinkedList<CodeBlock> _codeBlocks = new LinkedList<CodeBlock>(); protected CodeBlock _codeBlock; public Boolean isInCodeBlock() { return (_codeBlock != null); } public CodeBlock getCodeBlock() { return _codeBlock; } public Boolean shouldExecute() { if (_codeBlock == null) { return true; } return (Util.coalesce(_codeBlock.condition, false)); } public void enteredIfBlock(final Boolean conditionValue) { if (_codeBlock == null) { if (conditionValue == null) { throw new NullPointerException(); // conditionValue may only be null if it is within a un-executed nested block... } _codeBlock = new CodeBlock(CodeBlockType.IF, conditionValue); return; } final Boolean newConditionValue = (Util.coalesce(_codeBlock.condition, false) ? conditionValue : null); final CodeBlock newCodeBlock = new CodeBlock(CodeBlockType.IF, newConditionValue); newCodeBlock.parent = _codeBlock; _codeBlock = newCodeBlock; } public void enteredElseBlock() { if (_codeBlock == null) { throw new IllegalStateException("Entered Else-Block when not currently in a CodeBlock..."); } final Boolean newConditionValue = (_codeBlock.condition != null ? (! _codeBlock.condition) : null); final CodeBlock newCodeBlock = new CodeBlock(CodeBlockType.ELSE, newConditionValue); newCodeBlock.parent = _codeBlock.parent; _codeBlock = newCodeBlock; } public void exitedCodeBlock() { if (_codeBlock == null) { throw new IllegalStateException("Exited Block when not currently in a CodeBlock..."); } _codeBlock = _codeBlock.parent; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/DatabaseConnection.java<|end_filename|> package com.softwareverde.bitcoin.server.database; import java.sql.Connection; public interface DatabaseConnection extends com.softwareverde.database.DatabaseConnection<Connection> { Integer getRowsAffectedCount(); } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/util/BlockTestUtil.java<|end_filename|> package com.softwareverde.bitcoin.test.util; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; public class BlockTestUtil { /** * FakeMutableBlock does not require a proper Hash to be valid. * This modification allows the block to be valid without the required amount of Proof of Work. */ public static class FakeMutableBlock extends MutableBlock { @Override public Boolean isValid() { return true; } } public static FakeMutableBlock createBlock() { final FakeMutableBlock mutableBlock = new FakeMutableBlock(); mutableBlock.setDifficulty(Difficulty.BASE_DIFFICULTY); mutableBlock.setNonce(0L); mutableBlock.setTimestamp(MedianBlockTime.GENESIS_BLOCK_TIMESTAMP); mutableBlock.setVersion(Block.VERSION); return mutableBlock; } protected BlockTestUtil() { } } <|start_filename|>src/main/java/com/softwareverde/network/p2p/node/Node.java<|end_filename|> package com.softwareverde.network.p2p.node; import com.softwareverde.concurrent.pool.ThreadPool; import com.softwareverde.concurrent.pool.ThreadPoolThrottle; import com.softwareverde.constable.list.List; import com.softwareverde.logging.Logger; import com.softwareverde.network.ip.Ip; import com.softwareverde.network.p2p.message.ProtocolMessage; import com.softwareverde.network.p2p.message.type.AcknowledgeVersionMessage; import com.softwareverde.network.p2p.message.type.NodeIpAddressMessage; import com.softwareverde.network.p2p.message.type.PingMessage; import com.softwareverde.network.p2p.message.type.PongMessage; import com.softwareverde.network.p2p.message.type.SynchronizeVersionMessage; import com.softwareverde.network.p2p.node.address.NodeIpAddress; import com.softwareverde.network.socket.BinaryPacketFormat; import com.softwareverde.network.socket.BinarySocket; import com.softwareverde.util.CircleBuffer; import com.softwareverde.util.RotatingQueue; import com.softwareverde.util.Util; import com.softwareverde.util.type.time.SystemTime; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantReadWriteLock; public abstract class Node { public interface NodeAddressesReceivedCallback { void onNewNodeAddresses(List<NodeIpAddress> nodeIpAddress); } public interface NodeConnectedCallback { void onNodeConnected();} public interface HandshakeCompleteCallback { void onHandshakeComplete(); } public interface DisconnectedCallback { void onNodeDisconnected(); } public interface PingCallback { void onResult(Long latency); } protected static class PingRequest { public final PingCallback pingCallback; public final Long timestamp; public PingRequest(final PingCallback pingCallback, final Long currentTimeInMilliseconds) { this.pingCallback = pingCallback; this.timestamp = currentTimeInMilliseconds; } } protected static final RotatingQueue<Long> LOCAL_SYNCHRONIZATION_NONCES = new RotatingQueue<Long>(32); private static final Object NODE_ID_MUTEX = new Object(); private static Long _nextId = 0L; protected final NodeId _id; protected final NodeConnection _connection; protected final Long _initializationTime; protected final Boolean _isOutboundConnection; protected final SystemTime _systemTime; protected NodeIpAddress _localNodeIpAddress = null; protected final AtomicBoolean _handshakeHasBeenInvoked = new AtomicBoolean(false); protected final AtomicBoolean _synchronizeVersionMessageHasBeenSent = new AtomicBoolean(false); protected Boolean _handshakeIsComplete = false; protected Long _lastMessageReceivedTimestamp = 0L; protected final ConcurrentLinkedQueue<ProtocolMessage> _postHandshakeMessageQueue = new ConcurrentLinkedQueue<ProtocolMessage>(); protected Long _networkTimeOffset; // This field is an offset (in milliseconds) that should be added to the local time in order to adjust local SystemTime to this node's NetworkTime... protected final AtomicBoolean _hasBeenDisconnected = new AtomicBoolean(false); protected final ConcurrentHashMap<Long, PingRequest> _pingRequests = new ConcurrentHashMap<Long, PingRequest>(); protected NodeAddressesReceivedCallback _nodeAddressesReceivedCallback = null; protected NodeConnectedCallback _nodeConnectedCallback = null; protected HandshakeCompleteCallback _handshakeCompleteCallback = null; protected DisconnectedCallback _nodeDisconnectedCallback = null; protected final ConcurrentLinkedQueue<Runnable> _postConnectQueue = new ConcurrentLinkedQueue<Runnable>(); protected final ThreadPool _threadPool; /** * Latencies in milliseconds... */ protected final CircleBuffer<Long> _latenciesMs = new CircleBuffer<Long>(32); protected abstract PingMessage _createPingMessage(); protected abstract PongMessage _createPongMessage(final PingMessage pingMessage); protected abstract SynchronizeVersionMessage _createSynchronizeVersionMessage(); protected abstract AcknowledgeVersionMessage _createAcknowledgeVersionMessage(SynchronizeVersionMessage synchronizeVersionMessage); protected abstract NodeIpAddressMessage _createNodeIpAddressMessage(); protected final ReentrantReadWriteLock.ReadLock _sendSingleMessageLock; protected final ReentrantReadWriteLock.WriteLock _sendMultiMessageLock; protected void _queueMessage(final ProtocolMessage message) { try { _sendSingleMessageLock.lockInterruptibly(); } catch (final InterruptedException exception) { return; } try { if (_handshakeIsComplete) { _connection.queueMessage(message); } else { _postHandshakeMessageQueue.offer(message); } } finally { _sendSingleMessageLock.unlock(); } } /** * Guarantees that the messages are queued in the order provided, and that no other messages are sent between them. */ protected void _queueMessages(final List<? extends ProtocolMessage> messages) { try { _sendMultiMessageLock.lockInterruptibly(); } catch (final InterruptedException exception) { return; } try { if (_handshakeIsComplete) { for (final ProtocolMessage message : messages) { _connection.queueMessage(message); } } else { for (final ProtocolMessage message : messages) { _postHandshakeMessageQueue.offer(message); } } } finally { _sendMultiMessageLock.unlock(); } } protected void _disconnect() { if (_hasBeenDisconnected.getAndSet(true)) { return; } Logger.debug("Socket disconnected. " + "(" + this.getConnectionString() + ")"); final DisconnectedCallback nodeDisconnectedCallback = _nodeDisconnectedCallback; _nodeAddressesReceivedCallback = null; _nodeConnectedCallback = null; _handshakeCompleteCallback = null; _nodeDisconnectedCallback = null; _handshakeIsComplete = false; _postHandshakeMessageQueue.clear(); _pingRequests.clear(); if (_threadPool instanceof ThreadPoolThrottle) { ((ThreadPoolThrottle) _threadPool).stop(); } _connection.setOnDisconnectCallback(null); // Prevent any disconnect callbacks from repeating... _connection.cancelConnecting(); _connection.disconnect(); if (nodeDisconnectedCallback != null) { // Intentionally not using the thread pool since it has been shutdown... final Thread thread = new Thread(new Runnable() { @Override public void run() { nodeDisconnectedCallback.onNodeDisconnected(); } }); thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread thread, final Throwable exception) { Logger.error("Uncaught exception in Thread.", exception); } }); thread.start(); } } /** * Creates a SynchronizeVersion message and enqueues it to the connection. * NOTE: If the connection is not currently alive, this function will not be executed until it has been successfully * connected, otherwise _createSynchronizeVersionMessage() cannot determine the correct remote address. */ protected void _handshake() { if (! _handshakeHasBeenInvoked.getAndSet(true)) { final Runnable createAndQueueHandshake = new Runnable() { @Override public void run() { final SynchronizeVersionMessage synchronizeVersionMessage = _createSynchronizeVersionMessage(); final Long synchronizationNonce = synchronizeVersionMessage.getNonce(); synchronized (LOCAL_SYNCHRONIZATION_NONCES) { LOCAL_SYNCHRONIZATION_NONCES.add(synchronizationNonce); } _connection.queueMessage(synchronizeVersionMessage); synchronized (_synchronizeVersionMessageHasBeenSent) { _synchronizeVersionMessageHasBeenSent.set(true); _synchronizeVersionMessageHasBeenSent.notifyAll(); } } }; synchronized (_postConnectQueue) { if (_connection.isConnected()) { createAndQueueHandshake.run(); } else { _postConnectQueue.offer(createAndQueueHandshake); } } } } protected void _onConnect() { _handshake(); synchronized (_postConnectQueue) { Runnable postConnectRunnable; while ((postConnectRunnable = _postConnectQueue.poll()) != null) { postConnectRunnable.run(); } } if (_nodeConnectedCallback != null) { _threadPool.execute(new Runnable() { @Override public void run() { final NodeConnectedCallback callback = _nodeConnectedCallback; if (callback != null) { callback.onNodeConnected(); } } }); } } protected void _ping(final PingCallback pingCallback) { final PingMessage pingMessage = _createPingMessage(); final Long now = _systemTime.getCurrentTimeInMilliSeconds(); final PingRequest pingRequest = new PingRequest(pingCallback, now); _pingRequests.put(pingMessage.getNonce(), pingRequest); _queueMessage(pingMessage); } protected void _onPingReceived(final PingMessage pingMessage) { final PongMessage pongMessage = _createPongMessage(pingMessage); _queueMessage(pongMessage); } protected Long _onPongReceived(final PongMessage pongMessage) { final Long nonce = pongMessage.getNonce(); final PingRequest pingRequest = _pingRequests.remove(nonce); if (pingRequest == null) { return null; } final PingCallback pingCallback = pingRequest.pingCallback; final Long now = _systemTime.getCurrentTimeInMilliSeconds(); final Long msElapsed = (now - pingRequest.timestamp); _latenciesMs.push(msElapsed); if (pingCallback != null) { _threadPool.execute(new Runnable() { @Override public void run() { pingCallback.onResult(msElapsed); } }); } return msElapsed; } protected void _onSynchronizeVersion(final SynchronizeVersionMessage synchronizeVersionMessage) { // TODO: Should probably not accept any node version... { // Detect if the connection is to itself... final Long remoteNonce = synchronizeVersionMessage.getNonce(); synchronized (LOCAL_SYNCHRONIZATION_NONCES) { for (final Long pastNonce : LOCAL_SYNCHRONIZATION_NONCES) { if (Util.areEqual(pastNonce, remoteNonce)) { Logger.info("Detected connection to self. Disconnecting."); _disconnect(); return; } } } } { // Calculate the node's network time offset... final Long currentTime = _systemTime.getCurrentTimeInSeconds(); final Long nodeTime = synchronizeVersionMessage.getTimestamp(); _networkTimeOffset = ((nodeTime - currentTime) * 1000L); } _localNodeIpAddress = synchronizeVersionMessage.getRemoteNodeIpAddress(); { // Ensure that this node sends its SynchronizeVersion message before the AcknowledgeVersionMessage is transmitted... // NOTE: Since Node::handshake may have been invoked already, it's possible for a race condition between responding to // the SynchronizeVersion here and the other call to handshake. Therefore, _synchronizeVersionMessageHasBeenSent is // waited on until actually queuing the AcknowledgeVersionMessage. _handshake(); synchronized (_synchronizeVersionMessageHasBeenSent) { if (! _synchronizeVersionMessageHasBeenSent.get()) { try { _synchronizeVersionMessageHasBeenSent.wait(10000L); } catch (final Exception exception) { } } } final AcknowledgeVersionMessage acknowledgeVersionMessage = _createAcknowledgeVersionMessage(synchronizeVersionMessage); _connection.queueMessage(acknowledgeVersionMessage); } } protected void _onAcknowledgeVersionMessageReceived(final AcknowledgeVersionMessage acknowledgeVersionMessage) { _handshakeIsComplete = true; _threadPool.execute(new Runnable() { @Override public void run() { final HandshakeCompleteCallback callback = _handshakeCompleteCallback; if (callback != null) { callback.onHandshakeComplete(); } } }); ProtocolMessage protocolMessage; while ((protocolMessage = _postHandshakeMessageQueue.poll()) != null) { _queueMessage(protocolMessage); } } protected void _onNodeAddressesReceived(final NodeIpAddressMessage nodeIpAddressMessage) { final NodeAddressesReceivedCallback nodeAddressesReceivedCallback = _nodeAddressesReceivedCallback; final List<NodeIpAddress> nodeIpAddresses = nodeIpAddressMessage.getNodeIpAddresses(); if (nodeIpAddresses.isEmpty()) { return; } if (nodeAddressesReceivedCallback != null) { _threadPool.execute(new Runnable() { @Override public void run() { nodeAddressesReceivedCallback.onNewNodeAddresses(nodeIpAddresses); } }); } } protected void _initConnection() { _connection.setOnConnectCallback(new Runnable() { @Override public void run() { _onConnect(); } }); _connection.setOnDisconnectCallback(new Runnable() { @Override public void run() { _disconnect(); } }); } protected Long _calculateAveragePingMs() { final int itemCount = _latenciesMs.getCount(); long sum = 0L; long count = 0L; for (int i = 0; i < itemCount; ++i) { final Long value = _latenciesMs.get(i); if (value == null) { continue; } sum += value; count += 1L; } if (count == 0L) { return Long.MAX_VALUE; } return (sum / count); } public Node(final String host, final Integer port, final BinaryPacketFormat binaryPacketFormat, final ThreadPool threadPool) { this(host, port, binaryPacketFormat, new SystemTime(), threadPool); } public Node(final String host, final Integer port, final BinaryPacketFormat binaryPacketFormat, final SystemTime systemTime, final ThreadPool threadPool) { synchronized (NODE_ID_MUTEX) { _id = NodeId.wrap(_nextId); _nextId += 1; } _systemTime = systemTime; _connection = new NodeConnection(host, port, binaryPacketFormat, threadPool); _initializationTime = _systemTime.getCurrentTimeInMilliSeconds(); _threadPool = threadPool; _isOutboundConnection = true; final ReentrantReadWriteLock queueMessageLock = new ReentrantReadWriteLock(); _sendSingleMessageLock = queueMessageLock.readLock(); _sendMultiMessageLock = queueMessageLock.writeLock(); _initConnection(); } public Node(final BinarySocket binarySocket, final ThreadPool threadPool) { this(binarySocket, threadPool, false); } public Node(final BinarySocket binarySocket, final ThreadPool threadPool, final Boolean isOutboundConnection) { synchronized (NODE_ID_MUTEX) { _id = NodeId.wrap(_nextId); _nextId += 1; } _systemTime = new SystemTime(); _connection = new NodeConnection(binarySocket, threadPool); _initializationTime = _systemTime.getCurrentTimeInMilliSeconds(); _threadPool = threadPool; _isOutboundConnection = isOutboundConnection; final ReentrantReadWriteLock queueMessageLock = new ReentrantReadWriteLock(); _sendSingleMessageLock = queueMessageLock.readLock(); _sendMultiMessageLock = queueMessageLock.writeLock(); _initConnection(); } public NodeId getId() { return _id; } public Long getInitializationTimestamp() { return _initializationTime; } public void handshake() { _handshake(); } public Boolean handshakeIsComplete() { return _handshakeIsComplete; } public Long getNetworkTimeOffset() { return _networkTimeOffset; } public Long getLastMessageReceivedTimestamp() { return _lastMessageReceivedTimestamp; } public Boolean hasActiveConnection() { return ( (_connection.isConnected()) && (_lastMessageReceivedTimestamp > 0) ); } public String getConnectionString() { final Ip ip = _connection.getIp(); return ((ip != null ? ip.toString() : _connection.getHost()) + ":" + _connection.getPort()); } /** * Returns a NodeIpAddress consisting of the Ip and Port for the connection. * If the connection string was provided as a domain name, it will attempted to be resolved. * If the domain cannot be resolved, then null is returned. */ public NodeIpAddress getRemoteNodeIpAddress() { final Ip ip; { final Ip connectionIp = _connection.getIp(); if (connectionIp != null) { ip = connectionIp; } else { final String hostName = _connection.getHost(); final Ip ipFromString = Ip.fromString(hostName); if (ipFromString != null) { ip = ipFromString; } else { ip = Ip.fromHostName(hostName); } } } if (ip == null) { return null; } return new NodeIpAddress(ip, _connection.getPort()); } public NodeIpAddress getLocalNodeIpAddress() { if (! _handshakeIsComplete) { return null; } if (_localNodeIpAddress == null) { return null; } return _localNodeIpAddress.copy(); } public void setNodeAddressesReceivedCallback(final NodeAddressesReceivedCallback nodeAddressesReceivedCallback) { _nodeAddressesReceivedCallback = nodeAddressesReceivedCallback; } public void setNodeConnectedCallback(final NodeConnectedCallback nodeConnectedCallback) { _nodeConnectedCallback = nodeConnectedCallback; if (_connection.isConnected()) { if (nodeConnectedCallback != null) { nodeConnectedCallback.onNodeConnected(); } } } public void setHandshakeCompleteCallback(final HandshakeCompleteCallback handshakeCompleteCallback) { _handshakeCompleteCallback = handshakeCompleteCallback; } public void setDisconnectedCallback(final DisconnectedCallback nodeDisconnectedCallback) { _nodeDisconnectedCallback = nodeDisconnectedCallback; } public void setLocalNodeIpAddress(final NodeIpAddress nodeIpAddress) { _localNodeIpAddress = nodeIpAddress; } public void ping(final PingCallback pingCallback) { _ping(pingCallback); } public void broadcastNodeAddress(final NodeIpAddress nodeIpAddress) { final NodeIpAddressMessage nodeIpAddressMessage = _createNodeIpAddressMessage(); nodeIpAddressMessage.addAddress(nodeIpAddress); _queueMessage(nodeIpAddressMessage); } public void broadcastNodeAddresses(final List<? extends NodeIpAddress> nodeIpAddresses) { final NodeIpAddressMessage nodeIpAddressMessage = _createNodeIpAddressMessage(); for (final NodeIpAddress nodeIpAddress : nodeIpAddresses) { nodeIpAddressMessage.addAddress(nodeIpAddress); } _queueMessage(nodeIpAddressMessage); } /** * NodeConnection::connect must be called, even if the underlying socket was already connected. */ public void connect() { _connection.connect(); } public void disconnect() { _disconnect(); } public Boolean isConnected() { return _connection.isConnected(); } /** * Attempts to look up the Node's host, or returns null if the lookup fails. */ public String getHost() { return _connection.getHost(); } public Ip getIp() { return _connection.getIp(); } public Integer getPort() { return _connection.getPort(); } @Override public String toString() { return _connection.toString(); } @Override public int hashCode() { return _id.hashCode(); } @Override public boolean equals(final Object object) { if (! (object instanceof Node)) { return false; } return Util.areEqual(_id, ((Node) object)._id); } /** * Returns the average ping (in milliseconds) for the node over the course of the last 32 pings. */ public Long getAveragePing() { return _calculateAveragePingMs(); } public Boolean isOutboundConnection() { return _isOutboundConnection; } public Long getTotalBytesReceivedCount() { return _connection.getTotalBytesReceivedCount(); } public Long getTotalBytesSentCount() { return _connection.getTotalBytesSentCount(); } } <|start_filename|>src/server/java/com/softwareverde/servlet/session/SessionManager.java<|end_filename|> package com.softwareverde.servlet.session; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.http.cookie.Cookie; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.json.Json; import com.softwareverde.util.IoUtil; import com.softwareverde.util.StringUtil; import com.softwareverde.util.Util; import java.io.File; import java.security.SecureRandom; import java.util.List; public class SessionManager { public static final String SESSION_COOKIE_KEY = "authentication_token"; public static Cookie createSecureCookie(final String key, final String value) { final Cookie cookie = new Cookie(); cookie.setIsHttpOnly(true); cookie.setIsSameSiteStrict(true); cookie.setIsSecure(true); cookie.setPath("/"); cookie.setKey(key); cookie.setValue(value); return cookie; } public static SessionId getSessionId(final Request request) { final List<Cookie> cookies = request.getCookies(); for (final Cookie cookie : cookies) { final String cookieKey = cookie.getKey(); if (Util.areEqual(SESSION_COOKIE_KEY, cookieKey)) { final String sessionId = Util.coalesce(cookie.getValue()).replaceAll("[^0-9A-Za-z]", ""); return SessionId.wrap(sessionId); } } return null; } protected final String _cookiesDirectory; public SessionManager(final String cookiesDirectory) { _cookiesDirectory = cookiesDirectory; } public Session getSession(final Request request) { final SessionId sessionId = SessionManager.getSessionId(request); if (sessionId == null) { return null; } final String sessionData = StringUtil.bytesToString(IoUtil.getFileContents(_cookiesDirectory + sessionId)); if (sessionData.isEmpty()) { return null; } return Session.newSession(sessionId, sessionData); } public Session createSession(final Request request, final Response response) { final SecureRandom secureRandom = new SecureRandom(); final MutableByteArray authenticationToken = new MutableByteArray(Sha256Hash.BYTE_COUNT); secureRandom.nextBytes(authenticationToken.unwrap()); final Session session = Session.newSession(SessionId.wrap(authenticationToken.toString())); final Json sessionData = session.getMutableData(); IoUtil.putFileContents(_cookiesDirectory + session.getSessionId(), StringUtil.stringToBytes(sessionData.toString())); final Cookie sessionCookie = SessionManager.createSecureCookie(SESSION_COOKIE_KEY, authenticationToken.toString()); response.addCookie(sessionCookie); return session; } public void saveSession(final Session session) { IoUtil.putFileContents(_cookiesDirectory + session.getSessionId(), StringUtil.stringToBytes(session.toString())); } public void destroySession(final Request request, final Response response) { final SessionId sessionId = SessionManager.getSessionId(request); if (sessionId == null) { return; } try { final File file = new File(_cookiesDirectory + sessionId); file.delete(); } catch (final Exception exception) { } final Cookie sessionCookie = SessionManager.createSecureCookie(SESSION_COOKIE_KEY, ""); sessionCookie.setMaxAge(0, true); response.addCookie(sessionCookie); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/header/BitcoinProtocolMessageHeader.java<|end_filename|> package com.softwareverde.bitcoin.server.message.header; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.network.p2p.message.ProtocolMessageHeader; public class BitcoinProtocolMessageHeader implements ProtocolMessageHeader { public final byte[] magicNumber; public final MessageType command; public final int payloadByteCount; public final byte[] payloadChecksum; public BitcoinProtocolMessageHeader(final byte[] magicNumber, final MessageType command, final int payloadByteCount, final byte[] payloadChecksum) { this.magicNumber = magicNumber; this.command = command; this.payloadByteCount = payloadByteCount; this.payloadChecksum = payloadChecksum; } @Override public Integer getPayloadByteCount() { return this.payloadByteCount; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/ImmutableTransaction.java<|end_filename|> package com.softwareverde.bitcoin.transaction; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.transaction.coinbase.ImmutableCoinbaseTransaction; import com.softwareverde.bitcoin.transaction.input.ImmutableTransactionInput; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.locktime.ImmutableLockTime; import com.softwareverde.bitcoin.transaction.output.ImmutableTransactionOutput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bloomfilter.BloomFilter; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.constable.util.ConstUtil; import com.softwareverde.cryptography.hash.sha256.ImmutableSha256Hash; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.json.Json; import com.softwareverde.util.Util; public class ImmutableTransaction implements ConstTransaction { protected static final TransactionDeflater DEFAULT_TRANSACTION_DEFLATER = new TransactionDeflater(); protected static final AddressInflater DEFAULT_ADDRESS_INFLATER = new AddressInflater(); protected final TransactionDeflater _transactionDeflater; protected final AddressInflater _addressInflater; protected final ImmutableSha256Hash _hash; protected final Long _version; protected final List<ImmutableTransactionInput> _transactionInputs; protected final List<ImmutableTransactionOutput> _transactionOutputs; protected final ImmutableLockTime _lockTime; protected Integer _cachedByteCount = null; protected Integer _cachedHashCode = null; protected Integer _calculateByteCount() { return _transactionDeflater.getByteCount(this); } protected ImmutableTransaction(final TransactionDeflater transactionDeflater, final AddressInflater addressInflater, final Transaction transaction) { _transactionDeflater = transactionDeflater; _addressInflater = addressInflater; final Sha256Hash hash = transaction.getHash(); _hash = hash.asConst(); _version = transaction.getVersion(); _lockTime = transaction.getLockTime().asConst(); _transactionInputs = ImmutableListBuilder.newConstListOfConstItems(transaction.getTransactionInputs()); _transactionOutputs = ImmutableListBuilder.newConstListOfConstItems(transaction.getTransactionOutputs()); } public ImmutableTransaction(final Transaction transaction) { this(DEFAULT_TRANSACTION_DEFLATER, DEFAULT_ADDRESS_INFLATER, transaction); } @Override public ImmutableSha256Hash getHash() { return _hash; } @Override public Long getVersion() { return _version; } @Override public final List<TransactionInput> getTransactionInputs() { return ConstUtil.downcastList(_transactionInputs); } @Override public final List<TransactionOutput> getTransactionOutputs() { return ConstUtil.downcastList(_transactionOutputs); } @Override public ImmutableLockTime getLockTime() { return _lockTime; } @Override public Long getTotalOutputValue() { long totalValue = 0L; for (final TransactionOutput transactionOutput : _transactionOutputs) { totalValue += transactionOutput.getAmount(); } return totalValue; } @Override public Boolean matches(final BloomFilter bloomFilter) { final TransactionBloomFilterMatcher transactionBloomFilterMatcher = new TransactionBloomFilterMatcher(bloomFilter, _addressInflater); return transactionBloomFilterMatcher.shouldInclude(this); } @Override public ImmutableCoinbaseTransaction asCoinbase() { if (! Transaction.isCoinbaseTransaction(this)) { return null; } return new ImmutableCoinbaseTransaction(this); } @Override public Integer getByteCount() { final Integer cachedByteCount = _cachedByteCount; if (cachedByteCount != null) { return cachedByteCount; } final Integer byteCount = _calculateByteCount(); _cachedByteCount = byteCount; return byteCount; } @Override public ImmutableTransaction asConst() { return this; } @Override public Json toJson() { final TransactionDeflater transactionDeflater = new TransactionDeflater(); return transactionDeflater.toJson(this); } @Override public int hashCode() { final Integer cachedHashCode = _cachedHashCode; if (cachedHashCode != null) { return cachedHashCode; } final int hashCode = _hash.hashCode(); _cachedHashCode = hashCode; return hashCode; } @Override public boolean equals(final Object object) { if (! (object instanceof Transaction)) { return false; } return Util.areEqual(this.getHash(), ((Transaction) object).getHash()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/chain/time/VolatileMedianBlockTime.java<|end_filename|> package com.softwareverde.bitcoin.chain.time; /** * VolatileMedianBlockTime represents a MedianBlockTime that may update at any time. */ public interface VolatileMedianBlockTime extends MedianBlockTime { } <|start_filename|>www-shared/js/dialog.js<|end_filename|> var Dialog = {}; Dialog.create = function(title, body, confirm, deny) { if (Dialog.div == null) Dialog.init(); Dialog.confirm = confirm; Dialog.deny = deny; $("#dialog_title", Dialog.div).text(title); // Set the dialog title // Create Dialog Cancel Button var cancel_button = $("<div>X</div>"); cancel_button.addClass("dialog_cancel_button"); cancel_button.bind("click", function() { Dialog.close(false); }); $("#dialog_title", Dialog.div).append(cancel_button); // Set the dialog title // End Create Dialog Cancel Button $("#dialog_body", Dialog.div).html(body); // Set the dialog body if (typeof confirm === "function") { var button = $("<input type=\"button\" value=\"Okay\" />"); button.addClass("dialog-button"); button.bind("click", function() { Dialog.close(true); }); $("#dialog_body", Dialog.div).append(button); setTimeout(function() { button.focus(); }, 100); } if (typeof deny === "function") { var button = $("<input type=\"button\" value=\"Cancel\" />"); button.addClass("dialog-button"); button.bind("click", function() { Dialog.close(false); }); $("#dialog_body", Dialog.div).append(button); } Dialog.div.finish().fadeIn(250); } Dialog.init = function() { $("body").append("<div id=\"dialog\"><div id=\"dialog_title\"></div><div id=\"dialog_body\"></div></div>"); $("body").bind("keydown", function(e) { if (!$(Dialog.div).is(":visible")) return; var code = (e.keyCode ? e.keyCode : e.which); // Escape if (code == 27) { Dialog.close(); } }); Dialog.div = $("#dialog"); }; Dialog.close = function(result) { Dialog.div.finish().fadeOut(500); if (result) { if (typeof Dialog.confirm === "function") Dialog.confirm(); } else { if (typeof Dialog.deny === "function") Dialog.deny(); } }; Dialog.div = null; <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/FakeBlockStore.java<|end_filename|> package com.softwareverde.bitcoin.test; import com.softwareverde.bitcoin.CoreInflater; import com.softwareverde.bitcoin.block.Block; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.MutableBlock; import com.softwareverde.bitcoin.block.header.MutableBlockHeader; import com.softwareverde.bitcoin.inflater.BlockInflaters; import com.softwareverde.bitcoin.server.module.node.store.PendingBlockStore; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import java.util.HashMap; public class FakeBlockStore implements PendingBlockStore { protected final BlockInflaters _blockInflaters = new CoreInflater(); protected final HashMap<Sha256Hash, Block> _pendingBlocks = new HashMap<Sha256Hash, Block>(); protected final HashMap<Sha256Hash, Block> _blocks = new HashMap<Sha256Hash, Block>(); public FakeBlockStore() { } @Override public Boolean storePendingBlock(final Block block) { _pendingBlocks.put(block.getHash(), block); return true; } @Override public void removePendingBlock(final Sha256Hash blockHash) { _pendingBlocks.remove(blockHash); } @Override public ByteArray getPendingBlockData(final Sha256Hash blockHash) { final Block block = _pendingBlocks.get(blockHash); if (block == null) { return null; } final BlockDeflater blockDeflater = _blockInflaters.getBlockDeflater(); return blockDeflater.toBytes(block); } @Override public Boolean pendingBlockExists(final Sha256Hash blockHash) { return _pendingBlocks.containsKey(blockHash); } @Override public Boolean storeBlock(final Block block, final Long blockHeight) { _blocks.put(block.getHash(), block); return true; } @Override public void removeBlock(final Sha256Hash blockHash, final Long blockHeight) { _blocks.remove(blockHash); } @Override public MutableBlockHeader getBlockHeader(final Sha256Hash blockHash, final Long blockHeight) { final Block block = _blocks.get(blockHash); return new MutableBlockHeader(block); } @Override public MutableBlock getBlock(final Sha256Hash blockHash, final Long blockHeight) { final Block block = _blocks.get(blockHash); if (block instanceof MutableBlock) { return (MutableBlock) block; } return new MutableBlock(block); } @Override public ByteArray readFromBlock(final Sha256Hash blockHash, final Long blockHeight, final Long diskOffset, final Integer byteCount) { final Block block = _blocks.get(blockHash); if (block == null) { return null; } final BlockDeflater blockDeflater = _blockInflaters.getBlockDeflater(); final ByteArray byteArray = blockDeflater.toBytes(block); return ByteArray.wrap(byteArray.getBytes(diskOffset.intValue(), byteCount)); } public void clear() { _pendingBlocks.clear(); _blocks.clear(); } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/explorer/api/endpoint/SearchApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.explorer.api.endpoint; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.bitcoin.server.module.explorer.api.Environment; import com.softwareverde.bitcoin.server.module.explorer.api.v1.get.SearchHandler; import com.softwareverde.http.HttpMethod; import com.softwareverde.json.Json; import com.softwareverde.json.Jsonable; public class SearchApi extends ExplorerApiEndpoint { public static class SearchResult extends ApiResult { public enum ObjectType { BLOCK, BLOCK_HEADER, TRANSACTION, ADDRESS } private ObjectType _objectType; public void setObjectType(final ObjectType objectType) { _objectType = objectType; } private Jsonable _object; public void setObject(final Jsonable object) { _object = object; } @Override public Json toJson() { final Json json = super.toJson(); json.put("objectType", _objectType); json.put("object", _object); return json; } } public static Json makeRawObjectJson(final String hexData) { final Json object = new Json(false); object.put("data", hexData); return object; } public SearchApi(final String apiPrePath, final Environment environment) { super(environment); _defineEndpoint((apiPrePath + "/search"), HttpMethod.GET, new SearchHandler()); } } <|start_filename|>explorer/www/js/documentation.js<|end_filename|> class DocumentationUi { static search(objectHash) { document.location.href = "/?search=" + window.encodeURIComponent(objectHash); } } $(document).ready(function() { const searchInput = $("#search"); const loadingImage = $("#search-loading-image"); searchInput.keypress(function(event) { const key = event.which; if (key == KeyCodes.ENTER) { loadingImage.css("visibility", "visible"); const hash = searchInput.val(); DocumentationUi.search(hash); return false; } }); }); <|start_filename|>src/test/java/com/softwareverde/network/ip/Ipv4Tests.java<|end_filename|> package com.softwareverde.network.ip; import org.junit.Assert; import org.junit.Test; public class Ipv4Tests { @Test public void should_parse_loopback_ip_string() { // Setup final String ipString = "127.0.0.1"; final byte[] expectedBytes = new byte[] { (byte) 0x7F, (byte) 0x00, (byte) 0x00, (byte) 0x01 }; // Action final Ipv4 ipv4 = Ipv4.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv4.getBytes().getBytes()); } @Test public void should_parse_zeroed_ip_string() { // Setup final String ipString = "0.0.0.0"; final byte[] expectedBytes = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; // Action final Ipv4 ipv4 = Ipv4.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv4.getBytes().getBytes()); } @Test public void should_parse_max_ip_string() { // Setup final String ipString = "255.255.255.255"; final byte[] expectedBytes = new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }; // Action final Ipv4 ipv4 = Ipv4.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv4.getBytes().getBytes()); } @Test public void should_return_null_when_segment_is_out_of_range() { // Setup final String ipString = "256.255.255.255"; // Action final Ipv4 ipv4 = Ipv4.parse(ipString); // Assert Assert.assertNull(ipv4); } @Test public void should_return_null_when_segment_is_negative() { // Setup final String ipString = "0.-1.0.0"; // Action final Ipv4 ipv4 = Ipv4.parse(ipString); // Assert Assert.assertNull(ipv4); } @Test public void should_return_null_when_segment_contains_alpha() { // Setup final String ipString = "0.a1.0.0"; // Action final Ipv4 ipv4 = Ipv4.parse(ipString); // Assert Assert.assertNull(ipv4); } @Test public void should_return_null_when_segment_count_is_less_than_four() { // Setup final String ipString = "0.0.0"; // Action final Ipv4 ipv4 = Ipv4.parse(ipString); // Assert Assert.assertNull(ipv4); } @Test public void should_return_null_when_segment_count_is_greater_than_four() { // Setup final String ipString = "0.0.0.0.0"; // Action final Ipv4 ipv4 = Ipv4.parse(ipString); // Assert Assert.assertNull(ipv4); } @Test public void should_return_null_when_empty() { // Setup final String ipString = ""; // Action final Ipv4 ipv4 = Ipv4.parse(ipString); // Assert Assert.assertNull(ipv4); } @Test public void should_return_null_when_whitespace() { // Setup final String ipString = " \t "; // Action final Ipv4 ipv4 = Ipv4.parse(ipString); // Assert Assert.assertNull(ipv4); } @Test public void should_parse_untrimmed_loopback_ip_string() { // Setup final String ipString = " 127.0.0.1\t \t "; final byte[] expectedBytes = new byte[] { (byte) 0x7F, (byte) 0x00, (byte) 0x00, (byte) 0x01 }; // Action final Ipv4 ipv4 = Ipv4.parse(ipString); // Assert Assert.assertArrayEquals(expectedBytes, ipv4.getBytes().getBytes()); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/wallet/utxo/SpendableTransactionOutput.java<|end_filename|> package com.softwareverde.bitcoin.wallet.utxo; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.constable.Constable; import com.softwareverde.util.Util; import java.util.Comparator; public interface SpendableTransactionOutput extends Constable<ImmutableSpendableTransactionOutput> { Comparator<SpendableTransactionOutput> AMOUNT_ASCENDING_COMPARATOR = new Comparator<SpendableTransactionOutput>() { @Override public int compare(final SpendableTransactionOutput transactionOutput0, final SpendableTransactionOutput transactionOutput1) { return transactionOutput0.getTransactionOutput().getAmount().compareTo(transactionOutput1.getTransactionOutput().getAmount()); } }; Address getAddress(); TransactionOutputIdentifier getIdentifier(); TransactionOutput getTransactionOutput(); Boolean isSpent(); @Override ImmutableSpendableTransactionOutput asConst(); } abstract class SpendableTransactionOutputCore implements SpendableTransactionOutput { @Override public int hashCode() { return (this.getIdentifier().hashCode() + this.getTransactionOutput().hashCode() + this.isSpent().hashCode()); } @Override public boolean equals(final Object object) { if (! (object instanceof SpendableTransactionOutput)) { return false; } final SpendableTransactionOutput spendableTransactionOutput = (SpendableTransactionOutput) object; if (! Util.areEqual(this.getIdentifier(), spendableTransactionOutput.getIdentifier())) { return false; } if (! Util.areEqual(this.getTransactionOutput(), spendableTransactionOutput.getTransactionOutput())) { return false; } if (! Util.areEqual(this.isSpent(), spendableTransactionOutput.isSpent())) { return false; } return true; } @Override public String toString() { return (this.getIdentifier().toString() + "=" + this.getTransactionOutput().getAmount() + (this.isSpent() ? " (SPENT)" : "")); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/context/DatabaseContext.java<|end_filename|> package com.softwareverde.bitcoin.context; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; public interface DatabaseContext { DatabaseManager getDatabaseManager(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/stratum/task/ConfigurableStratumMineBlockTaskBuilder.java<|end_filename|> package com.softwareverde.bitcoin.server.stratum.task; import com.softwareverde.bitcoin.block.header.difficulty.Difficulty; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionWithFee; import com.softwareverde.bitcoin.transaction.coinbase.CoinbaseTransaction; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; public interface ConfigurableStratumMineBlockTaskBuilder extends StratumMineBlockTaskBuilder { void setBlockVersion(Long blockVersion); void setPreviousBlockHash(Sha256Hash previousBlockHash); void setExtraNonce(ByteArray extraNonce); void setDifficulty(Difficulty difficulty); void setCoinbaseTransaction(Transaction coinbaseTransaction); void setBlockHeight(Long blockHeight); void addTransaction(TransactionWithFee transactionWithFee); void removeTransaction(Sha256Hash transactionHash); void clearTransactions(); Long getBlockHeight(); CoinbaseTransaction getCoinbaseTransaction(); } <|start_filename|>src/main/java/com/softwareverde/network/socket/BinarySocketServer.java<|end_filename|> package com.softwareverde.network.socket; import com.softwareverde.concurrent.pool.ThreadPool; import java.net.Socket; public class BinarySocketServer extends SocketServer<BinarySocket> { protected static class BinarySocketFactory implements SocketFactory<BinarySocket> { protected final BinaryPacketFormat _binaryPacketFormat; protected final ThreadPool _threadPool; public BinarySocketFactory(final BinaryPacketFormat binaryPacketFormat, final ThreadPool threadPool) { _binaryPacketFormat = binaryPacketFormat; _threadPool = threadPool; } @Override public BinarySocket newSocket(final Socket socket) { return new BinarySocket(socket, _binaryPacketFormat, _threadPool); } } public interface SocketConnectedCallback extends SocketServer.SocketConnectedCallback<BinarySocket> { @Override void run(BinarySocket socketConnection); } public interface SocketDisconnectedCallback extends SocketServer.SocketDisconnectedCallback<BinarySocket> { @Override void run(BinarySocket socketConnection); } protected final BinaryPacketFormat _binaryPacketFormat; public BinarySocketServer(final Integer port, final BinaryPacketFormat binaryPacketFormat, final ThreadPool threadPool) { super(port, new BinarySocketFactory(binaryPacketFormat, threadPool), threadPool); _binaryPacketFormat = binaryPacketFormat; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/node/FailableRequest.java<|end_filename|> package com.softwareverde.bitcoin.server.node; import com.softwareverde.util.Util; import com.softwareverde.util.type.time.SystemTime; public class FailableRequest { protected static final SystemTime SYSTEM_TIME = new SystemTime(); protected static final Runnable DO_NOTHING = new Runnable() { @Override public void run() { } }; final Long requestStartTimeMs; final Long startingByteCountReceived; final BitcoinNode.BitcoinNodeCallback callback; final Runnable onFailure; public FailableRequest(final Long startingByteCountReceived, final BitcoinNode.BitcoinNodeCallback callback) { this(startingByteCountReceived, callback, DO_NOTHING); } public FailableRequest(final Long startingByteCountReceived, final BitcoinNode.BitcoinNodeCallback callback, final Runnable onFailure) { this.requestStartTimeMs = SYSTEM_TIME.getCurrentTimeInMilliSeconds(); this.startingByteCountReceived = startingByteCountReceived; this.callback = callback; this.onFailure = Util.coalesce(onFailure, DO_NOTHING); } public void onFailure() { if (this.onFailure != null) { this.onFailure.run(); } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/database/query/BatchedInsertQuery.java<|end_filename|> package com.softwareverde.bitcoin.server.database.query; public class BatchedInsertQuery extends Query { protected static class BatchedInsertQueryWrapper extends com.softwareverde.database.query.BatchedInsertQuery { public BatchedInsertQueryWrapper(final Query query, final Boolean shouldConsumeQuery) { super(query, shouldConsumeQuery, new ParameterFactory()); } } protected com.softwareverde.database.query.BatchedInsertQuery _batchedInsertQuery = null; protected void _requireBatchedInsertQuery() { if (_batchedInsertQuery == null) { _batchedInsertQuery = new BatchedInsertQueryWrapper(this, true); } } public BatchedInsertQuery(final String query) { super(query); } @Override public String getQueryString() { _requireBatchedInsertQuery(); return _batchedInsertQuery.getQueryString(); } public void clear() { _requireBatchedInsertQuery(); _batchedInsertQuery.clear(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/manager/banfilter/BanFilterCore.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.manager.banfilter; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManagerFactory; import com.softwareverde.bitcoin.server.module.node.database.node.BitcoinNodeDatabaseManager; import com.softwareverde.bitcoin.server.node.BitcoinNode; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.logging.Logger; import com.softwareverde.network.ip.Ip; import com.softwareverde.util.type.time.SystemTime; import java.util.HashSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class BanFilterCore implements BanFilter { public static class BanCriteria { public static final Integer FAILED_CONNECTION_ATTEMPT_COUNT = 10; public static final Long FAILED_CONNECTION_ATTEMPT_SECONDS_SPAN = 20L; public static List<Sha256Hash> INVALID_BLOCKS = new ImmutableList<Sha256Hash>( Sha256Hash.fromHexString("0000000000000000005CCD563C9ED7212AD591467CD3DB71A17D44918B687F34"), // BTC Block 504031 Sha256Hash.fromHexString("000000000000000001D956714215D96FFC00E0AFDA4CD0A96C96F8D802B1662B") // BSV Block 556767 ); } protected static final Long DEFAULT_BAN_DURATION = (60L * 60L); // 1 Hour (in seconds)... protected final SystemTime _systemTime = new SystemTime(); protected final DatabaseManagerFactory _databaseManagerFactory; protected final HashSet<Ip> _whitelist = new HashSet<>(); protected final HashSet<Pattern> _blacklist = new HashSet<>(); protected Long _banDurationInSeconds = DEFAULT_BAN_DURATION; protected void _unbanIp(final Ip ip, final DatabaseManager databaseManager) throws DatabaseException { final BitcoinNodeDatabaseManager nodeDatabaseManager = databaseManager.getNodeDatabaseManager(); nodeDatabaseManager.setIsBanned(ip, false); Logger.info("Unbanned " + ip); } protected void _banIp(final Ip ip, final DatabaseManager databaseManager) throws DatabaseException { final BitcoinNodeDatabaseManager nodeDatabaseManager = databaseManager.getNodeDatabaseManager(); nodeDatabaseManager.setIsBanned(ip, true); Logger.info("Banned " + ip); } protected Boolean _shouldBanIp(final Ip ip, final DatabaseManager databaseManager) throws DatabaseException { final BitcoinNodeDatabaseManager nodeDatabaseManager = databaseManager.getNodeDatabaseManager(); final Long sinceTimestamp = (_systemTime.getCurrentTimeInSeconds() - BanCriteria.FAILED_CONNECTION_ATTEMPT_SECONDS_SPAN); final Integer failedConnectionCount = nodeDatabaseManager.getFailedConnectionCountForIp(ip, sinceTimestamp); final boolean shouldBanIp = (failedConnectionCount >= BanCriteria.FAILED_CONNECTION_ATTEMPT_COUNT); if (shouldBanIp) { Logger.debug("Ip (" + ip + ") failed to connect " + failedConnectionCount + " times within " + BanCriteria.FAILED_CONNECTION_ATTEMPT_SECONDS_SPAN + "s."); } return shouldBanIp; } public BanFilterCore(final DatabaseManagerFactory databaseManagerFactory) { _databaseManagerFactory = databaseManagerFactory; } @Override public Boolean isIpBanned(final Ip ip) { if (_whitelist.contains(ip)) { Logger.debug("IP is Whitelisted: " + ip); return false; } try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final BitcoinNodeDatabaseManager nodeDatabaseManager = databaseManager.getNodeDatabaseManager(); final Long sinceTimestamp = (_systemTime.getCurrentTimeInSeconds() - _banDurationInSeconds); return nodeDatabaseManager.isBanned(ip, sinceTimestamp); } catch (final DatabaseException exception) { Logger.warn(exception); return false; } } @Override public void banIp(final Ip ip) { try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { _banIp(ip, databaseManager); } catch (final DatabaseException exception) { Logger.warn(exception); } } @Override public void unbanIp(final Ip ip) { try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { _unbanIp(ip, databaseManager); } catch (final DatabaseException exception) { Logger.warn(exception); } } @Override public void onNodeConnected(final Ip ip) { // Nothing. } @Override public void onNodeHandshakeComplete(final BitcoinNode bitcoinNode) { final String userAgent = bitcoinNode.getUserAgent(); if (userAgent == null) { return; } for (final Pattern pattern : _blacklist) { final Matcher matcher = pattern.matcher(userAgent); if (matcher.find()) { try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { final Ip ip = bitcoinNode.getIp(); _banIp(ip, databaseManager); } catch (final DatabaseException exception) { Logger.warn(exception); } bitcoinNode.disconnect(); } } } @Override public void onNodeDisconnected(final Ip ip) { try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { if (_shouldBanIp(ip, databaseManager)) { _banIp(ip, databaseManager); } } catch (final DatabaseException exception) { Logger.warn(exception); } } @Override public Boolean onInventoryReceived(final BitcoinNode bitcoinNode, final List<Sha256Hash> blockInventory) { for (final Sha256Hash blockHash : BanCriteria.INVALID_BLOCKS) { final boolean containsInvalidBlock = blockInventory.contains(blockHash); if (containsInvalidBlock) { final Ip ip = bitcoinNode.getIp(); try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { _banIp(ip, databaseManager); } catch (final DatabaseException exception) { Logger.warn(exception); } return false; } } return true; } @Override public Boolean onHeadersReceived(final BitcoinNode bitcoinNode, final List<BlockHeader> blockHeaders) { for (final BlockHeader blockHeader : blockHeaders) { final Sha256Hash blockHash = blockHeader.getHash(); final boolean containsInvalidBlock = BanCriteria.INVALID_BLOCKS.contains(blockHash); if (containsInvalidBlock) { final Ip ip = bitcoinNode.getIp(); try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { _banIp(ip, databaseManager); } catch (final DatabaseException exception) { Logger.warn(exception); } return false; } } return true; } @Override public void addToWhitelist(final Ip ip) { _whitelist.add(ip); try (final DatabaseManager databaseManager = _databaseManagerFactory.newDatabaseManager()) { _unbanIp(ip, databaseManager); } catch (final DatabaseException exception) { Logger.warn(exception); } Logger.debug("Added ip to Whitelist: " + ip); } @Override public void removeIpFromWhitelist(final Ip ip) { _whitelist.remove(ip); Logger.debug("Removed ip from Whitelist: " + ip); } @Override public void addToUserAgentBlacklist(final Pattern pattern) { _blacklist.add(pattern); } @Override public void removePatternFromUserAgentBlacklist(final Pattern pattern) { _blacklist.remove(pattern); } public void setBanDuration(final Long banDurationInSeconds) { _banDurationInSeconds = banDurationInSeconds; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/coinbase/CoinbaseTransaction.java<|end_filename|> package com.softwareverde.bitcoin.transaction.coinbase; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; public interface CoinbaseTransaction extends Transaction { UnlockingScript getCoinbaseScript(); Long getBlockReward(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/merkleroot/ImmutableMerkleRoot.java<|end_filename|> package com.softwareverde.bitcoin.merkleroot; import com.softwareverde.constable.Const; import com.softwareverde.cryptography.hash.sha256.ImmutableSha256Hash; import com.softwareverde.util.HexUtil; public class ImmutableMerkleRoot extends ImmutableSha256Hash implements MerkleRoot, Const { public static ImmutableMerkleRoot fromHexString(final String hexString) { if (hexString == null) { return null; } final byte[] hashBytes = HexUtil.hexStringToByteArray(hexString); if (hashBytes == null) { return null; } if (hashBytes.length != BYTE_COUNT) { return null; } return new ImmutableMerkleRoot(hashBytes); } public static ImmutableMerkleRoot copyOf(final byte[] bytes) { if (bytes.length != BYTE_COUNT) { return null; } return new ImmutableMerkleRoot(bytes); } public ImmutableMerkleRoot() { super(); } protected ImmutableMerkleRoot(final byte[] bytes) { super(bytes); } public ImmutableMerkleRoot(final MerkleRoot merkleRoot) { super(merkleRoot); } @Override public ImmutableMerkleRoot asConst() { return this; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/ConstTransaction.java<|end_filename|> package com.softwareverde.bitcoin.transaction; import com.softwareverde.constable.Const; /** * Acts as a parent interface for ImmutableTransaction, ensuring that {@link Transaction#asConst()} * returns an interface. This allows classes implementing Transaction to provide their own * immutable transaction base class, instead of being forced to use ImmutableTransaction. */ public interface ConstTransaction extends Const, Transaction { } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/database/pool/hikari/HikariDatabaseConnectionPool.java<|end_filename|> package com.softwareverde.bitcoin.server.database.pool.hikari; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionCore; import com.softwareverde.bitcoin.server.database.pool.DatabaseConnectionPool; import com.softwareverde.bitcoin.server.main.BitcoinVerdeDatabase; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.mysql.MysqlDatabaseConnection; import com.softwareverde.database.mysql.MysqlDatabaseConnectionFactory; import com.softwareverde.database.properties.DatabaseProperties; import com.softwareverde.logging.Logger; import com.softwareverde.logging.LoggerInstance; import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariPoolMXBean; import java.io.PrintWriter; import java.io.Writer; import java.sql.Connection; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * Special thanks to <NAME>&agrave;l for his contributions to developing this code. (2019-09-23) */ public class HikariDatabaseConnectionPool implements DatabaseConnectionPool { protected static class HikariConnectionWrapper extends DatabaseConnectionCore { public HikariConnectionWrapper(final MysqlDatabaseConnection core) { super(core); } @Override public Integer getRowsAffectedCount() { return ((MysqlDatabaseConnection) _core).getRowsAffectedCount(); } } protected final HikariDataSource _dataSource = new HikariDataSource(); protected final AtomicBoolean _isShutdown = new AtomicBoolean(false); protected final LoggerInstance _logger = Logger.getInstance(this.getClass()); protected void _initHikariDataSource(final DatabaseProperties databaseProperties) { // NOTE: Using the MariaDB driver causes an unbounded memory leak within MySQL 5.7 & 8 (and Percona 8). _dataSource.setDriverClassName(com.mysql.jdbc.Driver.class.getName()); _dataSource.setConnectionInitSql("SET NAMES 'utf8mb4'"); _dataSource.setConnectionTimeout(TimeUnit.SECONDS.toMillis(15)); _dataSource.setMaxLifetime(TimeUnit.HOURS.toMillis(1)); // NOTE: MySQL has a default max of 8 hours. _dataSource.setMaximumPoolSize(BitcoinVerdeDatabase.MAX_DATABASE_CONNECTION_COUNT); // NOTE: MySQL default is 151. _dataSource.setMinimumIdle(4); _dataSource.setAutoCommit(true); _dataSource.setLeakDetectionThreshold(60 * 1000L); final String hostname = databaseProperties.getHostname(); final Integer port = databaseProperties.getPort(); final String schema = databaseProperties.getSchema(); final String username = databaseProperties.getUsername(); final String password = databaseProperties.getPassword(); final String connectionString = MysqlDatabaseConnectionFactory.createConnectionString(hostname, port, schema); _dataSource.setJdbcUrl(connectionString); _dataSource.setUsername(username); _dataSource.setPassword(password); // NOTE: Caching prepared statements are likely not the cause of a memory leak within MySQL, however it wasn't // conclusively absolved, and since the performance benefit was not measured the caching is disabled. // { // Enable prepared statement caching... // final Properties config = new Properties(); // config.setProperty("useServerPrepStmts", "true"); // config.setProperty("rewriteBatchedStatements", "true"); // config.setProperty("cachePrepStmts", "true"); // config.setProperty("prepStmtCacheSize", "250"); // config.setProperty("prepStmtCacheSqlLimit", "2048"); // _dataSource.setDataSourceProperties(config); // } try { _dataSource.setLogWriter(new PrintWriter(new Writer() { @Override public void write(final char[] characterBuffer, final int readOffset, final int readByteCount) { final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < readByteCount; ++i) { stringBuilder.append(characterBuffer[readOffset + i]); } _logger.debug(stringBuilder.toString()); } @Override public void flush() { } @Override public void close() { } })); } catch (final Exception exception) { throw new RuntimeException(exception); } } public HikariDatabaseConnectionPool(final DatabaseProperties databaseProperties) { _initHikariDataSource(databaseProperties); } @Override public DatabaseConnection newConnection() throws DatabaseException { if (_isShutdown.get()) { throw new DatabaseException("newConnection after shutdown"); } try { final Connection connection = _dataSource.getConnection(); return new HikariConnectionWrapper(new MysqlDatabaseConnection(connection)); } catch (final Exception exception) { throw new DatabaseException(exception); } } @Override public void close() { if (_isShutdown.compareAndSet(false, true)) { _dataSource.close(); } } @Override public Integer getInUseConnectionCount() { final HikariPoolMXBean hikariPoolMXBean = _dataSource.getHikariPoolMXBean(); return hikariPoolMXBean.getActiveConnections(); } @Override public Integer getAliveConnectionCount() { final HikariPoolMXBean hikariPoolMXBean = _dataSource.getHikariPoolMXBean(); return hikariPoolMXBean.getIdleConnections(); } @Override public Integer getCurrentPoolSize() { final HikariPoolMXBean hikariPoolMXBean = _dataSource.getHikariPoolMXBean(); return hikariPoolMXBean.getTotalConnections(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/response/transaction/TransactionMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response.transaction; import com.softwareverde.bitcoin.inflater.TransactionInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.transaction.TransactionInflater; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; public class TransactionMessageInflater extends BitcoinProtocolMessageInflater { protected final TransactionInflaters _transactionInflaters; public TransactionMessageInflater(final TransactionInflaters transactionInflaters) { _transactionInflaters = transactionInflaters; } @Override public TransactionMessage fromBytes(final byte[] bytes) { final TransactionMessage transactionMessage = new TransactionMessage(_transactionInflaters); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.TRANSACTION); if (protocolMessageHeader == null) { return null; } final TransactionInflater transactionInflater = _transactionInflaters.getTransactionInflater(); transactionMessage._transaction = transactionInflater.fromBytes(byteArrayReader); return transactionMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/slp/mint/ImmutableSlpMintScript.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.slp.mint; import com.softwareverde.constable.Const; public class ImmutableSlpMintScript extends SlpMintScriptCore implements Const { public ImmutableSlpMintScript(final SlpMintScript slpMintScript) { super(slpMintScript); } @Override public ImmutableSlpMintScript asConst() { return this; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/indexer/BlockchainIndexerDatabaseManagerCore.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.indexer; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.server.database.BatchRunner; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.query.BatchedInsertQuery; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.bitcoin.server.database.query.ValueExtractor; import com.softwareverde.bitcoin.server.module.node.database.block.BlockRelationship; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.fullnode.FullNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.TransactionDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.transaction.fullnode.FullNodeTransactionDatabaseManager; import com.softwareverde.bitcoin.slp.SlpTokenId; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.TransactionId; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.ScriptType; import com.softwareverde.bitcoin.transaction.script.ScriptTypeId; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableList; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.query.parameter.InClauseParameter; import com.softwareverde.database.query.parameter.TypedParameter; import com.softwareverde.database.row.Row; import com.softwareverde.util.Tuple; import com.softwareverde.util.Util; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class BlockchainIndexerDatabaseManagerCore implements BlockchainIndexerDatabaseManager { protected static final String LAST_INDEXED_TRANSACTION_KEY = "last_indexed_transaction_id"; protected final FullNodeDatabaseManager _databaseManager; protected final AddressInflater _addressInflater; public BlockchainIndexerDatabaseManagerCore(final AddressInflater addressInflater, final FullNodeDatabaseManager databaseManager) { _databaseManager = databaseManager; _addressInflater = addressInflater; } /** * Inflates a unique set of TransactionId -> BlockchainSegmentId from the provided rows. * Each row must contain two key/value sets, with labels: {blockchain_segment_id, transaction_id} */ protected final Set<Tuple<TransactionId, BlockchainSegmentId>> _extractTransactionBlockchainSegmentIds(final java.util.List<Row> rows) { final HashSet<Tuple<TransactionId, BlockchainSegmentId>> transactionBlockchainSegmentIds = new HashSet<Tuple<TransactionId, BlockchainSegmentId>>(); for (final Row row : rows) { final TransactionId transactionId = TransactionId.wrap(row.getLong("transaction_id")); final BlockchainSegmentId transactionBlockchainSegmentId = BlockchainSegmentId.wrap(row.getLong("blockchain_segment_id")); final Tuple<TransactionId, BlockchainSegmentId> tuple = new Tuple<TransactionId, BlockchainSegmentId>(transactionId, transactionBlockchainSegmentId); transactionBlockchainSegmentIds.add(tuple); } return transactionBlockchainSegmentIds; } protected Set<TransactionId> _filterTransactionsConnectedToBlockchainSegment(final Set<Tuple<TransactionId, BlockchainSegmentId>> transactionBlockchainSegmentIds, final BlockchainSegmentId blockchainSegmentId, final Boolean includeUnconfirmedTransactions) throws DatabaseException { final HashMap<BlockchainSegmentId, Boolean> connectedBlockchainSegmentIds = new HashMap<BlockchainSegmentId, Boolean>(); // Used to cache the lookup result of connected BlockchainSegments. final HashSet<TransactionId> transactionIds = new HashSet<TransactionId>(); // Remove BlockchainSegments that are not connected to the desired blockchainSegmentId, and ensure TransactionIds are unique... final FullNodeTransactionDatabaseManager transactionDatabaseManager = _databaseManager.getTransactionDatabaseManager(); final BlockchainDatabaseManager blockchainDatabaseManager = _databaseManager.getBlockchainDatabaseManager(); for (final Tuple<TransactionId, BlockchainSegmentId> tuple : transactionBlockchainSegmentIds) { final TransactionId transactionId = tuple.first; final BlockchainSegmentId transactionBlockchainSegmentId = tuple.second; if (transactionBlockchainSegmentId == null) { // If Transaction was not attached to a block... if (! includeUnconfirmedTransactions) { // If unconfirmedTransactions are excluded, then remove the transaction... continue; } else { // Exclude if the transaction is not in the mempool... final Boolean transactionIsUnconfirmed = transactionDatabaseManager.isUnconfirmedTransaction(transactionId); if (! transactionIsUnconfirmed) { continue; } } } else { // If the BlockchainSegment is not connected to the desired blockchainSegment then remove it... final Boolean transactionIsConnectedToBlockchainSegment; { final Boolean cachedIsConnectedToBlockchainSegment = connectedBlockchainSegmentIds.get(transactionBlockchainSegmentId); if (cachedIsConnectedToBlockchainSegment != null) { transactionIsConnectedToBlockchainSegment = cachedIsConnectedToBlockchainSegment; } else { final Boolean isConnectedToBlockchainSegment = blockchainDatabaseManager.areBlockchainSegmentsConnected(blockchainSegmentId, transactionBlockchainSegmentId, BlockRelationship.ANY); transactionIsConnectedToBlockchainSegment = isConnectedToBlockchainSegment; connectedBlockchainSegmentIds.put(transactionBlockchainSegmentId, isConnectedToBlockchainSegment); } } if (! transactionIsConnectedToBlockchainSegment) { continue; } } transactionIds.add(transactionId); } return transactionIds; } protected AddressTransactions _getAddressTransactions(final BlockchainSegmentId blockchainSegmentId, final Address address) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows; final HashMap<TransactionId, MutableList<Integer>> previousOutputs = new HashMap<TransactionId, MutableList<Integer>>(); { // Load credits, with output_indexes... final java.util.List<Row> transactionOutputRows = databaseConnection.query( new Query("SELECT blocks.blockchain_segment_id, indexed_transaction_outputs.transaction_id, indexed_transaction_outputs.output_index FROM indexed_transaction_outputs LEFT OUTER JOIN block_transactions ON block_transactions.transaction_id = indexed_transaction_outputs.transaction_id LEFT OUTER JOIN blocks ON blocks.id = block_transactions.block_id WHERE indexed_transaction_outputs.address = ?") .setParameter(address) ); if (transactionOutputRows.isEmpty()) { new AddressTransactions(blockchainSegmentId); } // Build the outputIndexes map... for (final Row row : transactionOutputRows) { final TransactionId transactionId = TransactionId.wrap(row.getLong("transaction_id")); final Integer outputIndex = row.getInteger("output_index"); MutableList<Integer> indexes = previousOutputs.get(transactionId); if (indexes == null) { indexes = new MutableList<Integer>(1); previousOutputs.put(transactionId, indexes); } indexes.add(outputIndex); } rows = transactionOutputRows; } final HashMap<TransactionId, MutableList<Integer>> spentOutputs = new HashMap<TransactionId, MutableList<Integer>>(); { // Load debits, with input_indexes... final java.util.List<Row> transactionInputRows = databaseConnection.query( new Query("SELECT blocks.blockchain_segment_id, indexed_transaction_inputs.transaction_id, indexed_transaction_inputs.spends_transaction_id, indexed_transaction_inputs.spends_output_index FROM indexed_transaction_inputs LEFT OUTER JOIN block_transactions ON block_transactions.transaction_id = indexed_transaction_inputs.transaction_id LEFT OUTER JOIN blocks ON blocks.id = block_transactions.block_id WHERE (indexed_transaction_inputs.spends_transaction_id, indexed_transaction_inputs.spends_output_index) IN (?)") .setInClauseParameters(rows, new ValueExtractor<Row>() { @Override public InClauseParameter extractValues(final Row transactionOutputRows) { final Long transactionId = transactionOutputRows.getLong("transaction_id"); final Integer outputIndex = transactionOutputRows.getInteger("output_index"); final TypedParameter transactionIdTypedParameter = (transactionId != null ? new TypedParameter(transactionId) : TypedParameter.NULL); final TypedParameter outputIndexTypedParameter = (outputIndex != null ? new TypedParameter(outputIndex) : TypedParameter.NULL); return new InClauseParameter(transactionIdTypedParameter, outputIndexTypedParameter); } }) ); // Build the inputIndexes map... for (final Row row : transactionInputRows) { // final TransactionId transactionId = TransactionId.wrap(row.getLong("transaction_id")); final TransactionId spentTransactionId = TransactionId.wrap(row.getLong("spends_transaction_id")); final Integer spentOutputIndex = row.getInteger("spends_output_index"); MutableList<Integer> indexes = spentOutputs.get(spentTransactionId); if (indexes == null) { indexes = new MutableList<Integer>(1); spentOutputs.put(spentTransactionId, indexes); } indexes.add(spentOutputIndex); } rows.addAll(transactionInputRows); } // Get Transactions that are connected to the provided blockchainSegmentId... final Set<Tuple<TransactionId, BlockchainSegmentId>> transactionBlockchainSegmentIds = _extractTransactionBlockchainSegmentIds(rows); final Set<TransactionId> connectedTransactionIds = _filterTransactionsConnectedToBlockchainSegment(transactionBlockchainSegmentIds, blockchainSegmentId, true); // Remove Transactions that are not connected to this blockchain... { // PreviousOutputs final Iterator<TransactionId> iterator = previousOutputs.keySet().iterator(); while (iterator.hasNext()) { final TransactionId transactionId = iterator.next(); if (! connectedTransactionIds.contains(transactionId)) { iterator.remove(); } } } { // SpentOutputs final Iterator<TransactionId> iterator = spentOutputs.keySet().iterator(); while (iterator.hasNext()) { final TransactionId transactionId = iterator.next(); if (! connectedTransactionIds.contains(transactionId)) { iterator.remove(); } } } return new AddressTransactions(blockchainSegmentId, new ImmutableList<TransactionId>(connectedTransactionIds), previousOutputs, spentOutputs); } protected Long _getLastIndexedTransactionId() throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT value FROM properties WHERE `key` = ?") .setParameter(LAST_INDEXED_TRANSACTION_KEY) ); if (rows.isEmpty()) { return 0L; } final Row row = rows.get(0); return row.getLong("value"); } protected void _updateLastIndexedTransactionId(final List<TransactionId> transactionIds) throws DatabaseException { if (transactionIds.isEmpty()) { return; } final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); Long nextTransactionId = _getLastIndexedTransactionId(); for (final TransactionId transactionId : transactionIds) { final long transactionIdLong = transactionId.longValue(); if (transactionIdLong >= nextTransactionId) { nextTransactionId = transactionIdLong; } } databaseConnection.executeSql( new Query("INSERT INTO properties (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = VALUES (value)") .setParameter(LAST_INDEXED_TRANSACTION_KEY) .setParameter(nextTransactionId) ); } @Override public List<TransactionId> getTransactionIds(final BlockchainSegmentId blockchainSegmentId, final Address address, final Boolean includeUnconfirmedTransactions) throws DatabaseException { final AddressTransactions addressTransactions = _getAddressTransactions(blockchainSegmentId, address); return addressTransactions.transactionIds; } @Override public Long getAddressBalance(final BlockchainSegmentId blockchainSegmentId, final Address address) throws DatabaseException { final AddressTransactions addressTransactions = _getAddressTransactions(blockchainSegmentId, address); final List<Integer> emptyList = new MutableList<Integer>(0); long balance = 0L; final TransactionDatabaseManager transactionDatabaseManager = _databaseManager.getTransactionDatabaseManager(); for (final TransactionId transactionId : addressTransactions.transactionIds) { final Transaction transaction = transactionDatabaseManager.getTransaction(transactionId); // Collect the previousTransactions, and add the remembered outputs that credit into this account... final List<TransactionOutput> previousTransactionOutputs = transaction.getTransactionOutputs(); for (final Integer outputIndex : Util.coalesce(addressTransactions.previousOutputs.get(transactionId), emptyList)) { final TransactionOutput previousTransactionOutput = previousTransactionOutputs.get(outputIndex); balance += previousTransactionOutput.getAmount(); } } for (final TransactionId transactionId : addressTransactions.spentOutputs.keySet()) { final Transaction transaction = transactionDatabaseManager.getTransaction(transactionId); // Deduct all debits from the account for this transaction's outputs... final List<TransactionOutput> transactionOutputs = transaction.getTransactionOutputs(); for (final Integer outputIndex : Util.coalesce(addressTransactions.spentOutputs.get(transactionId), emptyList)) { final TransactionOutput transactionOutput = transactionOutputs.get(outputIndex); balance -= transactionOutput.getAmount(); } } return balance; } @Override public SlpTokenId getSlpTokenId(final TransactionId transactionId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT transactions.hash FROM indexed_transaction_outputs INNER JOIN transactions ON transactions.id = indexed_transaction_outputs.slp_transaction_id WHERE indexed_transaction_outputs.transaction_id = ?") .setParameter(transactionId) ); if (rows.isEmpty()) { return null; } final Row row = rows.get(0); return SlpTokenId.wrap(Sha256Hash.copyOf(row.getBytes("hash"))); } @Override public List<TransactionId> getSlpTransactionIds(final SlpTokenId slpTokenId) throws DatabaseException { final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT indexed_transaction_outputs.transaction_id FROM indexed_transaction_outputs INNER JOIN transactions ON transactions.id = indexed_transaction_outputs.slp_transaction_id WHERE transactions.hash = ?") .setParameter(slpTokenId) ); final MutableList<TransactionId> transactionIds = new MutableList<TransactionId>(rows.size()); for (final Row row : rows) { final TransactionId transactionId = TransactionId.wrap(row.getLong("transaction_id")); transactionIds.add(transactionId); } return transactionIds; } @Override public void queueTransactionsForProcessing(final List<TransactionId> transactionIds) throws DatabaseException { } @Override public List<TransactionId> getUnprocessedTransactions(final Integer batchSize) throws DatabaseException { final Long firstTransactionId = _getLastIndexedTransactionId(); final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT id FROM transactions WHERE id > ? ORDER BY id ASC LIMIT " + batchSize) .setParameter(firstTransactionId) ); if (rows.isEmpty()) { return new MutableList<TransactionId>(0); } final ImmutableListBuilder<TransactionId> listBuilder = new ImmutableListBuilder<TransactionId>(rows.size()); for (final Row row : rows) { final Long rowId = row.getLong("id"); final TransactionId transactionId = TransactionId.wrap(rowId); listBuilder.add(transactionId); } return listBuilder.build(); } @Override public void dequeueTransactionsForProcessing(final List<TransactionId> transactionIds) throws DatabaseException { _updateLastIndexedTransactionId(transactionIds); } @Override public void indexTransactionOutputs(final List<TransactionId> transactionIds, final List<Integer> outputIndexes, final List<Long> amounts, final List<ScriptType> scriptTypes, final List<Address> addresses, final List<TransactionId> slpTransactionIds) throws DatabaseException { final int itemCount = transactionIds.getCount(); if (transactionIds.getCount() != itemCount) { throw new DatabaseException("Mismatch parameter count transactionIds expected " + itemCount + " got " + transactionIds.getCount()); } if (outputIndexes.getCount() != itemCount) { throw new DatabaseException("Mismatch parameter count outputIndexes expected " + itemCount + " got " + outputIndexes.getCount()); } if (amounts.getCount() != itemCount) { throw new DatabaseException("Mismatch parameter count amounts expected " + itemCount + " got " + amounts.getCount()); } if (scriptTypes.getCount() != itemCount) { throw new DatabaseException("Mismatch parameter count scriptTypes expected " + itemCount + " got " + scriptTypes.getCount()); } if (addresses.getCount() != itemCount) { throw new DatabaseException("Mismatch parameter count addresses expected " + itemCount + " got " + addresses.getCount()); } if (slpTransactionIds.getCount() != itemCount) { throw new DatabaseException("Mismatch parameter count slpTransactionIds expected " + itemCount + " got " + slpTransactionIds.getCount()); } final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); // The BatchRunner expects to receive a single list; in order to use it here, a list of indexes is created as the batch. final MutableList<Integer> indexes = new MutableList<Integer>(itemCount); for (int i = 0; i < itemCount; ++i) { indexes.add(i); } final Integer batchSize = Math.min(1024, _databaseManager.getMaxQueryBatchSize()); final BatchRunner<Integer> batchRunner = new BatchRunner<Integer>(batchSize, false); batchRunner.run(indexes, new BatchRunner.Batch<Integer>() { @Override public void run(final List<Integer> batchItems) throws Exception { final BatchedInsertQuery batchedInsertQuery = new BatchedInsertQuery("INSERT INTO indexed_transaction_outputs (transaction_id, output_index, amount, address, script_type_id, slp_transaction_id) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE amount = VALUES(amount), address = VALUES(address), script_type_id = VALUES(script_type_id), slp_transaction_id = VALUES(slp_transaction_id)"); for (final Integer itemIndex : batchItems) { final TransactionId transactionId = transactionIds.get(itemIndex); final Integer outputIndex = outputIndexes.get(itemIndex); final Long amount = amounts.get(itemIndex); final Address address = addresses.get(itemIndex); final ScriptType scriptType = scriptTypes.get(itemIndex); final TransactionId slpTransactionId = slpTransactionIds.get(itemIndex); final ScriptTypeId scriptTypeId = scriptType.getScriptTypeId(); batchedInsertQuery .setParameter(transactionId) .setParameter(outputIndex) .setParameter(amount) .setParameter(address) .setParameter(scriptTypeId) .setParameter(slpTransactionId); } databaseConnection.executeSql(batchedInsertQuery); } }); } @Override public void indexTransactionInputs(final List<TransactionId> transactionIds, final List<Integer> inputIndexes, final List<TransactionOutputId> transactionOutputIds) throws DatabaseException { final int itemCount = transactionIds.getCount(); if (transactionIds.getCount() != itemCount) { throw new DatabaseException("Mismatch parameter count transactionIds expected " + itemCount + " got " + transactionIds.getCount()); } if (inputIndexes.getCount() != itemCount) { throw new DatabaseException("Mismatch parameter count inputIndexes expected " + itemCount + " got " + inputIndexes.getCount()); } if (transactionOutputIds.getCount() != itemCount) { throw new DatabaseException("Mismatch parameter count transactionOutputIds expected " + itemCount + " got " + transactionOutputIds.getCount()); } final DatabaseConnection databaseConnection = _databaseManager.getDatabaseConnection(); // The BatchRunner expects to receive a single list; in order to use it here, a list of indexes is created as the batch. final MutableList<Integer> indexes = new MutableList<Integer>(itemCount); for (int i = 0; i < itemCount; ++i) { indexes.add(i); } final Integer batchSize = Math.min(1024, _databaseManager.getMaxQueryBatchSize()); final BatchRunner<Integer> batchRunner = new BatchRunner<Integer>(batchSize); batchRunner.run(indexes, new BatchRunner.Batch<Integer>() { @Override public void run(final List<Integer> batchItems) throws Exception { final BatchedInsertQuery batchedInsertQuery = new BatchedInsertQuery("INSERT INTO indexed_transaction_inputs (transaction_id, input_index, spends_transaction_id, spends_output_index) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE spends_transaction_id = VALUES(spends_transaction_id), spends_output_index = VALUES(spends_output_index)"); for (final Integer itemIndex : batchItems) { final TransactionId transactionId = transactionIds.get(itemIndex); final Integer inputIndex = inputIndexes.get(itemIndex); final TransactionOutputId transactionOutputId = transactionOutputIds.get(itemIndex); batchedInsertQuery .setParameter(transactionId) .setParameter(inputIndex) .setParameter(transactionOutputId.getTransactionId()) .setParameter(transactionOutputId.getOutputIndex()); } databaseConnection.executeSql(batchedInsertQuery); } }); } } <|start_filename|>src/main/java/com/softwareverde/network/time/VolatileNetworkTime.java<|end_filename|> package com.softwareverde.network.time; /** * VolatileNetworkTime represents a NetworkTime that may update at any time. */ public interface VolatileNetworkTime extends NetworkTime { } <|start_filename|>src/main/java/com/softwareverde/bitcoin/util/Util.java<|end_filename|> package com.softwareverde.bitcoin.util; import java.util.ArrayList; import java.util.Map; public class Util extends com.softwareverde.util.Util { protected Util() { } public static <Key, Item> void addToListMap(final Key key, final Item item, final Map<Key, java.util.List<Item>> map) { java.util.List<Item> items = map.get(key); if (items == null) { items = new ArrayList<Item>(); map.put(key, items); } items.add(item); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/sync/transaction/pending/PendingTransactionId.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.sync.transaction.pending; import com.softwareverde.util.type.identifier.Identifier; public class PendingTransactionId extends Identifier { public static PendingTransactionId wrap(final Long value) { if (value == null) { return null; } return new PendingTransactionId(value); } protected PendingTransactionId(final Long value) { super(value); } } <|start_filename|>src/main/java/com/softwareverde/network/p2p/message/type/PongMessage.java<|end_filename|> package com.softwareverde.network.p2p.message.type; import com.softwareverde.network.p2p.message.ProtocolMessage; public interface PongMessage extends ProtocolMessage { Long getNonce(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/response/hash/InventoryItemType.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response.hash; public enum InventoryItemType { ERROR (0x00000000), TRANSACTION (0x00000001), BLOCK (0x00000002), MERKLE_BLOCK (0x00000003), COMPACT_BLOCK (0x00000004), EXTRA_THIN_BLOCK (0x00000005), // Custom Bitcoin Verde Types, VALID_SLP_TRANSACTION (0x42560001), INVALID_SLP_TRANSACTION (0x42560002); public static InventoryItemType fromValue(final int value) { for (final InventoryItemType inventoryItemType : InventoryItemType.values()) { if (inventoryItemType._value == value) { return inventoryItemType; } } return ERROR; } private final int _value; InventoryItemType(final int value) { _value = value; } public int getValue() { return _value; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/StratumApiEndpoint.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.module.api.ApiResult; import com.softwareverde.http.server.servlet.Servlet; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.logging.Logger; import com.softwareverde.servlet.session.SessionManager; public abstract class StratumApiEndpoint implements Servlet { protected final StratumProperties _stratumProperties; protected final SessionManager _sessionManager; public StratumApiEndpoint(final StratumProperties stratumProperties) { _stratumProperties = stratumProperties; _sessionManager = new SessionManager(_stratumProperties.getCookiesDirectory() + "/"); } protected abstract Response _onRequest(final Request request); @Override public final Response onRequest(final Request request) { try { return this._onRequest(request); } catch (final Exception exception) { Logger.warn(exception); } return new JsonResponse(Response.Codes.SERVER_ERROR, new ApiResult(false, "An internal error occurred.")); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/rpc/handler/QueryBlockchainHandler.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.rpc.handler; import com.softwareverde.bitcoin.chain.segment.BlockchainSegmentId; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.database.query.Query; import com.softwareverde.bitcoin.server.module.node.rpc.NodeRpcHandler; import com.softwareverde.bitcoin.server.module.node.rpc.blockchain.BlockchainMetadata; import com.softwareverde.bitcoin.server.module.node.rpc.blockchain.BlockchainMetadataBuilder; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.immutable.ImmutableListBuilder; import com.softwareverde.database.DatabaseException; import com.softwareverde.database.row.Row; import com.softwareverde.logging.Logger; public class QueryBlockchainHandler implements NodeRpcHandler.QueryBlockchainHandler { protected final DatabaseConnectionFactory _databaseConnectionFactory; public QueryBlockchainHandler(final DatabaseConnectionFactory databaseConnectionFactory) { _databaseConnectionFactory = databaseConnectionFactory; } @Override public List<BlockchainMetadata> getBlockchainMetadata() { try (final DatabaseConnection databaseConnection = _databaseConnectionFactory.newConnection()) { final BlockchainMetadataBuilder blockchainMetadataBuilder = new BlockchainMetadataBuilder(); final java.util.List<Row> rows = databaseConnection.query( new Query("SELECT blockchain_segment_id, blockchain_segments.nested_set_left, blockchain_segments.nested_set_right, parent_blockchain_segment_id, COUNT(*) AS block_count, MIN(block_height) AS min_block_height, MAX(block_height) AS max_block_height FROM blocks INNER JOIN blockchain_segments ON blockchain_segments.id = blocks.blockchain_segment_id GROUP BY blocks.blockchain_segment_id ORDER BY nested_set_left ASC, nested_set_right ASC") ); final ImmutableListBuilder<BlockchainMetadata> blockchainMetadataList = new ImmutableListBuilder<BlockchainMetadata>(rows.size()); for (final Row row : rows) { final BlockchainSegmentId blockchainSegmentId = BlockchainSegmentId.wrap(row.getLong("blockchain_segment_id")); final BlockchainSegmentId parentBlockchainSegmentId = BlockchainSegmentId.wrap(row.getLong("parent_blockchain_segment_id")); final Integer nestedSetLeft = row.getInteger("nested_set_left"); final Integer nestedSetRight = row.getInteger("nested_set_right"); final Long blockCount = row.getLong("block_count"); final Long minBlockHeight = row.getLong("min_block_height"); final Long maxBlockHeight = row.getLong("max_block_height"); blockchainMetadataBuilder.setBlockchainSegmentId(blockchainSegmentId); blockchainMetadataBuilder.setParentBlockchainSegmentId(parentBlockchainSegmentId); blockchainMetadataBuilder.setNestedSet(nestedSetLeft, nestedSetRight); blockchainMetadataBuilder.setBlockCount(blockCount); blockchainMetadataBuilder.setBlockHeight(minBlockHeight, maxBlockHeight); final BlockchainMetadata blockchainMetadata = blockchainMetadataBuilder.build(); if (blockchainMetadata != null) { blockchainMetadataList.add(blockchainMetadata); } } return blockchainMetadataList.build(); } catch (final DatabaseException exception) { Logger.warn(exception); return null; } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/MessageType.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.util.Util; public class MessageType { public static final Integer BYTE_COUNT = 12; public static final MessageType SYNCHRONIZE_VERSION = new MessageType("version"); public static final MessageType ACKNOWLEDGE_VERSION = new MessageType("verack"); public static final MessageType PING = new MessageType("ping"); public static final MessageType PONG = new MessageType("pong"); public static final MessageType NODE_ADDRESSES = new MessageType("addr"); public static final MessageType QUERY_BLOCKS = new MessageType("getblocks"); public static final MessageType INVENTORY = new MessageType("inv"); public static final MessageType QUERY_UNCONFIRMED_TRANSACTIONS = new MessageType("mempool"); public static final MessageType REQUEST_BLOCK_HEADERS = new MessageType("getheaders"); public static final MessageType BLOCK_HEADERS = new MessageType("headers"); public static final MessageType REQUEST_DATA = new MessageType("getdata"); public static final MessageType BLOCK = new MessageType("block", true); public static final MessageType TRANSACTION = new MessageType("tx"); public static final MessageType MERKLE_BLOCK = new MessageType("merkleblock", true); public static final MessageType NOT_FOUND = new MessageType("notfound"); public static final MessageType ERROR = new MessageType("reject"); public static final MessageType ENABLE_NEW_BLOCKS_VIA_HEADERS = new MessageType("sendheaders"); public static final MessageType ENABLE_COMPACT_BLOCKS = new MessageType("sendcmpct"); public static final MessageType REQUEST_EXTRA_THIN_BLOCK = new MessageType("get_xthin"); public static final MessageType EXTRA_THIN_BLOCK = new MessageType("xthinblock", true); public static final MessageType THIN_BLOCK = new MessageType("thinblock", true); public static final MessageType REQUEST_EXTRA_THIN_TRANSACTIONS = new MessageType("get_xblocktx"); public static final MessageType THIN_TRANSACTIONS = new MessageType("xblocktx", true); public static final MessageType FEE_FILTER = new MessageType("feefilter"); public static final MessageType REQUEST_PEERS = new MessageType("getaddr"); public static final MessageType SET_TRANSACTION_BLOOM_FILTER = new MessageType("filterload"); public static final MessageType UPDATE_TRANSACTION_BLOOM_FILTER = new MessageType("filteradd"); public static final MessageType CLEAR_TRANSACTION_BLOOM_FILTER = new MessageType("filterclear"); // BitcoinVerde Messages public static final MessageType QUERY_ADDRESS_BLOCKS = new MessageType("addrblocks", true); public static final MessageType ENABLE_SLP_TRANSACTIONS = new MessageType("sendslp", true); public static final MessageType QUERY_SLP_STATUS = new MessageType("getslpstatus", true); protected final ByteArray _bytes; protected final String _value; protected final Boolean _isLargeMessage; protected MessageType(final String value) { this(value, false); } protected MessageType(final String value, final Boolean isLargeMessage) { _value = value; _isLargeMessage = isLargeMessage; final MutableByteArray mutableByteArray = new MutableByteArray(BYTE_COUNT); final byte[] valueBytes = value.getBytes(); ByteUtil.setBytes(mutableByteArray.unwrap(), valueBytes); _bytes = mutableByteArray.asConst(); } public ByteArray getBytes() { return _bytes; } public String getValue() { return _value; } public Boolean isLargeMessage() { return _isLargeMessage; } @Override public boolean equals(final Object object) { if (this == object) { return true; } if (! (object instanceof MessageType)) { return false; } final MessageType messageType = (MessageType) object; return ( Util.areEqual(_bytes, messageType._bytes) && Util.areEqual(_value, messageType._value) ); } @Override public int hashCode() { return _value.hashCode(); } @Override public String toString() { return _value; } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/util/TransactionTestUtil.java<|end_filename|> package com.softwareverde.bitcoin.test.util; import com.softwareverde.bitcoin.address.Address; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.transaction.MutableTransaction; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.MutableTransactionInput; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.locktime.LockTime; import com.softwareverde.bitcoin.transaction.locktime.SequenceNumber; import com.softwareverde.bitcoin.transaction.output.MutableTransactionOutput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier; import com.softwareverde.bitcoin.transaction.script.ScriptBuilder; import com.softwareverde.bitcoin.transaction.script.locking.LockingScript; import com.softwareverde.bitcoin.transaction.script.signature.hashtype.HashType; import com.softwareverde.bitcoin.transaction.script.signature.hashtype.Mode; import com.softwareverde.bitcoin.transaction.script.unlocking.UnlockingScript; import com.softwareverde.bitcoin.transaction.signer.HashMapTransactionOutputRepository; import com.softwareverde.bitcoin.transaction.signer.SignatureContext; import com.softwareverde.bitcoin.transaction.signer.TransactionOutputRepository; import com.softwareverde.bitcoin.transaction.signer.TransactionSigner; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; public class TransactionTestUtil { protected TransactionTestUtil() { } public static MutableTransaction createTransaction() { final MutableTransaction mutableTransaction = new MutableTransaction(); mutableTransaction.setVersion(Transaction.VERSION); mutableTransaction.setLockTime(LockTime.MAX_TIMESTAMP); return mutableTransaction; } public static HashMapTransactionOutputRepository createTransactionOutputRepository(final Transaction... transactionsToSpend) { final HashMapTransactionOutputRepository transactionOutputRepository = new HashMapTransactionOutputRepository(); for (final Transaction transactionToSpend : transactionsToSpend) { int outputIndex = 0; for (final TransactionOutput transactionOutput : transactionToSpend.getTransactionOutputs()) { final TransactionOutputIdentifier transactionOutputIdentifierToSpend = new TransactionOutputIdentifier(transactionToSpend.getHash(), outputIndex); transactionOutputRepository.put(transactionOutputIdentifierToSpend, transactionOutput); outputIndex += 1; } } return transactionOutputRepository; } /** * Creates a signed transaction using the PrivateKey(s) provided. * One or more PrivateKeys may be provided. * If multiple PrivateKeys are provided then the order used corresponds to the Transaction's TransactionInputs. * The number of PrivateKeys may be less than the number of TransactionInputs, in which case the last PrivateKey will be used to sign the remaining TransactionInputs. */ public static Transaction signTransaction(final TransactionOutputRepository transactionOutputsToSpend, final Transaction unsignedTransaction, final PrivateKey... privateKeys) { Transaction partiallySignedTransaction = unsignedTransaction; final TransactionSigner transactionSigner = new TransactionSigner(); int privateKeyIndex = 0; int inputIndex = 0; final List<TransactionInput> transactionInputs = unsignedTransaction.getTransactionInputs(); for (final TransactionInput transactionInput : transactionInputs) { final TransactionOutputIdentifier transactionOutputIdentifierBeingSpent = TransactionOutputIdentifier.fromTransactionInput(transactionInput); final TransactionOutput transactionOutputBeingSpent = transactionOutputsToSpend.get(transactionOutputIdentifierBeingSpent); final SignatureContext signatureContext = new SignatureContext(partiallySignedTransaction, new HashType(Mode.SIGNATURE_HASH_ALL, true, false)); // BCH is not enabled at this block height... signatureContext.setInputIndexBeingSigned(inputIndex); signatureContext.setShouldSignInputScript(inputIndex, true, transactionOutputBeingSpent); final PrivateKey privateKey = privateKeys[privateKeyIndex]; if ((privateKeyIndex + 1) < privateKeys.length) { privateKeyIndex += 1; } partiallySignedTransaction = transactionSigner.signTransaction(signatureContext, privateKey, true); inputIndex += 1; } return partiallySignedTransaction; } public static MutableTransactionInput createTransactionInput(final TransactionOutputIdentifier transactionOutputIdentifierToSpend) { final MutableTransactionInput mutableTransactionInput = new MutableTransactionInput(); mutableTransactionInput.setSequenceNumber(SequenceNumber.MAX_SEQUENCE_NUMBER); mutableTransactionInput.setPreviousOutputTransactionHash(transactionOutputIdentifierToSpend.getTransactionHash()); mutableTransactionInput.setPreviousOutputIndex(transactionOutputIdentifierToSpend.getOutputIndex()); mutableTransactionInput.setUnlockingScript(UnlockingScript.EMPTY_SCRIPT); return mutableTransactionInput; } public static MutableTransactionOutput createTransactionOutput(final Address address) { return TransactionTestUtil.createTransactionOutput((50L * Transaction.SATOSHIS_PER_BITCOIN), address); } public static MutableTransactionOutput createTransactionOutput(final Long amount, final Address address) { final MutableTransactionOutput mutableTransactionOutput = new MutableTransactionOutput(); mutableTransactionOutput.setAmount(amount); final LockingScript lockingScript = ScriptBuilder.payToAddress(address); mutableTransactionOutput.setLockingScript(lockingScript); return mutableTransactionOutput; } public static Transaction createCoinbaseTransactionSpendableByPrivateKey(final PrivateKey privateKey) { return TransactionTestUtil.createCoinbaseTransactionSpendableByPrivateKey(privateKey, (50L * Transaction.SATOSHIS_PER_BITCOIN)); } public static Transaction createCoinbaseTransactionSpendableByPrivateKey(final PrivateKey privateKey, final Long outputAmount) { final AddressInflater addressInflater = new AddressInflater(); final MutableTransaction mutableTransaction = new MutableTransaction(); mutableTransaction.setVersion(Transaction.VERSION); mutableTransaction.setLockTime(LockTime.MAX_TIMESTAMP); final TransactionInput transactionInput; { final MutableTransactionInput mutableTransactionInput = new MutableTransactionInput(); mutableTransactionInput.setSequenceNumber(SequenceNumber.MAX_SEQUENCE_NUMBER); mutableTransactionInput.setPreviousOutputTransactionHash(Sha256Hash.EMPTY_HASH); mutableTransactionInput.setPreviousOutputIndex(-1); mutableTransactionInput.setUnlockingScript(UnlockingScript.EMPTY_SCRIPT); transactionInput = mutableTransactionInput; } mutableTransaction.addTransactionInput(transactionInput); final TransactionOutput transactionOutput; { final MutableTransactionOutput mutableTransactionOutput = new MutableTransactionOutput(); mutableTransactionOutput.setIndex(0); mutableTransactionOutput.setAmount(outputAmount); final LockingScript lockingScript = ScriptBuilder.payToAddress(addressInflater.fromPrivateKey(privateKey, true)); mutableTransactionOutput.setLockingScript(lockingScript); transactionOutput = mutableTransactionOutput; } mutableTransaction.addTransactionOutput(transactionOutput); return mutableTransaction; } } <|start_filename|>src/server/java/com/softwareverde/servlet/session/Session.java<|end_filename|> package com.softwareverde.servlet.session; import com.softwareverde.json.Json; public class Session { public static Session newSession(final SessionId sessionId) { if (sessionId == null) { return null; } return new Session(sessionId); } public static Session newSession(final SessionId sessionId, final String sessionData) { if (sessionId == null) { return null; } return new Session(sessionId, sessionData); } protected final SessionId _sessionId; protected final Json _data; protected Session(final SessionId sessionId) { _sessionId = sessionId; _data = new Json(false); } protected Session(final SessionId sessionId, final String sessionData) { _sessionId = sessionId; _data = Json.parse(sessionData); } public SessionId getSessionId() { return _sessionId; } public Json getMutableData() { return _data; } @Override public String toString() { return _data.toString(); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/block/BlockInflaterTests.java<|end_filename|> package com.softwareverde.bitcoin.block; import com.softwareverde.bitcoin.test.UnitTest; import com.softwareverde.bitcoin.util.IoUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import org.junit.Assert; import org.junit.Test; public class BlockInflaterTests extends UnitTest { @Test public void should_inflate_valid_block() { // Setup final BlockInflater blockInflater = new BlockInflater(); final BlockDeflater blockDeflater = new BlockDeflater(); final Sha256Hash expectedHash = Sha256Hash.fromHexString("00000000AFE94C578B4DC327AA64E1203283C5FD5F152CE886341766298CF523"); final ByteArray blockBytes = ByteArray.fromHexString(IoUtil.getResource("/blocks/00000000AFE94C578B4DC327AA64E1203283C5FD5F152CE886341766298CF523")); // Action final Block block = blockInflater.fromBytes(blockBytes); final ByteArray deflatedBlock = blockDeflater.toBytes(block); // Assert Assert.assertEquals(expectedHash, block.getHash()); Assert.assertEquals(blockBytes, deflatedBlock); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/CoreInflater.java<|end_filename|> package com.softwareverde.bitcoin; import com.softwareverde.bitcoin.address.AddressInflater; import com.softwareverde.bitcoin.block.BlockDeflater; import com.softwareverde.bitcoin.block.BlockInflater; import com.softwareverde.bitcoin.block.header.BlockHeaderDeflater; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.block.header.BlockHeaderWithTransactionCountInflater; import com.softwareverde.bitcoin.block.merkleroot.PartialMerkleTreeDeflater; import com.softwareverde.bitcoin.block.merkleroot.PartialMerkleTreeInflater; import com.softwareverde.bitcoin.bloomfilter.BloomFilterDeflater; import com.softwareverde.bitcoin.bloomfilter.BloomFilterInflater; import com.softwareverde.bitcoin.inflater.MasterInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeaderInflater; import com.softwareverde.bitcoin.server.message.type.node.address.NodeIpAddressInflater; import com.softwareverde.bitcoin.server.message.type.query.response.hash.InventoryItemInflater; import com.softwareverde.bitcoin.transaction.TransactionDeflater; import com.softwareverde.bitcoin.transaction.TransactionInflater; public class CoreInflater implements MasterInflater { protected final BitcoinProtocolMessageHeaderInflater _bitcoinProtocolMessageHeaderInflater; protected final NodeIpAddressInflater _nodeIpAddressInflater; protected final BlockHeaderInflater _blockHeaderInflater; protected final BlockHeaderDeflater _blockHeaderDeflater; protected final BlockHeaderWithTransactionCountInflater _blockHeaderWithTransactionCountInflater; protected final PartialMerkleTreeInflater _partialMerkleTreeInflater; protected final PartialMerkleTreeDeflater _partialMerkleTreeDeflater; protected final BloomFilterInflater _bloomFilterInflater; protected final BloomFilterDeflater _bloomFilterDeflater; protected final InventoryItemInflater _inventoryItemInflater; protected final BlockInflater _blockInflater; protected final BlockDeflater _blockDeflater; protected final TransactionInflater _transactionInflater; protected final TransactionDeflater _transactionDeflater; protected final AddressInflater _addressInflater; public CoreInflater() { _bitcoinProtocolMessageHeaderInflater = new BitcoinProtocolMessageHeaderInflater(); _nodeIpAddressInflater = new NodeIpAddressInflater(); _blockHeaderInflater = new BlockHeaderInflater(); _blockHeaderDeflater = new BlockHeaderDeflater(); _blockHeaderWithTransactionCountInflater = new BlockHeaderWithTransactionCountInflater(); _partialMerkleTreeInflater = new PartialMerkleTreeInflater(); _partialMerkleTreeDeflater = new PartialMerkleTreeDeflater(); _bloomFilterInflater = new BloomFilterInflater(); _bloomFilterDeflater = new BloomFilterDeflater(); _inventoryItemInflater = new InventoryItemInflater(); _blockInflater = new BlockInflater(); _blockDeflater = new BlockDeflater(); _transactionInflater = new TransactionInflater(); _transactionDeflater = new TransactionDeflater(); _addressInflater = new AddressInflater(); } @Override public BlockHeaderInflater getBlockHeaderInflater() { return _blockHeaderInflater; } @Override public BlockHeaderDeflater getBlockHeaderDeflater() { return _blockHeaderDeflater; } @Override public BlockInflater getBlockInflater() { return _blockInflater; } @Override public BlockDeflater getBlockDeflater() { return _blockDeflater; } @Override public TransactionInflater getTransactionInflater() { return _transactionInflater; } @Override public TransactionDeflater getTransactionDeflater() { return _transactionDeflater; } @Override public BitcoinProtocolMessageHeaderInflater getBitcoinProtocolMessageHeaderInflater() { return _bitcoinProtocolMessageHeaderInflater; } @Override public NodeIpAddressInflater getNodeIpAddressInflater() { return _nodeIpAddressInflater; } @Override public BlockHeaderWithTransactionCountInflater getBlockHeaderWithTransactionCountInflater() { return _blockHeaderWithTransactionCountInflater; } @Override public PartialMerkleTreeInflater getPartialMerkleTreeInflater() { return _partialMerkleTreeInflater; } @Override public PartialMerkleTreeDeflater getPartialMerkleTreeDeflater() { return _partialMerkleTreeDeflater; } @Override public AddressInflater getAddressInflater() { return _addressInflater; } @Override public BloomFilterInflater getBloomFilterInflater() { return _bloomFilterInflater; } @Override public BloomFilterDeflater getBloomFilterDeflater() { return _bloomFilterDeflater; } @Override public InventoryItemInflater getInventoryItemInflater() { return _inventoryItemInflater; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/spv/SpvDatabaseManager.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.spv; import com.softwareverde.bitcoin.server.configuration.CheckpointConfiguration; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.module.node.database.DatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.header.fullnode.FullNodeBlockHeaderDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.block.spv.SpvBlockDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.blockchain.BlockchainDatabaseManagerCore; import com.softwareverde.bitcoin.server.module.node.database.node.BitcoinNodeDatabaseManager; import com.softwareverde.bitcoin.server.module.node.database.node.BitcoinNodeDatabaseManagerCore; import com.softwareverde.bitcoin.server.module.node.database.transaction.spv.SpvTransactionDatabaseManager; import com.softwareverde.database.DatabaseException; public class SpvDatabaseManager implements DatabaseManager { protected final DatabaseConnection _databaseConnection; protected final Integer _maxQueryBatchSize; protected final CheckpointConfiguration _checkpointConfiguration; protected BitcoinNodeDatabaseManager _nodeDatabaseManager; protected BlockchainDatabaseManagerCore _blockchainDatabaseManager; protected SpvBlockDatabaseManager _blockDatabaseManager; protected FullNodeBlockHeaderDatabaseManager _blockHeaderDatabaseManager; protected SpvTransactionDatabaseManager _transactionDatabaseManager; public SpvDatabaseManager(final DatabaseConnection databaseConnection, final Integer maxQueryBatchSize, final CheckpointConfiguration checkpointConfiguration) { _databaseConnection = databaseConnection; _maxQueryBatchSize = maxQueryBatchSize; _checkpointConfiguration = checkpointConfiguration; } @Override public DatabaseConnection getDatabaseConnection() { return _databaseConnection; } @Override public BitcoinNodeDatabaseManager getNodeDatabaseManager() { if (_nodeDatabaseManager == null) { _nodeDatabaseManager = new BitcoinNodeDatabaseManagerCore(this); } return _nodeDatabaseManager; } @Override public BlockchainDatabaseManagerCore getBlockchainDatabaseManager() { if (_blockchainDatabaseManager == null) { _blockchainDatabaseManager = new BlockchainDatabaseManagerCore(this); } return _blockchainDatabaseManager; } @Override public SpvBlockDatabaseManager getBlockDatabaseManager() { if (_blockDatabaseManager == null) { _blockDatabaseManager = new SpvBlockDatabaseManager(this); } return _blockDatabaseManager; } @Override public FullNodeBlockHeaderDatabaseManager getBlockHeaderDatabaseManager() { if (_blockHeaderDatabaseManager == null) { _blockHeaderDatabaseManager = new FullNodeBlockHeaderDatabaseManager(this, _checkpointConfiguration); } return _blockHeaderDatabaseManager; } @Override public SpvTransactionDatabaseManager getTransactionDatabaseManager() { if (_transactionDatabaseManager == null) { _transactionDatabaseManager = new SpvTransactionDatabaseManager(this); } return _transactionDatabaseManager; } @Override public Integer getMaxQueryBatchSize() { return _maxQueryBatchSize; } @Override public void close() throws DatabaseException { _databaseConnection.close(); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bloomfilter/BloomFilterInflater.java<|end_filename|> package com.softwareverde.bitcoin.bloomfilter; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.bloomfilter.MutableBloomFilter; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.util.bytearray.Endian; public class BloomFilterInflater { public static final Integer MAX_BYTE_COUNT = (32 * 1024 * 1024); protected MutableBloomFilter _fromByteArrayReader(final ByteArrayReader byteArrayReader) { final Integer bloomFilterByteCount = byteArrayReader.readVariableSizedInteger().intValue(); if (bloomFilterByteCount > MAX_BYTE_COUNT) { return null; } final Integer bloomFilterBitCount = (bloomFilterByteCount * 8); final ByteArray bytes = MutableByteArray.wrap(byteArrayReader.readBytes(bloomFilterByteCount, Endian.BIG)); final Integer hashFunctionCount = byteArrayReader.readInteger(4, Endian.LITTLE); final Long nonce = byteArrayReader.readLong(4, Endian.LITTLE); final MutableByteArray bloomFilterBytes = new MutableByteArray(bloomFilterByteCount); for (int i = 0; i < bloomFilterBitCount; ++i) { final int bitcoinBloomFilterIndex = ( (i & 0x7FFFFFF8) + ((~i) & 0x00000007) ); // Aka: ( ((i / 8) * 8) + (7 - (i % 8)) ) final boolean bit = bytes.getBit(i); bloomFilterBytes.setBit(bitcoinBloomFilterIndex, bit); } final byte updateMode = byteArrayReader.readByte(); if (byteArrayReader.didOverflow()) { return null; } final MutableBloomFilter mutableBloomFilter = MutableBloomFilter.newInstance(bloomFilterBytes, hashFunctionCount, nonce); mutableBloomFilter.setUpdateMode(updateMode); return mutableBloomFilter; } public MutableBloomFilter fromBytes(final ByteArray byteArray) { final ByteArrayReader byteArrayReader = new ByteArrayReader(byteArray); return _fromByteArrayReader(byteArrayReader); } public MutableBloomFilter fromBytes(final ByteArrayReader byteArrayReader) { return _fromByteArrayReader(byteArrayReader); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/transaction/script/runner/context/TransactionContext.java<|end_filename|> package com.softwareverde.bitcoin.transaction.script.runner.context; import com.softwareverde.bitcoin.chain.time.MedianBlockTime; import com.softwareverde.bitcoin.transaction.Transaction; import com.softwareverde.bitcoin.transaction.input.TransactionInput; import com.softwareverde.bitcoin.transaction.output.TransactionOutput; import com.softwareverde.bitcoin.transaction.script.Script; import com.softwareverde.constable.Constable; import com.softwareverde.json.Jsonable; public interface TransactionContext extends Constable<ImmutableTransactionContext>, Jsonable { Long getBlockHeight(); MedianBlockTime getMedianBlockTime(); TransactionInput getTransactionInput(); TransactionOutput getTransactionOutput(); /** * Returns the Transaction being validated. */ Transaction getTransaction(); Integer getTransactionInputIndex(); /** * Returns the script that is currently being evaluated. * This script could be one of many things: * - The Tx Input's Unlocking Script * - The Tx Output's Locking Script * - The Tx P2SH */ Script getCurrentScript(); /** * Returns the index of the script's current execution index. * Calling this function during the execution of the first opcode will return zero. */ Integer getScriptIndex(); /** * Returns the index within script that starts with the index immediately after the last executed CODE_SEPARATOR operation. * If the script has not encountered a CodeSeparator, the return value will be zero. * Therefore, calling Script.subScript() with this return value will always be safe. * * Ex: Given: * ix: 0 | 1 | 2 | 3 * opcodes: NO_OP | NO_OP | CODE_SEPARATOR | NO_OP * Context.getScriptLastCodeSeparatorIndex() will return: 3 */ Integer getScriptLastCodeSeparatorIndex(); /** * Returns the total number of Signature operations executed thus far, as defined by HF20200515. */ Integer getSignatureOperationCount(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/merkleroot/PartialMerkleTreeDeflater.java<|end_filename|> package com.softwareverde.bitcoin.block.merkleroot; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.cryptography.hash.sha256.Sha256Hash; import com.softwareverde.util.bytearray.ByteArrayBuilder; import com.softwareverde.util.bytearray.Endian; public class PartialMerkleTreeDeflater { public ByteArray toBytes(final PartialMerkleTree partialMerkleTree) { final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(ByteUtil.integerToBytes(partialMerkleTree.getItemCount()), Endian.LITTLE); // Aka the BlockHeader's Transaction count... final List<Sha256Hash> hashes = partialMerkleTree.getHashes(); byteArrayBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(hashes.getCount())); for (final Sha256Hash hash : hashes) { byteArrayBuilder.appendBytes(hash, Endian.LITTLE); } final ByteArray flags = partialMerkleTree.getFlags(); byteArrayBuilder.appendBytes(ByteUtil.variableLengthIntegerToBytes(flags.getByteCount())); for (int i = 0; i < flags.getByteCount(); ++i) { byteArrayBuilder.appendByte(ByteUtil.reverseBits(flags.getByte(i))); } return MutableByteArray.wrap(byteArrayBuilder.build()); } public Integer getByteCount(final PartialMerkleTree partialMerkleTree) { final int blockHeaderTransactionCountByteCount = 4; final List<Sha256Hash> hashes = partialMerkleTree.getHashes(); final int itemCount = hashes.getCount(); final byte[] itemCountBytes = ByteUtil.variableLengthIntegerToBytes(itemCount); final ByteArray flags = partialMerkleTree.getFlags(); return (blockHeaderTransactionCountByteCount + itemCountBytes.length + (itemCount * Sha256Hash.BYTE_COUNT) + flags.getByteCount()); } } <|start_filename|>src/test/java/com/softwareverde/bitcoin/test/fake/database/FakeDatabaseConnectionFactory.java<|end_filename|> package com.softwareverde.bitcoin.test.fake.database; import com.softwareverde.bitcoin.server.database.DatabaseConnection; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.database.DatabaseException; public interface FakeDatabaseConnectionFactory extends DatabaseConnectionFactory { @Override default DatabaseConnection newConnection() throws DatabaseException { throw new UnsupportedOperationException(); } @Override default void close() throws DatabaseException { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/query/response/block/header/BlockHeadersMessage.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.query.response.block.header; import com.softwareverde.bitcoin.block.header.BlockHeader; import com.softwareverde.bitcoin.block.header.BlockHeaderDeflater; import com.softwareverde.bitcoin.block.header.BlockHeaderInflater; import com.softwareverde.bitcoin.inflater.BlockHeaderInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessage; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.server.message.type.request.header.RequestBlockHeadersMessage; import com.softwareverde.bitcoin.util.ByteUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.list.List; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.util.bytearray.ByteArrayBuilder; public class BlockHeadersMessage extends BitcoinProtocolMessage { protected final BlockHeaderInflaters _blockHeaderInflaters; protected final MutableList<BlockHeader> _blockHeaders = new MutableList<BlockHeader>(); public BlockHeadersMessage(final BlockHeaderInflaters blockHeaderInflaters) { super(MessageType.BLOCK_HEADERS); _blockHeaderInflaters = blockHeaderInflaters; } public void addBlockHeader(final BlockHeader blockHeader) { if (_blockHeaders.getCount() >= RequestBlockHeadersMessage.MAX_BLOCK_HEADER_HASH_COUNT) { return; } _blockHeaders.add(blockHeader); } public void clearBlockHeaders() { _blockHeaders.clear(); } public List<BlockHeader> getBlockHeaders() { return _blockHeaders; } @Override protected ByteArray _getPayload() { final int blockHeaderCount = _blockHeaders.getCount(); final byte[] blockHeaderCountBytes = ByteUtil.variableLengthIntegerToBytes(blockHeaderCount); final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder(); byteArrayBuilder.appendBytes(blockHeaderCountBytes); final BlockHeaderDeflater blockHeaderDeflater = _blockHeaderInflaters.getBlockHeaderDeflater(); for (int i = 0; i < blockHeaderCount; ++i) { final BlockHeader blockHeader = _blockHeaders.get(i); byteArrayBuilder.appendBytes(blockHeaderDeflater.toBytes(blockHeader)); final int transactionCount = 0; // blockHeader.getTransactionCount(); final byte[] transactionCountBytes = ByteUtil.variableLengthIntegerToBytes(transactionCount); byteArrayBuilder.appendBytes(transactionCountBytes); } return byteArrayBuilder; } @Override protected Integer _getPayloadByteCount() { final int blockHeaderCount = _blockHeaders.getCount(); final byte[] blockHeaderCountBytes = ByteUtil.variableLengthIntegerToBytes(blockHeaderCount); return (blockHeaderCountBytes.length + (blockHeaderCount * (BlockHeaderInflater.BLOCK_HEADER_BYTE_COUNT + 1))); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/Buip55.java<|end_filename|> package com.softwareverde.bitcoin.bip; import com.softwareverde.util.Util; public class Buip55 { public static final Long ACTIVATION_BLOCK_HEIGHT = 478559L; // Bitcoin Cash: UAHF - https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/uahf-technical-spec.md public static Boolean isEnabled(final Long blockHeight) { return (Util.coalesce(blockHeight, Long.MAX_VALUE) >= ACTIVATION_BLOCK_HEIGHT); } protected Buip55() { } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/module/node/database/transaction/BlockingQueueBatchRunner.java<|end_filename|> package com.softwareverde.bitcoin.server.module.node.database.transaction; import com.softwareverde.bitcoin.server.database.BatchRunner; import com.softwareverde.constable.list.mutable.MutableList; import com.softwareverde.logging.Logger; import com.softwareverde.util.Container; import com.softwareverde.util.timer.MilliTimer; import java.util.Comparator; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * BlockingQueueBatchRunner collects items into a batch, periodically executing them as a single batch. * The batching period waited is at most 100ms or until itemCountPerBatch items have been added. * To prevent exceeding a particular queue size, invoke ::waitForQueueCapacity. * Batches are executed within separate thread(s). */ public class BlockingQueueBatchRunner<T> extends Thread { protected static <T> BlockingQueueBatchRunner<T> newInstance(final Integer itemCountPerBatch, final Boolean executeAsynchronously, final Queue<T> itemQueue, final BatchRunner.Batch<T> batch) { final BatchRunner<T> batchRunner = new BatchRunner<T>(itemCountPerBatch, executeAsynchronously); final Container<Boolean> threadContinueContainer = new Container<Boolean>(true); final AtomicLong executionTime = new AtomicLong(0L); final AtomicInteger queuedItemCount = new AtomicInteger(0); final Container<Exception> exceptionContainer = new Container<Exception>(null); final Runnable coreRunnable = new Runnable() { @Override public void run() { final int batchSize = batchRunner.getItemCountPerBatch(); final MilliTimer executionTimer = new MilliTimer(); while ( threadContinueContainer.value || (! itemQueue.isEmpty()) ) { int batchItemCount = 0; final MutableList<T> batchedItems = new MutableList<T>(batchSize); while (batchItemCount < batchSize) { if (itemQueue.isEmpty()) { try { synchronized (itemQueue) { // This wait may timeout in two cases: // 1. An item hasn't been added in 100ms. // 2. The last item was added and a race condition occurred during notification. itemQueue.wait(100L); } } catch (final InterruptedException exception) { Logger.debug("Aborting BlockingQueueBatch."); return; } } final T item = itemQueue.poll(); if (item == null) { break; } queuedItemCount.addAndGet(-1); batchedItems.add(item); batchItemCount += 1; } if (! batchedItems.isEmpty()) { // batchedItems item count may always be less than batchSize due to a timeout on itemQueue.wait(L)... executionTimer.start(); try { batchRunner.run(batchedItems, batch); } catch (final Exception exception) { Logger.debug(exception); exceptionContainer.value = exception; return; // Abort execution of the remaining items for this BatchRunner... } finally { executionTimer.stop(); executionTime.addAndGet(executionTimer.getMillisecondsElapsed()); } } } } }; return new BlockingQueueBatchRunner<T>(threadContinueContainer, itemQueue, queuedItemCount, batchRunner, coreRunnable, executionTime, exceptionContainer); } public static <T> BlockingQueueBatchRunner<T> newInstance(final Boolean executeAsynchronously, final BatchRunner.Batch<T> batch) { return BlockingQueueBatchRunner.newInstance(1024, executeAsynchronously, batch); } public static <T> BlockingQueueBatchRunner<T> newInstance(final Integer itemCountPerBatch, final Boolean executeAsynchronously, final BatchRunner.Batch<T> batch) { final ConcurrentLinkedQueue<T> itemQueue = new ConcurrentLinkedQueue<T>(); return BlockingQueueBatchRunner.newInstance(itemCountPerBatch, executeAsynchronously, itemQueue, batch); } public static <T> BlockingQueueBatchRunner<T> newSortedInstance(final Integer itemCountPerBatch, final Integer initialCapacity, final Comparator<T> comparator, final Boolean executeAsynchronously, final BatchRunner.Batch<T> batch) { final Queue<T> sortedQueue = new PriorityBlockingQueue<T>(initialCapacity, comparator); return BlockingQueueBatchRunner.newInstance(itemCountPerBatch, executeAsynchronously, sortedQueue, batch); } protected final Container<Boolean> _threadContinueContainer; protected final Queue<T> _itemQueue; protected final AtomicInteger _queuedItemCount; protected final BatchRunner<T> _batchRunner; protected final AtomicLong _executionTime; protected final Container<Exception> _exceptionContainer; protected Integer _totalItemCount = 0; protected BlockingQueueBatchRunner(final Container<Boolean> threadContinueContainer, final Queue<T> itemQueue, final AtomicInteger queuedItemCount, final BatchRunner<T> batchRunner, final Runnable coreRunnable, final AtomicLong executionTime, final Container<Exception> exceptionContainer) { super(coreRunnable); _threadContinueContainer = threadContinueContainer; _itemQueue = itemQueue; _queuedItemCount = queuedItemCount; _batchRunner = batchRunner; _executionTime = executionTime; _exceptionContainer = exceptionContainer; } public Integer getItemCountPerBatch() { return _batchRunner.getItemCountPerBatch(); } public Long getExecutionTime() { return _executionTime.get(); } public Integer getTotalItemCount() { return _totalItemCount; } public Integer getQueueItemCount() { return _queuedItemCount.get(); } public void addItem(final T item) { if (_exceptionContainer.value != null) { return; } _itemQueue.add(item); _queuedItemCount.addAndGet(1); _totalItemCount += 1; synchronized (_itemQueue) { _itemQueue.notifyAll(); } } public void waitForQueueCapacity(final Integer maxCapacity) throws InterruptedException { while (_queuedItemCount.get() >= maxCapacity) { if (_exceptionContainer.value != null) { return; } if (! this.isAlive()) { return; } synchronized (_itemQueue) { _itemQueue.wait(100L); } } } /** * Informs the Thread to shut down after the queue has completed. */ public void finish() { _threadContinueContainer.value = false; synchronized (_itemQueue) { _itemQueue.notifyAll(); } } /** * Waits until the Thread is complete. * Throws an exception if one was encountered during executing any of the batches. * BlockingQueueBatchRunner::finish must be called before the thread will finish. * BlockingQueueBatchRunner::join may be used instead of this function, however any captured Exception will not be thrown. */ public void waitUntilFinished() throws Exception { super.join(); if (_exceptionContainer.value != null) { throw _exceptionContainer.value; } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/block/validator/thread/TaskHandlerFactory.java<|end_filename|> package com.softwareverde.bitcoin.block.validator.thread; public interface TaskHandlerFactory<T, S> { TaskHandler<T, S> newInstance(); } <|start_filename|>src/main/java/com/softwareverde/bitcoin/address/AddressInflater.java<|end_filename|> package com.softwareverde.bitcoin.address; import com.softwareverde.bitcoin.util.BitcoinUtil; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.MutableByteArray; import com.softwareverde.cryptography.secp256k1.key.PrivateKey; import com.softwareverde.cryptography.secp256k1.key.PublicKey; import com.softwareverde.cryptography.util.HashUtil; import com.softwareverde.logging.Logger; import com.softwareverde.util.ByteUtil; import com.softwareverde.util.HexUtil; import com.softwareverde.util.Util; import com.softwareverde.util.bytearray.ByteArrayBuilder; public class AddressInflater { public static final Integer BYTE_COUNT = Address.BYTE_COUNT; protected byte[] _hashPublicKey(final PublicKey publicKey) { return HashUtil.ripemd160(HashUtil.sha256(publicKey.getBytes())); } protected Address _fromPublicKey(final PublicKey publicKey, final Boolean asCompressed) { if (asCompressed) { final byte[] rawBitcoinAddress = _hashPublicKey(publicKey.compress()); return new CompressedAddress(rawBitcoinAddress); } else { final byte[] rawBitcoinAddress = _hashPublicKey(publicKey.decompress()); return new Address(rawBitcoinAddress); } } protected Address _fromPrivateKey(final PrivateKey privateKey, final Boolean asCompressed) { final PublicKey publicKey = privateKey.getPublicKey(); if (asCompressed) { final PublicKey compressedPublicKey = publicKey.compress(); final byte[] rawBitcoinAddress = _hashPublicKey(compressedPublicKey); return new CompressedAddress(rawBitcoinAddress); } else { final PublicKey uncompressedPublicKey = publicKey.decompress(); final byte[] rawBitcoinAddress = _hashPublicKey(uncompressedPublicKey); return new Address(rawBitcoinAddress); } } protected Address _fromBase58Check(final String base58CheckString, final Boolean isCompressed) { final byte[] bytesWithPrefixWithChecksum; try { bytesWithPrefixWithChecksum = BitcoinUtil.base58StringToBytes(base58CheckString); } catch (final Exception exception) { return null; } if (bytesWithPrefixWithChecksum.length < (Address.PREFIX_BYTE_COUNT + Address.CHECKSUM_BYTE_COUNT)) { return null; } final byte[] bytesWithoutPrefixAndWithoutChecksum = ByteUtil.copyBytes(bytesWithPrefixWithChecksum, Address.PREFIX_BYTE_COUNT, bytesWithPrefixWithChecksum.length - Address.CHECKSUM_BYTE_COUNT - Address.PREFIX_BYTE_COUNT); final byte prefix = bytesWithPrefixWithChecksum[0]; final byte[] checksum = ByteUtil.copyBytes(bytesWithPrefixWithChecksum, bytesWithPrefixWithChecksum.length - Address.CHECKSUM_BYTE_COUNT, Address.CHECKSUM_BYTE_COUNT); final byte[] calculatedChecksum = Address._calculateChecksum(prefix, bytesWithoutPrefixAndWithoutChecksum); final Boolean checksumIsValid = (ByteUtil.areEqual(calculatedChecksum, checksum)); if (! checksumIsValid) { return null; } switch (prefix) { case Address.PREFIX: { if (isCompressed) { return new CompressedAddress(bytesWithoutPrefixAndWithoutChecksum); } else { return new Address(bytesWithoutPrefixAndWithoutChecksum); } } case PayToScriptHashAddress.PREFIX: { return new PayToScriptHashAddress(bytesWithoutPrefixAndWithoutChecksum); } default: { Logger.warn("Unknown Address Prefix: 0x"+ HexUtil.toHexString(new byte[] { prefix })); return null; } } } protected Address _fromBase32Check(final String base32String, final Boolean isCompressed) { { // Check for mixed-casing... boolean hasUpperCase = false; boolean hasLowerCase = false; for (int i = 0; i < base32String.length(); ++i) { final char c = base32String.charAt(i); if (Character.isAlphabetic(c)) { if (Character.isUpperCase(c)) { hasUpperCase = true; } else { hasLowerCase = true; } } } if (hasUpperCase && hasLowerCase) { return null; } } final String prefix; final String base32WithoutPrefix; if (base32String.contains(":")) { final int separatorIndex = base32String.indexOf(':'); prefix = base32String.substring(0, separatorIndex).toLowerCase(); base32WithoutPrefix = base32String.substring(separatorIndex + 1).toLowerCase(); } else { prefix = "bitcoincash"; base32WithoutPrefix = base32String.toLowerCase(); } final int checksumBitCount = 40; final int checksumCharacterCount = (checksumBitCount / 5); final ByteArray payloadBytes; final ByteArray checksum; { if (base32WithoutPrefix.length() < checksumCharacterCount) { return null; } final int checksumStartCharacterIndex = (base32WithoutPrefix.length() - checksumCharacterCount); payloadBytes = MutableByteArray.wrap(BitcoinUtil.base32StringToBytes(base32WithoutPrefix.substring(0, checksumStartCharacterIndex))); checksum = MutableByteArray.wrap(BitcoinUtil.base32StringToBytes(base32WithoutPrefix.substring(checksumStartCharacterIndex))); } if (payloadBytes == null) { return null; } if (checksum == null) { return null; } final byte version = payloadBytes.getByte(0); if ((version & 0x80) != 0x00) { return null; } // The version byte's most significant bit must be 0... final byte addressType = (byte) ((version >> 3) & 0x0F); final int hashByteCount = (20 + ((version & 0x07) * 4)); if (payloadBytes.getByteCount() < (hashByteCount + 1)) { return null; } final ByteArray hash = MutableByteArray.wrap(payloadBytes.getBytes(1, hashByteCount)); final ByteArray checksumPayload = AddressInflater.buildBase32ChecksumPreImage(prefix, version, hash); final ByteArray calculatedChecksum = AddressInflater.calculateBase32Checksum(checksumPayload); if (! Util.areEqual(calculatedChecksum, checksum)) { return null; } if (addressType == PayToScriptHashAddress.BASE_32_PREFIX) { // P2SH return new PayToScriptHashAddress(hash.getBytes()); } if (addressType == Address.BASE_32_PREFIX) { // P2PKH if (isCompressed) { return new CompressedAddress(hash.getBytes()); } else { return new Address(hash.getBytes()); } } if (isCompressed) { return new CompressedAddress(hash.getBytes()); } else { return new Address(hash.getBytes()); } } /** * Returns the preImage for the provided prefix/version/hash provided. * The preImage is returned as an array of 5-bit integers. */ public static ByteArray buildBase32ChecksumPreImage(final String prefix, final Byte version, final ByteArray hash) { final ByteArrayBuilder checksumPayload = new ByteArrayBuilder(); for (final char c : prefix.toCharArray()) { checksumPayload.appendByte((byte) (c & 0x1F)); } checksumPayload.appendByte((byte) 0x00); if (version != null) { // 0b01234567 >> 3 -> 0bxxx01234 // 0b01234567 & 0x07 << 2 -> 0bxxx567xx final byte versionByte0 = (byte) (version >> 3); checksumPayload.appendByte(versionByte0); final byte versionByte1 = (byte) ((version & 0x07) << 2); if (hash.isEmpty()) { checksumPayload.appendByte(versionByte1); } else { final MutableByteArray b = new MutableByteArray(1); b.setByte(0, versionByte1); int writeBitIndex = 3; for (int hashReadBit = 0; hashReadBit < (hash.getByteCount() * 8); ++hashReadBit) { b.setBit(((writeBitIndex % 5) + 3), hash.getBit(hashReadBit)); writeBitIndex += 1; if ((writeBitIndex % 5) == 0) { checksumPayload.appendByte(b.getByte(0)); b.setByte(0, (byte) 0x00); } } if ((writeBitIndex % 5) != 0) { checksumPayload.appendByte(b.getByte(0)); } } } checksumPayload.appendBytes(new MutableByteArray(8)); return MutableByteArray.wrap(checksumPayload.build()); } /** * Creates a checksum as 5-bit integers for byteArray. * byteArray should be formatted as an array of 5-bit integers. */ public static ByteArray calculateBase32Checksum(final ByteArray byteArray) { long c = 0x01; for (int i = 0; i < byteArray.getByteCount(); ++i) { final byte d = byteArray.getByte(i); final long c0 = (c >> 35); c = (((c & 0x07FFFFFFFFL) << 5) ^ d); if ((c0 & 0x01) != 0x00) { c ^= 0x98F2BC8E61L; } if ((c0 & 0x02) != 0x00) { c ^= 0x79B76D99E2L; } if ((c0 & 0x04) != 0x00) { c ^= 0xF33E5FB3C4L; } if ((c0 & 0x08) != 0x00) { c ^= 0xAE2EABE2A8L; } if ((c0 & 0x10) != 0x00) { c ^= 0x1E4F43E470L; } } final long checksum = (c ^ 0x01); final byte[] checksumBytes = ByteUtil.longToBytes(checksum); final MutableByteArray checksumByteArray = new MutableByteArray(5); for (int i = 0; i < 5; ++i) { checksumByteArray.setByte(i, checksumBytes[i + 3]); } return checksumByteArray; } public Address fromPrivateKey(final PrivateKey privateKey) { return _fromPrivateKey(privateKey, false); } public Address fromPrivateKey(final PrivateKey privateKey, final Boolean asCompressed) { return _fromPrivateKey(privateKey, asCompressed); } public Address fromBytes(final ByteArray bytes) { if (bytes.getByteCount() != Address.BYTE_COUNT) { return null; } return new Address(bytes.getBytes()); } public Address fromBytes(final ByteArray bytes, final Boolean isCompressed) { if (bytes.getByteCount() != Address.BYTE_COUNT) { return null; } if (isCompressed) { return new CompressedAddress(bytes.getBytes()); } else { return new Address(bytes.getBytes()); } } public Address fromPublicKey(final PublicKey publicKey) { return _fromPublicKey(publicKey, publicKey.isCompressed()); } public Address fromPublicKey(final PublicKey publicKey, final Boolean asCompressed) { return _fromPublicKey(publicKey, asCompressed); } public Address fromBase58Check(final String base58CheckString) { return _fromBase58Check(base58CheckString, false); } /** * Returns a CompressedAddress from the base58CheckString. * NOTE: Validation that the string is actually derived from a compressed PublicKey is impossible, * therefore, only use this function if the sourced string is definitely a compressed PublicKey. */ public Address fromBase58Check(final String base58CheckString, final Boolean isCompressed) { return _fromBase58Check(base58CheckString, isCompressed); } public Address fromBase32Check(final String base32String) { return _fromBase32Check(base32String, false); } public Address fromBase32Check(final String base32String, final Boolean isCompressed) { return _fromBase32Check(base32String, isCompressed); } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/bloomfilter/set/SetTransactionBloomFilterMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.bloomfilter.set; import com.softwareverde.bitcoin.bloomfilter.BloomFilterInflater; import com.softwareverde.bitcoin.inflater.BloomFilterInflaters; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.bloomfilter.BloomFilter; public class SetTransactionBloomFilterMessageInflater extends BitcoinProtocolMessageInflater { public static final Long MAX_SIZE = 36000L; public static final Integer MAX_HASH_FUNCTION_COUNT = 50; protected final BloomFilterInflaters _bloomFilterInflaters; public SetTransactionBloomFilterMessageInflater(final BloomFilterInflaters bloomFilterInflaters) { _bloomFilterInflaters = bloomFilterInflaters; } @Override public SetTransactionBloomFilterMessage fromBytes(final byte[] bytes) { final SetTransactionBloomFilterMessage setTransactionBloomFilterMessage = new SetTransactionBloomFilterMessage(_bloomFilterInflaters); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.SET_TRANSACTION_BLOOM_FILTER); if (protocolMessageHeader == null) { return null; } final BloomFilterInflater bloomFilterInflater = _bloomFilterInflaters.getBloomFilterInflater(); final BloomFilter bloomFilter = bloomFilterInflater.fromBytes(byteArrayReader); if (bloomFilter == null) { return null; } setTransactionBloomFilterMessage.setBloomFilter(bloomFilter); if (byteArrayReader.didOverflow()) { return null; } return setTransactionBloomFilterMessage; } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/bip/Bip68.java<|end_filename|> package com.softwareverde.bitcoin.bip; public class Bip68 { public static final Long ACTIVATION_BLOCK_HEIGHT = 419328L; // Relative Lock-Time Using Consensus-Enforced Sequence Numbers - https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki public static Boolean isEnabled(final Long blockHeight) { return (blockHeight >= ACTIVATION_BLOCK_HEIGHT); // https://www.reddit.com/r/Bitcoin/comments/4r9tiv/csv_soft_fork_has_activated_as_of_block_419328 } protected Bip68() { } } <|start_filename|>src/main/java/org/jocl/Jocl.java<|end_filename|> /*package org.jocl; public class Jocl { public static final int CL_DEVICE_TYPE_CPU = 0; public static final int CL_CONTEXT_PLATFORM = 0; public static final int CL_MEM_READ_ONLY = 1; public static final int CL_MEM_COPY_HOST_PTR = 2; public static final int CL_MEM_WRITE_ONLY = 3; public static final int CL_TRUE = 1; public static class Sizeof { public static int cl_uint = 0; public static int cl_mem = 0; } public static class CL { public static void setExceptionsEnabled(final boolean b) { } public static String stringFor_cl_device_type(final Object o) { return ""; } } public static class Pointer { public static Pointer to(final Object o) { return new Pointer(); } } public static class cl_context { } public static class cl_kernel { } public static class cl_command_queue { } public static class cl_mem { } public static class cl_device_id { } public static class cl_program { } public static class cl_platform_id { } public static void clGetPlatformIDs(final int i, final Object o, final int[] numPlatformsArray) { } public static class cl_context_properties { public void addProperty(final Object o, final Object b) { } } public static void clGetDeviceIDs(final Object a, final Object b, final Object c, final Object d, final Object e) { } public static cl_context clCreateContext(final Object a, final Object b, final Object c, final Object d, final Object e, final Object f) { return new cl_context(); } public static cl_command_queue clCreateCommandQueue(final Object a, final Object b, final Object c, final Object d) { return new cl_command_queue(); } public static cl_program clCreateProgramWithSource(final Object a, final Object b, final Object c, final Object d, final Object e) { return new cl_program(); } public static void clBuildProgram(final Object a, final Object b, final Object c, final Object d, final Object e, final Object f) { } public static cl_kernel clCreateKernel(final Object a, final Object b, final Object c) { return new cl_kernel(); } public static void clReleaseProgram(final Object o) { } public static cl_mem clCreateBuffer(final Object a, final Object b, final Object c, final Object d, final Object e) { return new cl_mem(); } public static void clSetKernelArg(final Object a, final Object b, final Object c, final Object d) { } public static void clReleaseKernel(final Object a) { } public static void clReleaseCommandQueue(final Object a) { } public static void clFinish(final Object a) { } public static void clEnqueueWriteBuffer(final Object a, final Object b, final Object c, final Object d, final Object e, final Object f, final Object g, final Object h, final Object i) { } public static void clEnqueueNDRangeKernel(final Object a, final Object b, final Object c, final Object d, final Object e, final Object f, final Object g, final Object h, final Object i) { } public static void clEnqueueReadBuffer(final Object a, final Object b, final Object c, final Object d, final Object e, final Object f, final Object g, final Object h, final Object i) { } } */ <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/message/type/bloomfilter/update/UpdateTransactionBloomFilterMessageInflater.java<|end_filename|> package com.softwareverde.bitcoin.server.message.type.bloomfilter.update; import com.softwareverde.bitcoin.server.message.BitcoinProtocolMessageInflater; import com.softwareverde.bitcoin.server.message.header.BitcoinProtocolMessageHeader; import com.softwareverde.bitcoin.server.message.type.MessageType; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.constable.bytearray.ByteArray; import com.softwareverde.constable.bytearray.ImmutableByteArray; public class UpdateTransactionBloomFilterMessageInflater extends BitcoinProtocolMessageInflater { @Override public UpdateTransactionBloomFilterMessage fromBytes(final byte[] bytes) { final UpdateTransactionBloomFilterMessage updateTransactionBloomFilterMessage = new UpdateTransactionBloomFilterMessage(); final ByteArrayReader byteArrayReader = new ByteArrayReader(bytes); final BitcoinProtocolMessageHeader protocolMessageHeader = _parseHeader(byteArrayReader, MessageType.UPDATE_TRANSACTION_BLOOM_FILTER); if (protocolMessageHeader == null) { return null; } final ByteArray item = new ImmutableByteArray(byteArrayReader.readBytes(byteArrayReader.remainingByteCount())); updateTransactionBloomFilterMessage.setItem(item); if (byteArrayReader.didOverflow()) { return null; } return updateTransactionBloomFilterMessage; } } <|start_filename|>src/server/java/com/softwareverde/bitcoin/server/module/stratum/api/endpoint/account/UnauthenticateApi.java<|end_filename|> package com.softwareverde.bitcoin.server.module.stratum.api.endpoint.account; import com.softwareverde.bitcoin.miner.pool.AccountId; import com.softwareverde.bitcoin.server.configuration.StratumProperties; import com.softwareverde.bitcoin.server.database.DatabaseConnectionFactory; import com.softwareverde.bitcoin.server.module.stratum.api.endpoint.StratumApiResult; import com.softwareverde.http.HttpMethod; import com.softwareverde.http.querystring.GetParameters; import com.softwareverde.http.querystring.PostParameters; import com.softwareverde.http.server.servlet.request.Request; import com.softwareverde.http.server.servlet.response.JsonResponse; import com.softwareverde.http.server.servlet.response.Response; import com.softwareverde.servlet.AuthenticatedServlet; public class UnauthenticateApi extends AuthenticatedServlet { protected final DatabaseConnectionFactory _databaseConnectionFactory; public UnauthenticateApi(final StratumProperties stratumProperties, final DatabaseConnectionFactory databaseConnectionFactory) { super(stratumProperties); _databaseConnectionFactory = databaseConnectionFactory; } @Override protected Response _onAuthenticatedRequest(final AccountId accountId, final Request request) { final GetParameters getParameters = request.getGetParameters(); final PostParameters postParameters = request.getPostParameters(); if (request.getMethod() != HttpMethod.POST) { return new JsonResponse(Response.Codes.BAD_REQUEST, new StratumApiResult(false, "Invalid method.")); } { // AUTHENTICATE // Requires GET: // Requires POST: final Response response = new JsonResponse(Response.Codes.OK, new StratumApiResult(true, null)); _sessionManager.destroySession(request, response); return response; } } } <|start_filename|>src/main/java/com/softwareverde/bitcoin/server/configuration/WalletProperties.java<|end_filename|> package com.softwareverde.bitcoin.server.configuration; public class WalletProperties { public static final Integer PORT = 8888; public static final Integer TLS_PORT = 4444; protected Integer _port; protected String _rootDirectory; protected Integer _tlsPort; protected String _tlsKeyFile; protected String _tlsCertificateFile; public Integer getPort() { return _port; } public String getRootDirectory() { return _rootDirectory; } public Integer getTlsPort() { return _tlsPort; } public String getTlsKeyFile() { return _tlsKeyFile; } public String getTlsCertificateFile() { return _tlsCertificateFile; } }
imaginaryusername/bitcoin-verde
<|start_filename|>MyApp/Pods/abseil/absl/debugging/internal/examine_stack.cc<|end_filename|> // // Copyright 2018 The Abseil Authors. // // 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 // // https://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 "absl/debugging/internal/examine_stack.h" #ifndef _WIN32 #include <unistd.h> #endif #include <csignal> #include <cstdio> #include "absl/base/attributes.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/macros.h" #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { // Returns the program counter from signal context, nullptr if // unknown. vuc is a ucontext_t*. We use void* to avoid the use of // ucontext_t on non-POSIX systems. void* GetProgramCounter(void* vuc) { #ifdef __linux__ if (vuc != nullptr) { ucontext_t* context = reinterpret_cast<ucontext_t*>(vuc); #if defined(__aarch64__) return reinterpret_cast<void*>(context->uc_mcontext.pc); #elif defined(__arm__) return reinterpret_cast<void*>(context->uc_mcontext.arm_pc); #elif defined(__i386__) if (14 < ABSL_ARRAYSIZE(context->uc_mcontext.gregs)) return reinterpret_cast<void*>(context->uc_mcontext.gregs[14]); #elif defined(__mips__) return reinterpret_cast<void*>(context->uc_mcontext.pc); #elif defined(__powerpc64__) return reinterpret_cast<void*>(context->uc_mcontext.gp_regs[32]); #elif defined(__powerpc__) return reinterpret_cast<void*>(context->uc_mcontext.regs->nip); #elif defined(__riscv) return reinterpret_cast<void*>(context->uc_mcontext.__gregs[REG_PC]); #elif defined(__s390__) && !defined(__s390x__) return reinterpret_cast<void*>(context->uc_mcontext.psw.addr & 0x7fffffff); #elif defined(__s390__) && defined(__s390x__) return reinterpret_cast<void*>(context->uc_mcontext.psw.addr); #elif defined(__x86_64__) if (16 < ABSL_ARRAYSIZE(context->uc_mcontext.gregs)) return reinterpret_cast<void*>(context->uc_mcontext.gregs[16]); #else #error "Undefined Architecture." #endif } #elif defined(__akaros__) auto* ctx = reinterpret_cast<struct user_context*>(vuc); return reinterpret_cast<void*>(get_user_ctx_pc(ctx)); #endif static_cast<void>(vuc); return nullptr; } // The %p field width for printf() functions is two characters per byte, // and two extra for the leading "0x". static constexpr int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*); // Print a program counter, its stack frame size, and its symbol name. // Note that there is a separate symbolize_pc argument. Return addresses may be // at the end of the function, and this allows the caller to back up from pc if // appropriate. static void DumpPCAndFrameSizeAndSymbol(void (*writerfn)(const char*, void*), void* writerfn_arg, void* pc, void* symbolize_pc, int framesize, const char* const prefix) { char tmp[1024]; const char* symbol = "(unknown)"; if (absl::Symbolize(symbolize_pc, tmp, sizeof(tmp))) { symbol = tmp; } char buf[1024]; if (framesize <= 0) { snprintf(buf, sizeof(buf), "%s@ %*p (unknown) %s\n", prefix, kPrintfPointerFieldWidth, pc, symbol); } else { snprintf(buf, sizeof(buf), "%s@ %*p %9d %s\n", prefix, kPrintfPointerFieldWidth, pc, framesize, symbol); } writerfn(buf, writerfn_arg); } // Print a program counter and the corresponding stack frame size. static void DumpPCAndFrameSize(void (*writerfn)(const char*, void*), void* writerfn_arg, void* pc, int framesize, const char* const prefix) { char buf[100]; if (framesize <= 0) { snprintf(buf, sizeof(buf), "%s@ %*p (unknown)\n", prefix, kPrintfPointerFieldWidth, pc); } else { snprintf(buf, sizeof(buf), "%s@ %*p %9d\n", prefix, kPrintfPointerFieldWidth, pc, framesize); } writerfn(buf, writerfn_arg); } void DumpPCAndFrameSizesAndStackTrace( void* pc, void* const stack[], int frame_sizes[], int depth, int min_dropped_frames, bool symbolize_stacktrace, void (*writerfn)(const char*, void*), void* writerfn_arg) { if (pc != nullptr) { // We don't know the stack frame size for PC, use 0. if (symbolize_stacktrace) { DumpPCAndFrameSizeAndSymbol(writerfn, writerfn_arg, pc, pc, 0, "PC: "); } else { DumpPCAndFrameSize(writerfn, writerfn_arg, pc, 0, "PC: "); } } for (int i = 0; i < depth; i++) { if (symbolize_stacktrace) { // Pass the previous address of pc as the symbol address because pc is a // return address, and an overrun may occur when the function ends with a // call to a function annotated noreturn (e.g. CHECK). Note that we don't // do this for pc above, as the adjustment is only correct for return // addresses. DumpPCAndFrameSizeAndSymbol(writerfn, writerfn_arg, stack[i], reinterpret_cast<char*>(stack[i]) - 1, frame_sizes[i], " "); } else { DumpPCAndFrameSize(writerfn, writerfn_arg, stack[i], frame_sizes[i], " "); } } if (min_dropped_frames > 0) { char buf[100]; snprintf(buf, sizeof(buf), " @ ... and at least %d more frames\n", min_dropped_frames); writerfn(buf, writerfn_arg); } } } // namespace debugging_internal ABSL_NAMESPACE_END } // namespace absl <|start_filename|>MyApp/Pods/GoogleUtilities/GoogleUtilities/Tests/Unit/Network/third_party/GTMHTTPServer.h<|end_filename|> /* Copyright 2010 Google Inc. * * 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. */ // // GTMHTTPServer.h // // This is a *very* *simple* webserver that can be built into something, it is // not meant to stand up a site, it sends all requests to its delegate for // processing on the main thread. It does not support pipelining, etc. It's // great for places where you need a simple webserver to unittest some code // that hits a server. // // NOTE: there are several TODOs left in here as markers for things that could // be done if one wanted to add more to this class. // // Based a little on HTTPServer, part of the CocoaHTTPServer sample code found at // https://opensource.apple.com/source/HTTPServer/HTTPServer-11/CocoaHTTPServer/ // License for the CocoaHTTPServer sample code: // // Software License Agreement (BSD License) // // Copyright (c) 2011, Deusty, LLC // All rights reserved. // // Redistribution and use of this software in source and binary forms, // with or without modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the // following disclaimer. // // * Neither the name of Deusty nor the names of its // contributors may be used to endorse or promote products // derived from this software without specific prior // written permission of Deusty, LLC. // // 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. #import <Foundation/Foundation.h> #if GTM_IPHONE_SDK #import <CFNetwork/CFNetwork.h> #endif // GTM_IPHONE_SDK // Global constants needed for errors from start #undef _EXTERN #undef _INITIALIZE_AS #ifdef GTMHTTPSERVER_DEFINE_GLOBALS #define _EXTERN #define _INITIALIZE_AS(x) = x #else #define _EXTERN extern #define _INITIALIZE_AS(x) #endif _EXTERN NSString *const kGTMHTTPServerErrorDomain _INITIALIZE_AS(@"com.google.mactoolbox.HTTPServerDomain"); enum { kGTMHTTPServerSocketCreateFailedError = -100, kGTMHTTPServerBindFailedError = -101, kGTMHTTPServerListenFailedError = -102, kGTMHTTPServerHandleCreateFailedError = -103, }; @class GTMHTTPRequestMessage, GTMHTTPResponseMessage; // ---------------------------------------------------------------------------- // See comment at top of file for the intended use of this class. @interface GTMHTTPServer : NSObject { @private id delegate_; // WEAK uint16_t port_; BOOL reusePort_; BOOL localhostOnly_; NSFileHandle *listenHandle_; NSMutableArray *connections_; } // The delegate must support the httpServer:handleRequest: method in // NSObject(GTMHTTPServerDelegateMethods) below. - (id)initWithDelegate:(id)delegate; - (id)delegate; // Passing port zero will let one get assigned. - (uint16_t)port; - (void)setPort:(uint16_t)port; // Controls listening socket behavior: SO_REUSEADDR vs SO_REUSEPORT. // The default is NO (SO_REUSEADDR) - (BOOL)reusePort; - (void)setReusePort:(BOOL)reusePort; // Receive connections on the localHost loopback address only or on all // interfaces for this machine. The default is to only listen on localhost. - (BOOL)localhostOnly; - (void)setLocalhostOnly:(BOOL)yesno; // Start/Stop the web server. If there is an error starting up the server, |NO| // is returned, and the specific startup failure can be returned in |error| (see // above for the error domain and error codes). If the server is started, |YES| // is returned and the server's delegate is called for any requests that come // in. - (BOOL)start:(NSError **)error; - (void)stop; // returns the number of requests currently active in the server (i.e.-being // read in, sent replies). - (NSUInteger)activeRequestCount; @end @interface NSObject (GTMHTTPServerDelegateMethods) - (GTMHTTPResponseMessage *)httpServer:(GTMHTTPServer *)server handleRequest:(GTMHTTPRequestMessage *)request; @end // ---------------------------------------------------------------------------- // Encapsulates an http request, one of these is sent to the server's delegate // for each request. @interface GTMHTTPRequestMessage : NSObject { @private CFHTTPMessageRef message_; } - (NSString *)version; - (NSURL *)URL; - (NSString *)method; - (NSData *)body; - (NSDictionary *)allHeaderFieldValues; @end // ---------------------------------------------------------------------------- // Encapsulates an http response, the server's delegate should return one for // each request received. @interface GTMHTTPResponseMessage : NSObject { @private CFHTTPMessageRef message_; } + (instancetype)responseWithString:(NSString *)plainText; + (instancetype)responseWithHTMLString:(NSString *)htmlString; + (instancetype)responseWithBody:(NSData *)body contentType:(NSString *)contentType statusCode:(int)statusCode; + (instancetype)emptyResponseWithCode:(int)statusCode; // TODO: class method for redirections? // TODO: add helper for expire/no-cache - (void)setValue:(NSString *)value forHeaderField:(NSString *)headerField; - (void)setHeaderValuesFromDictionary:(NSDictionary *)dict; @end <|start_filename|>MyApp/Pods/abseil/absl/status/status_payload_printer.cc<|end_filename|> // Copyright 2019 The Abseil Authors. // // 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 // // https://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 "absl/status/status_payload_printer.h" #include <atomic> #include "absl/base/attributes.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace status_internal { namespace { // Tried constant initialized global variable but it doesn't work with Lexan // (MSVC's `std::atomic` has trouble constant initializing). std::atomic<StatusPayloadPrinter>& GetStatusPayloadPrinterStorage() { ABSL_CONST_INIT static std::atomic<StatusPayloadPrinter> instance{nullptr}; return instance; } } // namespace void SetStatusPayloadPrinter(StatusPayloadPrinter printer) { GetStatusPayloadPrinterStorage().store(printer, std::memory_order_relaxed); } StatusPayloadPrinter GetStatusPayloadPrinter() { return GetStatusPayloadPrinterStorage().load(std::memory_order_relaxed); } } // namespace status_internal ABSL_NAMESPACE_END } // namespace absl <|start_filename|>MyApp/Pods/abseil/absl/container/btree_map.h<|end_filename|> // Copyright 2018 The Abseil Authors. // // 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 // // https://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. // // ----------------------------------------------------------------------------- // File: btree_map.h // ----------------------------------------------------------------------------- // // This header file defines B-tree maps: sorted associative containers mapping // keys to values. // // * `absl::btree_map<>` // * `absl::btree_multimap<>` // // These B-tree types are similar to the corresponding types in the STL // (`std::map` and `std::multimap`) and generally conform to the STL interfaces // of those types. However, because they are implemented using B-trees, they // are more efficient in most situations. // // Unlike `std::map` and `std::multimap`, which are commonly implemented using // red-black tree nodes, B-tree maps use more generic B-tree nodes able to hold // multiple values per node. Holding multiple values per node often makes // B-tree maps perform better than their `std::map` counterparts, because // multiple entries can be checked within the same cache hit. // // However, these types should not be considered drop-in replacements for // `std::map` and `std::multimap` as there are some API differences, which are // noted in this header file. // // Importantly, insertions and deletions may invalidate outstanding iterators, // pointers, and references to elements. Such invalidations are typically only // an issue if insertion and deletion operations are interleaved with the use of // more than one iterator, pointer, or reference simultaneously. For this // reason, `insert()` and `erase()` return a valid iterator at the current // position. #ifndef ABSL_CONTAINER_BTREE_MAP_H_ #define ABSL_CONTAINER_BTREE_MAP_H_ #include "absl/container/internal/btree.h" // IWYU pragma: export #include "absl/container/internal/btree_container.h" // IWYU pragma: export namespace absl { ABSL_NAMESPACE_BEGIN // absl::btree_map<> // // An `absl::btree_map<K, V>` is an ordered associative container of // unique keys and associated values designed to be a more efficient replacement // for `std::map` (in most cases). // // Keys are sorted using an (optional) comparison function, which defaults to // `std::less<K>`. // // An `absl::btree_map<K, V>` uses a default allocator of // `std::allocator<std::pair<const K, V>>` to allocate (and deallocate) // nodes, and construct and destruct values within those nodes. You may // instead specify a custom allocator `A` (which in turn requires specifying a // custom comparator `C`) as in `absl::btree_map<K, V, C, A>`. // template <typename Key, typename Value, typename Compare = std::less<Key>, typename Alloc = std::allocator<std::pair<const Key, Value>>> class btree_map : public container_internal::btree_map_container< container_internal::btree<container_internal::map_params< Key, Value, Compare, Alloc, /*TargetNodeSize=*/256, /*Multi=*/false>>> { using Base = typename btree_map::btree_map_container; public: // Constructors and Assignment Operators // // A `btree_map` supports the same overload set as `std::map` // for construction and assignment: // // * Default constructor // // absl::btree_map<int, std::string> map1; // // * Initializer List constructor // // absl::btree_map<int, std::string> map2 = // {{1, "huey"}, {2, "dewey"}, {3, "louie"},}; // // * Copy constructor // // absl::btree_map<int, std::string> map3(map2); // // * Copy assignment operator // // absl::btree_map<int, std::string> map4; // map4 = map3; // // * Move constructor // // // Move is guaranteed efficient // absl::btree_map<int, std::string> map5(std::move(map4)); // // * Move assignment operator // // // May be efficient if allocators are compatible // absl::btree_map<int, std::string> map6; // map6 = std::move(map5); // // * Range constructor // // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}}; // absl::btree_map<int, std::string> map7(v.begin(), v.end()); btree_map() {} using Base::Base; // btree_map::begin() // // Returns an iterator to the beginning of the `btree_map`. using Base::begin; // btree_map::cbegin() // // Returns a const iterator to the beginning of the `btree_map`. using Base::cbegin; // btree_map::end() // // Returns an iterator to the end of the `btree_map`. using Base::end; // btree_map::cend() // // Returns a const iterator to the end of the `btree_map`. using Base::cend; // btree_map::empty() // // Returns whether or not the `btree_map` is empty. using Base::empty; // btree_map::max_size() // // Returns the largest theoretical possible number of elements within a // `btree_map` under current memory constraints. This value can be thought // of as the largest value of `std::distance(begin(), end())` for a // `btree_map<Key, T>`. using Base::max_size; // btree_map::size() // // Returns the number of elements currently within the `btree_map`. using Base::size; // btree_map::clear() // // Removes all elements from the `btree_map`. Invalidates any references, // pointers, or iterators referring to contained elements. using Base::clear; // btree_map::erase() // // Erases elements within the `btree_map`. If an erase occurs, any references, // pointers, or iterators are invalidated. // Overloads are listed below. // // iterator erase(iterator position): // iterator erase(const_iterator position): // // Erases the element at `position` of the `btree_map`, returning // the iterator pointing to the element after the one that was erased // (or end() if none exists). // // iterator erase(const_iterator first, const_iterator last): // // Erases the elements in the open interval [`first`, `last`), returning // the iterator pointing to the element after the interval that was erased // (or end() if none exists). // // template <typename K> size_type erase(const K& key): // // Erases the element with the matching key, if it exists, returning the // number of elements erased. using Base::erase; // btree_map::insert() // // Inserts an element of the specified value into the `btree_map`, // returning an iterator pointing to the newly inserted element, provided that // an element with the given key does not already exist. If an insertion // occurs, any references, pointers, or iterators are invalidated. // Overloads are listed below. // // std::pair<iterator,bool> insert(const value_type& value): // // Inserts a value into the `btree_map`. Returns a pair consisting of an // iterator to the inserted element (or to the element that prevented the // insertion) and a bool denoting whether the insertion took place. // // std::pair<iterator,bool> insert(value_type&& value): // // Inserts a moveable value into the `btree_map`. Returns a pair // consisting of an iterator to the inserted element (or to the element that // prevented the insertion) and a bool denoting whether the insertion took // place. // // iterator insert(const_iterator hint, const value_type& value): // iterator insert(const_iterator hint, value_type&& value): // // Inserts a value, using the position of `hint` as a non-binding suggestion // for where to begin the insertion search. Returns an iterator to the // inserted element, or to the existing element that prevented the // insertion. // // void insert(InputIterator first, InputIterator last): // // Inserts a range of values [`first`, `last`). // // void insert(std::initializer_list<init_type> ilist): // // Inserts the elements within the initializer list `ilist`. using Base::insert; // btree_map::insert_or_assign() // // Inserts an element of the specified value into the `btree_map` provided // that a value with the given key does not already exist, or replaces the // corresponding mapped type with the forwarded `obj` argument if a key for // that value already exists, returning an iterator pointing to the newly // inserted element. Overloads are listed below. // // pair<iterator, bool> insert_or_assign(const key_type& k, M&& obj): // pair<iterator, bool> insert_or_assign(key_type&& k, M&& obj): // // Inserts/Assigns (or moves) the element of the specified key into the // `btree_map`. If the returned bool is true, insertion took place, and if // it's false, assignment took place. // // iterator insert_or_assign(const_iterator hint, // const key_type& k, M&& obj): // iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj): // // Inserts/Assigns (or moves) the element of the specified key into the // `btree_map` using the position of `hint` as a non-binding suggestion // for where to begin the insertion search. using Base::insert_or_assign; // btree_map::emplace() // // Inserts an element of the specified value by constructing it in-place // within the `btree_map`, provided that no element with the given key // already exists. // // The element may be constructed even if there already is an element with the // key in the container, in which case the newly constructed element will be // destroyed immediately. Prefer `try_emplace()` unless your key is not // copyable or moveable. // // If an insertion occurs, any references, pointers, or iterators are // invalidated. using Base::emplace; // btree_map::emplace_hint() // // Inserts an element of the specified value by constructing it in-place // within the `btree_map`, using the position of `hint` as a non-binding // suggestion for where to begin the insertion search, and only inserts // provided that no element with the given key already exists. // // The element may be constructed even if there already is an element with the // key in the container, in which case the newly constructed element will be // destroyed immediately. Prefer `try_emplace()` unless your key is not // copyable or moveable. // // If an insertion occurs, any references, pointers, or iterators are // invalidated. using Base::emplace_hint; // btree_map::try_emplace() // // Inserts an element of the specified value by constructing it in-place // within the `btree_map`, provided that no element with the given key // already exists. Unlike `emplace()`, if an element with the given key // already exists, we guarantee that no element is constructed. // // If an insertion occurs, any references, pointers, or iterators are // invalidated. // // Overloads are listed below. // // std::pair<iterator, bool> try_emplace(const key_type& k, Args&&... args): // std::pair<iterator, bool> try_emplace(key_type&& k, Args&&... args): // // Inserts (via copy or move) the element of the specified key into the // `btree_map`. // // iterator try_emplace(const_iterator hint, // const key_type& k, Args&&... args): // iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args): // // Inserts (via copy or move) the element of the specified key into the // `btree_map` using the position of `hint` as a non-binding suggestion // for where to begin the insertion search. using Base::try_emplace; // btree_map::extract() // // Extracts the indicated element, erasing it in the process, and returns it // as a C++17-compatible node handle. Overloads are listed below. // // node_type extract(const_iterator position): // // Extracts the element at the indicated position and returns a node handle // owning that extracted data. // // template <typename K> node_type extract(const K& x): // // Extracts the element with the key matching the passed key value and // returns a node handle owning that extracted data. If the `btree_map` // does not contain an element with a matching key, this function returns an // empty node handle. // // NOTE: In this context, `node_type` refers to the C++17 concept of a // move-only type that owns and provides access to the elements in associative // containers (https://en.cppreference.com/w/cpp/container/node_handle). // It does NOT refer to the data layout of the underlying btree. using Base::extract; // btree_map::merge() // // Extracts elements from a given `source` btree_map into this // `btree_map`. If the destination `btree_map` already contains an // element with an equivalent key, that element is not extracted. using Base::merge; // btree_map::swap(btree_map& other) // // Exchanges the contents of this `btree_map` with those of the `other` // btree_map, avoiding invocation of any move, copy, or swap operations on // individual elements. // // All iterators and references on the `btree_map` remain valid, excepting // for the past-the-end iterator, which is invalidated. using Base::swap; // btree_map::at() // // Returns a reference to the mapped value of the element with key equivalent // to the passed key. using Base::at; // btree_map::contains() // // template <typename K> bool contains(const K& key) const: // // Determines whether an element comparing equal to the given `key` exists // within the `btree_map`, returning `true` if so or `false` otherwise. // // Supports heterogeneous lookup, provided that the map is provided a // compatible heterogeneous comparator. using Base::contains; // btree_map::count() // // template <typename K> size_type count(const K& key) const: // // Returns the number of elements comparing equal to the given `key` within // the `btree_map`. Note that this function will return either `1` or `0` // since duplicate elements are not allowed within a `btree_map`. // // Supports heterogeneous lookup, provided that the map is provided a // compatible heterogeneous comparator. using Base::count; // btree_map::equal_range() // // Returns a closed range [first, last], defined by a `std::pair` of two // iterators, containing all elements with the passed key in the // `btree_map`. using Base::equal_range; // btree_map::find() // // template <typename K> iterator find(const K& key): // template <typename K> const_iterator find(const K& key) const: // // Finds an element with the passed `key` within the `btree_map`. // // Supports heterogeneous lookup, provided that the map is provided a // compatible heterogeneous comparator. using Base::find; // btree_map::operator[]() // // Returns a reference to the value mapped to the passed key within the // `btree_map`, performing an `insert()` if the key does not already // exist. // // If an insertion occurs, any references, pointers, or iterators are // invalidated. Otherwise iterators are not affected and references are not // invalidated. Overloads are listed below. // // T& operator[](key_type&& key): // T& operator[](const key_type& key): // // Inserts a value_type object constructed in-place if the element with the // given key does not exist. using Base::operator[]; // btree_map::get_allocator() // // Returns the allocator function associated with this `btree_map`. using Base::get_allocator; // btree_map::key_comp(); // // Returns the key comparator associated with this `btree_map`. using Base::key_comp; // btree_map::value_comp(); // // Returns the value comparator associated with this `btree_map`. using Base::value_comp; }; // absl::swap(absl::btree_map<>, absl::btree_map<>) // // Swaps the contents of two `absl::btree_map` containers. template <typename K, typename V, typename C, typename A> void swap(btree_map<K, V, C, A> &x, btree_map<K, V, C, A> &y) { return x.swap(y); } // absl::erase_if(absl::btree_map<>, Pred) // // Erases all elements that satisfy the predicate pred from the container. template <typename K, typename V, typename C, typename A, typename Pred> void erase_if(btree_map<K, V, C, A> &map, Pred pred) { for (auto it = map.begin(); it != map.end();) { if (pred(*it)) { it = map.erase(it); } else { ++it; } } } // absl::btree_multimap // // An `absl::btree_multimap<K, V>` is an ordered associative container of // keys and associated values designed to be a more efficient replacement for // `std::multimap` (in most cases). Unlike `absl::btree_map`, a B-tree multimap // allows multiple elements with equivalent keys. // // Keys are sorted using an (optional) comparison function, which defaults to // `std::less<K>`. // // An `absl::btree_multimap<K, V>` uses a default allocator of // `std::allocator<std::pair<const K, V>>` to allocate (and deallocate) // nodes, and construct and destruct values within those nodes. You may // instead specify a custom allocator `A` (which in turn requires specifying a // custom comparator `C`) as in `absl::btree_multimap<K, V, C, A>`. // template <typename Key, typename Value, typename Compare = std::less<Key>, typename Alloc = std::allocator<std::pair<const Key, Value>>> class btree_multimap : public container_internal::btree_multimap_container< container_internal::btree<container_internal::map_params< Key, Value, Compare, Alloc, /*TargetNodeSize=*/256, /*Multi=*/true>>> { using Base = typename btree_multimap::btree_multimap_container; public: // Constructors and Assignment Operators // // A `btree_multimap` supports the same overload set as `std::multimap` // for construction and assignment: // // * Default constructor // // absl::btree_multimap<int, std::string> map1; // // * Initializer List constructor // // absl::btree_multimap<int, std::string> map2 = // {{1, "huey"}, {2, "dewey"}, {3, "louie"},}; // // * Copy constructor // // absl::btree_multimap<int, std::string> map3(map2); // // * Copy assignment operator // // absl::btree_multimap<int, std::string> map4; // map4 = map3; // // * Move constructor // // // Move is guaranteed efficient // absl::btree_multimap<int, std::string> map5(std::move(map4)); // // * Move assignment operator // // // May be efficient if allocators are compatible // absl::btree_multimap<int, std::string> map6; // map6 = std::move(map5); // // * Range constructor // // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}}; // absl::btree_multimap<int, std::string> map7(v.begin(), v.end()); btree_multimap() {} using Base::Base; // btree_multimap::begin() // // Returns an iterator to the beginning of the `btree_multimap`. using Base::begin; // btree_multimap::cbegin() // // Returns a const iterator to the beginning of the `btree_multimap`. using Base::cbegin; // btree_multimap::end() // // Returns an iterator to the end of the `btree_multimap`. using Base::end; // btree_multimap::cend() // // Returns a const iterator to the end of the `btree_multimap`. using Base::cend; // btree_multimap::empty() // // Returns whether or not the `btree_multimap` is empty. using Base::empty; // btree_multimap::max_size() // // Returns the largest theoretical possible number of elements within a // `btree_multimap` under current memory constraints. This value can be // thought of as the largest value of `std::distance(begin(), end())` for a // `btree_multimap<Key, T>`. using Base::max_size; // btree_multimap::size() // // Returns the number of elements currently within the `btree_multimap`. using Base::size; // btree_multimap::clear() // // Removes all elements from the `btree_multimap`. Invalidates any references, // pointers, or iterators referring to contained elements. using Base::clear; // btree_multimap::erase() // // Erases elements within the `btree_multimap`. If an erase occurs, any // references, pointers, or iterators are invalidated. // Overloads are listed below. // // iterator erase(iterator position): // iterator erase(const_iterator position): // // Erases the element at `position` of the `btree_multimap`, returning // the iterator pointing to the element after the one that was erased // (or end() if none exists). // // iterator erase(const_iterator first, const_iterator last): // // Erases the elements in the open interval [`first`, `last`), returning // the iterator pointing to the element after the interval that was erased // (or end() if none exists). // // template <typename K> size_type erase(const K& key): // // Erases the elements matching the key, if any exist, returning the // number of elements erased. using Base::erase; // btree_multimap::insert() // // Inserts an element of the specified value into the `btree_multimap`, // returning an iterator pointing to the newly inserted element. // Any references, pointers, or iterators are invalidated. Overloads are // listed below. // // iterator insert(const value_type& value): // // Inserts a value into the `btree_multimap`, returning an iterator to the // inserted element. // // iterator insert(value_type&& value): // // Inserts a moveable value into the `btree_multimap`, returning an iterator // to the inserted element. // // iterator insert(const_iterator hint, const value_type& value): // iterator insert(const_iterator hint, value_type&& value): // // Inserts a value, using the position of `hint` as a non-binding suggestion // for where to begin the insertion search. Returns an iterator to the // inserted element. // // void insert(InputIterator first, InputIterator last): // // Inserts a range of values [`first`, `last`). // // void insert(std::initializer_list<init_type> ilist): // // Inserts the elements within the initializer list `ilist`. using Base::insert; // btree_multimap::emplace() // // Inserts an element of the specified value by constructing it in-place // within the `btree_multimap`. Any references, pointers, or iterators are // invalidated. using Base::emplace; // btree_multimap::emplace_hint() // // Inserts an element of the specified value by constructing it in-place // within the `btree_multimap`, using the position of `hint` as a non-binding // suggestion for where to begin the insertion search. // // Any references, pointers, or iterators are invalidated. using Base::emplace_hint; // btree_multimap::extract() // // Extracts the indicated element, erasing it in the process, and returns it // as a C++17-compatible node handle. Overloads are listed below. // // node_type extract(const_iterator position): // // Extracts the element at the indicated position and returns a node handle // owning that extracted data. // // template <typename K> node_type extract(const K& x): // // Extracts the element with the key matching the passed key value and // returns a node handle owning that extracted data. If the `btree_multimap` // does not contain an element with a matching key, this function returns an // empty node handle. // // NOTE: In this context, `node_type` refers to the C++17 concept of a // move-only type that owns and provides access to the elements in associative // containers (https://en.cppreference.com/w/cpp/container/node_handle). // It does NOT refer to the data layout of the underlying btree. using Base::extract; // btree_multimap::merge() // // Extracts elements from a given `source` btree_multimap into this // `btree_multimap`. If the destination `btree_multimap` already contains an // element with an equivalent key, that element is not extracted. using Base::merge; // btree_multimap::swap(btree_multimap& other) // // Exchanges the contents of this `btree_multimap` with those of the `other` // btree_multimap, avoiding invocation of any move, copy, or swap operations // on individual elements. // // All iterators and references on the `btree_multimap` remain valid, // excepting for the past-the-end iterator, which is invalidated. using Base::swap; // btree_multimap::contains() // // template <typename K> bool contains(const K& key) const: // // Determines whether an element comparing equal to the given `key` exists // within the `btree_multimap`, returning `true` if so or `false` otherwise. // // Supports heterogeneous lookup, provided that the map is provided a // compatible heterogeneous comparator. using Base::contains; // btree_multimap::count() // // template <typename K> size_type count(const K& key) const: // // Returns the number of elements comparing equal to the given `key` within // the `btree_multimap`. // // Supports heterogeneous lookup, provided that the map is provided a // compatible heterogeneous comparator. using Base::count; // btree_multimap::equal_range() // // Returns a closed range [first, last], defined by a `std::pair` of two // iterators, containing all elements with the passed key in the // `btree_multimap`. using Base::equal_range; // btree_multimap::find() // // template <typename K> iterator find(const K& key): // template <typename K> const_iterator find(const K& key) const: // // Finds an element with the passed `key` within the `btree_multimap`. // // Supports heterogeneous lookup, provided that the map is provided a // compatible heterogeneous comparator. using Base::find; // btree_multimap::get_allocator() // // Returns the allocator function associated with this `btree_multimap`. using Base::get_allocator; // btree_multimap::key_comp(); // // Returns the key comparator associated with this `btree_multimap`. using Base::key_comp; // btree_multimap::value_comp(); // // Returns the value comparator associated with this `btree_multimap`. using Base::value_comp; }; // absl::swap(absl::btree_multimap<>, absl::btree_multimap<>) // // Swaps the contents of two `absl::btree_multimap` containers. template <typename K, typename V, typename C, typename A> void swap(btree_multimap<K, V, C, A> &x, btree_multimap<K, V, C, A> &y) { return x.swap(y); } // absl::erase_if(absl::btree_multimap<>, Pred) // // Erases all elements that satisfy the predicate pred from the container. template <typename K, typename V, typename C, typename A, typename Pred> void erase_if(btree_multimap<K, V, C, A> &map, Pred pred) { for (auto it = map.begin(); it != map.end();) { if (pred(*it)) { it = map.erase(it); } else { ++it; } } } ABSL_NAMESPACE_END } // namespace absl #endif // ABSL_CONTAINER_BTREE_MAP_H_ <|start_filename|>MyApp/Pods/abseil/absl/flags/flag.cc<|end_filename|> // // Copyright 2019 The Abseil Authors. // // 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 // // https://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 "absl/flags/flag.h" #include "absl/base/config.h" #include "absl/flags/internal/commandlineflag.h" #include "absl/flags/internal/flag.h" namespace absl { ABSL_NAMESPACE_BEGIN // This global mutex protects on-demand construction of flag objects in MSVC // builds. #if defined(_MSC_VER) && !defined(__clang__) namespace flags_internal { ABSL_CONST_INIT static absl::Mutex construction_guard(absl::kConstInit); absl::Mutex* GetGlobalConstructionGuard() { return &construction_guard; } } // namespace flags_internal #endif ABSL_NAMESPACE_END } // namespace absl <|start_filename|>MyApp/Pods/GoogleUtilities/GoogleUtilities/SwizzlerTestHelpers/GULSwizzlingCache.h<|end_filename|> /* * Copyright 2018 Google LLC * * 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. */ #import <Foundation/Foundation.h> /** This class handles the caching and retrieval of IMPs as we swizzle and unswizzle them. It uses * two C++ STL unordered_maps as the underlying data store. This class is NOT thread safe. */ @interface GULSwizzlingCache : NSObject /** Singleton initializer. * * @return a singleton GULSwizzlingCache. */ + (instancetype)sharedInstance; /** Save the existing IMP that exists before we install the new IMP for a class, selector combo. * If the currentIMP is something that we put there, it will ignore it and instead point newIMP * to what existed before we swizzled. * * @param newIMP new The IMP that is going to replace the current IMP. * @param currentIMP The IMP returned by class_getMethodImplementation. * @param aClass The class that we're swizzling. * @param selector The selector we're swizzling. */ - (void)cacheCurrentIMP:(IMP)currentIMP forNewIMP:(IMP)newIMP forClass:(Class)aClass withSelector:(SEL)selector; /** Save the existing IMP that exists before we install the new IMP for a class, selector combo. * If the currentIMP is something that we put there, it will ignore it and instead point newIMP * to what existed before we swizzled. * * @param newIMP new The IMP that is going to replace the current IMP. * @param currentIMP The IMP returned by class_getMethodImplementation. * @param aClass The class that we're swizzling. * @param selector The selector we're swizzling. */ + (void)cacheCurrentIMP:(IMP)currentIMP forNewIMP:(IMP)newIMP forClass:(Class)aClass withSelector:(SEL)selector; /** Returns the cached IMP that would be invoked with the class and selector combo had we * never swizzled. * * @param aClass The class the selector would be invoked on. * @param selector The selector * @return The original IMP i.e. the one that existed right before GULSwizzler swizzled either * this or a superclass. */ - (IMP)cachedIMPForClass:(Class)aClass withSelector:(SEL)selector; /** Clears the cache of values we no longer need because we've unswizzled the relevant method. * * @param swizzledIMP The IMP we replaced the existing IMP with. * @param selector The selector which that we swizzled for. * @param aClass The class that we're swizzling. */ - (void)clearCacheForSwizzledIMP:(IMP)swizzledIMP selector:(SEL)selector aClass:(Class)aClass; @end <|start_filename|>MyApp/Pods/abseil/absl/flags/usage_config.cc<|end_filename|> // // Copyright 2019 The Abseil Authors. // // 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 // // https://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 "absl/flags/usage_config.h" #include <iostream> #include <string> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/const_init.h" #include "absl/base/thread_annotations.h" #include "absl/flags/internal/path_util.h" #include "absl/flags/internal/program_name.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/synchronization/mutex.h" extern "C" { // Additional report of fatal usage error message before we std::exit. Error is // fatal if is_fatal argument to ReportUsageError is true. ABSL_ATTRIBUTE_WEAK void AbslInternalReportFatalUsageError(absl::string_view) {} } // extern "C" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { namespace { // -------------------------------------------------------------------- // Returns true if flags defined in the filename should be reported with // -helpshort flag. bool ContainsHelpshortFlags(absl::string_view filename) { // By default we only want flags in binary's main. We expect the main // routine to reside in <program>.cc or <program>-main.cc or // <program>_main.cc, where the <program> is the name of the binary. auto suffix = flags_internal::Basename(filename); if (!absl::ConsumePrefix(&suffix, flags_internal::ShortProgramInvocationName())) return false; return absl::StartsWith(suffix, ".") || absl::StartsWith(suffix, "-main.") || absl::StartsWith(suffix, "_main."); } // -------------------------------------------------------------------- // Returns true if flags defined in the filename should be reported with // -helppackage flag. bool ContainsHelppackageFlags(absl::string_view filename) { // TODO(rogeeff): implement properly when registry is available. return ContainsHelpshortFlags(filename); } // -------------------------------------------------------------------- // Generates program version information into supplied output. std::string VersionString() { std::string version_str(flags_internal::ShortProgramInvocationName()); version_str += "\n"; #if !defined(NDEBUG) version_str += "Debug build (NDEBUG not #defined)\n"; #endif return version_str; } // -------------------------------------------------------------------- // Normalizes the filename specific to the build system/filesystem used. std::string NormalizeFilename(absl::string_view filename) { // Skip any leading slashes auto pos = filename.find_first_not_of("\\/"); if (pos == absl::string_view::npos) return ""; filename.remove_prefix(pos); return std::string(filename); } // -------------------------------------------------------------------- ABSL_CONST_INIT absl::Mutex custom_usage_config_guard(absl::kConstInit); ABSL_CONST_INIT FlagsUsageConfig* custom_usage_config ABSL_GUARDED_BY(custom_usage_config_guard) = nullptr; } // namespace FlagsUsageConfig GetUsageConfig() { absl::MutexLock l(&custom_usage_config_guard); if (custom_usage_config) return *custom_usage_config; FlagsUsageConfig default_config; default_config.contains_helpshort_flags = &ContainsHelpshortFlags; default_config.contains_help_flags = &ContainsHelppackageFlags; default_config.contains_helppackage_flags = &ContainsHelppackageFlags; default_config.version_string = &VersionString; default_config.normalize_filename = &NormalizeFilename; return default_config; } void ReportUsageError(absl::string_view msg, bool is_fatal) { std::cerr << "ERROR: " << msg << std::endl; if (is_fatal) { AbslInternalReportFatalUsageError(msg); } } } // namespace flags_internal void SetFlagsUsageConfig(FlagsUsageConfig usage_config) { absl::MutexLock l(&flags_internal::custom_usage_config_guard); if (!usage_config.contains_helpshort_flags) usage_config.contains_helpshort_flags = flags_internal::ContainsHelpshortFlags; if (!usage_config.contains_help_flags) usage_config.contains_help_flags = flags_internal::ContainsHelppackageFlags; if (!usage_config.contains_helppackage_flags) usage_config.contains_helppackage_flags = flags_internal::ContainsHelppackageFlags; if (!usage_config.version_string) usage_config.version_string = flags_internal::VersionString; if (!usage_config.normalize_filename) usage_config.normalize_filename = flags_internal::NormalizeFilename; if (flags_internal::custom_usage_config) *flags_internal::custom_usage_config = usage_config; else flags_internal::custom_usage_config = new FlagsUsageConfig(usage_config); } ABSL_NAMESPACE_END } // namespace absl <|start_filename|>MyApp/Pods/abseil/absl/synchronization/internal/waiter.cc<|end_filename|> // Copyright 2017 The Abseil Authors. // // 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 // // https://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 "absl/synchronization/internal/waiter.h" #include "absl/base/config.h" #ifdef _WIN32 #include <windows.h> #else #include <pthread.h> #include <sys/time.h> #include <unistd.h> #endif #ifdef __linux__ #include <linux/futex.h> #include <sys/syscall.h> #endif #ifdef ABSL_HAVE_SEMAPHORE_H #include <semaphore.h> #endif #include <errno.h> #include <stdio.h> #include <time.h> #include <atomic> #include <cassert> #include <cstdint> #include <new> #include <type_traits> #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/thread_identity.h" #include "absl/base/optimization.h" #include "absl/synchronization/internal/kernel_timeout.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace synchronization_internal { static void MaybeBecomeIdle() { base_internal::ThreadIdentity *identity = base_internal::CurrentThreadIdentityIfPresent(); assert(identity != nullptr); const bool is_idle = identity->is_idle.load(std::memory_order_relaxed); const int ticker = identity->ticker.load(std::memory_order_relaxed); const int wait_start = identity->wait_start.load(std::memory_order_relaxed); if (!is_idle && ticker - wait_start > Waiter::kIdlePeriods) { identity->is_idle.store(true, std::memory_order_relaxed); } } #if ABSL_WAITER_MODE == ABSL_WAITER_MODE_FUTEX // Some Android headers are missing these definitions even though they // support these futex operations. #ifdef __BIONIC__ #ifndef SYS_futex #define SYS_futex __NR_futex #endif #ifndef FUTEX_WAIT_BITSET #define FUTEX_WAIT_BITSET 9 #endif #ifndef FUTEX_PRIVATE_FLAG #define FUTEX_PRIVATE_FLAG 128 #endif #ifndef FUTEX_CLOCK_REALTIME #define FUTEX_CLOCK_REALTIME 256 #endif #ifndef FUTEX_BITSET_MATCH_ANY #define FUTEX_BITSET_MATCH_ANY 0xFFFFFFFF #endif #endif class Futex { public: static int WaitUntil(std::atomic<int32_t> *v, int32_t val, KernelTimeout t) { int err = 0; if (t.has_timeout()) { // https://locklessinc.com/articles/futex_cheat_sheet/ // Unlike FUTEX_WAIT, FUTEX_WAIT_BITSET uses absolute time. struct timespec abs_timeout = t.MakeAbsTimespec(); // Atomically check that the futex value is still 0, and if it // is, sleep until abs_timeout or until woken by FUTEX_WAKE. err = syscall( SYS_futex, reinterpret_cast<int32_t *>(v), FUTEX_WAIT_BITSET | FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME, val, &abs_timeout, nullptr, FUTEX_BITSET_MATCH_ANY); } else { // Atomically check that the futex value is still 0, and if it // is, sleep until woken by FUTEX_WAKE. err = syscall(SYS_futex, reinterpret_cast<int32_t *>(v), FUTEX_WAIT | FUTEX_PRIVATE_FLAG, val, nullptr); } if (err != 0) { err = -errno; } return err; } static int Wake(std::atomic<int32_t> *v, int32_t count) { int err = syscall(SYS_futex, reinterpret_cast<int32_t *>(v), FUTEX_WAKE | FUTEX_PRIVATE_FLAG, count); if (ABSL_PREDICT_FALSE(err < 0)) { err = -errno; } return err; } }; Waiter::Waiter() { futex_.store(0, std::memory_order_relaxed); } Waiter::~Waiter() = default; bool Waiter::Wait(KernelTimeout t) { // Loop until we can atomically decrement futex from a positive // value, waiting on a futex while we believe it is zero. // Note that, since the thread ticker is just reset, we don't need to check // whether the thread is idle on the very first pass of the loop. bool first_pass = true; while (true) { int32_t x = futex_.load(std::memory_order_relaxed); while (x != 0) { if (!futex_.compare_exchange_weak(x, x - 1, std::memory_order_acquire, std::memory_order_relaxed)) { continue; // Raced with someone, retry. } return true; // Consumed a wakeup, we are done. } if (!first_pass) MaybeBecomeIdle(); const int err = Futex::WaitUntil(&futex_, 0, t); if (err != 0) { if (err == -EINTR || err == -EWOULDBLOCK) { // Do nothing, the loop will retry. } else if (err == -ETIMEDOUT) { return false; } else { ABSL_RAW_LOG(FATAL, "Futex operation failed with error %d\n", err); } } first_pass = false; } } void Waiter::Post() { if (futex_.fetch_add(1, std::memory_order_release) == 0) { // We incremented from 0, need to wake a potential waiter. Poke(); } } void Waiter::Poke() { // Wake one thread waiting on the futex. const int err = Futex::Wake(&futex_, 1); if (ABSL_PREDICT_FALSE(err < 0)) { ABSL_RAW_LOG(FATAL, "Futex operation failed with error %d\n", err); } } #elif ABSL_WAITER_MODE == ABSL_WAITER_MODE_CONDVAR class PthreadMutexHolder { public: explicit PthreadMutexHolder(pthread_mutex_t *mu) : mu_(mu) { const int err = pthread_mutex_lock(mu_); if (err != 0) { ABSL_RAW_LOG(FATAL, "pthread_mutex_lock failed: %d", err); } } PthreadMutexHolder(const PthreadMutexHolder &rhs) = delete; PthreadMutexHolder &operator=(const PthreadMutexHolder &rhs) = delete; ~PthreadMutexHolder() { const int err = pthread_mutex_unlock(mu_); if (err != 0) { ABSL_RAW_LOG(FATAL, "pthread_mutex_unlock failed: %d", err); } } private: pthread_mutex_t *mu_; }; Waiter::Waiter() { const int err = pthread_mutex_init(&mu_, 0); if (err != 0) { ABSL_RAW_LOG(FATAL, "pthread_mutex_init failed: %d", err); } const int err2 = pthread_cond_init(&cv_, 0); if (err2 != 0) { ABSL_RAW_LOG(FATAL, "pthread_cond_init failed: %d", err2); } waiter_count_ = 0; wakeup_count_ = 0; } Waiter::~Waiter() { const int err = pthread_mutex_destroy(&mu_); if (err != 0) { ABSL_RAW_LOG(FATAL, "pthread_mutex_destroy failed: %d", err); } const int err2 = pthread_cond_destroy(&cv_); if (err2 != 0) { ABSL_RAW_LOG(FATAL, "pthread_cond_destroy failed: %d", err2); } } bool Waiter::Wait(KernelTimeout t) { struct timespec abs_timeout; if (t.has_timeout()) { abs_timeout = t.MakeAbsTimespec(); } PthreadMutexHolder h(&mu_); ++waiter_count_; // Loop until we find a wakeup to consume or timeout. // Note that, since the thread ticker is just reset, we don't need to check // whether the thread is idle on the very first pass of the loop. bool first_pass = true; while (wakeup_count_ == 0) { if (!first_pass) MaybeBecomeIdle(); // No wakeups available, time to wait. if (!t.has_timeout()) { const int err = pthread_cond_wait(&cv_, &mu_); if (err != 0) { ABSL_RAW_LOG(FATAL, "pthread_cond_wait failed: %d", err); } } else { const int err = pthread_cond_timedwait(&cv_, &mu_, &abs_timeout); if (err == ETIMEDOUT) { --waiter_count_; return false; } if (err != 0) { ABSL_RAW_LOG(FATAL, "pthread_cond_timedwait failed: %d", err); } } first_pass = false; } // Consume a wakeup and we're done. --wakeup_count_; --waiter_count_; return true; } void Waiter::Post() { PthreadMutexHolder h(&mu_); ++wakeup_count_; InternalCondVarPoke(); } void Waiter::Poke() { PthreadMutexHolder h(&mu_); InternalCondVarPoke(); } void Waiter::InternalCondVarPoke() { if (waiter_count_ != 0) { const int err = pthread_cond_signal(&cv_); if (ABSL_PREDICT_FALSE(err != 0)) { ABSL_RAW_LOG(FATAL, "pthread_cond_signal failed: %d", err); } } } #elif ABSL_WAITER_MODE == ABSL_WAITER_MODE_SEM Waiter::Waiter() { if (sem_init(&sem_, 0, 0) != 0) { ABSL_RAW_LOG(FATAL, "sem_init failed with errno %d\n", errno); } wakeups_.store(0, std::memory_order_relaxed); } Waiter::~Waiter() { if (sem_destroy(&sem_) != 0) { ABSL_RAW_LOG(FATAL, "sem_destroy failed with errno %d\n", errno); } } bool Waiter::Wait(KernelTimeout t) { struct timespec abs_timeout; if (t.has_timeout()) { abs_timeout = t.MakeAbsTimespec(); } // Loop until we timeout or consume a wakeup. // Note that, since the thread ticker is just reset, we don't need to check // whether the thread is idle on the very first pass of the loop. bool first_pass = true; while (true) { int x = wakeups_.load(std::memory_order_relaxed); while (x != 0) { if (!wakeups_.compare_exchange_weak(x, x - 1, std::memory_order_acquire, std::memory_order_relaxed)) { continue; // Raced with someone, retry. } // Successfully consumed a wakeup, we're done. return true; } if (!first_pass) MaybeBecomeIdle(); // Nothing to consume, wait (looping on EINTR). while (true) { if (!t.has_timeout()) { if (sem_wait(&sem_) == 0) break; if (errno == EINTR) continue; ABSL_RAW_LOG(FATAL, "sem_wait failed: %d", errno); } else { if (sem_timedwait(&sem_, &abs_timeout) == 0) break; if (errno == EINTR) continue; if (errno == ETIMEDOUT) return false; ABSL_RAW_LOG(FATAL, "sem_timedwait failed: %d", errno); } } first_pass = false; } } void Waiter::Post() { // Post a wakeup. if (wakeups_.fetch_add(1, std::memory_order_release) == 0) { // We incremented from 0, need to wake a potential waiter. Poke(); } } void Waiter::Poke() { if (sem_post(&sem_) != 0) { // Wake any semaphore waiter. ABSL_RAW_LOG(FATAL, "sem_post failed with errno %d\n", errno); } } #elif ABSL_WAITER_MODE == ABSL_WAITER_MODE_WIN32 class Waiter::WinHelper { public: static SRWLOCK *GetLock(Waiter *w) { return reinterpret_cast<SRWLOCK *>(&w->mu_storage_); } static CONDITION_VARIABLE *GetCond(Waiter *w) { return reinterpret_cast<CONDITION_VARIABLE *>(&w->cv_storage_); } static_assert(sizeof(SRWLOCK) == sizeof(void *), "`mu_storage_` does not have the same size as SRWLOCK"); static_assert(alignof(SRWLOCK) == alignof(void *), "`mu_storage_` does not have the same alignment as SRWLOCK"); static_assert(sizeof(CONDITION_VARIABLE) == sizeof(void *), "`ABSL_CONDITION_VARIABLE_STORAGE` does not have the same size " "as `CONDITION_VARIABLE`"); static_assert( alignof(CONDITION_VARIABLE) == alignof(void *), "`cv_storage_` does not have the same alignment as `CONDITION_VARIABLE`"); // The SRWLOCK and CONDITION_VARIABLE types must be trivially constructible // and destructible because we never call their constructors or destructors. static_assert(std::is_trivially_constructible<SRWLOCK>::value, "The `SRWLOCK` type must be trivially constructible"); static_assert( std::is_trivially_constructible<CONDITION_VARIABLE>::value, "The `CONDITION_VARIABLE` type must be trivially constructible"); static_assert(std::is_trivially_destructible<SRWLOCK>::value, "The `SRWLOCK` type must be trivially destructible"); static_assert(std::is_trivially_destructible<CONDITION_VARIABLE>::value, "The `CONDITION_VARIABLE` type must be trivially destructible"); }; class LockHolder { public: explicit LockHolder(SRWLOCK* mu) : mu_(mu) { AcquireSRWLockExclusive(mu_); } LockHolder(const LockHolder&) = delete; LockHolder& operator=(const LockHolder&) = delete; ~LockHolder() { ReleaseSRWLockExclusive(mu_); } private: SRWLOCK* mu_; }; Waiter::Waiter() { auto *mu = ::new (static_cast<void *>(&mu_storage_)) SRWLOCK; auto *cv = ::new (static_cast<void *>(&cv_storage_)) CONDITION_VARIABLE; InitializeSRWLock(mu); InitializeConditionVariable(cv); waiter_count_ = 0; wakeup_count_ = 0; } // SRW locks and condition variables do not need to be explicitly destroyed. // https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-initializesrwlock // https://stackoverflow.com/questions/28975958/why-does-windows-have-no-deleteconditionvariable-function-to-go-together-with Waiter::~Waiter() = default; bool Waiter::Wait(KernelTimeout t) { SRWLOCK *mu = WinHelper::GetLock(this); CONDITION_VARIABLE *cv = WinHelper::GetCond(this); LockHolder h(mu); ++waiter_count_; // Loop until we find a wakeup to consume or timeout. // Note that, since the thread ticker is just reset, we don't need to check // whether the thread is idle on the very first pass of the loop. bool first_pass = true; while (wakeup_count_ == 0) { if (!first_pass) MaybeBecomeIdle(); // No wakeups available, time to wait. if (!SleepConditionVariableSRW(cv, mu, t.InMillisecondsFromNow(), 0)) { // GetLastError() returns a Win32 DWORD, but we assign to // unsigned long to simplify the ABSL_RAW_LOG case below. The uniform // initialization guarantees this is not a narrowing conversion. const unsigned long err{GetLastError()}; // NOLINT(runtime/int) if (err == ERROR_TIMEOUT) { --waiter_count_; return false; } else { ABSL_RAW_LOG(FATAL, "SleepConditionVariableSRW failed: %lu", err); } } first_pass = false; } // Consume a wakeup and we're done. --wakeup_count_; --waiter_count_; return true; } void Waiter::Post() { LockHolder h(WinHelper::GetLock(this)); ++wakeup_count_; InternalCondVarPoke(); } void Waiter::Poke() { LockHolder h(WinHelper::GetLock(this)); InternalCondVarPoke(); } void Waiter::InternalCondVarPoke() { if (waiter_count_ != 0) { WakeConditionVariable(WinHelper::GetCond(this)); } } #else #error Unknown ABSL_WAITER_MODE #endif } // namespace synchronization_internal ABSL_NAMESPACE_END } // namespace absl <|start_filename|>MyApp/Pods/abseil/absl/flags/internal/path_util.h<|end_filename|> // // Copyright 2019 The Abseil Authors. // // 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 // // https://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 ABSL_FLAGS_INTERNAL_PATH_UTIL_H_ #define ABSL_FLAGS_INTERNAL_PATH_UTIL_H_ #include "absl/base/config.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { // A portable interface that returns the basename of the filename passed as an // argument. It is similar to basename(3) // <https://linux.die.net/man/3/basename>. // For example: // flags_internal::Basename("a/b/prog/file.cc") // returns "file.cc" // flags_internal::Basename("file.cc") // returns "file.cc" inline absl::string_view Basename(absl::string_view filename) { auto last_slash_pos = filename.find_last_of("/\\"); return last_slash_pos == absl::string_view::npos ? filename : filename.substr(last_slash_pos + 1); } // A portable interface that returns the directory name of the filename // passed as an argument, including the trailing slash. // Returns the empty string if a slash is not found in the input file name. // For example: // flags_internal::Package("a/b/prog/file.cc") // returns "a/b/prog/" // flags_internal::Package("file.cc") // returns "" inline absl::string_view Package(absl::string_view filename) { auto last_slash_pos = filename.find_last_of("/\\"); return last_slash_pos == absl::string_view::npos ? absl::string_view() : filename.substr(0, last_slash_pos + 1); } } // namespace flags_internal ABSL_NAMESPACE_END } // namespace absl #endif // ABSL_FLAGS_INTERNAL_PATH_UTIL_H_ <|start_filename|>MyApp/Pods/abseil/absl/random/random.h<|end_filename|> // Copyright 2017 The Abseil Authors. // // 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 // // https://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. // // ----------------------------------------------------------------------------- // File: random.h // ----------------------------------------------------------------------------- // // This header defines the recommended Uniform Random Bit Generator (URBG) // types for use within the Abseil Random library. These types are not // suitable for security-related use-cases, but should suffice for most other // uses of generating random values. // // The Abseil random library provides the following URBG types: // // * BitGen, a good general-purpose bit generator, optimized for generating // random (but not cryptographically secure) values // * InsecureBitGen, a slightly faster, though less random, bit generator, for // cases where the existing BitGen is a drag on performance. #ifndef ABSL_RANDOM_RANDOM_H_ #define ABSL_RANDOM_RANDOM_H_ #include <random> #include "absl/random/distributions.h" // IWYU pragma: export #include "absl/random/internal/nonsecure_base.h" // IWYU pragma: export #include "absl/random/internal/pcg_engine.h" // IWYU pragma: export #include "absl/random/internal/pool_urbg.h" #include "absl/random/internal/randen_engine.h" #include "absl/random/seed_sequences.h" // IWYU pragma: export namespace absl { ABSL_NAMESPACE_BEGIN // ----------------------------------------------------------------------------- // absl::BitGen // ----------------------------------------------------------------------------- // // `absl::BitGen` is a general-purpose random bit generator for generating // random values for use within the Abseil random library. Typically, you use a // bit generator in combination with a distribution to provide random values. // // Example: // // // Create an absl::BitGen. There is no need to seed this bit generator. // absl::BitGen gen; // // // Generate an integer value in the closed interval [1,6] // int die_roll = absl::uniform_int_distribution<int>(1, 6)(gen); // // `absl::BitGen` is seeded by default with non-deterministic data to produce // different sequences of random values across different instances, including // different binary invocations. This behavior is different than the standard // library bit generators, which use golden values as their seeds. Default // construction intentionally provides no stability guarantees, to avoid // accidental dependence on such a property. // // `absl::BitGen` may be constructed with an optional seed sequence type, // conforming to [rand.req.seed_seq], which will be mixed with additional // non-deterministic data. // // Example: // // // Create an absl::BitGen using an std::seed_seq seed sequence // std::seed_seq seq{1,2,3}; // absl::BitGen gen_with_seed(seq); // // // Generate an integer value in the closed interval [1,6] // int die_roll2 = absl::uniform_int_distribution<int>(1, 6)(gen_with_seed); // // `absl::BitGen` meets the requirements of the Uniform Random Bit Generator // (URBG) concept as per the C++17 standard [rand.req.urng] though differs // slightly with [rand.req.eng]. Like its standard library equivalents (e.g. // `std::mersenne_twister_engine`) `absl::BitGen` is not cryptographically // secure. // // Constructing two `absl::BitGen`s with the same seed sequence in the same // binary will produce the same sequence of variates within the same binary, but // need not do so across multiple binary invocations. // // This type has been optimized to perform better than Mersenne Twister // (https://en.wikipedia.org/wiki/Mersenne_Twister) and many other complex URBG // types on modern x86, ARM, and PPC architectures. // // This type is thread-compatible, but not thread-safe. // --------------------------------------------------------------------------- // absl::BitGen member functions // --------------------------------------------------------------------------- // absl::BitGen::operator()() // // Calls the BitGen, returning a generated value. // absl::BitGen::min() // // Returns the smallest possible value from this bit generator. // absl::BitGen::max() // // Returns the largest possible value from this bit generator., and // absl::BitGen::discard(num) // // Advances the internal state of this bit generator by `num` times, and // discards the intermediate results. // --------------------------------------------------------------------------- using BitGen = random_internal::NonsecureURBGBase< random_internal::randen_engine<uint64_t>>; // ----------------------------------------------------------------------------- // absl::InsecureBitGen // ----------------------------------------------------------------------------- // // `absl::InsecureBitGen` is an efficient random bit generator for generating // random values, recommended only for performance-sensitive use cases where // `absl::BitGen` is not satisfactory when compute-bounded by bit generation // costs. // // Example: // // // Create an absl::InsecureBitGen // absl::InsecureBitGen gen; // for (size_t i = 0; i < 1000000; i++) { // // // Generate a bunch of random values from some complex distribution // auto my_rnd = some_distribution(gen, 1, 1000); // } // // Like `absl::BitGen`, `absl::InsecureBitGen` is seeded by default with // non-deterministic data to produce different sequences of random values across // different instances, including different binary invocations. (This behavior // is different than the standard library bit generators, which use golden // values as their seeds.) // // `absl::InsecureBitGen` may be constructed with an optional seed sequence // type, conforming to [rand.req.seed_seq], which will be mixed with additional // non-deterministic data. (See std_seed_seq.h for more information.) // // `absl::InsecureBitGen` meets the requirements of the Uniform Random Bit // Generator (URBG) concept as per the C++17 standard [rand.req.urng] though // its implementation differs slightly with [rand.req.eng]. Like its standard // library equivalents (e.g. `std::mersenne_twister_engine`) // `absl::InsecureBitGen` is not cryptographically secure. // // Prefer `absl::BitGen` over `absl::InsecureBitGen` as the general type is // often fast enough for the vast majority of applications. using InsecureBitGen = random_internal::NonsecureURBGBase<random_internal::pcg64_2018_engine>; // --------------------------------------------------------------------------- // absl::InsecureBitGen member functions // --------------------------------------------------------------------------- // absl::InsecureBitGen::operator()() // // Calls the InsecureBitGen, returning a generated value. // absl::InsecureBitGen::min() // // Returns the smallest possible value from this bit generator. // absl::InsecureBitGen::max() // // Returns the largest possible value from this bit generator. // absl::InsecureBitGen::discard(num) // // Advances the internal state of this bit generator by `num` times, and // discards the intermediate results. // --------------------------------------------------------------------------- ABSL_NAMESPACE_END } // namespace absl #endif // ABSL_RANDOM_RANDOM_H_
JQHxx/Mall-SwiftUI
<|start_filename|>components/overflow-group/test/overflow-group.axe.js<|end_filename|> import '../overflow-group.js'; import '../../button/button.js'; import '../../button/button-subtle.js'; import { expect, fixture, html } from '@open-wc/testing'; describe('d2l-overflow-group', () => { it('default', async() => { const normal = await fixture(html`<d2l-overflow-group> <d2l-button>1</d2l-button> <d2l-button>2</d2l-button> <d2l-button>3</d2l-button> </d2l-overflow-group>`); await expect(normal).to.be.accessible(); }); it('overflowing', async() => { const overflow = await fixture(html`<d2l-overflow-group max-to-show="2"> <d2l-button>1</d2l-button> <d2l-button>2</d2l-button> <d2l-button>3</d2l-button> </d2l-overflow-group>`); await expect(overflow).to.be.accessible(); }); it('subtle', async() => { const subtle = await fixture(html`<d2l-overflow-group opener-style="subtle"> <d2l-button-subtle>1</d2l-button-subtle> <d2l-button-subtle>2</d2l-button-subtle> <d2l-button-subtle>3</d2l-button-subtle> </d2l-overflow-group>`); await expect(subtle).to.be.accessible(); }); it('subtle-overflow', async() => { const subtleOverflow = await fixture(html`<d2l-overflow-group opener-style="subtle" max-to-show="2"> <d2l-button-subtle>1</d2l-button-subtle> <d2l-button-subtle>2</d2l-button-subtle> <d2l-button-subtle>3</d2l-button-subtle> </d2l-overflow-group>`); await expect(subtleOverflow).to.be.accessible(); }); }); <|start_filename|>components/card/test/card.test.js<|end_filename|> import '../card.js'; import { expect, fixture, html } from '@open-wc/testing'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-card', () => { it('should construct', () => { runConstructor('d2l-card'); }); it('should not set href attribute if null', async() => { const elem = await fixture(html`<d2l-card></d2l-card>`); elem.href = null; await elem.updateComplete; const anchorElem = elem.shadowRoot.querySelector('a'); expect(anchorElem.hasAttribute('href')).to.be.false; }); }); <|start_filename|>components/form/form-element-localize-helper.js<|end_filename|> import { formatNumber } from '@brightspace-ui/intl/lib/number.js'; import { tryGetLabelText } from './form-helper.js'; const _localizeGenericElement = (localize, ele, labelText) => { switch (true) { case ele.validity.valueMissing: return localize('components.form-element.valueMissing', { label: labelText }); default: return localize('components.form-element.defaultError', { label: labelText }); } }; const _localizeInputNumberElement = (localize, ele, labelText) => { switch (true) { case ele.validity.rangeUnderflow: return localize('components.form-element.input.number.rangeUnderflow', { min: formatNumber(parseFloat(ele.min)), minExclusive: false }); case ele.validity.rangeOverflow: return localize('components.form-element.input.number.rangeOverflow', { max: formatNumber(parseFloat(ele.max)), maxExclusive: false }); default: return _localizeGenericElement(localize, ele, labelText); } }; const _localizeInputUrlElement = (localize, ele, labelText) => { switch (true) { case ele.validity.typeMismatch: return localize('components.form-element.input.url.typeMismatch'); default: return _localizeGenericElement(localize, ele, labelText); } }; const _localizeInputEmailElement = (localize, ele, labelText) => { switch (true) { case ele.validity.typeMismatch: return localize('components.form-element.input.email.typeMismatch'); default: return _localizeGenericElement(localize, ele, labelText); } }; const _localizeInputTextElement = (localize, ele, labelText) => { switch (true) { case ele.validity.tooShort: return localize('components.form-element.input.text.tooShort', { label: labelText, minlength: formatNumber(ele.minLength) }); default: return _localizeGenericElement(localize, ele, labelText); } }; const _localizeInputElement = (localize, ele, labelText) => { const type = ele.type; switch (type) { case 'number': return _localizeInputNumberElement(localize, ele, labelText); case 'url': return _localizeInputUrlElement(localize, ele, labelText); case 'email': return _localizeInputEmailElement(localize, ele, labelText); case 'text': return _localizeInputTextElement(localize, ele, labelText); default: return _localizeGenericElement(localize, ele, labelText); } }; export const localizeFormElement = (localize, ele) => { if (ele.validity.valid) { return null; } const tagName = ele.tagName.toLowerCase(); const labelText = tryGetLabelText(ele) || localize('components.form-element.defaultFieldLabel'); switch (tagName) { case 'input': return _localizeInputElement(localize, ele, labelText); case 'textarea': return _localizeInputTextElement(localize, ele, labelText); default: return _localizeGenericElement(localize, ele, labelText); } }; <|start_filename|>components/list/list-item-placement-marker.js<|end_filename|> import '../colors/colors.js'; import { css, html, LitElement } from 'lit-element/lit-element.js'; import { RtlMixin } from '../../mixins/rtl-mixin.js'; class ListItemPlacementMarker extends RtlMixin(LitElement) { static get styles() { return css` :host { display: block; } :host([hidden]) { display: none; } .d2l-list-drag-marker-line { height: 12px; margin-left: -1px; margin-right: -1px; stroke: var(--d2l-color-celestine); stroke-width: 3px; width: 100%; } .d2l-list-drag-marker-linecap { fill: var(--d2l-color-celestine); height: 12px; margin-left: -1px; margin-right: 0; stroke: none; width: 4px; } :host([dir="rtl"]) .d2l-list-drag-marker-linecap { margin-left: 0; margin-right: -1px; } .d2l-list-drag-marker-circle { fill: none; height: 12px; margin-left: 0; margin-right: -1px; stroke: var(--d2l-color-celestine); stroke-width: 3px; width: 12px; } :host([dir="rtl"]) .d2l-list-drag-marker-circle { margin-left: -1px; margin-right: 0; } .d2l-list-drag-marker { display: flex; flex-wrap: nowrap; } `; } render() { return html` <div class="d2l-list-drag-marker"> <svg class="d2l-list-drag-marker-circle"> <circle cx="50%" cy="50%" r="3.8px"/> </svg> <svg class="d2l-list-drag-marker-line"> <line x1="0" y1="50%" x2="100%" y2="50%" /> </svg> <svg class="d2l-list-drag-marker-linecap"> <circle cx="50%" cy="50%" r="1.5px"/> </svg> </div> `; } } customElements.define('d2l-list-item-placement-marker', ListItemPlacementMarker); <|start_filename|>components/validation/validation-custom-mixin.js<|end_filename|> import { isCustomFormElement } from '../form/form-helper.js'; export const ValidationCustomMixin = superclass => class extends superclass { static get properties() { return { failureText: { type: String, attribute: 'failure-text' }, for: { type: String } }; } constructor() { super(); this._forElement = null; } get forElement() { return this._forElement; } connectedCallback() { super.connectedCallback(); this._updateForElement(); this.dispatchEvent(new CustomEvent('d2l-validation-custom-connected', { bubbles: true })); } disconnectedCallback() { super.disconnectedCallback(); if (isCustomFormElement(this._forElement)) { this._forElement.validationCustomDisconnected(this); } this._forElement = null; this.dispatchEvent(new CustomEvent('d2l-validation-custom-disconnected')); } updated(changedProperties) { super.updated(changedProperties); changedProperties.forEach((_, prop) => { if (prop === 'for') { this._updateForElement(); } }); } async validate() { throw new Error('ValidationCustomMixin requires validate to be overridden'); } _updateForElement() { const oldForElement = this._forElement; if (this.for) { const root = this.getRootNode(); this._forElement = root.getElementById(this.for); if (!this._forElement) { throw new Error(`validation-custom failed to find element with id ${this.for}`); } } else { this._forElement = null; } if (this._forElement !== oldForElement) { if (isCustomFormElement(oldForElement)) { oldForElement.validationCustomDisconnected(this); } if (isCustomFormElement(this._forElement)) { this._forElement.validationCustomConnected(this); } } } }; <|start_filename|>components/filter/test/filter-dimension-set.test.js<|end_filename|> import '../filter-dimension-set.js'; import '../filter-dimension-set-value.js'; import { expect, fixture, html, oneEvent } from '@open-wc/testing'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; import { spy } from 'sinon'; const dimensionfixture = html` <d2l-filter-dimension-set key="dim" text="Dim"> <d2l-filter-dimension-set-value key="1" text="Value 1"></d2l-filter-dimension-set-value> <d2l-filter-dimension-set-value key="2" text="Value 2"></d2l-filter-dimension-set-value> </d2l-filter-dimension-set>`; describe('d2l-filter-dimension-set', () => { it('should construct', () => { runConstructor('d2l-filter-dimension-set'); }); describe('slot change', () => { it('values added after initial render are handled', async() => { const elem = await fixture(dimensionfixture); expect(elem.querySelectorAll('d2l-filter-dimension-set-value').length).to.equal(2); const newValue = document.createElement('d2l-filter-dimension-set-value'); newValue.key = 'newValue'; elem.appendChild(newValue); await elem.updateComplete; const values = elem.querySelectorAll('d2l-filter-dimension-set-value'); expect(values.length).to.equal(3); expect(values[0].key).to.equal('1'); expect(values[1].key).to.equal('2'); expect(values[2].key).to.equal('newValue'); }); }); describe('data change', () => { it('fires data change event when its data changes', async() => { const elem = await fixture(dimensionfixture); const eventSpy = spy(elem, 'dispatchEvent'); elem.text = 'Test'; elem.loading = true; const e = await oneEvent(elem, 'd2l-filter-dimension-data-change'); expect(e.detail.dimensionKey).to.equal('dim'); expect(e.detail.valueKey).to.be.undefined; expect(e.detail.changes.size).to.equal(2); expect(e.detail.changes.get('text')).to.equal('Test'); expect(e.detail.changes.get('loading')).to.equal(true); expect(eventSpy).to.be.calledOnce; }); it('fires data change event when data changes in one of its values', async() => { const elem = await fixture(dimensionfixture); const eventSpy = spy(elem, 'dispatchEvent'); const value = elem.querySelector('d2l-filter-dimension-set-value[key="2"]'); setTimeout(() => value.selected = true); const e = await oneEvent(elem, 'd2l-filter-dimension-data-change'); expect(e.detail.dimensionKey).to.equal('dim'); expect(e.detail.valueKey).to.equal('2'); expect(e.detail.changes.size).to.equal(1); expect(e.detail.changes.get('selected')).to.be.true; expect(eventSpy).to.be.calledOnce; }); }); }); <|start_filename|>components/form/test/form-native.test.js<|end_filename|> import '../../validation/validation-custom.js'; import '../form-native.js'; import './form-element.js'; import { expect, fixture } from '@open-wc/testing'; import { html } from 'lit-element/lit-element.js'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-form-native', () => { const _validateCheckbox = e => { e.detail.resolve(e.detail.forElement.checked); }; const formFixture = html` <d2l-form-native> <d2l-validation-custom for="mycheck" @d2l-validation-custom-validate=${_validateCheckbox} failure-text="The checkbox failed validation" > </d2l-validation-custom> <input type="checkbox" id="mycheck" name="checkers" value="red-black"> <input type="file" name="optional-file"> <select aria-label="Pets" name="pets" id="pets" required> <option value="">--Please choose an option--</option> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="hamster">Hamster</option> <option value="parrot">Parrot</option> <option value="spider">Spider</option> <option value="goldfish">Goldfish</option> </select> <input type="radio" id="myradio" name="optional-radio"> <d2l-test-form-element id="custom-ele"></d2l-test-form-element> </d2l-form-native> `; let form; beforeEach(async() => { form = await fixture(formFixture); }); describe('constructor', () => { it('should construct', () => { runConstructor('d2l-form-native'); }); }); describe('validate', () => { it('should validate validation-customs', async() => { const errors = await form.validate(); const ele = form.querySelector('#mycheck'); expect(errors.get(ele)).to.include.members(['The checkbox failed validation']); }); it('should validate native form elements', async() => { const errors = await form.validate(); const ele = form.querySelector('#pets'); expect(errors.get(ele)).to.include.members(['Pets is required.']); }); it('should validate custom form elements', async() => { const formElement = form.querySelector('#custom-ele'); formElement.value = 'Non-empty'; formElement.setValidity({ rangeOverflow: true }); const errors = await form.validate(); expect(errors.get(formElement)).to.include.members(['Test form element failed with an overridden validation message']); }); }); describe('submit', () => { it('should not submit if there are errors', async() => { let submitted = false; form.addEventListener('submit', () => submitted = true); await form.submit(); expect(submitted).to.be.false; }); it('should submit with form values', async() => { const mycheck = form.querySelector('#mycheck'); mycheck.checked = true; const pets = form.querySelector('#pets > option:nth-child(4)'); pets.selected = true; const formElement = form.querySelector('#custom-ele'); formElement.value = 'Non-empty'; formElement.formValue = { 'key-1': 'val-1', 'key-2': 'val-2' }; const myradio = form.querySelector('#myradio'); myradio.checked = true; const submitPromise = new Promise(resolve => { form.addEventListener('submit', (e) => { e.preventDefault(); resolve(); }); }); const formDataPromise = new Promise(resolve => { form.addEventListener('formdata', (e) => { const { formData } = e.detail; expect(formData.get('checkers')).to.equal('red-black'); expect(formData.get('pets')).to.equal('hamster'); expect(formData.get('key-1')).to.equal('val-1'); expect(formData.get('key-2')).to.equal('val-2'); expect(formData.get('optional-radio')).to.equal('on'); resolve(); }); }); form.submit(); await Promise.all([submitPromise, formDataPromise]); }); }); }); <|start_filename|>components/skeleton/demo/skeleton-test-link.js<|end_filename|> import { css, html, LitElement } from 'lit-element/lit-element.js'; import { classMap } from 'lit-html/directives/class-map.js'; import { linkStyles } from '../../link/link.js'; import { SkeletonMixin } from '../skeleton-mixin.js'; export class SkeletonTestLink extends SkeletonMixin(LitElement) { static get properties() { return { type: { type: String }, width: { type: Number } }; } static get styles() { return [ super.styles, linkStyles, css` :host { display: block; } ` ]; } constructor() { super(); this.type = 'normal'; } render() { const classes = { 'd2l-link': true, 'd2l-link-main': this.type === 'main', 'd2l-link-small': this.type === 'small', 'd2l-skeletize': true }; if (this.width !== undefined) { classes[`d2l-skeletize-${this.width}`] = true; } return html`<a href="https://d2l.com" class="${classMap(classes)}">Link (${this.type})</a>`; } } customElements.define('d2l-test-skeleton-link', SkeletonTestLink); <|start_filename|>helpers/test/dismissible.test.js<|end_filename|> import { assert, expect } from '@open-wc/testing'; import { clearDismissible, setDismissible } from '../dismissible.js'; import { spy } from 'sinon'; function pressEscape() { const event = new CustomEvent('keyup', { detail: 0, bubbles: true, cancelable: true, composed: true }); event.keyCode = 27; event.code = 27; document.dispatchEvent(event); } describe('dismissible', () => { const ids = []; beforeEach(() => { spy(document, 'removeEventListener'); }); afterEach(() => { ids.forEach((id) => { clearDismissible(id); }); ids.splice(0); document.removeEventListener.restore(); }); it('should call callback on ESC', async(done) => { setDismissible(() => done()); pressEscape(); }); it('should not call callback on clear', () => { const id = setDismissible(() => { throw new Error('callback called'); }); assert.doesNotThrow(() => clearDismissible(id)); }); it('should dismiss via ESC in FILO order', async(done) => { ids.push(setDismissible(() => { throw new Error('callback called'); })); setDismissible(() => done()); assert.doesNotThrow(() => pressEscape()); }); it('should skip manually dismissed entries', async(done) => { setDismissible(() => done()); const id = setDismissible(() => { throw new Error('callback called'); }); assert.doesNotThrow(() => { clearDismissible(id); pressEscape(); }); }); it('should handle unrecognized id during clear', () => { assert.doesNotThrow(() => clearDismissible(123)); }); [undefined, null, 0, 'hello', []].forEach((cb) => { it(`should handle invalid callback: ${cb}`, () => { assert.doesNotThrow(() => { setDismissible(cb); pressEscape(); }); }); }); it.skip('should remove event listener when stack is empty via ESC', () => { setDismissible(); pressEscape(); expect(document.removeEventListener.calledOnce).to.be.true; }); it.skip('should remove event listener when stack is empty via clear', () => { const id = setDismissible(); clearDismissible(id); expect(document.removeEventListener.calledOnce).to.be.true; }); }); <|start_filename|>components/switch/test/switch-visibility.axe.js<|end_filename|> import '../switch-visibility.js'; import { expect, fixture, html } from '@open-wc/testing'; describe('d2l-switch-visibility', () => { it('default', async() => { const elem = await fixture(html`<d2l-switch-visibility></d2l-switch-visibility>`); await expect(elem).to.be.accessible(); }); }); <|start_filename|>components/meter/meter-radial.js<|end_filename|> import '../colors/colors.js'; import { bodySmallStyles, heading4Styles } from '../typography/styles.js'; import { css, html, LitElement } from 'lit-element/lit-element.js'; import { classMap } from 'lit-html/directives/class-map.js'; import { MeterMixin } from './meter-mixin.js'; import { RtlMixin } from '../../mixins/rtl-mixin.js'; /** * A half-circle progress indicator. */ class MeterRadial extends MeterMixin(RtlMixin(LitElement)) { static get styles() { return [ heading4Styles, bodySmallStyles, css` :host { display: inline-block; width: 4.2rem; } .d2l-meter-radial { display: flex; flex-direction: column; justify-content: center; } .d2l-meter-radial-full-bar, .d2l-meter-radial-progress-bar { fill: none; stroke-linecap: round; stroke-width: 9; } .d2l-meter-radial-full-bar { stroke: var(--d2l-color-gypsum); } :host([foreground-light]) .d2l-meter-radial-full-bar { stroke: rgba(255, 255, 255, 0.5); } .d2l-meter-radial-progress-bar { stroke: var(--d2l-color-celestine); } :host([foreground-light]) .d2l-meter-radial-progress-bar { stroke: white; } .d2l-meter-radial-text { color: var(--d2l-color-ferrite); fill: var(--d2l-color-ferrite); line-height: 0.8rem; text-align: center; } :host([foreground-light]) .d2l-meter-radial-text { color: white; fill: white; } :host([dir="rtl"]) .d2l-meter-radial-text-ltr { direction: ltr; } ` ]; } render() { const lengthOfLine = 115; // found by approximating half the perimeter of the ellipse with radii 38 and 35 const percent = this.max > 0 ? (this.value / this.max) : 0; const visibility = (percent < 0.005) ? 'hidden' : 'visible'; const progressFill = percent * lengthOfLine; const primary = this._primary(this.value, this.max); const secondary = this._secondary(this.value, this.max, this.text); const secondaryTextElement = this.text ? html`<div class="d2l-body-small d2l-meter-radial-text">${secondary}</div>` : html``; const textClasses = { 'd2l-meter-radial-text-ltr': !this.percent, 'd2l-heading-4': true, 'd2l-meter-radial-text': true }; return html ` <div class="d2l-meter-radial" role="img" aria-label="${this._ariaLabel(primary, secondary)}"> <svg viewBox="0 0 84 46"> <path class="d2l-meter-radial-full-bar" d="M5 40a37 35 0 0 1 74 0" /> <path class="d2l-meter-radial-progress-bar" d="M5 40a37 35 0 0 1 74 0" stroke-dasharray="${progressFill} ${lengthOfLine}" stroke-dashoffset="0" visibility="${visibility}" /> <text class=${classMap(textClasses)} x="38" y="2" text-anchor="middle" transform="translate(5 39)"> ${primary} </text> </svg> ${secondaryTextElement} </div> `; } } customElements.define('d2l-meter-radial', MeterRadial); <|start_filename|>components/card/test/card-loading-shimmer.axe.js<|end_filename|> import '../card-loading-shimmer.js'; import { expect, fixture, html } from '@open-wc/testing'; describe('d2l-card-loading-shimmer', () => { it('default', async() => { const elem = await fixture(html`<d2l-card-loading-shimmer>Content</d2l-card-loading-shimmer>`); await expect(elem).to.be.accessible(); }); it('loading', async() => { const elem = await fixture(html`<d2l-card-loading-shimmer loading>Content</d2l-card-loading-shimmer>`); await expect(elem).to.be.accessible(); }); }); <|start_filename|>helpers/gestures.js<|end_filename|> const maxTime = 2000; const minDistance = 30; export function registerGestureSwipe(node) { node.addEventListener('touchstart', handleTouchStart); } function handleTouchStart(e) { const node = this; /* eslint-disable-line no-invalid-this */ let tracking = { start: { time: performance.now(), x: e.touches[0].clientX, y: e.touches[0].clientY } }; const reset = () => { tracking = null; node.removeEventListener('touchend', handleTouchEnd); /* eslint-disable-line no-use-before-define */ node.removeEventListener('touchermove', handleTouchMove); /* eslint-disable-line no-use-before-define */ node.removeEventListener('touchcancel', handleTouchCancel); /* eslint-disable-line no-use-before-define */ }; const handleTouchCancel = () => { reset(); return; }; const handleTouchEnd = () => { if (!tracking || !tracking.end) { return; } const elapsedTime = performance.now() - tracking.start.time; if (elapsedTime > maxTime) { reset(); return; } const distanceX = tracking.end.x - tracking.start.x; const distanceY = tracking.end.y - tracking.start.y; // angle of right-angle tri from y (radians) let theta = Math.atan(Math.abs(distanceX) / Math.abs(distanceY)); // angle of arc from y (deg) if (distanceY > 0 && distanceX > 0) { // swipe down and right theta = (Math.PI - theta) * 57.3; } else if (distanceY > 0 && distanceX < 0) { // swipe down and left theta = (Math.PI + theta) * 57.3; } else if (distanceY < 0 && distanceX > 0) { // swipe up and right theta = theta * 57.3; } else if (distanceY < 0 && distanceX < 0) { // swipe up and left theta = ((2 * Math.PI) - theta) * 57.3; } let horizontal = 'none'; if (Math.abs(distanceX) >= minDistance) { if (theta > 205 && theta < 335) { horizontal = 'left'; } else if (theta > 25 && theta < 155) { horizontal = 'right'; } } let vertical = 'none'; if (Math.abs(distanceY) >= minDistance) { if (theta > 295 || theta < 65) { vertical = 'up'; } else if (theta > 115 && theta < 245) { vertical = 'down'; } } node.dispatchEvent(new CustomEvent('d2l-gesture-swipe', { detail: { distance: { x: distanceX, y: distanceY }, direction: { angle: theta, horizontal: horizontal, vertical: vertical }, duration: elapsedTime } })); reset(); }; const handleTouchMove = (e) => { if (!tracking) { return; } e.preventDefault(); tracking.end = { x: e.touches[0].clientX, y: e.touches[0].clientY }; }; node.addEventListener('touchend', handleTouchEnd); node.addEventListener('touchmove', handleTouchMove); node.addEventListener('touchcancel', handleTouchCancel); } <|start_filename|>components/list/test/list-item-role-mixin.test.js<|end_filename|> import '../list.js'; import { defineCE, expect, fixture } from '@open-wc/testing'; import { ListItemRoleMixin } from '../list-item-role-mixin.js'; import { LitElement } from 'lit-element/lit-element.js'; const tag = defineCE( class extends ListItemRoleMixin(LitElement) { } ); describe('ListItemRoleMixin', () => { it('leaves role as undefined if not a child of d2l-list', async() => { const el = await fixture(`<div><${tag}></${tag}></div>`); expect(el.querySelector(tag).role).to.be.undefined; }); it('changes role to rowgroup when list parent has grid enabled', async() => { const el = await fixture(`<d2l-list grid><${tag}></${tag}></d2l-list>`); expect(el.querySelector(tag).role).to.equal('rowgroup'); }); it('changes role to listitem when list parent has grid disabled', async() => { const el = await fixture(`<d2l-list><${tag}></${tag}></d2l-list>`); expect(el.querySelector(tag).role).to.equal('listitem'); }); }); <|start_filename|>components/dialog/test/dialog.test.js<|end_filename|> import '../dialog.js'; import { expect, fixture, oneEvent } from '@open-wc/testing'; import { getComposedActiveElement } from '../../../helpers/focus.js'; import { html } from 'lit-element/lit-element.js'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-dialog', () => { describe('constructor', () => { it('should construct', () => { runConstructor('d2l-dialog'); }); }); describe.skip('focus management', () => { it('should focus on close button if no focusable elements inside', async() => { const el = await fixture(html`<d2l-dialog opened>not focusable</d2l-dialog>`); await oneEvent(el, 'd2l-dialog-open'); expect(getComposedActiveElement().getAttribute('aria-label')).to.equal('Close this dialog'); }); it('should focus on first element when opened initially', async() => { const el = await fixture(html`<d2l-dialog opened><button>focus</button></d2l-dialog>`); const button = el.querySelector('button'); await oneEvent(el, 'd2l-dialog-open'); expect(getComposedActiveElement()).to.equal(button); }); it('should focus on first element when opened later', async() => { const el = await fixture(html`<d2l-dialog><button>focus</button></d2l-dialog>`); const button = el.querySelector('button'); setTimeout(() => el.opened = true); await oneEvent(el, 'd2l-dialog-open'); expect(getComposedActiveElement()).to.equal(button); }); }); }); <|start_filename|>mixins/localize-dynamic-mixin.js<|end_filename|> import { getLocalizeOverrideResources } from '../helpers/getLocalizeResources.js'; import { LocalizeMixin } from './localize-mixin.js'; const fallbackLang = 'en'; export const LocalizeDynamicMixin = superclass => class extends LocalizeMixin(superclass) { static async getLocalizeResources(langs, { importFunc, osloCollection }) { for (const lang of [...langs, fallbackLang]) { const resources = await importFunc(lang).catch(() => {}); if (resources) { if (osloCollection) { return await getLocalizeOverrideResources( lang, resources, () => osloCollection ); } return { language: lang, resources }; } } } static get localizeConfig() { return {}; } }; <|start_filename|>components/card/test/card-content-title.axe.js<|end_filename|> import '../card-content-title.js'; import { expect, fixture, html } from '@open-wc/testing'; describe('d2l-card-content-title', () => { it('default', async() => { const elem = await fixture(html`<d2l-card-content-title>Title</d2l-card-content-title>`); await expect(elem).to.be.accessible; }); }); <|start_filename|>components/breadcrumbs/test/breadcrumbs.test.js<|end_filename|> import '../breadcrumbs.js'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-breadcrumbs', () => { describe('constructor', () => { it('should construct', () => { runConstructor('d2l-breadcrumbs'); }); }); }); <|start_filename|>components/switch/test/switch.axe.js<|end_filename|> import '../switch.js'; import { expect, fixture, html, oneEvent } from '@open-wc/testing'; describe('d2l-switch', () => { it('off', async() => { const elem = await fixture(html`<d2l-switch text="some text"></d2l-switch>`); await expect(elem).to.be.accessible(); }); it('on', async() => { const elem = await fixture(html`<d2l-switch text="some text" on></d2l-switch>`); await expect(elem).to.be.accessible(); }); it('disabled', async() => { const elem = await fixture(html`<d2l-switch text="some text" disabled></d2l-switch>`); await expect(elem).to.be.accessible(); }); it('tooltip', async() => { const elem = await fixture(html`<d2l-switch text="some text" tooltip="tooltip text"></d2l-switch>`); await expect(elem).to.be.accessible(); }); it('hidden label', async() => { const elem = await fixture(html`<d2l-switch text="some text" text-position="hidden"></d2l-switch>`); await expect(elem).to.be.accessible(); }); it('focused', async() => { const elem = await fixture(html`<d2l-switch text="some text"></d2l-switch>`); setTimeout(() => elem.focus()); await oneEvent(elem, 'focus'); await expect(elem).to.be.accessible(); }); }); <|start_filename|>mixins/provider-mixin.js<|end_filename|> export function provideInstance(node, key, obj) { if (!node._providerInstances) { node._providerInstances = new Map(); node.addEventListener('d2l-request-instance', e => { if (node._providerInstances.has(e.detail.key)) { e.detail.instance = node._providerInstances.get(e.detail.key); e.stopPropagation(); } }); } node._providerInstances.set(key, obj); } export const ProviderMixin = superclass => class extends superclass { provideInstance(key, obj) { provideInstance(this, key, obj); } }; export function requestInstance(node, key) { const event = new CustomEvent('d2l-request-instance', { detail: { key }, bubbles: true, composed: true, cancelable: true }); node.dispatchEvent(event); return event.detail.instance; } export const RequesterMixin = superclass => class extends superclass { requestInstance(key) { return requestInstance(this, key); } }; <|start_filename|>components/inputs/test/input-date-time-range.test.js<|end_filename|> import { aTimeout, expect, fixture, oneEvent } from '@open-wc/testing'; import { getDocumentLocaleSettings } from '@brightspace-ui/intl/lib/common.js'; import { getShiftedEndDateTime } from '../input-date-time-range.js'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; const basicFixture = '<d2l-input-date-time-range label="label text"></d2l-input-date-time-range>'; const minMaxFixture = '<d2l-input-date-time-range label="Assignment Dates" min-value="2018-08-27T12:30:00Z" max-value="2018-09-30T12:30:00Z"></d2l-input-date-time-range>'; const startSelector = 'd2l-input-date-time.d2l-input-date-time-range-start'; const endSelector = 'd2l-input-date-time.d2l-input-date-time-range-end'; function dispatchEvent(elem, eventType) { const e = new Event( eventType, { bubbles: true, composed: false } ); elem.dispatchEvent(e); } function getChildElem(elem, selector) { return elem.shadowRoot.querySelector(selector); } describe('d2l-input-date-time-range', () => { const documentLocaleSettings = getDocumentLocaleSettings(); documentLocaleSettings.timezone.identifier = 'America/Toronto'; describe('constructor', () => { it('should construct', () => { runConstructor('d2l-input-date-time-range'); }); }); describe('utility', () => { ['America/Toronto', 'Australia/Eucla'].forEach((timezone) => { const inclusive = false; describe(`getShiftedEndDateTime in ${timezone}`, () => { before(async() => { documentLocaleSettings.timezone.identifier = timezone; await aTimeout(10); // Fixes flaky tests likely caused by timezone not yet being set }); after(() => { documentLocaleSettings.timezone.identifier = 'America/Toronto'; }); it('should return correctly forward shifted end date when localized without Z', () => { const prevStartValue = '2020-10-15T04:00:00.000'; const prevEnd = '2020-10-17T04:00:00.000'; const start = '2020-10-16T04:00:00.000'; const newEndValue = '2020-10-18T04:00:00.000'; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, true)).to.equal(newEndValue); }); it('should shift as expected when times are different but dates the same because of UTC', () => { let prevStartValue, start, prevEnd, newEndValue; if (timezone === 'America/Toronto') { prevStartValue = '2020-10-14T12:00:00.000Z'; prevEnd = '2020-10-15T02:00:00.000Z'; start = '2020-10-14T08:00:00.000Z'; newEndValue = '2020-10-14T22:00:00.000Z'; } else { prevStartValue = '2020-10-13T22:00:00.000Z'; prevEnd = '2020-10-14T12:00:00.000Z'; start = '2020-10-13T18:00:00.000Z'; newEndValue = '2020-10-14T08:00:00.000Z'; } expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, false)).to.equal(newEndValue); }); it('should not shift if start and end dates are different because of UTC time', () => { const prevStartValue = '2020-10-20T02:00:00.000Z'; const start = '2020-10-20T03:00:00.000Z'; let prevEnd; if (timezone === 'America/Toronto') { prevEnd = '2020-10-20T06:00:00.000Z'; } else { prevEnd = '2020-10-20T20:00:00.000Z'; } expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, false)).to.equal(prevEnd); }); }); [true, false].forEach((localized) => { describe(`getShiftedEndDateTime in ${timezone} with localized ${localized}`, () => { beforeEach(async() => { documentLocaleSettings.timezone.identifier = timezone; }); afterEach(() => { documentLocaleSettings.timezone.identifier = 'America/Toronto'; }); describe('date change', () => { it('should return correctly forward shifted end date', () => { const prevStartValue = '2020-10-15T04:00:00.000Z'; const prevEnd = '2020-10-17T04:00:00.000Z'; const start = '2020-10-16T04:00:00.000Z'; const newEndValue = `2020-10-18T04:00:00.000${localized ? '' : 'Z'}`; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, localized)).to.equal(newEndValue); }); it.skip('should return correctly backward shifted end date', () => { const prevStartValue = '2020-10-15T04:00:00.000Z'; const prevEnd = '2020-10-17T04:00:00.000Z'; const start = '2020-10-14T04:00:00.000Z'; const newEndValue = `2020-10-16T04:00:00.000${localized ? '' : 'Z'}`; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, localized)).to.equal(newEndValue); }); it('should return correctly shifted end date when initial dates were equal', () => { const prevStartValue = '2020-12-27T04:01:00.000Z'; const prevEnd = '2020-12-27T12:00:00.000Z'; const start = '2021-01-03T04:01:00.000Z'; const newEndValue = `2021-01-03T12:00:00.000${localized ? '' : 'Z'}`; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, localized)).to.equal(newEndValue); }); it('should return initial end date if prev start value was after end date', () => { const prevStartValue = '2020-10-15T04:00:00.000Z'; const prevEnd = '2020-10-12T04:00:00.000Z'; const start = '2020-10-11T04:00:00.000Z'; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, localized)).to.equal(prevEnd); }); it('should return initial end date if not inclusive and prev start value was equal to end date', () => { const prevStartValue = '2020-10-15T04:00:00.000Z'; const prevEnd = '2020-10-15T04:00:00.000Z'; const start = '2020-10-10T04:00:00.000Z'; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, localized)).to.equal(prevEnd); }); it('should return correctly shifted end date if inclusive and prev start value was equal to end date', () => { const prevStartValue = '2020-10-15T04:00:00.000Z'; const prevEnd = '2020-10-15T04:00:00.000Z'; const start = `2020-10-10T04:00:00.000${localized ? '' : 'Z'}`; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, true, localized)).to.equal(start); }); }); describe('time change', () => { it('should not shift if start and end dates are different', () => { const prevStartValue = '2020-10-10T06:00:00.000Z'; const prevEnd = '2020-10-15T06:00:00.000Z'; const start = '2020-10-10T08:00:00.000Z'; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, localized)).to.equal(prevEnd); }); it('should shift forward as expected when times are different but dates the same', () => { const prevStartValue = '2020-10-15T06:00:00.000Z'; const prevEnd = '2020-10-15T07:00:00.000Z'; const start = '2020-10-15T08:00:00.000Z'; const newEndValue = `2020-10-15T09:00:00.000${localized ? '' : 'Z'}`; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, localized)).to.equal(newEndValue); }); it('should shift backward as expected when times are different but dates the same', () => { const prevStartValue = '2020-10-15T06:00:00.000Z'; const prevEnd = '2020-10-15T07:00:00.000Z'; const start = '2020-10-15T04:00:00.000Z'; const newEndValue = `2020-10-15T05:00:00.000${localized ? '' : 'Z'}`; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, localized)).to.equal(newEndValue); }); it('should not shift when previously same and not inclusive', () => { const prevStartValue = '2020-10-15T04:00:00.000Z'; const prevEnd = '2020-10-15T04:00:00.000Z'; const start = '2020-10-15T08:00:00.000Z'; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, false, localized)).to.equal(prevEnd); }); it('should shift as expected when previously same and inclusive', () => { const prevStartValue = '2020-10-15T06:00:00.000Z'; const prevEnd = '2020-10-15T06:00:00.000Z'; const start = '2020-10-15T08:00:00.000Z'; const newEndValue = `2020-10-15T08:00:00.000${localized ? '' : 'Z'}`; expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, true, localized)).to.equal(newEndValue); }); it('should only shift at latest to 11:59 PM', () => { let prevStartValue, prevEnd, start, newEndValue; if (timezone === 'America/Toronto') { prevStartValue = '2020-10-15T06:00:00.000Z'; prevEnd = '2020-10-15T20:00:00.000Z'; start = '2020-10-15T14:00:00.000Z'; newEndValue = localized ? '2020-10-15T23:59:00.000' : '2020-10-16T03:59:00.000Z'; } else { prevStartValue = '2020-10-15T17:00:00.000Z'; prevEnd = '2020-10-15T23:00:00.000Z'; start = localized ? '2020-10-15T20:00:00.000Z' : '2020-10-16T10:15:00.000Z'; newEndValue = localized ? '2020-10-15T23:59:00.000' : '2020-10-16T15:14:00.000Z'; } expect(getShiftedEndDateTime(start, prevEnd, prevStartValue, inclusive, localized)).to.equal(newEndValue); }); }); }); }); }); }); describe('values', () => { it('should fire "change" event when start value changes', async() => { const elem = await fixture(basicFixture); const inputElem = getChildElem(elem, startSelector); inputElem.value = '2018-02-02T05:00:00.000Z'; setTimeout(() => dispatchEvent(inputElem, 'change')); await oneEvent(elem, 'change'); expect(elem.startValue).to.equal('2018-02-02T05:00:00.000Z'); }); it('should fire "change" event when end value changes', async() => { const elem = await fixture(basicFixture); const inputElem = getChildElem(elem, endSelector); inputElem.value = '2020-12-02T15:00:00.000Z'; setTimeout(() => dispatchEvent(inputElem, 'change')); await oneEvent(elem, 'change'); expect(elem.endValue).to.equal('2020-12-02T15:00:00.000Z'); }); it('should default start and end values to undefined', async() => { const elem = await fixture(basicFixture); expect(elem.startValue).to.equal(undefined); expect(elem.endValue).to.equal(undefined); }); describe('validation', () => { it('should be valid if start date and no end date', async() => { const elem = await fixture(minMaxFixture); const inputElem = getChildElem(elem, startSelector); inputElem.value = '2018-09-01T12:00:00.000Z'; setTimeout(() => dispatchEvent(inputElem, 'change')); await oneEvent(elem, 'change'); expect(elem.startValue).to.equal('2018-09-01T12:00:00.000Z'); expect(elem.invalid).to.be.false; expect(elem.validationError).to.be.null; }); it('should be valid if end date and no start date', async() => { const elem = await fixture(minMaxFixture); const inputElem = getChildElem(elem, endSelector); inputElem.value = '2018-08-27T12:31:00Z'; setTimeout(() => dispatchEvent(inputElem, 'change')); await oneEvent(elem, 'change'); expect(elem.endValue).to.equal('2018-08-27T12:31:00Z'); expect(elem.invalid).to.be.false; expect(elem.validationError).to.be.null; }); it('should be valid if start date before end date', async() => { const elem = await fixture(minMaxFixture); await updateStartEnd(elem, '2018-08-27T12:31:00Z', '2018-08-27T12:32:00Z'); expect(elem.invalid).to.be.false; expect(elem.validationError).to.be.null; }); it('should be invalid if start date equals end date', async() => { const elem = await fixture(minMaxFixture); await updateStartEnd(elem, '2018-08-27T12:32:00Z', '2018-08-27T12:32:00Z'); expect(elem.invalid).to.be.true; expect(elem.validationError).to.equal('Start Date must be before End Date'); }); it('should be invalid if start date after end date', async() => { const elem = await fixture(minMaxFixture); await updateStartEnd(elem, '2018-08-31T12:32:00Z', '2018-08-29T12:32:00Z'); expect(elem.invalid).to.be.true; expect(elem.validationError).to.equal('Start Date must be before End Date'); }); async function updateStartEnd(elem, startDate, endDate) { let firedCount = 0; elem.addEventListener('change', () => { firedCount++; }); const inputElemStart = getChildElem(elem, startSelector); inputElemStart.value = startDate; setTimeout(() => dispatchEvent(inputElemStart, 'change')); await oneEvent(elem, 'change'); expect(elem.startValue).to.equal(startDate); const inputElemEnd = getChildElem(elem, endSelector); inputElemEnd.value = endDate; setTimeout(() => dispatchEvent(inputElemEnd, 'change')); await oneEvent(inputElemEnd, 'change'); expect(elem.endValue).to.equal(endDate); await aTimeout(1); expect(firedCount).to.equal(2); } }); }); }); <|start_filename|>helpers/viewport-size.js<|end_filename|> let vh, vw; let ticking = false; function requestTick() { if (!ticking) { requestAnimationFrame(update); } ticking = true; } function update() { ticking = false; document.documentElement.style.setProperty('--d2l-vh', `${vh}px`); document.documentElement.style.setProperty('--d2l-vw', `${vw}px`); } function onResize() { vh = window.innerHeight * 0.01; vw = window.innerWidth * 0.01; requestTick(); } let installed = false; if (!installed) { installed = true; window.addEventListener('resize', onResize); } onResize(); <|start_filename|>components/alert/test/alert.axe.js<|end_filename|> import '../alert.js'; import { expect, fixture, html } from '@open-wc/testing'; describe('d2l-alert', () => { [ 'default', 'warning', 'critical', 'success', 'call-to-action', 'error' ].forEach((testCase) => { it(`passes aXe tests for type "${testCase}"`, async() => { /** * @type {'default'|'critical'|'success'|'warning'} */ const type = testCase; const el = await fixture(html`<d2l-alert type="${type}">message</d2l-alert>`); await expect(el).to.be.accessible(); }); }); }); <|start_filename|>components/alert/test/alert-toast-helper.js<|end_filename|> export async function getRect(page, selector) { const offsetTop = await page.$eval(selector, (toast) => { const elem = toast.shadowRoot.querySelector('.d2l-alert-toast-container'); return elem.offsetTop; }); return { x: 0, y: offsetTop - 10, width: page.viewport().width, height: page.viewport().height - offsetTop + 10 }; } export async function open(page, selector) { return page.$eval(selector, (toast) => toast.open = true); } <|start_filename|>components/inputs/test/input-percent.test.js<|end_filename|> import '../input-percent.js'; import { aTimeout, expect, fixture, html, oneEvent } from '@open-wc/testing'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; const normalFixture = html`<d2l-input-percent label="label"></d2l-input-percent>`; const defaultValueFixture = html`<d2l-input-percent label="label" value="80"></d2l-input-percent>`; function dispatchEvent(elem, eventType) { const e = new Event( eventType, { bubbles: true, composed: false } ); elem.dispatchEvent(e); } describe('d2l-input-percent', () => { describe('constructor', () => { it('should construct', () => { runConstructor('d2l-input-percent'); }); }); describe('events', () => { it('should not fire "change" event when property changes', async() => { const elem = await fixture(normalFixture); let fired = false; elem.addEventListener('change', () => { fired = true; }); elem.value = 10; await elem.updateComplete; expect(fired).to.be.false; elem.setAttribute('value', 15); await elem.updateComplete; expect(fired).to.be.false; }); it('should fire "change" event when underlying value changes', async() => { const elem = await fixture(defaultValueFixture); await aTimeout(1); const inputNumberElement = elem.shadowRoot.querySelector('d2l-input-number'); setTimeout(() => { inputNumberElement.value = 90; dispatchEvent(inputNumberElement, 'change'); }); await oneEvent(elem, 'change'); expect(elem.value).to.equal(90); }); it('should not fire "change" event when underlying value doesn\'t change', async() => { const elem = await fixture(defaultValueFixture); let fired = false; elem.addEventListener('change', () => { fired = true; }); const inputNumberElement = elem.shadowRoot.querySelector('d2l-input-number'); setTimeout(() => { inputNumberElement.setAttribute('value', 80); dispatchEvent(inputNumberElement, 'change'); }); await aTimeout(1); expect(fired).to.be.false; }); }); }); <|start_filename|>components/table/test/table-test-sticky-visual-diff.js<|end_filename|> import '../../../components/inputs/input-number.js'; import '../../../components/inputs/input-text.js'; import { css, html, LitElement } from 'lit-element/lit-element.js'; import { tableStyles } from '../table-wrapper.js'; const url = new URL(window.location.href); const type = url.searchParams.get('type') === 'light' ? 'light' : 'default'; class TestTableStickyVisualDiff extends LitElement { static get styles() { return [tableStyles, css` .d2l-visual-diff { margin-bottom: 300px; max-width: 600px; } `]; } render() { return html` <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="one-row-thead"> <table class="d2l-table"> <thead> <tr class="top"> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> </thead> <tbody> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr class="down"> <td>Cell 2-A</td> <td><d2l-input-text label="label" label-hidden value="Cell 2-B" input-width="100px"></d2l-input-text></td> <td class="over">Cell 2-C</td> </tr> <tr> <td>Cell 3-A</td> <td>Cell 3-B</td> <td>Cell 3-C</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="one-row-no-thead-class"> <table class="d2l-table"> <tr class="d2l-table-header top"> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr class="down"> <td>Cell 2-A</td> <td><d2l-input-text label="label" label-hidden value="Cell 2-B" input-width="100px"></d2l-input-text></td> <td class="over">Cell 2-C</td> </tr> <tr> <td>Cell 3-A</td> <td>Cell 3-B</td> <td>Cell 3-C</td> </tr> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="one-row-no-thead-attr"> <table class="d2l-table"> <tr header class="top"> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr class="down"> <td>Cell 2-A</td> <td><d2l-input-text label="label" label-hidden value="Cell 2-B" input-width="100px"></d2l-input-text></td> <td class="over">Cell 2-C</td> </tr> <tr> <td>Cell 3-A</td> <td>Cell 3-B</td> <td>Cell 3-C</td> </tr> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="multi-row-thead"> <table class="d2l-table"> <thead> <tr> <th rowspan="2" class="top">Country</th> <th colspan="5">Fruit Production (tons)</th> </tr> <tr> <th>Apples</th> <th>Oranges</th> <th>Bananas</th> <th>Peaches</th> <th>Grapes</th> </tr> </thead> <tbody> <tr> <th class="down">Canada</th> <td>356,863</td> <td>0</td> <th>0</th> <td>23,239</td> <td class="over">90,911</td> </tr> <tr> <th>Australia</th> <td>308,298</td> <td>398,610</td> <td><d2l-input-number label="label" label-hidden value="354241"></d2l-input-number></td> <td>80,807</td> <td>1,772,911</td> </tr> <tr> <th>Mexico</th> <td>716,931</td> <td>4,603,253</td> <td>2,384,778</td> <td>176,909</td> <td>351,310</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="multi-row-no-thead-class"> <table class="d2l-table"> <tr class="d2l-table-header"> <th rowspan="2" class="top">Country</th> <th colspan="5">Fruit Production (tons)</th> </tr> <tr class="d2l-table-header"> <th>Apples</th> <th>Oranges</th> <th>Bananas</th> <th>Peaches</th> <th>Grapes</th> </tr> <tr> <th class="down">Canada</th> <td>356,863</td> <td>0</td> <th>0</th> <td>23,239</td> <td class="over">90,911</td> </tr> <tr> <th>Australia</th> <td>308,298</td> <td>398,610</td> <td><d2l-input-number label="label" label-hidden value="354241"></d2l-input-number></td> <td>80,807</td> <td>1,772,911</td> </tr> <tr> <th>Mexico</th> <td>716,931</td> <td>4,603,253</td> <td>2,384,778</td> <td>176,909</td> <td>351,310</td> </tr> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="multi-row-no-thead-attr"> <table class="d2l-table"> <tr header> <th rowspan="2" class="top">Country</th> <th colspan="5">Fruit Production (tons)</th> </tr> <tr header> <th>Apples</th> <th>Oranges</th> <th>Bananas</th> <th>Peaches</th> <th>Grapes</th> </tr> <tr> <th class="down">Canada</th> <td>356,863</td> <td>0</td> <th>0</th> <td>23,239</td> <td class="over">90,911</td> </tr> <tr> <th>Australia</th> <td>308,298</td> <td>398,610</td> <td><d2l-input-number label="label" label-hidden value="354241"></d2l-input-number></td> <td>80,807</td> <td>1,772,911</td> </tr> <tr> <th>Mexico</th> <td>716,931</td> <td>4,603,253</td> <td>2,384,778</td> <td>176,909</td> <td>351,310</td> </tr> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="selected-one-row"> <table class="d2l-table"> <tr header> <th rowspan="2" style="width: 1%" class="top"><input type="checkbox"></th> <th rowspan="2">Country</th> <th colspan="5">Fruit Production (tons)</th> </tr> <tr header> <th>Apples</th> <th>Oranges</th> <th>Bananas</th> <th>Peaches</th> <th>Grapes</th> </tr> <tr> <td class="down"><input type="checkbox"></td> <th>Canada</th> <td>356,863</td> <td>0</td> <th>0</th> <td>23,239</td> <td class="over">90,911</td> </tr> <tr selected> <td><input type="checkbox" checked></td> <th>Australia</th> <td>308,298</td> <td>398,610</td> <td><d2l-input-number label="label" label-hidden value="354241"></d2l-input-number></td> <td>80,807</td> <td>1,772,911</td> </tr> <tr> <td><input type="checkbox"></td> <th>Mexico</th> <td>716,931</td> <td>4,603,253</td> <td>2,384,778</td> <td>176,909</td> <td>351,310</td> </tr> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="selected-top-bottom"> <table class="d2l-table"> <tr header> <th rowspan="2" style="width: 1%" class="top"><input type="checkbox"></th> <th rowspan="2">Country</th> <th colspan="5">Fruit Production (tons)</th> </tr> <tr header> <th>Apples</th> <th>Oranges</th> <th>Bananas</th> <th>Peaches</th> <th>Grapes</th> </tr> <tr selected> <td class="down"><input type="checkbox" checked></td> <th>Canada</th> <td>356,863</td> <td>0</td> <th>0</th> <td>23,239</td> <td class="over">90,911</td> </tr> <tr> <td><input type="checkbox"></td> <th>Australia</th> <td>308,298</td> <td>398,610</td> <td><d2l-input-number label="label" label-hidden value="354241"></d2l-input-number></td> <td>80,807</td> <td>1,772,911</td> </tr> <tr selected> <td><input type="checkbox" checked></td> <th>Mexico</th> <td>716,931</td> <td>4,603,253</td> <td>2,384,778</td> <td>176,909</td> <td>351,310</td> </tr> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="selected-all"> <table class="d2l-table"> <tr header> <th rowspan="2" style="width: 1%" class="top"><input type="checkbox"></th> <th rowspan="2">Country</th> <th colspan="5">Fruit Production (tons)</th> </tr> <tr header> <th>Apples</th> <th>Oranges</th> <th>Bananas</th> <th>Peaches</th> <th>Grapes</th> </tr> <tr selected> <td class="down"><input type="checkbox" checked></td> <th>Canada</th> <td>356,863</td> <td>0</td> <th>0</th> <td>23,239</td> <td class="over">90,911</td> </tr> <tr selected> <td><input type="checkbox" checked></td> <th>Australia</th> <td>308,298</td> <td>398,610</td> <td><d2l-input-number label="label" label-hidden value="354241"></d2l-input-number></td> <td>80,807</td> <td>1,772,911</td> </tr> <tr selected> <td><input type="checkbox" checked></td> <th>Mexico</th> <td>716,931</td> <td>4,603,253</td> <td>2,384,778</td> <td>176,909</td> <td>351,310</td> </tr> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="fixed-column-class"> <table class="d2l-table"> <thead> <tr> <th rowspan="2" style="width: 1%" class="top"><input type="checkbox"></th> <th rowspan="2" class="d2l-table-sticky-cell">Country</th> <th colspan="5">Fruit Production (tons)</th> </tr> <tr> <th>Apples</th> <th>Oranges</th> <th>Bananas</th> <th>Peaches</th> <th>Grapes</th> </tr> </thead> <tbody> <tr> <td class="down"><input type="checkbox"></td> <th class="d2l-table-sticky-cell">Canada</th> <td>356,863</td> <td>0</td> <th>0</th> <td>23,239</td> <td class="over">90,911</td> </tr> <tr selected> <td><input type="checkbox" checked></td> <th class="d2l-table-sticky-cell">Australia</th> <td><d2l-input-number label="label" label-hidden value="308298"></d2l-input-number></td> <td>398,610</td> <td>354,241</td> <td>80,807</td> <td>1,772,911</td> </tr> <tr> <td><input type="checkbox"></td> <th class="d2l-table-sticky-cell">Mexico</th> <td>716,931</td> <td>4,603,253</td> <td>2,384,778</td> <td>176,909</td> <td>351,310</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="fixed-column-attr"> <table class="d2l-table"> <thead> <tr> <th rowspan="2" style="width: 1%" class="top"><input type="checkbox"></th> <th rowspan="2" sticky>Country</th> <th colspan="5">Fruit Production (tons)</th> </tr> <tr> <th>Apples</th> <th>Oranges</th> <th>Bananas</th> <th>Peaches</th> <th>Grapes</th> </tr> </thead> <tbody> <tr> <td class="down"><input type="checkbox"></td> <th sticky>Canada</th> <td>356,863</td> <td>0</td> <th>0</th> <td>23,239</td> <td class="over">90,911</td> </tr> <tr selected> <td><input type="checkbox" checked></td> <th sticky>Australia</th> <td><d2l-input-number label="label" label-hidden value="308298"></d2l-input-number></td> <td>398,610</td> <td>354,241</td> <td>80,807</td> <td>1,772,911</td> </tr> <tr> <td><input type="checkbox"></td> <th sticky>Mexico</th> <td>716,931</td> <td>4,603,253</td> <td>2,384,778</td> <td>176,909</td> <td>351,310</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" sticky-headers id="one-column"> <table class="d2l-table"> <thead> <tr class="top"> <th>Header A</th> </tr> </thead> <tbody> <tr class="down over"> <td>Cell 1-A</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> `; } } customElements.define('d2l-test-table-sticky-visual-diff', TestTableStickyVisualDiff); <|start_filename|>components/skeleton/demo/skeleton-test-box.js<|end_filename|> import '../../colors/colors.js'; import { css, html, LitElement } from 'lit-element/lit-element.js'; import { SkeletonMixin } from '../skeleton-mixin.js'; export class SkeletonTestBox extends SkeletonMixin(LitElement) { static get styles() { return [ super.styles, css` :host { display: block; } .d2l-demo-box { background-color: var(--d2l-color-fluorite-plus-2); border: 1px solid var(--d2l-color-fluorite); border-radius: 4px; color: var(--d2l-color-fluorite); height: 100px; padding: 10px; width: 300px; } ` ]; } render() { return html` <div class="d2l-demo-box d2l-skeletize">Bordered Box</div> `; } } customElements.define('d2l-test-skeleton-box', SkeletonTestBox); <|start_filename|>components/skeleton/demo/skeleton-test-heading.js<|end_filename|> import { css, html, LitElement } from 'lit-element/lit-element.js'; import { heading1Styles, heading2Styles, heading3Styles, heading4Styles } from '../../typography/styles.js'; import { SkeletonMixin } from '../skeleton-mixin.js'; export class SkeletonTestHeading extends SkeletonMixin(LitElement) { static get properties() { return { level: { type: Number }, width: { type: Number } }; } static get styles() { return [ super.styles, heading1Styles, heading2Styles, heading3Styles, heading4Styles, css` :host { display: block; } ` ]; } render() { const width = this.width !== undefined ? ` d2l-skeletize-${this.width}` : ''; if (this.level === 1) { return html`<h1 class="d2l-heading-1 d2l-skeletize${width}"><slot></slot></h1>`; } else if (this.level === 2) { return html`<h2 class="d2l-heading-2 d2l-skeletize${width}"><slot></slot></h2>`; } else if (this.level === 3) { return html`<h3 class="d2l-heading-3 d2l-skeletize${width}"><slot></slot></h3>`; } else if (this.level === 4) { return html`<h4 class="d2l-heading-4 d2l-skeletize${width}"><slot></slot></h4>`; } } } customElements.define('d2l-test-skeleton-heading', SkeletonTestHeading); <|start_filename|>components/menu/test/menu-item-mixin.test.js<|end_filename|> import { defineCE, expect, fixture, oneEvent } from '@open-wc/testing'; import { LitElement } from 'lit-element/lit-element.js'; import { MenuItemMixin } from '../menu-item-mixin.js'; const tag = defineCE( class extends MenuItemMixin(LitElement) {} ); function dispatchKeyEvent(elem, key) { const eventObj = document.createEvent('Events'); eventObj.initEvent('keydown', true, true); eventObj.keyCode = key; elem.dispatchEvent(eventObj); } describe('MenuItemMixin', () => { let elem; beforeEach(async() => { elem = await fixture(`<${tag} id="my-menu-item"></${tag}>`); }); describe('accessibility', () => { it('has role="menuitem"', () => { expect(elem.getAttribute('role')).to.equal('menuitem'); }); it('adds aria-disabled to disabled menu item', async() => { const disabledElem = await fixture(`<${tag} id="my-menu-item-disabled" disabled></${tag}>`); expect(disabledElem.getAttribute('aria-disabled')).to.equal('true'); }); it('adds aria-label to menu items', async() => { const elem = await fixture(`<${tag} id="my-menu-item" text="menu-item"></${tag}>`); expect(elem.getAttribute('aria-label')).to.equal('menu-item'); }); it('overrides aria-label with description text', async() => { const elem = await fixture(`<${tag} id="my-menu-item" text="menu-item" description="description-text"></${tag}>`); expect(elem.getAttribute('aria-label')).to.equal('description-text'); }); }); describe('events', () => { it('dispatches "d2l-menu-item-select" event when item clicked', async() => { setTimeout(() => elem.click()); const { target } = await oneEvent(elem, 'd2l-menu-item-select'); expect(target.id).to.equal('my-menu-item'); }); it('dispatches "d2l-menu-item-select" event when enter key pressed on item', async() => { setTimeout(() => dispatchKeyEvent(elem, 13)); const { target } = await oneEvent(elem, 'd2l-menu-item-select'); expect(target.id).to.equal('my-menu-item'); }); it('dispatches "d2l-menu-item-select" event when space key pressed on item', async() => { setTimeout(() => dispatchKeyEvent(elem, 32)); const { target } = await oneEvent(elem, 'd2l-menu-item-select'); expect(target.id).to.equal('my-menu-item'); }); it('does not dispatch select event for disabled item', async() => { elem.disabled = true; await elem.updateComplete; let dispatched = false; elem.addEventListener('d2l-menu-item-select', () => dispatched = true); elem.click(); expect(dispatched).to.be.false; }); }); }); <|start_filename|>components/card/card-content-meta.js<|end_filename|> import '../colors/colors.js'; import { css, html, LitElement } from 'lit-element/lit-element.js'; /** * A helper for providing layout/style for meta data within the `content` slot. * @slot - Slot for meta data text */ class CardContentMeta extends LitElement { static get styles() { return css` :host { box-sizing: border-box; color: var(--d2l-color-tungsten); display: inline-block; font-size: 0.7rem; font-weight: 400; line-height: 1rem; } :host span { display: inline-block; /* extra inline-block helps reset display context to opt-out of underline */ } `; } render() { return html`<span><slot></slot></span>`; } } customElements.define('d2l-card-content-meta', CardContentMeta); <|start_filename|>helpers/dateTime.js<|end_filename|> import { convertLocalToUTCDateTime, convertUTCToLocalDateTime, getDateTimeDescriptor } from '@brightspace-ui/intl/lib/dateTime.js'; // val is an object containing year, month, date export function formatDateInISO(val) { if (!val || !Object.prototype.hasOwnProperty.call(val, 'year') || !Object.prototype.hasOwnProperty.call(val, 'month') || !Object.prototype.hasOwnProperty.call(val, 'date') ) { throw new Error('Invalid input: Expected input to be object containing year, month, and date'); } let month = val.month, date = val.date; if (val.month.toString().length < 2) month = `0${month}`; if (val.date.toString().length < 2) date = `0${date}`; return `${val.year}-${month}-${date}`; } // val is an object containing year, month, date, hours, minutes, seconds // if local is true, no Z since not in UTC export function formatDateTimeInISO(val, local) { if (!val) { throw new Error('Invalid input: Expected input to be an object'); } return `${formatDateInISO({ year: val.year, month: val.month, date: val.date })}T${formatTimeInISO({ hours: val.hours, minutes: val.minutes, seconds: val.seconds })}.000${local ? '' : 'Z'}`; } // val is an object containing hours, minutes, seconds export function formatTimeInISO(val) { if (!val || !Object.prototype.hasOwnProperty.call(val, 'hours') || !Object.prototype.hasOwnProperty.call(val, 'minutes') || !Object.prototype.hasOwnProperty.call(val, 'seconds') ) { throw new Error('Invalid input: Expected input to be object containing hours, minutes, and seconds'); } let hours = val.hours, minutes = val.minutes, seconds = val.seconds; if (hours.toString().length < 2) hours = `0${hours}`; if (minutes.toString().length < 2) minutes = `0${minutes}`; if (seconds.toString().length < 2) seconds = `0${seconds}`; return `${hours}:${minutes}:${seconds}`; } export function formatDateInISOTime(val) { let hours = val.getHours(), minutes = val.getMinutes(), seconds = val.getSeconds(); if (hours.toString().length < 2) hours = `0${hours}`; if (minutes.toString().length < 2) minutes = `0${minutes}`; if (seconds.toString().length < 2) seconds = `0${seconds}`; return `${hours}:${minutes}:${seconds}`; } export function getAdjustedTime(startObj, prevStartObj, endObj) { const hourDiff = startObj.hours - prevStartObj.hours; const minuteDiff = startObj.minutes - prevStartObj.minutes; let newEndHour = endObj.hours + hourDiff; let newEndMinute = endObj.minutes + minuteDiff; if (newEndMinute > 59) { newEndHour++; newEndMinute -= 60; } else if (newEndMinute < 0) { newEndHour--; newEndMinute += 60; } if (newEndHour > 23) { newEndHour = 23; newEndMinute = 59; } else if (newEndHour < 0) { newEndHour = 0; newEndMinute = 0; } return { hours: newEndHour, minutes: newEndMinute }; } export function getClosestValidDate(minValue, maxValue, dateTime) { const today = getToday(); const todayDate = getDateFromDateObj(today); const todayOutput = dateTime ? formatDateTimeInISO(convertLocalToUTCDateTime(today)) : formatDateInISO(today); const minDate = dateTime ? getDateFromISODateTime(minValue) : getDateFromISODate(minValue); const maxDate = dateTime ? getDateFromISODateTime(maxValue) : getDateFromISODate(maxValue); if (minValue && maxValue) { if (isDateInRange(todayDate, minDate, maxDate)) return todayOutput; else { const diffToMin = Math.abs(todayDate.getTime() - minDate.getTime()); const diffToMax = Math.abs(todayDate.getTime() - maxDate.getTime()); if (diffToMin < diffToMax) return minValue; else return maxValue; } } else if (minValue) { if (isDateInRange(todayDate, minDate, undefined)) return todayOutput; else return minValue; } else if (maxValue) { if (isDateInRange(todayDate, undefined, maxDate)) return todayOutput; else return maxValue; } else return todayOutput; } export function getDateFromDateObj(val) { return new Date(val.year, parseInt(val.month) - 1, val.date); } export function getDateFromISODate(val) { if (!val) return null; const date = parseISODate(val); return getDateFromDateObj(date); } export function getDateFromISODateTime(val) { if (!val) return null; const parsed = parseISODateTime(val); const localDateTime = convertUTCToLocalDateTime(parsed); return new Date(localDateTime.year, localDateTime.month - 1, localDateTime.date, localDateTime.hours, localDateTime.minutes, localDateTime.seconds); } export function getDateFromISOTime(val) { if (!val) return null; const time = parseISOTime(val); const today = getToday(); return new Date(today.year, today.month - 1, today.date, time.hours, time.minutes, time.seconds); } export function getDateNoConversion(value) { const parsed = parseISODateTime(value); return new Date(parsed.year, parsed.month - 1, parsed.date, parsed.hours, parsed.minutes, parsed.seconds); } let dateTimeDescriptor = null; export function getDateTimeDescriptorShared(refresh) { if (!dateTimeDescriptor || refresh) dateTimeDescriptor = getDateTimeDescriptor(); return dateTimeDescriptor; } export function getLocalDateTimeFromUTCDateTime(dateTime) { const dateObj = parseISODateTime(dateTime); const localDateTime = convertUTCToLocalDateTime(dateObj); return formatDateTimeInISO(localDateTime, true); } export function getToday() { const val = new Date().toISOString(); const dateTime = parseISODateTime(val); return convertUTCToLocalDateTime(dateTime); } export function getUTCDateTimeFromLocalDateTime(date, time) { if (!date || !time) throw new Error('Invalid input: Expected date and time'); const dateObj = parseISODate(date); const timeObj = parseISOTime(time); const utcDateTime = convertLocalToUTCDateTime(Object.assign(dateObj, timeObj)); return formatDateTimeInISO(utcDateTime); } export function isDateInRange(date, min, max) { if (!date) return false; const afterMin = !min || (min && date.getTime() >= min.getTime()); const beforeMax = !max || (max && date.getTime() <= max.getTime()); return afterMin && beforeMax; } export function isValidTime(val) { const re = /([0-9]{1,2}):([0-9]{1,2})(:([0-9]{1,2}))?/; const match = val.match(re); return match !== null; } export function parseISODate(val) { if (!val) return null; const re = /([0-9]{4})-([0-9]{2})-([0-9]{2})/; const match = val.match(re); if (!match || match.length !== 4) { throw new Error('Invalid input: Expected format is YYYY-MM-DD'); } return { year: parseInt(match[1]), month: parseInt(match[2]), // month starts at 1 date: parseInt(match[3]) }; } export function parseISODateTime(val) { if (!val) return null; const re = /([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})/; const match = val.match(re); if (!match || match.length !== 7) { throw new Error('Invalid input: Expected format is YYYY-MM-DDTHH:mm:ss.sssZ'); } return { year: parseInt(match[1]), month: parseInt(match[2]), // month starts at 1 date: parseInt(match[3]), hours: parseInt(match[4]), minutes: parseInt(match[5]), seconds: parseInt(match[6]) }; } export function parseISOTime(val) { let hours = 0; let minutes = 0; let seconds = 0; const re = /([0-9]{1,2}):([0-9]{1,2})(:([0-9]{1,2}))?/; const match = val.match(re); if (match === null) { throw new Error('Invalid input: Expected format is hh:mm:ss'); } if (match.length > 1) { hours = parseInt(match[1]); if (isNaN(hours) || hours < 0 || hours > 23) { hours = 0; } } if (match.length > 2) { minutes = parseInt(match[2]); if (isNaN(minutes) || minutes < 0 || minutes > 59) { minutes = 0; } } if (match.length > 3) { seconds = parseInt(match[4]); if (isNaN(seconds) || seconds < 0 || seconds > 59) { seconds = 0; } } return { hours: hours, minutes: minutes, seconds: seconds }; } <|start_filename|>components/button/test/button-icon.axe.js<|end_filename|> import '../button-icon.js'; import { expect, fixture, html, oneEvent } from '@open-wc/testing'; describe('d2l-button-icon', () => { it('normal', async() => { const el = await fixture(html`<d2l-button-icon icon="tier1:gear" text="Icon Button"></d2l-button-icon>`); await expect(el).to.be.accessible(); }); it('disabled', async() => { const el = await fixture(html`<d2l-button-icon disabled icon="tier1:gear" text="Icon Button"></d2l-button-icon>`); await expect(el).to.be.accessible(); }); it('disabled-tooltip', async() => { const el = await fixture(html`<d2l-button-icon disabled disabled-tooltip="tooltip text" icon="tier1:gear" text="Icon Button"></d2l-button-icon>`); await expect(el).to.be.accessible(); }); it('focused', async() => { const el = await fixture(html`<d2l-button-icon icon="tier1:gear" text="Icon Button"></d2l-button-icon>`); setTimeout(() => el.shadowRoot.querySelector('button').focus()); await oneEvent(el, 'focus'); await expect(el).to.be.accessible(); }); }); <|start_filename|>components/form/test/form.test.js<|end_filename|> import '../../validation/validation-custom.js'; import '../form.js'; import './form-element.js'; import './nested-form.js'; import { expect, fixture } from '@open-wc/testing'; import { html } from 'lit-element/lit-element.js'; describe('d2l-form', () => { const _validateCheckbox = e => { e.detail.resolve(e.detail.forElement.checked); }; describe('single form', () => { const formFixture = html` <d2l-form> <d2l-validation-custom for="mycheck" @d2l-validation-custom-validate=${_validateCheckbox} failure-text="The checkbox failed validation" > </d2l-validation-custom> <input type="checkbox" id="mycheck" name="checkers" value="red-black"> <input type="file" name="optional-file"> <select aria-label="Pets" name="pets" id="pets" required> <option value="">--Please choose an option--</option> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="hamster">Hamster</option> <option value="parrot">Parrot</option> <option value="spider">Spider</option> <option value="goldfish">Goldfish</option> </select> <input type="radio" id="myradio" name="optional-radio"> <d2l-test-form-element id="custom-ele"></d2l-test-form-element> </d2l-form> `; let form; beforeEach(async() => { form = await fixture(formFixture); }); describe('validate', () => { it('should validate validation-customs', async() => { const errors = await form.validate(); const ele = form.querySelector('#mycheck'); expect(errors.get(ele)).to.include.members(['The checkbox failed validation']); }); it('should validate native form elements', async() => { const errors = await form.validate(); const ele = form.querySelector('#pets'); expect(errors.get(ele)).to.include.members(['Pets is required.']); }); it('should validate custom form elements', async() => { const formElement = form.querySelector('#custom-ele'); formElement.value = 'Non-empty'; formElement.setValidity({ rangeOverflow: true }); const errors = await form.validate(); expect(errors.get(formElement)).to.include.members(['Test form element failed with an overridden validation message']); }); }); describe('submit', () => { it('should not submit if there are errors', async() => { let submitted = false; form.addEventListener('d2l-form-submit', () => submitted = true); await form.submit(); expect(submitted).to.be.false; }); it('should submit with form values', done => { const mycheck = form.querySelector('#mycheck'); mycheck.checked = true; const pets = form.querySelector('#pets > option:nth-child(4)'); pets.selected = true; const formElement = form.querySelector('#custom-ele'); formElement.value = 'Non-empty'; formElement.formValue = { 'key-1': 'val-1', 'key-2': 'val-2' }; const myradio = form.querySelector('#myradio'); myradio.checked = true; form.addEventListener('d2l-form-submit', (e) => { e.preventDefault(); const { formData } = e.detail; expect(formData.checkers).to.equal('red-black'); expect(formData.pets).to.equal('hamster'); expect(formData['key-1']).to.equal('val-1'); expect(formData['key-2']).to.equal('val-2'); expect(formData['optional-file']).to.be.empty; expect(formData['optional-radio']).to.equal('on'); done(); }); form.submit(); }); }); }); describe('nested form', () => { const _validateStory = e => { e.detail.resolve(e.detail.forElement.value === 'The PERFECT story'); }; const rootFormFixture = html` <d2l-form> <d2l-validation-custom for="mycheck" @d2l-validation-custom-validate=${_validateCheckbox} failure-text="The checkbox failed validation" > </d2l-validation-custom> <input type="checkbox" id="mycheck" name="checkers" value="red-black"> <div> <d2l-form id="nested-form"> <select aria-label="Home planet" name="home-planet" id="nested-home-planet" required> <option value="">--Please choose an option--</option> <option value="earth">Earth</option> <option value="other">Other</option> </select> <label>Story<input type="text" id="nested-story" name="story"></label> <d2l-validation-custom for="nested-story" @d2l-validation-custom-validate=${_validateStory} failure-text="Wrong story" > </d2l-validation-custom> <d2l-test-form-element id="nested-custom-ele"></d2l-test-form-element> </d2l-form> </div> <select aria-label="Pets" name="pets" id="pets" required> <option value="">--Please choose an option--</option> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="hamster">Hamster</option> <option value="parrot">Parrot</option> <option value="spider">Spider</option> <option value="goldfish">Goldfish</option> </select> <d2l-test-nested-form id="composed-nested-form"></d2l-test-nested-form> <input type="radio" id="myradio" name="optional-radio"> <d2l-test-form-element id="custom-ele"></d2l-test-form-element> </d2l-form> `; let form; beforeEach(async() => { form = await fixture(rootFormFixture); }); const fillForm = () => { const mycheck = form.querySelector('#mycheck'); mycheck.checked = true; const pets = form.querySelector('#pets > option:nth-child(4)'); pets.selected = true; const formElement = form.querySelector('#custom-ele'); formElement.value = 'Non-empty'; formElement.formValue = { 'key-1': 'val-1', 'key-2': 'val-2' }; const myradio = form.querySelector('#myradio'); myradio.checked = true; }; const fillNestedForm = () => { const nestedFormEle = form.querySelector('#nested-form'); const homePlanet = nestedFormEle.querySelector('#nested-home-planet > option:nth-child(2)'); homePlanet.selected = true; const story = nestedFormEle.querySelector('#nested-story'); story.value = 'The PERFECT story'; const formElement = nestedFormEle.querySelector('#nested-custom-ele'); formElement.value = 'Non-empty'; formElement.formValue = { 'nested-key-1': 'nested-val-1', 'nested-key-2': 'nested-val-2' }; }; describe('validate', () => { [ { noDirectNesting: false, noComposedNesting: false }, { noDirectNesting: true, noComposedNesting: false }, { noDirectNesting: false, noComposedNesting: true }, ].forEach(({ noDirectNesting, noComposedNesting }) => { it(`should validate nested forms in tree order with${noDirectNesting ? ' no ' : ' '}direct nesting and${noComposedNesting ? ' no ' : ' '}composed nesting`, async() => { const formElement = form.querySelector('#custom-ele'); formElement.value = 'Non-empty'; formElement.setValidity({ rangeOverflow: true }); const nestedFormEle = form.querySelector('#nested-form'); nestedFormEle.noNesting = noDirectNesting; const composedNestedFormEle = form.querySelector('#composed-nested-form'); composedNestedFormEle.noNesting = noComposedNesting; const expectedErrors = [ [form.querySelector('#mycheck'), ['The checkbox failed validation']], ...(nestedFormEle.noNesting ? [] : [ [nestedFormEle.querySelector('#nested-home-planet'), ['Home planet is required.']], [nestedFormEle.querySelector('#nested-story'), ['Wrong story']], [nestedFormEle.querySelector('#nested-custom-ele'), ['Test form element is required.']], ]), [form.querySelector('#pets'), ['Pets is required.']], ...(composedNestedFormEle.noNesting ? [] : [ [composedNestedFormEle.shadowRoot.querySelector('#composed-nested-first-name'), ['First Name is required.']], [composedNestedFormEle.shadowRoot.querySelector('#composed-nested-pets'), ['Expected Hamster']], [composedNestedFormEle.shadowRoot.querySelector('#composed-nested-custom-ele'), ['Test form element is required.']], ]), [formElement, ['Test form element failed with an overridden validation message']] ]; const errors = await form.validate(); const actualErrors = [...errors.entries()]; expect(actualErrors).to.deep.equal(expectedErrors); }); }); }); describe('submit', () => { [ { noDirectNesting: false, noComposedNesting: false }, { noDirectNesting: true, noComposedNesting: false }, { noDirectNesting: false, noComposedNesting: true }, ].forEach(({ noDirectNesting, noComposedNesting }) => { it(`should not submit if there are errors in a nested form with${noDirectNesting ? ' no ' : ' '}direct nesting and${noComposedNesting ? ' no ' : ' '}composed nesting`, async() => { fillForm(); const nestedForm = form.querySelector('#nested-form'); nestedForm.noNesting = noDirectNesting; const composedNestedFormEle = form.querySelector('#composed-nested-form'); const composedNestedForm = composedNestedFormEle.shadowRoot.querySelector('d2l-form'); composedNestedForm.noNesting = noComposedNesting; let submitted = false; form.addEventListener('d2l-form-submit', () => submitted = true); nestedForm.addEventListener('d2l-form-submit', () => submitted = true); composedNestedForm.addEventListener('d2l-form-submit', () => submitted = true); await form.submit(); expect(submitted).to.be.false; }); }); [ { noDirectNesting: false, noComposedNesting: false }, { noDirectNesting: true, noComposedNesting: false }, { noDirectNesting: false, noComposedNesting: true }, ].forEach(({ noDirectNesting, noComposedNesting }) => { it(`should submit all forms with form values with${noDirectNesting ? ' no ' : ' '}direct nesting and${noComposedNesting ? ' no ' : ' '}composed nesting`, async() => { const nestedForm = form.querySelector('#nested-form'); nestedForm.noNesting = noDirectNesting; const composedNestedFormEle = form.querySelector('#composed-nested-form'); const composedNestedForm = composedNestedFormEle.shadowRoot.querySelector('d2l-form'); composedNestedFormEle.noNesting = noComposedNesting; if (!noDirectNesting) { fillNestedForm(); } if (!noComposedNesting) { composedNestedFormEle.fill(); } fillForm(); const formPromise = new Promise(resolve => { form.addEventListener('d2l-form-submit', (e) => { const expectedFormData = { 'checkers': 'red-black', 'pets': 'hamster', 'optional-radio': 'on', 'key-1': 'val-1', 'key-2': 'val-2' }; const { formData } = e.detail; expect(formData).to.deep.equal(expectedFormData); resolve(); }); }); const nestedFormPromise = new Promise(resolve => { if (noDirectNesting) { resolve(); } nestedForm.addEventListener('d2l-form-submit', (e) => { const expectedFormData = { 'home-planet': 'earth', 'story': 'The PERFECT story', 'nested-key-1': 'nested-val-1', 'nested-key-2': 'nested-val-2', }; const { formData } = e.detail; expect(formData).to.deep.equal(expectedFormData); resolve(); }); }); const composedNestedFormPromise = new Promise(resolve => { if (noComposedNesting) { resolve(); } composedNestedForm.addEventListener('d2l-form-submit', (e) => { const expectedFormData = { 'first-name': '<NAME>', 'pets': 'hamster', 'composed-nested-key-1': 'val-1', 'composed-nested-key-2': 'val-2' }; const { formData } = e.detail; expect(formData).to.deep.equal(expectedFormData); resolve(); }); }); form.submit(); await Promise.all([formPromise, nestedFormPromise, composedNestedFormPromise]); }); }); }); }); }); <|start_filename|>components/table/test/table.test.js<|end_filename|> import '../table-wrapper.js'; import { expect, fixture, html } from '@open-wc/testing'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-table-wrapper', () => { describe('constructor', () => { it('should construct', () => { runConstructor('d2l-table-wrapper'); }); }); describe('body class', () => { afterEach(() => { document.body.classList.remove('d2l-table-sticky-headers'); }); it('should add class to body when sticky', async() => { await fixture(html`<d2l-table-wrapper sticky-headers></d2l-table-wrapper>`); expect(document.body.classList.contains('d2l-table-sticky-headers')).to.be.true; }); it('should not add class to body when not sticky', async() => { await fixture(html`<d2l-table-wrapper></d2l-table-wrapper>`); expect(document.body.classList.contains('d2l-table-sticky-headers')).to.be.false; }); }); }); <|start_filename|>components/inputs/input-styles.js<|end_filename|> import '../colors/colors.js'; import { css } from 'lit-element/lit-element.js'; export const inputStyles = css` .d2l-input { background-color: var(--d2l-input-background-color, #ffffff); border-radius: var(--d2l-input-border-radius, 0.3rem); border-style: solid; box-shadow: inset 0 2px 0 0 rgba(181, 189, 194, 0.2); /* corundum */ box-sizing: border-box; color: var(--d2l-color-ferrite); display: inline-block; font-family: inherit; font-size: 0.8rem; font-weight: 400; height: var(--d2l-input-height, auto); letter-spacing: 0.02rem; line-height: 1.2rem; /* using min-height AND line-height as IE11 doesn't support line-height on inputs */ margin: 0; min-height: calc(2rem + 2px); min-width: calc(2rem + 1em); position: var(--d2l-input-position, relative); /* overridden by sticky headers in grades */ text-align: var(--d2l-input-text-align, start); vertical-align: middle; width: 100%; } .d2l-input, .d2l-input:hover:disabled, .d2l-input:focus:disabled, [aria-invalid="true"].d2l-input:disabled { border-color: var(--d2l-input-border-color, var(--d2l-color-galena)); border-width: 1px; padding: var(--d2l-input-padding, 0.4rem 0.75rem); } .d2l-input::placeholder { color: var(--d2l-color-mica); font-size: 0.8rem; font-weight: 400; opacity: 1; /* Firefox has non-1 default */ } .d2l-input::-ms-input-placeholder { color: var(--d2l-color-mica); font-size: 0.8rem; font-weight: 400; } .d2l-input:hover, .d2l-input:focus, .d2l-input-focus { border-color: var(--d2l-color-celestine); border-width: 2px; outline-style: none; outline-width: 0; padding: var(--d2l-input-padding-focus, calc(0.4rem - 1px) calc(0.75rem - 1px)); } [aria-invalid="true"].d2l-input { border-color: var(--d2l-color-cinnabar); } .d2l-input:disabled { opacity: 0.5; } .d2l-input::-webkit-search-cancel-button, .d2l-input::-webkit-search-decoration { display: none; } .d2l-input::-ms-clear { display: none; height: 0; width: 0; } textarea.d2l-input { line-height: normal; } textarea.d2l-input, textarea.d2l-input:hover:disabled, textarea.d2l-input:focus:disabled, textarea[aria-invalid="true"].d2l-input:disabled { padding-bottom: 0.5rem; padding-top: 0.5rem; } textarea.d2l-input:hover, textarea.d2l-input:focus { padding: var(--d2l-input-padding-focus, calc(0.75rem - 1px)); padding-bottom: calc(0.5rem - 1px); padding-top: calc(0.5rem - 1px); } textarea.d2l-input[aria-invalid="true"] { background-image: url("data:image/svg+xml;base64,PH<KEY> background-position: top 12px right 18px; background-repeat: no-repeat; background-size: 0.8rem 0.8rem; padding-right: calc(18px + 0.8rem); } textarea.d2l-input[aria-invalid="true"]:hover, textarea.d2l-input[aria-invalid="true"]:focus { background-position: top calc(12px - 1px) right calc(18px - 1px); padding-right: calc(18px + 0.8rem - 1px); } :host([dir='rtl']) textarea.d2l-input[aria-invalid="true"] { background-position: top 12px left 18px; padding: var(--d2l-input-padding, 0.75rem); padding-bottom: 0.5rem; padding-left: calc(18px + 0.8rem); padding-top: 0.5rem; } :host([dir='rtl']) textarea.d2l-input[aria-invalid="true"]:focus, :host([dir='rtl']) textarea.d2l-input[aria-invalid="true"]:hover { background-position: top calc(12px - 1px) left calc(18px - 1px); padding: var(--d2l-input-padding-focus, calc(0.75rem - 1px)); padding-bottom: calc(0.5rem - 1px); padding-left: calc(18px + 0.8rem - 1px); padding-top: calc(0.5rem - 1px); } textarea[aria-invalid="true"].d2l-input:disabled { background-image: none; } `; <|start_filename|>components/list/list-item-content.js<|end_filename|> import '../colors/colors.js'; import { bodyCompactStyles, bodySmallStyles } from '../typography/styles.js'; import { css, html, LitElement } from 'lit-element/lit-element.js'; /** * A component for consistent layout of primary and secondary text in a list item. * @slot - Primary text of the list item * @slot secondary - Secondary text of the list item * @slot supporting-info - Information that supports the list item */ class ListItemContent extends LitElement { static get styles() { return [ bodySmallStyles, bodyCompactStyles, css` :host { overflow-x: hidden; } .d2l-list-item-content-text { color: var(--d2l-list-item-content-text-color); margin: 0; overflow: hidden; text-decoration: var(--d2l-list-item-content-text-decoration, none); } .d2l-list-item-content-text-secondary { color: var(--d2l-list-item-content-text-secondary-color, var(--d2l-color-tungsten)); margin: 0; margin-top: 0.15rem; overflow: hidden; } .d2l-list-item-content-text-supporting-info { color: var(--d2l-color-ferrite); margin: 0; margin-top: 0.15rem; overflow: hidden; } `]; } render() { return html` <div class="d2l-list-item-content-text d2l-body-compact"><slot></slot></div> <div class="d2l-list-item-content-text-secondary d2l-body-small"><slot name="secondary"></slot></div> <div class="d2l-list-item-content-text-supporting-info d2l-body-small"><slot name="supporting-info"></slot></div> `; } } customElements.define('d2l-list-item-content', ListItemContent); <|start_filename|>components/menu/demo/custom-menu-item.js<|end_filename|> import { css, html, LitElement } from 'lit-element/lit-element.js'; import { MenuItemMixin } from '../menu-item-mixin.js'; import { menuItemStyles } from '../menu-item-styles.js'; class CustomMenuItem extends MenuItemMixin(LitElement) { static get properties() { return { text: { type: String } }; } static get styles() { return [ menuItemStyles, css` :host { padding: 0.75rem 1.5rem; } :host(:hover) .d2l-menu-item-text, :host(:focus) .d2l-menu-item-text { -webkit-transform: rotateY(360deg); transform: rotateY(360deg); transition: transform 2s; } ` ]; } render() { return html` <div class="d2l-menu-item-text">${this.text}</div> <slot></slot> `; } } customElements.define('d2l-custom-menu-item', CustomMenuItem); <|start_filename|>components/card/card-content-title.js<|end_filename|> import { css, html, LitElement } from 'lit-element/lit-element.js'; /** * A helper for providing layout/style for a title within the `content` slot. * @slot - Slot for title text */ class CardContentTitle extends LitElement { static get styles() { return css` :host { box-sizing: border-box; display: block; font-size: 0.95rem; font-weight: 400; line-height: 1.4rem; } `; } render() { return html`<slot></slot>`; } } customElements.define('d2l-card-content-title', CardContentTitle); <|start_filename|>components/form/form-helper.js<|end_filename|> import { cssEscape } from '../../helpers/dom.js'; const formElements = { button: true, fieldset: true, input: true, object: true, output: true, select: true, textarea: true }; export const isElement = (node) => node && node.nodeType === Node.ELEMENT_NODE; export const isCustomElement = (node) => isElement(node) && node.nodeName.indexOf('-') !== -1; export const isCustomFormElement = (node) => isCustomElement(node) && !!node.formAssociated; export const isNativeFormElement = (node) => { if (!isElement(node)) { return false; } const nodeName = node.nodeName.toLowerCase(); return !!formElements[nodeName]; }; const _findFormElementsHelper = (ele, eles, isFormElementPredicate, visitChildrenPredicate) => { if (isNativeFormElement(ele) || isCustomFormElement(ele) || isFormElementPredicate(ele)) { eles.push(ele); } if (visitChildrenPredicate(ele)) { for (const child of ele.children) { _findFormElementsHelper(child, eles, isFormElementPredicate, visitChildrenPredicate); } } }; export const findFormElements = (root, isFormElementPredicate = () => false, visitChildrenPredicate = () => true) => { const eles = []; _findFormElementsHelper(root, eles, isFormElementPredicate, visitChildrenPredicate); return eles; }; const _tryGetLabelElement = ele => { if (ele.labels && ele.labels.length > 0) { return ele.labels[0]; } const rootNode = ele.getRootNode(); if (!rootNode || rootNode === document) { return null; } const parent = ele.parentElement; if (parent && ele.parentElement.tagName === 'LABEL') { return parent; } if (ele.id) { const rootNode = ele.getRootNode(); return rootNode.querySelector(`label[for="${cssEscape(ele.id)}"]`); } return null; }; export const tryGetLabelText = (ele) => { const labelElement = _tryGetLabelElement(ele); if (labelElement) { const labelText = [...labelElement.childNodes] .filter(node => node.nodeType === Node.TEXT_NODE) .reduce((acc, node) => acc + node.textContent, '') .trim(); if (labelText) { return labelText; } } if (ele.hasAttribute('aria-label')) { const labelText = ele.getAttribute('aria-label'); if (labelText) { return labelText; } } if (ele.hasAttribute('aria-labelledby')) { const labelledby = ele.getAttribute('aria-labelledby'); const ids = labelledby.split(' '); const root = ele.getRootNode(); for (const id of ids) { const label = root.getElementById(id); if (label) { const labelText = label.textContent.trim(); if (labelText) { return labelText; } } } } if (ele.hasAttribute('title')) { const labelText = ele.getAttribute('title'); if (labelText) { return labelText; } } const tagName = ele.nodeName.toLowerCase(); if (tagName === 'button' && ele.textContent) { const labelText = ele.textContent.trim(); if (labelText) { return labelText; } } if (tagName === 'input') { if (ele.type === 'button' || ele.type === 'submit' || ele.type === 'reset' && ele.value) { const labelText = ele.value; if (labelText) { return labelText; } } if (ele.type === 'image') { const labelText = ele.alt; if (labelText) { return labelText; } } } return null; }; const _getCustomFormElementData = (node) => { if (node.formValue instanceof Object) { return { ...node.formValue }; } if (node.name) { return { [node.name]: node.formValue }; } return {}; }; const _hasFormData = (node, submitter) => { if (node.disabled) { return false; } const tagName = node.nodeName.toLowerCase(); if (tagName === 'button' && node !== submitter) { return false; } if (tagName === 'input') { const type = node.getAttribute('type'); if ((type === 'checkbox' || type === 'radio') && !node.checked) { return false; } if (type === 'submit' && node !== submitter) { return false; } if (type === 'reset') { return false; } } if (tagName === 'object' || tagName === 'output') { return false; } return true; }; // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-form-data-set export const getFormElementData = (node, submitter) => { const eleData = {}; if (!_hasFormData(node, submitter)) { return eleData; } const tagName = node.nodeName.toLowerCase(); if (isCustomFormElement(node)) { return _getCustomFormElementData(node); } const name = node.getAttribute('name'); if (!name) { return eleData; } const type = node.getAttribute('type'); if (tagName === 'input' && type === 'file') { eleData[name] = node.files; return eleData; } eleData[name] = node.value; return eleData; }; export const flattenMap = (map) => { const flattened = new Map(); for (const [key, val] of map) { if (val instanceof Map) { const subMap = flattenMap(val); for (const [nestedKey, nestedVal] of subMap) { flattened.set(nestedKey, nestedVal); } } else { flattened.set(key, val); } } return flattened; }; <|start_filename|>components/breadcrumbs/test/breadcrumb.test.js<|end_filename|> import '../breadcrumb.js'; import '../breadcrumb-current-page.js'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-breadcrumb', () => { describe('constructor', () => { it('should construct', () => { runConstructor('d2l-breadcrumb'); }); it('should construct current page', () => { runConstructor('d2l-breadcrumb-current-page'); }); }); }); <|start_filename|>.stylelintrc.json<|end_filename|> { "extends": "@brightspace-ui/stylelint-config", "ignoreFiles": [ "components/demo/code-dark-plus-styles.js", "components/demo/code-tomorrow-styles.js" ] } <|start_filename|>components/breadcrumbs/test/breadcrumbs.axe.js<|end_filename|> import '../breadcrumb.js'; import '../breadcrumb-current-page.js'; import '../breadcrumbs.js'; import { expect, fixture, html } from '@open-wc/testing'; describe('d2l-breadcrumbs', () => { [ 'max-width: 250px; width: 250px;', '', ].forEach((style) => { [true, false].forEach((compact) => { it(`passes aXe tests for style="${style}" and compact="${compact}"`, async() => { const elem = await fixture(html` <d2l-breadcrumbs style="${style}" ?compact="${compact}"> <d2l-breadcrumb href="#" text="Basic Item 1"></d2l-breadcrumb> <d2l-breadcrumb href="#" text="Basic Item 2"></d2l-breadcrumb> <d2l-breadcrumb href="#" text="Basic Item 3" aria-label="Aria for Item 3"></d2l-breadcrumb> </d2l-breadcrumbs> `); await expect(elem).to.be.accessible(); }); }); }); it('passes aXe for current page', async() => { const elem = await fixture(html` <d2l-breadcrumbs> <d2l-breadcrumb href="page1.html" text="Page 1"></d2l-breadcrumb> <d2l-breadcrumb-current-page text="Current Page"></d2l-breadcrumb-current-page> </d2l-breadcrumbs>`); await expect(elem).to.be.accessible(); }); }); <|start_filename|>components/scroll-wrapper/test/scroll-wrapper.axe.js<|end_filename|> import '../scroll-wrapper.js'; import { expect, fixture, html } from '@open-wc/testing'; describe('d2l-scroll-wrapper', () => { it('smaller', async() => { const elem = await fixture(html`<d2l-scroll-wrapper><div style="width: 200px;"></div></d2l-scroll-wrapper>`); await expect(elem).to.be.accessible(); }); it('overflow', async() => { const elem = await fixture(html`<d2l-scroll-wrapper><div style="width: 400px;"></div></d2l-scroll-wrapper>`); await expect(elem).to.be.accessible(); }); it('overflow-hide-actions', async() => { const elem = await fixture(html`<d2l-scroll-wrapper hide-actions><div style="width: 400px;"></div></d2l-scroll-wrapper>`); await expect(elem).to.be.accessible(); }); }); <|start_filename|>components/menu/menu-item-separator.js<|end_filename|> import { css, LitElement } from 'lit-element/lit-element.js'; /** * A component for displaying a more distinct separator between menu items. */ class MenuItemSeparator extends LitElement { static get styles() { return css` :host { border-top: 1px solid var(--d2l-menu-separator-color); display: block; margin-top: -1px; position: relative; z-index: 1; } `; } firstUpdated() { super.firstUpdated(); this.setAttribute('role', 'separator'); } } customElements.define('d2l-menu-item-separator', MenuItemSeparator); <|start_filename|>components/inputs/input-checkbox-spacer.js<|end_filename|> import { css, html, LitElement } from 'lit-element/lit-element.js'; import { RtlMixin } from '../../mixins/rtl-mixin.js'; /** * Used to align related content below checkboxes * @slot - Additional related content */ class InputCheckboxSpacer extends RtlMixin(LitElement) { static get styles() { return css` :host { box-sizing: border-box; display: block; margin-bottom: 0.9rem; padding-left: 1.7rem; } :host([dir="rtl"]) { padding-left: 0; padding-right: 1.7rem; } `; } render() { return html`<slot></slot>`; } } customElements.define('d2l-input-checkbox-spacer', InputCheckboxSpacer); <|start_filename|>components/card/test/card-footer-link.test.js<|end_filename|> import '../card-footer-link.js'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-card-footer-link', () => { it('should construct', () => { runConstructor('d2l-card-footer-link'); }); }); <|start_filename|>components/form/test/form-helper.test.js<|end_filename|> import './form-element.js'; import '../../status-indicator/status-indicator.js'; import '../../tooltip/tooltip.js'; import { defineCE, expect, fixture } from '@open-wc/testing'; import { findFormElements, flattenMap, getFormElementData, isCustomElement, isCustomFormElement, isElement, isNativeFormElement, tryGetLabelText } from '../form-helper.js'; import { html, LitElement } from 'lit-element/lit-element.js'; const buttonFixture = html`<button type="button">Add to favorites</button>`; const fieldsetFixture = html` <fieldset> <legend>Choose your favorite monster</legend> <input type="radio" id="kraken" name="monster"> <label for="kraken">Kraken</label><br/> <input type="radio" id="sasquatch" name="monster"> <label for="sasquatch">Sasquatch</label><br/> <input type="radio" id="mothman" name="monster"> <label for="mothman">Mothman</label> </fieldset> `; const inputFixture = html`<input type="text" id="name" name="name" required minlength="4" maxlength="8" size="10">`; const objectFixture = html`<object name="image" type="image/png" width="300" height="200"></object>`; const outputFixture = html`<output name="result">60</output>`; const selectFixture = html` <select name="pets" id="pet-select"> <option value="">--Please choose an option--</option> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="hamster">Hamster</option> <option value="parrot">Parrot</option> <option value="spider">Spider</option> <option value="goldfish">Goldfish</option> </select> `; const textareaFixture = html`<textarea id="story" name="story" rows="5" cols="33">It was a dark and stormy night...</textarea>`; const divFixture = html` <div> <p>Beware of the leopard</p> </div> `; const labelFixture = html` <label>Do you like peas? <input type="checkbox" name="peas"> </label> `; const formFixture = html` <form action="" method="GET"> <div> <label for="name">Enter your name: </label> <input type="text" name="name" id="name" required> </div> </form> `; const d2lStatusIndicatorFixture = html`<d2l-status-indicator text="test subtle"></d2l-status-indicator>`; const h1Fixture = html`<h1>Beetles</h1>`; const formElementFixture = html`<d2l-test-form-element></d2l-test-form-element>`; describe('form-helper', () => { describe('elements', () => { [ { tag: 'button', fixture: buttonFixture, expected: { isElement: true, isCustomElement: false, isNativeFormElement: true, isCustomFormElement: false } }, { tag: 'fieldset', fixture: fieldsetFixture, expected: { isElement: true, isCustomElement: false, isNativeFormElement: true, isCustomFormElement: false } }, { tag: 'input', fixture: inputFixture, expected: { isElement: true, isCustomElement: false, isNativeFormElement: true, isCustomFormElement: false } }, { tag: 'object', fixture: objectFixture, expected: { isElement: true, isCustomElement: false, isNativeFormElement: true, isCustomFormElement: false } }, { tag: 'output', fixture: outputFixture, expected: { isElement: true, isCustomElement: false, isNativeFormElement: true, isCustomFormElement: false } }, { tag: 'select', fixture: selectFixture, expected: { isElement: true, isCustomElement: false, isNativeFormElement: true, isCustomFormElement: false } }, { tag: 'textarea', fixture: textareaFixture, expected: { isElement: true, isCustomElement: false, isNativeFormElement: true, isCustomFormElement: false } }, { tag: 'div', fixture: divFixture, expected: { isElement: true, isCustomElement: false, isNativeFormElement: false, isCustomFormElement: false } }, { tag: 'label', fixture: labelFixture, expected: { isElement: true, isCustomElement: false, isNativeFormElement: false, isCustomFormElement: false } }, { tag: 'form', fixture: formFixture, expected: { isElement: true, isCustomElement: false, isNativeFormElement: false, isCustomFormElement: false } }, { tag: 'h1', fixture: h1Fixture, expected: { isElement: true, isCustomElement: false, isNativeFormElement: false, isCustomFormElement: false } }, { tag: 'd2l-status-indicator', fixture: d2lStatusIndicatorFixture, expected: { isElement: true, isCustomElement: true, isNativeFormElement: false, isCustomFormElement: false } }, { tag: 'd2l-test-form-element', fixture: formElementFixture, expected: { isElement: true, isCustomElement: true, isNativeFormElement: false, isCustomFormElement: true } } ].forEach(({ tag, fixture: eleFixture, expected }) => { describe(tag, () => { let ele; beforeEach(async() => { ele = await fixture(eleFixture); }); it(`${tag} should ${expected.isElement ? '' : 'not '}be an element`, () => { expect(isElement(ele)).to.equal(expected.isElement); }); it(`${tag} should ${expected.isCustomElement ? '' : 'not '}be a custom element`, () => { expect(isCustomElement(ele)).to.equal(expected.isCustomElement); }); it(`${tag} should ${expected.isNativeFormElement ? '' : 'not '}be a native form element`, () => { expect(isNativeFormElement(ele)).to.equal(expected.isNativeFormElement); }); it(`${tag} should ${expected.isCustomFormElement ? '' : 'not '}be a custom form element`, () => { expect(isCustomFormElement(ele)).to.equal(expected.isCustomFormElement); }); }); }); }); describe('tryGetLabelText', () => { const composedLabelTag = defineCE( class extends LitElement { render() { return html` <div> <label for="target">Do you like peas?</label> <input id='target' type="checkbox" name="peas"> </div> `; } } ); const implicitLabelFixture = html` <label>Do you like peas? <input id='target' type="checkbox" name="peas"> </label> `; const implicitLabelWithTooltipFixture = html` <label>Do you like peas? <input id='target' type="checkbox" name="peas"> <d2l-tooltip for="target">Tooltip that shouldn't be included in label text</d2l-tooltip> </label> `; const explicitLabelFixture = html` <div> <label for="target">Do you like peas?</label> <input id='target' type="checkbox" name="peas"> </div> `; const ariaLabelFixture = html` <div> <input aria-label="Do you like peas?" id='target' type="checkbox" name="peas"> </div> `; const ariaLabelledByFixture = html` <div> <div id="label">Do you like peas?</div> <input aria-labelledby="label" id='target' type="checkbox" name="peas"> </div> `; const titleLabelFixture = html` <div> <input title="Do you like peas?" id='target' type="checkbox" name="peas"> </div> `; const buttonLabelFixture = html` <div> <button id='target' name="peas">Do you like peas?</button> </div> `; const inputButtonLabelFixture = html` <div> <input id='target' type="button" name="peas" value="Do you like peas?"/> </div> `; const submitButtonLabelFixture = html` <div> <input id='target' type="submit" name="peas" value="Do you like peas?"/> </div> `; const resetButtonLabelFixture = html` <div> <input id='target' type="reset" name="peas" value="Do you like peas?"/> </div> `; const imageLabelFixture = html` <div> <input id='target' type="image" name="peas" alt="Do you like peas?"/> </div> `; const emptyLabelFixture = html` <div> <label for="target"> </label> <input id='target' type="checkbox" name="peas"> </div> `; const composedLabelFixture = `<${composedLabelTag}><${composedLabelTag}/>`; [ { type: 'implicit', fixture: implicitLabelFixture }, { type: 'implicit with tooltip', fixture: implicitLabelWithTooltipFixture }, { type: 'explicit', fixture: explicitLabelFixture }, { type: 'aria-label', fixture: ariaLabelFixture }, { type: 'aria-labelledby', fixture: ariaLabelledByFixture }, { type: 'title', fixture: titleLabelFixture }, { type: 'button', fixture: buttonLabelFixture }, { type: 'button input', fixture: inputButtonLabelFixture }, { type: 'submit input', fixture: submitButtonLabelFixture }, { type: 'reset input', fixture: resetButtonLabelFixture }, { type: 'image input', fixture: imageLabelFixture }, ].forEach(({ type, fixture: eleFixture }) => { it(`should find an ${type} label`, async() => { const ele = await fixture(eleFixture); const target = ele.querySelector('#target'); expect(tryGetLabelText(target)).to.equal('Do you like peas?'); }); }); it('should find a composed label', async() => { const ele = await fixture(composedLabelFixture); const target = ele.shadowRoot.querySelector('#target'); expect(tryGetLabelText(target)).to.equal('Do you like peas?'); }); [ { type: 'empty', fixture: emptyLabelFixture }, ].forEach(({ type, fixture: eleFixture }) => { it(`shouldn't find an ${type} label`, async() => { const ele = await fixture(eleFixture); const target = ele.querySelector('#target'); expect(tryGetLabelText(target)).to.be.null; }); }); }); describe('findFormElements', () => { const formElementsFixture = html` <div> <h1>My Form</h1> <fieldset id="ele-1"> <legend>Choose your favorite monster</legend> <input id="ele-2" type="radio" name="monster" value="kraken"> <br><label for="ele-2">Kraken</label><br/> <input id="ele-3" type="radio" name="monster" value="sasquatch"> <br><label for="ele-3">Sasquatch</label><br/> </fieldset> <label for="ele-4">Checkers</label> <input id="ele-4" type="checkbox" name="checkers" value="red-black"> <div> <label for="ele-5">Name</label> <input id="ele-5" type="text" name="name"> <div> <select id="ele-6" name="pets" required> <option value="">--Please choose an option--</option> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="hamster">Hamster</option> <option value="parrot">Parrot</option> <option value="spider">Spider</option> <option value="goldfish">Goldfish</option> </select> <d2l-test-form-element id="ele-7"></d2l-test-form-element> </div> </div> <object id="ele-8" type="image/png" width="300" height="200"></object> <div id="fake-form-element"></div> <label>Email <input id="ele-9" type="email"/> </label> <div id="secondary"> <h2>Secondary</h2> <label for="ele-10">Tell us your story</label> <textarea id="ele-10" title="my title" minlength="20" name="story">It was...</textarea> <div> <input id="ele-11" type="range" name="b" value="50" max="100" min="15" /> + <input id="ele-12" type="number" name="a" value="10" /> = <output id="ele-13" name="result" for="ele-11 ele-12">60</output> </div> </div> <button id="ele-14" type="submit" name="action">Update</button> <button id="ele-15" type="reset" name="action">Delete</button> <button id="ele-16" name="other" value="other">Other</button> </div> `; let root; beforeEach(async() => { root = await fixture(formElementsFixture); }); it('should find all form elements', () => { const formElements = findFormElements(root); let id = 1; for (const formElement of formElements) { const expectedFormElement = root.querySelector(`#ele-${id}`); expect(formElement).to.equal(expectedFormElement); id += 1; } }); it('should not find form elements inside elements that fail the visitChildrenPredicate', () => { const secondaryEle = root.querySelector('#secondary'); const formElements = findFormElements(root, undefined, ele => ele !== secondaryEle); const ele10 = root.querySelector('#ele-10'); const ele11 = root.querySelector('#ele-11'); const ele12 = root.querySelector('#ele-12'); const ele13 = root.querySelector('#ele-13'); expect(formElements).to.not.include.members([ele10, ele11, ele12, ele13]); }); it('should find elements that pass the isFormElementPredicate', () => { const fakeFormElement = root.querySelector('#fake-form-element'); const formElements = findFormElements(root, ele => ele === fakeFormElement); expect(formElements).to.include.members([fakeFormElement]); }); }); describe('flattenMap', () => { it('should flatten errors', async() => { const errors = new Map(); const pairs = []; const set = (map, key, value) => { if (!(value instanceof Map)) { pairs.push([key, value]); } map.set(key, value); }; set(errors, 'a', 1); const subErrors1 = new Map(); set(subErrors1, 'ba', 'a value'); set(subErrors1, 'bb', { prop: 'my prop' }); const subSubErrors1 = new Map(); set(subSubErrors1, 'bca', 99); set(subSubErrors1, 'bcb', new Map()); set(subErrors1, 'bc', subSubErrors1); set(errors, 'b', subErrors1); set(errors, 'c', [1, 2, 3, 4]); set(errors, 'd', 'another val'); const subErrors2 = new Map(); set(subErrors2, 'ea', ['x', 'y']); set(subErrors2, 'eb', 1024); set(errors, 'e', subErrors2); const flatErrors = flattenMap(errors); for (const [key, value] of pairs) { expect(flatErrors.get(key)).to.equal(value); } }); }); describe('getFormElementData', () => { describe('custom form element', () => { let formElement; beforeEach(async() => { formElement = await fixture(formElementFixture); }); it('should not have any data by default', async() => { const eleData = getFormElementData(formElement); expect(eleData).to.be.empty; }); it('should not have any data if disabled', async() => { formElement.disabled = true; formElement.name = 'my-key'; formElement.setFormValue('my-value'); const eleData = getFormElementData(formElement); expect(eleData).to.be.empty; }); it('should use the name and formValue if it is a string', async() => { formElement.name = 'my-key'; formElement.setFormValue('my-value'); const eleData = getFormElementData(formElement); expect(eleData).to.deep.equal({ 'my-key': 'my-value' }); }); it('should use the formValue if it is an object', async() => { const formValue = { 'my-key-1': 'my-val-1', 'my-key-2': 'my-val-2' }; formElement.setFormValue(formValue); const eleData = getFormElementData(formElement); expect(eleData).to.deep.equal(formValue); }); }); describe('native form element', () => { [ { name: 'should have data when the button is the submitter', isSubmitter: true }, { name: 'should have not data when the button is not the submitter', isSubmitter: false } ].forEach(({ name, isSubmitter }) => { it(name, async() => { const container = await fixture(html` <div> <button id="pets" type="submit" name="pets" value="the value"></button> <button id="dogs" type="submit" name="dogs" value="other value"></button> </div> `); const clicked = container.querySelector('#pets'); const submitter = isSubmitter ? clicked : container.querySelector('#dogs'); const eleData = getFormElementData(clicked, submitter); if (isSubmitter) { expect(eleData).to.deep.equal({ pets: 'the value' }); } else { expect(eleData).to.empty; } }); }); it('should get files for file inputs', async() => { const fileInput = await fixture(html`<input type="file" name="file-input"/>`); const eleData = getFormElementData(fileInput); expect(eleData).to.deep.equal({ ['file-input']: fileInput.files }); }); it('should get names and values', async() => { const form = await fixture(html` <form> <input type="text" name="input-without-value"/> <input type="text" name="input-with-value" value="input-value" /> <input type="text" name="input-with-value-disabled" value="input value disabled" disabled /> <textarea name="textarea-without-value"></textarea> <textarea name="textarea-with-value">textarea value</textarea> <textarea name="textarea-with-value-disabled" disabled>textarea value disabled</textarea> <object name="object-without-value" type="image/png" width="300" height="200"></object> <output name="output-without-value"></output> <output name="output-with-value">output value</output> <output name="output-with-value-disabled">output value disabled</output> <select name="select-disabled" disabled> <option value="">--Please choose an option--</option> <option value="spider">Spider</option> <option value="goldfish" selected>Goldfish</option> </select> <select name="select-selected"> <option value="">--Please choose an option--</option> <option value="spider">Spider</option> <option value="goldfish" selected>Goldfish</option> </select> <select name="select-default"> <option value="">--Please choose an option--</option> <option value="spider">Spider</option> <option value="goldfish">Goldfish</option> </select> <button name="button-with-value" type="submit" value="button value"></button> <button name="button-without-value" type="submit"></button> <input name="input-submit-with-value" type="submit" value="input-submit-value"/> <input name="input-submit-without-value" type="submit"/> <input name="input-reset-with-value" type="reset" value="input-reset-value"/> <input name="input-reset-without-value" type="reset"/> <input type="checkbox" name="checkbox-default-value-checked" checked /> <input type="checkbox" name="checkbox-custom-value-checked" value="custom-value-checked" checked /> <input type="checkbox" name="checkbox-default-value-checked-disabled" checked disabled /> <input type="checkbox" name="checkbox-default-value" /> <input type="checkbox" name="checkbox-custom-value" value="custom-value" /> <input type="radio" name="radio-default-value-checked" checked /> <input type="radio" name="radio-custom-value-checked" value="custom-value-checked" checked /> <input type="radio" name="radio-default-value-checked-disabled" checked disabled /> <input type="radio" name="radio-default-value" /> <input type="radio" name="radio-custom-value" value="custom-value" /> </form> `); const actualFormData = [...form.elements].reduce((acc, ele) => ({ ...acc, ...getFormElementData(ele) }), {}); const expectedFormData = new FormData(form); let expectedEntries = 0; for (const entry of expectedFormData) { const key = entry[0]; const value = entry[1]; expect(actualFormData[key]).to.equal(value); expectedEntries += 1; } expect(Object.entries(actualFormData).length).to.equal(expectedEntries); }); }); }); }); <|start_filename|>components/tabs/tab-internal.js<|end_filename|> import '../colors/colors.js'; import { css, html, LitElement } from 'lit-element/lit-element.js'; import { RtlMixin } from '../../mixins/rtl-mixin.js'; const keyCodes = { ENTER: 13, SPACE: 32 }; class Tab extends RtlMixin(LitElement) { static get properties() { return { ariaSelected: { type: String, reflect: true, attribute: 'aria-selected' }, controlsPanel: { type: String, reflect: true, attribute: 'controls-panel' }, role: { type: String, reflect: true }, text: { type: String } }; } static get styles() { return css` :host { box-sizing: border-box; display: inline-block; max-width: 200px; outline: none; position: relative; vertical-align: middle; } .d2l-tab-text { margin: 0.5rem; overflow: hidden; padding: 0.1rem; text-overflow: ellipsis; white-space: nowrap; } :host(:first-child) .d2l-tab-text { margin-left: 0; } :host([dir="rtl"]:first-child) .d2l-tab-text { margin-left: 0.6rem; margin-right: 0; } .d2l-tab-selected-indicator { border-top: 4px solid var(--d2l-color-celestine); border-top-left-radius: 4px; border-top-right-radius: 4px; bottom: 0; display: none; margin: 1px 0.6rem 0 0.6rem; position: absolute; -webkit-transition: box-shadow 0.2s; transition: box-shadow 0.2s; width: calc(100% - 1.2rem); } :host(:first-child) .d2l-tab-selected-indicator { margin-left: 0; width: calc(100% - 0.6rem); } :host([dir="rtl"]:first-child) .d2l-tab-selected-indicator { margin-left: 0.6rem; margin-right: 0; } :host(.focus-visible) > .d2l-tab-text { border-radius: 0.3rem; box-shadow: 0 0 0 2px var(--d2l-color-celestine); color: var(--d2l-color-celestine); } :host([aria-selected="true"]:focus) { text-decoration: none; } :host(:hover) { color: var(--d2l-color-celestine); cursor: pointer; } :host([aria-selected="true"]:hover) { color: inherit; cursor: default; } :host([aria-selected="true"]) .d2l-tab-selected-indicator { display: block; } @media (prefers-reduced-motion: reduce) { .d2l-tab-selected-indicator { -webkit-transition: none; transition: none; } } `; } constructor() { super(); this.ariaSelected = 'false'; this.role = 'tab'; this.tabIndex = -1; } firstUpdated(changedProperties) { super.firstUpdated(changedProperties); this.addEventListener('click', () => { this.ariaSelected = 'true'; }); this.addEventListener('keydown', (e) => { if (e.keyCode !== keyCodes.SPACE) return; e.stopPropagation(); e.preventDefault(); }); this.addEventListener('keyup', (e) => { if (e.keyCode !== keyCodes.ENTER && e.keyCode !== keyCodes.SPACE) return; this.ariaSelected = 'true'; }); } render() { return html` <div class="d2l-tab-text">${this.text}</div> <div class="d2l-tab-selected-indicator"></div> `; } update(changedProperties) { super.update(changedProperties); changedProperties.forEach((oldVal, prop) => { if (prop === 'ariaSelected' && this.ariaSelected === 'true') { this.dispatchEvent(new CustomEvent( 'd2l-tab-selected', { bubbles: true, composed: true } )); } else if (prop === 'text') { this.title = this.text; } }); } } customElements.define('d2l-tab-internal', Tab); <|start_filename|>mixins/demo/localize-test.js<|end_filename|> import { html, LitElement } from 'lit-element/lit-element.js'; import { LocalizeMixin } from '../../mixins/localize-mixin.js'; class LocalizeTest extends LocalizeMixin(LitElement) { static get properties() { return { name: { type: String } }; } static async getLocalizeResources(langs) { const langResources = { 'ar': { 'hello': 'مرحبا {name}' }, 'de': { 'hello': 'Hallo {name}' }, 'en': { 'hello': 'Hello {name}', 'plural': 'You have {itemCount, plural, =0 {no items} one {1 item} other {{itemCount} items}}.' }, 'en-ca': { 'hello': 'Hello, {name} eh' }, 'es': { 'hello': 'Hola {name}' }, 'fr': { 'hello': 'Bonjour {name}' }, 'ja': { 'hello': 'こんにちは {name}' }, 'ko': { 'hello': '안녕하세요 {name}' }, 'pt-br': { 'hello': 'Olá {name}' }, 'tr': { 'hello': 'Merhaba {name}' }, 'zh-cn': { 'hello': '你好 {name}' }, 'zh-tw': { 'hello': '你好 {name}' } }; for (let i = 0; i < langs.length; i++) { if (langResources[langs[i]]) { return { language: langs[i], resources: langResources[langs[i]] }; } } return null; } render() { requestAnimationFrame( () => this.dispatchEvent(new CustomEvent('d2l-test-localize-render', { bubbles: false, composed: false })) ); return html` <p>${this.localize('hello', { name: this.name })}</p> `; } } customElements.define('d2l-test-localize', LocalizeTest); <|start_filename|>components/colors/demo/color-swatch.js<|end_filename|> import { css, html, LitElement } from 'lit-element/lit-element.js'; class ColorSwatch extends LitElement { static get properties() { return { name: { type: String, reflect: true } }; } static get styles() { return css` :host { border-radius: 8px; box-sizing: border-box; color: #ffffff; display: block; font-size: 0.7rem; font-weight: 400; margin: 0.3rem; padding: 0.3rem; width: 300px; } :host([name="regolith"]) { background-color: var(--d2l-color-regolith); color: var(--d2l-color-ferrite); } :host([name="sylvite"]) { background-color: var(--d2l-color-sylvite); color: var(--d2l-color-ferrite); } :host([name="gypsum"]) { background-color: var(--d2l-color-gypsum); color: var(--d2l-color-ferrite); } :host([name="mica"]) { background-color: var(--d2l-color-mica); color: var(--d2l-color-ferrite); } :host([name="corundum"]) { background-color: var(--d2l-color-corundum); color: var(--d2l-color-ferrite); } :host([name="chromite"]) { background-color: var(--d2l-color-chromite); color: var(--d2l-color-ferrite); } :host([name="galena"]) { background-color: var(--d2l-color-galena); } :host([name="tungsten"]) { background-color: var(--d2l-color-tungsten); } :host([name="ferrite"]) { background-color: var(--d2l-color-ferrite); } :host([name="primary-accent-action"]) { background-color: var(--d2l-color-primary-accent-action); } :host([name="primary-accent-indicator"]) { background-color: var(--d2l-color-primary-accent-indicator); } :host([name="feedback-error"]) { background-color: var(--d2l-color-feedback-error); } :host([name="feedback-warning"]) { background-color: var(--d2l-color-feedback-warning); } :host([name="feedback-success"]) { background-color: var(--d2l-color-feedback-success); } :host([name="feedback-action"]) { background-color: var(--d2l-color-feedback-action); } :host([name="zircon-plus-2"]) { background-color: var(--d2l-color-zircon-plus-2); color: var(--d2l-color-ferrite); } :host([name="zircon-plus-1"]) { background-color: var(--d2l-color-zircon-plus-1); color: var(--d2l-color-ferrite); } :host([name="zircon"]) { background-color: var(--d2l-color-zircon); } :host([name="zircon-minus-1"]) { background-color: var(--d2l-color-zircon-minus-1); } :host([name="celestine-plus-2"]) { background-color: var(--d2l-color-celestine-plus-2); color: var(--d2l-color-ferrite); } :host([name="celestine-plus-1"]) { background-color: var(--d2l-color-celestine-plus-1); color: var(--d2l-color-ferrite); } :host([name="celestine"]) { background-color: var(--d2l-color-celestine); } :host([name="celestine-minus-1"]) { background-color: var(--d2l-color-celestine-minus-1); } :host([name="amethyst-plus-2"]) { background-color: var(--d2l-color-amethyst-plus-2); color: var(--d2l-color-ferrite); } :host([name="amethyst-plus-1"]) { background-color: var(--d2l-color-amethyst-plus-1); color: var(--d2l-color-ferrite); } :host([name="amethyst"]) { background-color: var(--d2l-color-amethyst); } :host([name="amethyst-minus-1"]) { background-color: var(--d2l-color-amethyst-minus-1); } :host([name="fluorite-plus-2"]) { background-color: var(--d2l-color-fluorite-plus-2); color: var(--d2l-color-ferrite); } :host([name="fluorite-plus-1"]) { background-color: var(--d2l-color-fluorite-plus-1); color: var(--d2l-color-ferrite); } :host([name="fluorite"]) { background-color: var(--d2l-color-fluorite); } :host([name="fluorite-minus-1"]) { background-color: var(--d2l-color-fluorite-minus-1); } :host([name="tourmaline-plus-2"]) { background-color: var(--d2l-color-tourmaline-plus-2); color: var(--d2l-color-ferrite); } :host([name="tourmaline-plus-1"]) { background-color: var(--d2l-color-tourmaline-plus-1); color: var(--d2l-color-ferrite); } :host([name="tourmaline"]) { background-color: var(--d2l-color-tourmaline); } :host([name="tourmaline-minus-1"]) { background-color: var(--d2l-color-tourmaline-minus-1); } :host([name="cinnabar-plus-2"]) { background-color: var(--d2l-color-cinnabar-plus-2); color: var(--d2l-color-ferrite); } :host([name="cinnabar-plus-1"]) { background-color: var(--d2l-color-cinnabar-plus-1); color: var(--d2l-color-ferrite); } :host([name="cinnabar"]) { background-color: var(--d2l-color-cinnabar); } :host([name="cinnabar-minus-1"]) { background-color: var(--d2l-color-cinnabar-minus-1); } :host([name="carnelian-plus-1"]) { background-color: var(--d2l-color-carnelian-plus-1); color: var(--d2l-color-ferrite); } :host([name="carnelian"]) { background-color: var(--d2l-color-carnelian); color: var(--d2l-color-ferrite); } :host([name="carnelian-minus-1"]) { background-color: var(--d2l-color-carnelian-minus-1); } :host([name="carnelian-minus-2"]) { background-color: var(--d2l-color-carnelian-minus-2); } :host([name="citrine-plus-1"]) { background-color: var(--d2l-color-citrine-plus-1); color: var(--d2l-color-ferrite); } :host([name="citrine"]) { background-color: var(--d2l-color-citrine); color: var(--d2l-color-ferrite); } :host([name="citrine-minus-1"]) { background-color: var(--d2l-color-citrine-minus-1); } :host([name="citrine-minus-2"]) { background-color: var(--d2l-color-citrine-minus-2); } :host([name="peridot-plus-1"]) { background-color: var(--d2l-color-peridot-plus-1); color: var(--d2l-color-ferrite); } :host([name="peridot"]) { background-color: var(--d2l-color-peridot); color: var(--d2l-color-ferrite); } :host([name="peridot-minus-1"]) { background-color: var(--d2l-color-peridot-minus-1); } :host([name="peridot-minus-2"]) { background-color: var(--d2l-color-peridot-minus-2); } :host([name="olivine-plus-1"]) { background-color: var(--d2l-color-olivine-plus-1); color: var(--d2l-color-ferrite); } :host([name="olivine"]) { background-color: var(--d2l-color-olivine); color: var(--d2l-color-ferrite); } :host([name="olivine-minus-1"]) { background-color: var(--d2l-color-olivine-minus-1); } :host([name="olivine-minus-2"]) { background-color: var(--d2l-color-olivine-minus-2); } :host([name="malachite-plus-1"]) { background-color: var(--d2l-color-malachite-plus-1); color: var(--d2l-color-ferrite); } :host([name="malachite"]) { background-color: var(--d2l-color-malachite); color: var(--d2l-color-ferrite); } :host([name="malachite-minus-1"]) { background-color: var(--d2l-color-malachite-minus-1); } :host([name="malachite-minus-2"]) { background-color: var(--d2l-color-malachite-minus-2); } `; } render() { return html` <div>${this.name}</div> `; } } customElements.define('d2l-color-swatch', ColorSwatch); <|start_filename|>mixins/demo/arrow-keys-test.js<|end_filename|> import '../../components/colors/colors.js'; import { css, html, LitElement } from 'lit-element/lit-element.js'; import { ArrowKeysMixin } from '../arrow-keys-mixin.js'; export class ArrowKeysTest extends ArrowKeysMixin(LitElement) { static get styles() { return css` :host { display: inline-block; } .d2l-arrowkeys-focusable { border: 2px solid var(--d2l-color-ferrite); border-radius: 4px; display: inline-block; padding: 1rem; } .d2l-arrowkeys-focusable:focus { border: 2px solid var(--d2l-color-celestine); } `; } render() { const inner = html` <div class="d2l-arrowkeys-focusable" tabindex="0"></div> <div class="d2l-arrowkeys-focusable" tabindex="-1"></div> <div class="d2l-arrowkeys-focusable" tabindex="-1"></div> <div class="d2l-arrowkeys-focusable" tabindex="-1"></div> <div class="d2l-arrowkeys-focusable" tabindex="-1"></div>`; return html`<div id="d2l-arrowkeys-mixin-test"> ${this.arrowKeysContainer(inner)} </div>`; } } customElements.define('d2l-test-arrow-keys', ArrowKeysTest); <|start_filename|>components/icons/icon-styles.js<|end_filename|> import '../colors/colors.js'; import { css } from 'lit-element/lit-element.js'; export const iconStyles = css` :host { -webkit-align-items: center; align-items: center; color: var(--d2l-color-ferrite); display: -ms-inline-flexbox; display: -webkit-inline-flex; display: inline-flex; fill: var(--d2l-icon-fill-color, currentcolor); -ms-flex-align: center; -ms-flex-pack: center; height: var(--d2l-icon-height, 18px); -webkit-justify-content: center; justify-content: center; stroke: var(--d2l-icon-stroke-color, none); vertical-align: middle; width: var(--d2l-icon-width, 18px); } :host([hidden]) { display: none; } svg, ::slotted(svg) { display: block; height: 100%; pointer-events: none; width: 100%; } :host([dir="rtl"]) svg[mirror-in-rtl], :host([dir="rtl"]) ::slotted(svg[mirror-in-rtl]) { -webkit-transform: scale(-1, 1); transform: scale(-1, 1); transform-origin: center; } `; <|start_filename|>components/card/test/card.axe.js<|end_filename|> import '../card.js'; import { expect, fixture, html } from '@open-wc/testing'; describe('d2l-card', () => { it('default', async() => { const elem = await fixture(html`<d2l-card><div slot="content">Content</div></d2l-card>`); await expect(elem).to.be.accessible(); }); it('subtle', async() => { const elem = await fixture(html`<d2l-card subtle><div slot="content">Content</div></d2l-card>`); await expect(elem).to.be.accessible(); }); it('default link', async() => { const elem = await fixture(html`<d2l-card text="Link Text" href="https://d2l.com"><div slot="content">Content</div></d2l-card>`); await expect(elem).to.be.accessible(); }); it('default link + focused', async() => { const elem = await fixture(html`<d2l-card text="Link Text" href="https://d2l.com"><div slot="content">Content</div></d2l-card>`); elem.focus(); await expect(elem).to.be.accessible(); }); it('subtle link', async() => { const elem = await fixture(html`<d2l-card subtle text="Link Text" href="https://d2l.com"><div slot="content">Content</div></d2l-card>`); await expect(elem).to.be.accessible(); }); it('subtle link + focused', async() => { const elem = await fixture(html`<d2l-card subtle text="Link Text" href="https://d2l.com"><div slot="content">Content</div></d2l-card>`); elem.focus(); await expect(elem).to.be.accessible(); }); }); <|start_filename|>components/menu/test/menu.axe.js<|end_filename|> import '../menu.js'; import '../menu-item.js'; import { expect, fixture, html } from '@open-wc/testing'; describe('d2l-menu', () => { it('should pass all aXe tests', async() => { const elem = await fixture(html` <d2l-menu label="menu label"> <d2l-menu-item>label 1</d2l-menu-item> <d2l-menu-item>label 2</d2l-menu-item> </d2l-menu> `); await expect(elem).to.be.accessible(); }); }); <|start_filename|>components/menu/test/menu-item-link.test.js<|end_filename|> import '../menu-item-link.js'; import { expect, fixture, html } from '@open-wc/testing'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-menu-item-link', () => { describe('constructor', () => { it('should construct', () => { runConstructor('d2l-menu-item-link'); }); it('should sprout "aria-label"', async() => { // without explicit aria-label, Voiceover on iOS cannot find nested label inside <a> element const elem = await fixture(html`<d2l-menu-item-link text="link text"></d2l-menu-item-link>`); expect(elem.getAttribute('aria-label')).to.equal('link text'); }); it('should sprout "aria-label" with description text', async() => { const elem = await fixture(html`<d2l-menu-item-link text="link text" description="no this text"></d2l-menu-item-link>`); expect(elem.getAttribute('aria-label')).to.equal('no this text'); }); }); }); <|start_filename|>components/icons/getFileIconType.js<|end_filename|> export function getFileIconTypeFromExtension(extensionString) { switch (extensionString.toLowerCase()) { case 'zip': case 'tar': case 'z': case 'gz': case 'arj': case 'gzip': case 'bzip2': case 'sit': return 'file-archive'; case 'aac': case 'acc': case 'm4a': case 'm4p': case 'mid': case 'midi': case 'mp3': case 'mpa': case 'oga': case 'ra': case 'ram': case 'rax': case 'wav': case 'wma': return 'file-audio'; case 'doc': case 'docm': case 'docx': case 'dot': case 'dotm': case 'dotx': case 'rtf': return 'file-document'; case 'ico': case 'jpg': case 'jpeg': case 'gif': case 'bmp': case 'png': case 'mac': case 'pic': case 'pict': case 'pnt': case 'pntg': case 'svg': case 'tif': case 'tiff': return 'file-image'; case 'pot': case 'potx': case 'potm': case 'ppam': case 'ppsx': case 'ppsm': case 'ppt': case 'pptx': case 'pptm': return 'file-presentation'; case '3gp': case 'asf': case 'asx': case 'avi': case 'divx': case 'flv': case 'm4v': case 'mkv': case 'mov': case 'mp4': case 'mpeg': case 'mpg': case 'ogg': case 'ogv': case 'qt': case 'qti': case 'rm': case 'swf': case 'webm': case 'wm': case 'wmv': return 'file-video'; default: // default to file-document return 'file-document'; } } export function getFileIconTypeFromFilename(filename) { const index = filename.lastIndexOf('.'); if (index < 0) { return 'file-document'; // default to file-document } else { return getFileIconTypeFromExtension(filename.substring(index + 1)); } } <|start_filename|>components/card/test/card-loading-shimmer.test.js<|end_filename|> import '../card-loading-shimmer.js'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-card-loading-shimmer', () => { it('should construct', () => { runConstructor('d2l-card-loading-shimmer'); }); }); <|start_filename|>components/filter/test/filter-dimension-set-value.test.js<|end_filename|> import '../filter-dimension-set-value.js'; import { expect, fixture, html, oneEvent } from '@open-wc/testing'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; import { spy } from 'sinon'; const valuefixture = html` <d2l-filter-dimension-set-value key="value" text="Value"></d2l-filter-dimension-set-value> `; describe('d2l-filter-dimension-set-value', () => { it('should construct', () => { runConstructor('d2l-filter-dimension-set-value'); }); describe('data change', () => { it('fires data change event when its data changes', async() => { const elem = await fixture(valuefixture); const eventSpy = spy(elem, 'dispatchEvent'); elem.text = 'Test'; const e = await oneEvent(elem, 'd2l-filter-dimension-set-value-data-change'); expect(e.detail.valueKey).to.equal('value'); expect(e.detail.changes.size).to.equal(1); expect(e.detail.changes.get('text')).to.equal('Test'); expect(eventSpy).to.be.calledOnce; }); }); }); <|start_filename|>components/demo/code-view-styles.js<|end_filename|> import { css } from 'lit-element/lit-element.js'; export const styles = css` :host { border: 1px solid var(--d2l-color-tungsten); border-radius: 6px; box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2); display: block; max-width: 900px; overflow: hidden; position: relative; } :host([hidden]) { display: none; } :host .d2l-code-view-code { font-size: 14px; } :host .d2l-code-view-code::before { box-sizing: border-box; color: var(--d2l-color-tungsten); content: attr(data-language); font-size: 0.7rem; margin: 0 0.4rem; padding: 0; position: absolute; right: 0; top: 0; } :host([hide-language]) .d2l-code-view-code::before { display: none; } :host .d2l-code-view-src { display: none; } pre[class*="language-"] { margin: 0; padding: 18px; } `; <|start_filename|>mixins/focus-visible-polyfill-mixin.js<|end_filename|> let polyfillLoading = false; export const FocusVisiblePolyfillMixin = superclass => class extends superclass { connectedCallback() { super.connectedCallback(); if (!this.shadowRoot) return; if (window.applyFocusVisiblePolyfill) { window.applyFocusVisiblePolyfill(this.shadowRoot); return; } window.addEventListener('focus-visible-polyfill-ready', () => { // somehow it's occasionally still not available if (this.shadowRoot && window.applyFocusVisiblePolyfill) { window.applyFocusVisiblePolyfill(this.shadowRoot); } }, { once: true }); if (!polyfillLoading) { polyfillLoading = true; import('focus-visible'); } } }; <|start_filename|>helpers/test/dateTime.test.js<|end_filename|> import { formatDateInISO, formatDateTimeInISO, formatTimeInISO, getClosestValidDate, getDateFromDateObj, getDateFromISODate, getDateFromISODateTime, getDateFromISOTime, getLocalDateTimeFromUTCDateTime, getToday, getUTCDateTimeFromLocalDateTime, isDateInRange, parseISODate, parseISODateTime, parseISOTime } from '../dateTime.js'; import { expect } from '@open-wc/testing'; import { getDocumentLocaleSettings } from '@brightspace-ui/intl/lib/common.js'; import sinon from 'sinon'; describe('date-time', () => { const documentLocaleSettings = getDocumentLocaleSettings(); documentLocaleSettings.timezone.identifier = 'America/Toronto'; describe('formatDateInISO', () => { it('should return the correct date', () => { const date = { year: 2020, month: 3, date: 1 }; expect(formatDateInISO(date)).to.equal('2020-03-01'); }); it('should return the correct date', () => { const date = { year: 2020, month: 12, date: 20 }; expect(formatDateInISO(date)).to.equal('2020-12-20'); }); it('should throw when incorrect input', () => { expect(() => { formatDateInISO('hello'); }).to.throw('Invalid input: Expected input to be object containing year, month, and date'); }); it('should throw when no year', () => { expect(() => { formatDateInISO({ month: 10, date: 20 }); }).to.throw('Invalid input: Expected input to be object containing year, month, and date'); }); it('should throw when no month', () => { expect(() => { formatDateInISO({ year: 2013, date: 20 }); }).to.throw('Invalid input: Expected input to be object containing year, month, and date'); }); it('should throw when no date', () => { expect(() => { formatDateInISO({ year: 2013, month: 3 }); }).to.throw('Invalid input: Expected input to be object containing year, month, and date'); }); }); describe('formatDateTimeInISO', () => { it('should return the correct date-time', () => { const date = { year: 2020, month: 3, date: 1, hours: 12, minutes: 24, seconds: 36 }; expect(formatDateTimeInISO(date)).to.equal('2020-03-01T12:24:36.000Z'); }); it('should return the correct date', () => { const date = { year: 2020, month: 12, date: 20, hours: 1, minutes: 2, seconds: 3 }; expect(formatDateTimeInISO(date)).to.equal('2020-12-20T01:02:03.000Z'); }); it('should throw when no input', () => { expect(() => { formatDateTimeInISO(); }).to.throw('Invalid input: Expected input to be an object'); }); it('should throw when missing time data', () => { const date = { year: 2020, month: 12, date: 20 }; expect(() => { formatDateTimeInISO(date); }).to.throw(); }); it('should throw when missing date data', () => { const date = { hours: 1, minutes: 2, seconds: 3 }; expect(() => { formatDateTimeInISO(date); }).to.throw(); }); }); describe('formatTimeInISO', () => { it('should return the correct time', () => { const time = { hours: 1, minutes: 2, seconds: 3 }; expect(formatTimeInISO(time)).to.equal('01:02:03'); }); it('should return the correct date', () => { const time = { hours: 11, minutes: 22, seconds: 33 }; expect(formatTimeInISO(time)).to.equal('11:22:33'); }); it('should throw when incorrect input', () => { expect(() => { formatTimeInISO('hello'); }).to.throw('Invalid input: Expected input to be object containing hours, minutes, and seconds'); }); it('should throw when no hours', () => { expect(() => { formatTimeInISO({ minutes: 10, seconds: 20 }); }).to.throw('Invalid input: Expected input to be object containing hours, minutes, and seconds'); }); it('should throw when no minutes', () => { expect(() => { formatTimeInISO({ hours: 2013, seconds: 20 }); }).to.throw('Invalid input: Expected input to be object containing hours, minutes, and seconds'); }); it('should throw when no seconds', () => { expect(() => { formatTimeInISO({ hours: 2013, minutes: 3 }); }).to.throw('Invalid input: Expected input to be object containing hours, minutes, and seconds'); }); }); describe('getDateFromDateObj', () => { it('should return the correct date', () => { const date = { year: 2020, month: 3, date: 1 }; expect(getDateFromDateObj(date)).to.deep.equal(new Date(2020, 2, 1)); }); it('should throw when invalid date format', () => { expect(() => { getDateFromDateObj(); }).to.throw(); }); }); ['America/Toronto', 'Australia/Eucla'].forEach((timezone) => { describe(`getClosestValidDate in ${timezone}`, () => { let clock; const today = '2018-02-12T20:00:00.000Z'; const todayDate = timezone === 'America/Toronto' ? '2018-02-12' : '2018-02-13'; before(() => { documentLocaleSettings.timezone.identifier = timezone; const newToday = new Date(today); clock = sinon.useFakeTimers({ now: newToday.getTime(), toFake: ['Date'] }); }); after(() => { clock.restore(); documentLocaleSettings.timezone.identifier = 'America/Toronto'; }); describe('dateTime', () => { it('returns today when no min and max', () => { expect(getClosestValidDate(null, null, true)).to.equal(today); }); it('returns today when today after min', () => { expect(getClosestValidDate('2017-12-12T08:00:00.000Z', null, true)).to.equal(today); }); it('returns today when today before max', () => { expect(getClosestValidDate(null, '2020-11-12T08:00:00.000Z', true)).to.equal(today); }); it('returns min when today before min', () => { const min = '2020-12-12T12:00:00.000Z'; expect(getClosestValidDate(min, null, true)).to.equal(min); }); it('returns max when today after max', () => { const max = '2017-12-12T08:00:00.000Z'; expect(getClosestValidDate(null, max, true)).to.equal(max); }); it('returns today when between min and max', () => { expect(getClosestValidDate('2015-12-12T08:00:00.000Z', '2020-12-12T08:00:00.000Z', true)).to.equal(today); }); }); describe('date', () => { it('returns today when no min and max', () => { expect(getClosestValidDate(null, null, false)).to.equal(todayDate); }); it('returns today when today after min', () => { expect(getClosestValidDate('2015-01-10', null, false)).to.equal(todayDate); }); it('returns today when today before max', () => { expect(getClosestValidDate(null, '2020-11-10', false)).to.equal(todayDate); }); it('returns min when today before min', () => { const min = '2020-01-13'; expect(getClosestValidDate(min, null, false)).to.equal(min); }); it('returns max when today after max', () => { const max = '2015-07-10'; expect(getClosestValidDate(null, max, false)).to.equal(max); }); it('returns today when between min and max', () => { expect(getClosestValidDate('2015-07-10', '2021-01-01', false)).to.equal(todayDate); }); }); }); }); describe('getDateFromISODate', () => { it('should return the correct date', () => { expect(getDateFromISODate('2019-01-30')).to.deep.equal(new Date(2019, 0, 30)); }); it('should throw when invalid date format', () => { expect(() => { getDateFromISODate('2019/01/30'); }).to.throw('Invalid input: Expected format is YYYY-MM-DD'); }); }); describe('getDateFromISODateTime', () => { after(() => { documentLocaleSettings.timezone.identifier = 'America/Toronto'; }); it('should return the correct date', () => { expect(getDateFromISODateTime('2019-01-30T12:30:00Z')).to.deep.equal(new Date(2019, 0, 30, 7, 30, 0)); }); it('should return expected date in Australia/Eucla timezone', () => { documentLocaleSettings.timezone.identifier = 'Australia/Eucla'; expect(getDateFromISODateTime('2019-01-30T12:30:00Z')).to.deep.equal(new Date(2019, 0, 30, 21, 15, 0)); }); it('should throw when invalid date format', () => { expect(() => { getDateFromISODateTime('2019/01/30T12:34:46Z'); }).to.throw('Invalid input: Expected format is YYYY-MM-DDTHH:mm:ss.sssZ'); }); }); describe('getDateFromISOTime', () => { it('should return the correct date/time', () => { const newToday = new Date('2018-02-12T20:00:00Z'); const clock = sinon.useFakeTimers({ now: newToday.getTime(), toFake: ['Date'] }); expect(getDateFromISOTime('12:10:30')).to.deep.equal(new Date(2018, 1, 12, 12, 10, 30)); clock.restore(); }); }); describe('getLocalDateTimeFromUTCDateTime', () => { it('should return the correct date and time', () => { expect(getLocalDateTimeFromUTCDateTime('2019-01-30T12:05:10.000Z')).to.equal('2019-01-30T07:05:10.000'); }); it('should return the correct date and time', () => { expect(getLocalDateTimeFromUTCDateTime('2019-11-02T03:00:00.000Z')).to.equal('2019-11-01T23:00:00.000'); }); }); describe('getToday', () => { let clock; beforeEach(() => { const newToday = new Date('2018-02-12T20:00:00Z'); clock = sinon.useFakeTimers({ now: newToday.getTime(), toFake: ['Date'] }); }); afterEach(() => { clock.restore(); documentLocaleSettings.timezone.identifier = 'America/Toronto'; }); it('should return expected day in America/Toronto timezone', () => { expect(getToday()).to.deep.equal({ year: 2018, month: 2, date: 12, hours: 15, minutes: 0, seconds: 0 }); }); it('should return expected day in Australia/Eucla timezone', () => { documentLocaleSettings.timezone.identifier = 'Australia/Eucla'; expect(getToday()).to.deep.equal({ year: 2018, month: 2, date: 13, hours: 4, minutes: 45, seconds: 0 }); }); }); describe('getUTCDateTimeFromLocalDateTime', () => { it('should return the correct result', () => { const date = '2019-02-10'; const time = '14:20:30'; expect(getUTCDateTimeFromLocalDateTime(date, time)).to.equal('2019-02-10T19:20:30.000Z'); }); it('should return the correct result', () => { const date = '2030-01-20'; const time = '2:3:4'; expect(getUTCDateTimeFromLocalDateTime(date, time)).to.equal('2030-01-20T07:03:04.000Z'); }); it('should return the correct result when date contains time', () => { const date = '2030-01-20T12:00:00'; const time = '2:3:4'; expect(getUTCDateTimeFromLocalDateTime(date, time)).to.equal('2030-01-20T07:03:04.000Z'); }); it('should return the correct result when time contains date', () => { const date = '2030-01-20'; const time = '2012-01-10T2:3:4'; expect(getUTCDateTimeFromLocalDateTime(date, time)).to.equal('2030-01-20T07:03:04.000Z'); }); it('should throw when no time', () => { expect(() => { getUTCDateTimeFromLocalDateTime('2019-01-03'); }).to.throw('Invalid input: Expected date and time'); }); }); describe('isDateInRange', () => { const date = new Date(2018, 2, 3, 12, 0, 0); it('should return false if no parameters', () => { expect(isDateInRange()).to.be.false; }); it('should return true if no min and max', () => { expect(isDateInRange(date)).to.be.true; }); it('should return true if min and date is after min', () => { const min = new Date(2018, 1, 30, 12, 0, 0); expect(isDateInRange(date, min)).to.be.true; }); it('should return true if min and date is equal to min', () => { const min = new Date(2018, 2, 3, 12, 0, 0); expect(isDateInRange(date, min)).to.be.true; }); it('should return true if min and date has same date as min but time is after min', () => { const min = new Date(2018, 2, 3, 8, 0, 0); expect(isDateInRange(date, min)).to.be.true; }); it('should return false if min and date has same date as min but time is before min', () => { const min = new Date(2018, 2, 3, 15, 0, 0); expect(isDateInRange(date, min)).to.be.false; }); it('should return true if max and date is before max', () => { const max = new Date(2018, 5, 1, 12, 0, 0); expect(isDateInRange(date, undefined, max)).to.be.true; }); it('should return true if max and date is equal to max', () => { const max = new Date(2018, 2, 3, 12, 0, 0); expect(isDateInRange(date, undefined, max)).to.be.true; }); it('should return true if max and date has same date as max but time is before max', () => { const max = new Date(2018, 2, 3, 18, 0, 0); expect(isDateInRange(date, undefined, max)).to.be.true; }); it('should return false if max and date has same date as max but time is after max', () => { const max = new Date(2018, 2, 3, 10, 0, 0); expect(isDateInRange(date, undefined, max)).to.be.false; }); it('should return true if date is between min and max', () => { const min = new Date(2018, 2, 2, 12, 0, 0); const max = new Date(2018, 2, 4, 12, 0, 0); expect(isDateInRange(date, min, max)).to.be.true; }); it('should return false if min and date is before min', () => { const min = new Date(2018, 2, 4, 12, 0, 0); expect(isDateInRange(date, min, undefined)).to.be.false; }); it('should return false if max and date is after max', () => { const max = new Date(2018, 2, 1, 12, 0, 0); expect(isDateInRange(date, undefined, max)).to.be.false; }); it('should return false if min and max and date is before min', () => { const min = new Date(2018, 4, 2, 12, 0, 0); const max = new Date(2018, 4, 28, 12, 0, 0); expect(isDateInRange(date, min, max)).to.be.false; }); it('should return false if min and max and date is after max', () => { const min = new Date(2018, 0, 2, 12, 0, 0); const max = new Date(2018, 0, 28, 12, 0, 0); expect(isDateInRange(date, min, max)).to.be.false; }); }); describe('parseISODate', () => { it('should return correct date', () => { expect(parseISODate('2019-01-30')).to.deep.equal({ year: 2019, month: 1, date: 30 }); }); it('should return correct date when full ISO date', () => { expect(parseISODate('2019-01-30T15:00:00.000Z')).to.deep.equal({ year: 2019, month: 1, date: 30 }); }); it('should throw when invalid date format', () => { expect(() => { parseISODate('2019/01/30'); }).to.throw('Invalid input: Expected format is YYYY-MM-DD'); }); }); describe('parseISODateTime', () => { it('should return correct date if date and time provided', () => { expect(parseISODateTime('2019-10-30T12:10:30.000Z')).to.deep.equal({ year: 2019, month: 10, date: 30, hours: 12, minutes: 10, seconds: 30 }); }); it('should throw when invalid date format', () => { expect(() => { parseISODateTime('2019/01/30'); }).to.throw('Invalid input: Expected format is YYYY-MM-DD'); }); }); describe('parseISOTime', () => { it('should return correct time when full ISO date', () => { expect(parseISOTime('2019-02-12T18:00:00.000Z')).to.deep.equal({ hours: 18, minutes: 0, seconds: 0 }); }); it('should return correct time when hours, minutes, seconds', () => { expect(parseISOTime('12:10:30')).to.deep.equal({ hours: 12, minutes: 10, seconds: 30 }); }); it('should return correct time when hours, minutes', () => { expect(parseISOTime('12:10')).to.deep.equal({ hours: 12, minutes: 10, seconds: 0 }); }); it('should throw when invalid time format', () => { expect(() => { parseISOTime('12'); }).to.throw('Invalid input: Expected format is hh:mm:ss'); }); ['12', '', '2019-02-12', 'text'].forEach((val) => { it(`should throw when invalid time format: "${val}"`, () => { expect(() => parseISOTime(val)).to.throw('Invalid input: Expected format is hh:mm:ss'); }); }); }); }); <|start_filename|>components/icons/test/getFileIconType.test.js<|end_filename|> import { getFileIconTypeFromExtension, getFileIconTypeFromFilename } from '../getFileIconType.js'; import { expect } from '@open-wc/testing'; describe('getFileIconType', () => { describe('getFileIconTypeFromExtension', () => { const emptyExts = ['', ' ', '.']; const files = [['DoCx', 'file-document'], ['PNG', 'file-image'], ['mp4', 'file-video']]; it('should return the correct default', () => { emptyExts.forEach(ext => { expect(getFileIconTypeFromExtension(ext)).to.equal('file-document'); }); }); it('should return correct file type', () => { files.forEach(([ext, expected]) => { expect(getFileIconTypeFromExtension(ext)).to.equal(expected); }); }); }); describe('getFileIconTypeFromFilename', () => { const emptyNames = ['', ' ', 'some_file', '.config']; const filenames = [['my-document.DoCx', 'file-document'], ['..PNG', 'file-image'], ['.mp4', 'file-video']]; it('should return the correct default', () => { emptyNames.forEach(name => { expect(getFileIconTypeFromFilename(name)).to.equal('file-document'); }); }); it('should return correct file type', () => { filenames.forEach(([name, expected]) => { expect(getFileIconTypeFromFilename(name)).to.equal(expected); }); }); }); }); <|start_filename|>components/button/test/button-subtle.axe.js<|end_filename|> import '../button-subtle.js'; import { expect, fixture, html, oneEvent } from '@open-wc/testing'; describe('d2l-button-subtle', () => { it('normal', async() => { const el = await fixture(html`<d2l-button-subtle text="Subtle Button"></d2l-button-subtle>`); await expect(el).to.be.accessible(); }); it('normal + disabled', async() => { const el = await fixture(html`<d2l-button-subtle disabled text="Disabled Subtle Button"></d2l-button-subtle>`); await expect(el).to.be.accessible(); }); it('normal + disabled + disabled-tooltip', async() => { const el = await fixture(html`<d2l-button-subtle disabled disabled-tooltip="tooltip text" text="Disabled Subtle Button"></d2l-button-subtle>`); await expect(el).to.be.accessible(); }); it('normal + focused', async() => { const el = await fixture(html`<d2l-button-subtle text="Subtle Button"></d2l-button-subtle>`); setTimeout(() => el.shadowRoot.querySelector('button').focus()); await oneEvent(el, 'focus'); await expect(el).to.be.accessible(); }); it('icon', async() => { const el = await fixture(html`<d2l-button-subtle text="Subtle Button with Icon" icon="tier1:gear"></d2l-button-subtle>`); await expect(el).to.be.accessible(); }); it('icon + disabled', async() => { const el = await fixture(html`<d2l-button-subtle disabled text="Subtle Button with Icon" icon="tier1:gear"></d2l-button-subtle>`); await expect(el).to.be.accessible(); }); it('icon + focused', async() => { const el = await fixture(html`<d2l-button-subtle text="Subtle Button with Icon" icon="tier1:gear"></d2l-button-subtle>`); setTimeout(() => el.shadowRoot.querySelector('button').focus()); await oneEvent(el, 'focus'); await expect(el).to.be.accessible(); }); }); <|start_filename|>mixins/visible-on-ancestor-mixin.js<|end_filename|> import { findComposedAncestor, isComposedAncestor } from '../helpers/dom.js'; import { css } from 'lit-element/lit-element.js'; const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches; export const visibleOnAncestorStyles = css` :host([__voa-state="hidden"]), :host([__voa-state="hiding"]) { opacity: 0 !important; transform: translateY(-10px) !important; } :host([__voa-state="showing"]), :host([__voa-state="hiding"]) { transition: transform 200ms ease-out, opacity 200ms ease-out !important; } @media only screen and (hover: none), only screen and (-moz-touch-enabled: 1) { :host([__voa-state="hidden"]), :host([__voa-state="hiding"]) { opacity: 1 !important; transform: translateY(0) !important; } :host([__voa-state="hidden"][d2l-visible-on-ancestor-no-hover-hide]), :host([__voa-state="hiding"][d2l-visible-on-ancestor-no-hover-hide]) { opacity: 0 !important; transform: translateY(-10px) !important; } } `; export const VisibleOnAncestorMixin = superclass => class extends superclass { static get properties() { return { /** * @ignore */ visibleOnAncestor: { type: Boolean, reflect: true, attribute: 'visible-on-ancestor' }, __voaState: { type: String, reflect: true, attribute: '__voa-state' } }; } constructor() { super(); this.visibleOnAncestor = false; } attributeChangedCallback(name, oldval, newval) { if (name === 'visible-on-ancestor' && this.__voaAttached) { if (newval) this.__voaInit(); else this.__voaUninit(); } super.attributeChangedCallback(name, oldval, newval); } connectedCallback() { super.connectedCallback(); this.__voaAttached = true; if (this.visibleOnAncestor) { requestAnimationFrame(() => this.__voaInit()); } else this.__voaState = null; } disconnectedCallback() { this.__voaAttached = false; this.__voaUninit(); super.disconnectedCallback(); } __voaHandleBlur(e) { if (isComposedAncestor(this.__voaTarget, e.relatedTarget)) return; this.__voaFocusIn = false; this.__voaHide(); } __voaHandleFocus() { this.__voaFocusIn = true; this.__voaShow(); } __voaHandleMouseEnter() { this.__voaMouseOver = true; this.__voaShow(); } __voaHandleMouseLeave() { this.__voaMouseOver = false; this.__voaHide(); } __voaHide() { if (this.__voaFocusIn || this.__voaMouseOver) return; if (reduceMotion) { this.__voaState = 'hidden'; } else { const handleTransitionEnd = (e) => { if (e.propertyName !== 'transform') return; this.removeEventListener('transitionend', handleTransitionEnd); this.__voaState = 'hidden'; }; this.addEventListener('transitionend', handleTransitionEnd); this.__voaState = 'hiding'; } } __voaInit() { if (!this.visibleOnAncestor) return; this.__voaTarget = findComposedAncestor(this, (node) => { if (!node || node.nodeType !== 1) return false; return (node.classList.contains('d2l-visible-on-ancestor-target')); }); if (!this.__voaTarget) { this.__voaState = null; return; } this.__voaHandleBlur = this.__voaHandleBlur.bind(this); this.__voaHandleFocus = this.__voaHandleFocus.bind(this); this.__voaHandleMouseEnter = this.__voaHandleMouseEnter.bind(this); this.__voaHandleMouseLeave = this.__voaHandleMouseLeave.bind(this); this.__voaTarget.addEventListener('focus', this.__voaHandleFocus, true); this.__voaTarget.addEventListener('blur', this.__voaHandleBlur, true); this.__voaTarget.addEventListener('mouseenter', this.__voaHandleMouseEnter); this.__voaTarget.addEventListener('mouseleave', this.__voaHandleMouseLeave); this.__voaState = 'hidden'; } __voaShow() { if (reduceMotion) { this.__voaState = 'shown'; } else { const handleTransitionEnd = (e) => { if (e.propertyName !== 'transform') return; this.removeEventListener('transitionend', handleTransitionEnd); this.__voaState = 'shown'; }; this.addEventListener('transitionend', handleTransitionEnd); this.__voaState = 'showing'; } } __voaUninit() { this.__voaState = null; if (!this.__voaTarget) return; this.__voaTarget.removeEventListener('focus', this.__voaHandleFocus, true); this.__voaTarget.removeEventListener('blur', this.__voaHandleBlur, true); this.__voaTarget.removeEventListener('mouseenter', this.__voaHandleMouseEnter); this.__voaTarget.removeEventListener('mouseleave', this.__voaHandleMouseLeave); this.__voaTarget = null; } }; <|start_filename|>components/validation/validation-custom.js<|end_filename|> import { LitElement } from 'lit-element/lit-element.js'; import { ValidationCustomMixin } from './validation-custom-mixin.js'; class ValidationCustom extends ValidationCustomMixin(LitElement) { async validate() { const validation = new Promise(resolve => { const details = { detail: { forElement: this.forElement, resolve } }; const event = new CustomEvent('d2l-validation-custom-validate', details); return this.dispatchEvent(event); }); return validation; } } customElements.define('d2l-validation-custom', ValidationCustom); <|start_filename|>components/validation/test/validation-custom.test.js<|end_filename|> import '../validation-custom.js'; import { aTimeout, expect, fixture, html, oneEvent } from '@open-wc/testing'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; const basicFixture = html` <div> <div> <input id="target" type="text"/> </div> <d2l-validation-custom for="target" failure-text="An error occurred"></d2l-validation-custom> </div> `; describe('d2l-validation-custom', () => { let root, custom; beforeEach(async() => { root = await fixture(basicFixture); custom = root.querySelector('d2l-validation-custom'); }); describe('constructor', () => { it('should construct', () => { runConstructor('d2l-validation-custom'); }); }); describe('for', () => { it('should find for-element using for attribute', () => { const expectedForElement = root.querySelector('#target'); expect(custom.forElement).to.equal(expectedForElement); }); }); describe('events', () => { it('should fire connected event', async() => { const unconnectedCustom = document.createElement('d2l-validation-custom'); setTimeout(() => root.appendChild(unconnectedCustom), 0); await oneEvent(unconnectedCustom, 'd2l-validation-custom-connected'); }); it('should fire disconnected event', async() => { setTimeout(() => custom.remove(), 0); await oneEvent(custom, 'd2l-validation-custom-disconnected'); expect(custom.forElement).to.be.null; }); [true, false].forEach(expectedIsValid => { it('should fire validate event for async handler', async() => { const validationHandler = async(e) => { await aTimeout(0); e.detail.resolve(expectedIsValid); }; custom.addEventListener('d2l-validation-custom-validate', validationHandler); const isValid = await custom.validate(); expect(isValid).to.equal(expectedIsValid); }); it('should fire validate event for sync handler', async() => { const validationHandler = (e) => { e.detail.resolve(expectedIsValid); }; custom.addEventListener('d2l-validation-custom-validate', validationHandler); const isValid = await custom.validate(); expect(isValid).to.equal(expectedIsValid); }); }); }); }); <|start_filename|>test/styles.css<|end_filename|> html { font-size: 20px; } body { padding: 30px; } .visual-diff { caret-color: transparent; margin-bottom: 30px; } .visual-diff-translucent { background: repeating-linear-gradient( 45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px ); } .visual-diff-dark { background-color: #000000; } <|start_filename|>directives/animate/demo/animate-test.js<|end_filename|> import '../../../components/button/button.js'; import '../../../components/inputs/input-checkbox.js'; import '../../../components/list/list.js'; import '../../../components/list/list-item.js'; import { css, html, LitElement } from 'lit-element/lit-element.js'; import { hide, show } from '../animate.js'; export class AnimateTest extends LitElement { static get properties() { return { _listVisibility: { type: Boolean, reflect: false }, _renderCount: { type: Number, reflect: false } }; } static get styles() { return css` :host { display: block; } d2l-list { margin-bottom: 0.9rem; max-width: 400px; } `; } constructor() { super(); this._counter = 3; this._doAnimate = false; this._items = [ { number: 1, state: 'existing' }, { number: 2, state: 'existing' }, { number: 3, state: 'existing' } ]; this._listVisibility = true; this._renderCount = 0; } render() { const animateAction = this._listVisibility ? show({ skip: !this._doAnimate }) : hide({ skip: !this._doAnimate }); const items = this._items.map((item) => { let animateAction = undefined; let showItem = false; if (item.state === 'remove') { item.state = 'removed'; animateAction = hide(); showItem = true; } else if (item.state === 'new') { item.state = 'existing'; animateAction = show(); showItem = true; } else if (item.state === 'existing') { showItem = true; } return showItem ? html`<d2l-list-item .animate="${animateAction}"> Item ${item.number} <d2l-button-icon slot="actions" icon="tier1:delete" text="Remove" @click="${this._handleRemove}" data-number="${item.number}"></d2l-button-icon> </d2l-list-item>` : null; }); return html` <d2l-input-checkbox .checked="${this._listVisibility}" @change="${this._handleToggleList}">Show items</d2l-input-checkbox> <d2l-list .animate="${animateAction}">${items}</d2l-list> <d2l-button @click="${this._handleAddItem}" ?disabled="${!this._listVisibility}">Add Item</d2l-button> <d2l-button @click="${this._handleReRender}">Re-render (${this._renderCount})</d2l-button> `; } _handleAddItem() { this._counter++; this._items.push({ number: this._counter, state: 'new' }); this.requestUpdate(); } _handleRemove(e) { const removeItem = this._items.find(item => item.number === parseInt(e.target.getAttribute('data-number'))); if (removeItem) { removeItem.state = 'remove'; this.requestUpdate(); } } _handleReRender() { this._renderCount++; } _handleToggleList(e) { this._listVisibility = e.target.checked; this._doAnimate = true; } } customElements.define('d2l-animate-test', AnimateTest); <|start_filename|>components/list/test/list.axe.js<|end_filename|> import '../list.js'; import '../list-item.js'; import '../list-item-button.js'; import { expect, fixture, html } from '@open-wc/testing'; const normalFixture = html` <d2l-list> <d2l-list-item> <div class="d2l-list-item-text d2l-body-compact">Identify categories of physical activities</div> <div class="d2l-list-item-text-secondary d2l-body-small">Specific Expectation A1.2</div> </d2l-list-item> <d2l-list-item href="http://www.d2l.com"> <div class="d2l-list-item-text d2l-body-compact">Identify categories of physical activities</div> <div class="d2l-list-item-text-secondary d2l-body-small">Specific Expectation A1.2</div> </d2l-list-item> <d2l-list-item-button> <div class="d2l-list-item-text d2l-body-compact">Apply a decision-making process to assess risks and make safe decisions in a variety of situations</div> <div class="d2l-list-item-text-secondary d2l-body-small">Specific Expectation B2.1</div> </d2l-list-item-button> </d2l-list> `; describe('d2l-list', () => { it('should pass all aXe tests', async() => { const elem = await fixture(normalFixture); await expect(elem).to.be.accessible(); }); }); <|start_filename|>templates/primary-secondary/test/primary-secondary.test.js<|end_filename|> import '../primary-secondary.js'; import { expect, fixture, html } from '@open-wc/testing'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-template-primary-secondary', () => { [ { name: 'fixed', resizable: false }, { name: 'resizable', resizable: true }, ].forEach((testCase) => { it(`${testCase.name} should pass all aXe tests`, async() => { const elem = await fixture(html`<d2l-template-primary-secondary ?resizable="${testCase.resizable}"></d2l-template-primary-secondary>`); await expect(elem).to.be.accessible(); }); }); it('should construct', () => { runConstructor('d2l-template-primary-secondary'); }); }); <|start_filename|>components/typography/styles.js<|end_filename|> import { css } from 'lit-element/lit-element.js'; export const bodyStandardStyles = css` .d2l-body-standard { font-size: 0.95rem; font-weight: 400; line-height: 1.4rem; } :host([skeleton]) .d2l-body-standard.d2l-skeletize::before { bottom: 0.35rem; top: 0.3rem; } :host([skeleton]) .d2l-body-standard.d2l-skeletize-paragraph-2 { max-height: 2.8rem; } :host([skeleton]) .d2l-body-standard.d2l-skeletize-paragraph-3 { max-height: 4.2rem; } :host([skeleton]) .d2l-body-standard.d2l-skeletize-paragraph-5 { max-height: 7rem; } @media (max-width: 615px) { .d2l-body-standard { font-size: 0.8rem; line-height: 1.2rem; } :host([skeleton]) .d2l-body-standard.d2l-skeletize::before { bottom: 0.3rem; top: 0.3rem; } :host([skeleton]) .d2l-body-standard.d2l-skeletize-paragraph-2 { max-height: 2.4rem; } :host([skeleton]) .d2l-body-standard.d2l-skeletize-paragraph-3 { max-height: 3.6rem; } :host([skeleton]) .d2l-body-standard.d2l-skeletize-paragraph-5 { max-height: 6rem; } } `; export const bodyCompactStyles = css` .d2l-body-compact { font-size: 0.8rem; font-weight: 400; line-height: 1.2rem; } :host([skeleton]) .d2l-body-compact.d2l-skeletize::before { bottom: 0.3rem; top: 0.3rem; } :host([skeleton]) .d2l-body-compact.d2l-skeletize-paragraph-2 { max-height: 2.4rem; } :host([skeleton]) .d2l-body-compact.d2l-skeletize-paragraph-3 { max-height: 3.6rem; } :host([skeleton]) .d2l-body-compact.d2l-skeletize-paragraph-5 { max-height: 6rem; } `; export const bodySmallStyles = css` .d2l-body-small { color: var(--d2l-color-tungsten); font-size: 0.7rem; font-weight: 400; line-height: 1rem; margin: auto; } :host([skeleton]) .d2l-body-small.d2l-skeletize::before { bottom: 0.25rem; top: 0.2rem; } :host([skeleton]) .d2l-body-small.d2l-skeletize-paragraph-2 { max-height: 2rem; } :host([skeleton]) .d2l-body-small.d2l-skeletize-paragraph-3 { max-height: 3rem; } :host([skeleton]) .d2l-body-small.d2l-skeletize-paragraph-5 { max-height: 5rem; } @media (max-width: 615px) { .d2l-body-small { font-size: 0.6rem; line-height: 0.9rem; } :host([skeleton]) .d2l-body-small.d2l-skeletize::before { bottom: 0.25rem; top: 0.2rem; } :host([skeleton]) .d2l-body-small.d2l-skeletize-paragraph-2 { max-height: 1.8rem; } :host([skeleton]) .d2l-body-small.d2l-skeletize-paragraph-3 { max-height: 2.7rem; } :host([skeleton]) .d2l-body-small.d2l-skeletize-paragraph-5 { max-height: 4.5rem; } } `; export const heading1Styles = css` .d2l-heading-1 { font-size: 2rem; font-weight: 400; line-height: 2.4rem; margin: 1.5rem 0 1.5rem 0; } :host([skeleton]) .d2l-heading-1.d2l-skeletize { height: 2.4rem; overflow: hidden; } :host([skeleton]) .d2l-heading-1.d2l-skeletize::before { bottom: 0.45rem; top: 0.45rem; } @media (max-width: 615px) { .d2l-heading-1 { font-size: 1.5rem; line-height: 1.8rem; } :host([skeleton]) .d2l-heading-1.d2l-skeletize { height: 1.8rem; } :host([skeleton]) .d2l-heading-1.d2l-skeletize::before { bottom: 0.3rem; top: 0.35rem; } } `; export const heading2Styles = css` .d2l-heading-2 { font-size: 1.5rem; font-weight: 400; line-height: 1.8rem; margin: 1.5rem 0 1.5rem 0; } :host([skeleton]) .d2l-heading-2.d2l-skeletize { height: 1.8rem; overflow: hidden; } :host([skeleton]) .d2l-heading-2.d2l-skeletize::before { bottom: 0.3rem; top: 0.35rem; } @media (max-width: 615px) { .d2l-heading-2 { font-size: 1rem; font-weight: 700; line-height: 1.5rem; } :host([skeleton]) .d2l-heading-2.d2l-skeletize { height: 1.5rem; } :host([skeleton]) .d2l-heading-2.d2l-skeletize::before { bottom: 0.35rem; top: 0.35rem; } } `; export const heading3Styles = css` .d2l-heading-3 { font-size: 1rem; font-weight: 700; line-height: 1.5rem; margin: 1.5rem 0 1.5rem 0; } :host([skeleton]) .d2l-heading-3.d2l-skeletize { height: 1.5rem; overflow: hidden; } :host([skeleton]) .d2l-heading-3.d2l-skeletize::before { bottom: 0.35rem; top: 0.35rem; } @media (max-width: 615px) { .d2l-heading-3 { font-size: 0.8rem; line-height: 1.2rem; } :host([skeleton]) .d2l-heading-3.d2l-skeletize { height: 1.2rem; } :host([skeleton]) .d2l-heading-3.d2l-skeletize::before { bottom: 0.3rem; top: 0.25rem; } } `; export const heading4Styles = css` .d2l-heading-4 { font-size: 0.8rem; font-weight: 700; line-height: 1.2rem; margin: 1.5rem 0 1.5rem 0; } :host([skeleton]) .d2l-heading-4.d2l-skeletize { height: 1.2rem; overflow: hidden; } :host([skeleton]) .d2l-heading-4.d2l-skeletize::before { bottom: 0.25rem; top: 0.25rem; } `; export const labelStyles = css` .d2l-label-text { font-size: 0.7rem; font-weight: 700; letter-spacing: 0.2px; line-height: 1rem; } :host([skeleton]) .d2l-label-text.d2l-skeletize::before { bottom: 0.25rem; top: 0.15rem; } `; <|start_filename|>components/inputs/test/input-textarea.test.js<|end_filename|> import '../input-textarea.js'; import { expect, fixture, html, oneEvent } from '@open-wc/testing'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; const normalFixture = html`<d2l-input-textarea label="label"></d2l-input-textarea>`; function dispatchEvent(elem, eventType, composed) { const e = new Event( eventType, { bubbles: true, cancelable: false, composed: composed } ); getTextArea(elem).dispatchEvent(e); } function getTextArea(elem) { return elem.shadowRoot.querySelector('textarea'); } function getLabel(elem) { return elem.shadowRoot.querySelector('.d2l-input-label'); } describe('d2l-input-textarea', () => { describe('constructor', () => { it('should construct', () => { runConstructor('d2l-input-textarea'); }); }); describe('accessibility', () => { it('should display visible label', async() => { const elem = await fixture(normalFixture); expect(getLabel(elem).innerText).to.equal('label'); }); it('should put hidden label on "aria-label"', async() => { const elem = await fixture(html`<d2l-input-textarea label="label" label-hidden></d2l-input-textarea>`); expect(getLabel(elem)).to.be.null; expect(getTextArea(elem).getAttribute('aria-label')).to.equal('label'); }); it('should set aria-describedby when description', async() => { const elem = await fixture(html`<d2l-input-textarea label="label" description="text description"></d2l-input-textarea>`); const description = elem.shadowRoot.querySelector('div.d2l-offscreen'); expect(getTextArea(elem).hasAttribute('aria-describedby')).to.be.true; expect(description.textContent).to.equal('text description'); }); it('should not set aria-describedby when no description', async() => { const elem = await fixture(normalFixture); expect(getTextArea(elem).hasAttribute('aria-describedby')).to.be.false; }); it('should set aria-required when required', async() => { const elem = await fixture(html`<d2l-input-textarea label="label" required></d2l-input-textarea>`); const textarea = getTextArea(elem); expect(textarea.required).to.be.true; expect(textarea.getAttribute('aria-required')).to.equal('true'); }); }); describe('validation', () => { it('should be invalid when empty and required', async() => { const elem = await fixture(normalFixture); elem.required = true; const errors = await elem.validate(); expect(errors).to.contain('label is required.'); }); it('should be valid when required has value', async() => { const elem = await fixture(normalFixture); elem.required = true; elem.value = 'hi'; const errors = await elem.validate(); expect(errors).to.be.empty; }); it('should be invalid when length is less than min length', async() => { const elem = await fixture(normalFixture); elem.minlength = 10; elem.value = 'only nine'; const errors = await elem.validate(); expect(errors).to.contain('label must be at least 10 characters'); }); it('should be valid when length is greater than or equal to min length', async() => { const elem = await fixture(normalFixture); elem.minlength = 10; elem.value = 'more than nine'; const errors = await elem.validate(); expect(errors).to.be.empty; }); it('should be valid with min length when empty', async() => { const elem = await fixture(normalFixture); elem.minlength = 10; const errors = await elem.validate(); expect(errors).to.be.empty; }); }); describe('value', () => { it('should dispatch uncomposed "change" event when textarea changes', async() => { const elem = await fixture(normalFixture); setTimeout(() => dispatchEvent(elem, 'change', false)); const { composed } = await oneEvent(elem, 'change'); expect(composed).to.be.false; }); it('should dispatch "input" event when textarea changes', async() => { const elem = await fixture(normalFixture); setTimeout(() => dispatchEvent(elem, 'input', true)); await oneEvent(elem, 'input'); }); }); }); <|start_filename|>components/html-block/test/html-block.axe.js<|end_filename|> import '../html-block.js'; import { expect, fixture, html } from '@open-wc/testing'; describe('d2l-html-block', () => { it('simple', async() => { const elem = await fixture(html`<d2l-html-block><template>some html</template></d2l-html-block>`); await expect(elem).to.be.accessible(); }); }); <|start_filename|>components/skeleton/demo/skeleton-test-paragraph.js<|end_filename|> import { bodyCompactStyles, bodySmallStyles, bodyStandardStyles, labelStyles } from '../../typography/styles.js'; import { css, html, LitElement } from 'lit-element/lit-element.js'; import { classMap } from 'lit-html/directives/class-map.js'; import { SkeletonMixin } from '../skeleton-mixin.js'; export class SkeletonTestParagraph extends SkeletonMixin(LitElement) { static get properties() { return { lines: { type: Number }, type: { type: String } }; } static get styles() { return [ super.styles, bodyStandardStyles, bodyCompactStyles, bodySmallStyles, labelStyles, css` :host { display: block; } ` ]; } constructor() { super(); this.type = 'standard'; } render() { const classes = { 'd2l-body-standard': this.type === 'standard', 'd2l-body-compact': this.type === 'compact', 'd2l-body-small': this.type === 'small', 'd2l-label-text': this.type === 'label', 'd2l-skeletize': this.lines !== 2 && this.lines !== 3 && this.lines !== 5, 'd2l-skeletize-paragraph-2': this.lines === 2, 'd2l-skeletize-paragraph-3': this.lines === 3, 'd2l-skeletize-paragraph-5': this.lines === 5 }; if (this.lines) { return html`<p class="${classMap(classes)}">${this.type} ${this.lines}-line</p>`; } else { return html`<span class="${classMap(classes)}">${this.type}</span>`; } } } customElements.define('d2l-test-skeleton-paragraph', SkeletonTestParagraph); <|start_filename|>components/skeleton/demo/skeleton-test-width.js<|end_filename|> import { css, html, LitElement } from 'lit-element/lit-element.js'; import { SkeletonMixin } from '../skeleton-mixin.js'; export class SkeletonTestWidth extends SkeletonMixin(LitElement) { static get styles() { return [ super.styles, css`:host { display: block; }` ]; } render() { const sizes = [...Array(19).keys()].map(i => (i + 1) * 5); return sizes.map(s => html`<p class="d2l-skeletize d2l-skeletize-${s}">${s}&#37;</p>`); } } customElements.define('d2l-test-skeleton-width', SkeletonTestWidth); <|start_filename|>components/selection/test/selection-component.js<|end_filename|> import { css, html, LitElement } from 'lit-element/lit-element.js'; import { SelectionMixin } from '../selection-mixin.js'; class TestSelection extends SelectionMixin(LitElement) { static get styles() { return css` :host { display: block; } `; } render() { return html` <slot></slot> `; } } customElements.define('d2l-test-selection', TestSelection); <|start_filename|>components/more-less/test/more-less.test.js<|end_filename|> import '../more-less.js'; import { expect, fixture, html, oneEvent } from '@open-wc/testing'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; export function waitForHeight(elem) { return new Promise((resolve) => { function check() { const content = elem.shadowRoot.querySelector('.d2l-more-less-content'); if (content.style.height === '') { setTimeout(() => check(), 10); } else { // Need the second timeout here to give the transition a chance to finish setTimeout(() => resolve(), 400); } } check(); }); } export async function waitForRender(elem) { await oneEvent(elem, 'd2l-more-less-render'); } describe('d2l-more-less', () => { describe('constructor', () => { it('should construct', () => { runConstructor('d2l-more-less'); }); }); describe('expanded', () => { let elem; beforeEach(async() => { elem = await fixture(html` <d2l-more-less expanded> <p id="clone-target">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum elementum venenatis arcu sit amet varius. Maecenas posuere magna arcu, quis maximus odio fringilla ac. Integer ligula lorem, faucibus sit amet cursus vel, pellentesque a justo. Aliquam urna metus, molestie at tempor eget, vestibulum a purus. Donec aliquet rutrum mi. Duis ornare congue tempor. Nullam sed massa fermentum, tincidunt leo eu, vestibulum orci. Sed ultrices est in lacus venenatis, posuere suscipit arcu scelerisque. In aliquam ipsum rhoncus, lobortis ligula ut, molestie orci. Proin scelerisque tempor posuere. Phasellus consequat, lorem quis hendrerit tempor, sem lectus sagittis nunc, in tristique dui arcu non arcu. Nunc aliquam nisi et sapien commodo lacinia. <a href="javascript:void(0);">Quisque</a> iaculis orci vel odio varius porta. Fusce tincidunt dolor enim, vitae sollicitudin purus suscipit eu.</p> </d2l-more-less> `); await waitForRender(elem); await waitForHeight(elem); }); it('should expand when more content is dynamically added', async() => { const content = elem.shadowRoot.querySelector('.d2l-more-less-content'); const previousContentHeight = content.scrollHeight; expect(elem.offsetHeight).to.be.above(content.scrollHeight); const p = document.getElementById('clone-target'); content.appendChild(p.cloneNode(true)); await waitForHeight(elem); expect(content.scrollHeight).to.be.above(previousContentHeight); expect(elem.offsetHeight).to.be.above(content.scrollHeight); }); }); }); <|start_filename|>components/form/test/form-element-localize-helper.test.js<|end_filename|> import '../../validation/validation-custom.js'; import './form-element.js'; import { defineCE, expect, fixture } from '@open-wc/testing'; import { html, LitElement } from 'lit-element/lit-element.js'; import { LocalizeCoreElement } from '../../../lang/localize-core-element.js'; import { localizeFormElement } from '../form-element-localize-helper.js'; const formTag = defineCE( class extends LocalizeCoreElement(LitElement) {} ); const formFixture = `<${formTag}></${formTag}`; describe('form-element-localize-helper', () => { let localize; beforeEach(async() => { const form = await fixture(formFixture); localize = form.localize.bind(form); }); describe('basic', () => { const inputFixture = html`<input type="text"/>`; let input; beforeEach(async() => { input = await fixture(inputFixture); }); it('should localize required error', async() => { input.required = true; const errorMessage = localizeFormElement(localize, input); expect(errorMessage).to.equal('Field is required.'); }); it('should localize unknown error', async() => { input.pattern = '[A-Za-z]{3}'; input.value = 'A'; const errorMessage = localizeFormElement(localize, input); expect(errorMessage).to.equal('Field is invalid.'); }); }); describe('input', () => { describe('number', () => { const inputFixture = html`<input type="number"/>`; let input; beforeEach(async() => { input = await fixture(inputFixture); }); it('should localize range underflow error', async() => { input.min = '100'; input.value = '10'; const errorMessage = localizeFormElement(localize, input); expect(errorMessage).to.equal('Number must be greater than or equal to 100.'); }); it('should localize range overflowflow error', async() => { input.max = '9'; input.value = '100'; const errorMessage = localizeFormElement(localize, input); expect(errorMessage).to.equal('Number must be less than or equal to 9.'); }); }); describe('url', () => { const inputFixture = html`<input type="url"/>`; let input; beforeEach(async() => { input = await fixture(inputFixture); }); it('should localize type mismatch error', async() => { input.value = 'notaurl'; const errorMessage = localizeFormElement(localize, input); expect(errorMessage).to.equal('URL is not valid'); }); }); describe('email', () => { const inputFixture = html`<input aria-label="Contact" type="email"/>`; let input; beforeEach(async() => { input = await fixture(inputFixture); }); it('should localize type mismatch error', async() => { input.value = 'notanemail'; const errorMessage = localizeFormElement(localize, input); expect(errorMessage).to.equal('Email is not valid'); }); }); }); }); <|start_filename|>components/card/test/card-content-title.test.js<|end_filename|> import '../card-content-title.js'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-card-content-title', () => { it('should construct', () => { runConstructor('d2l-card-content-title'); }); }); <|start_filename|>components/table/test/table-test-visual-diff.js<|end_filename|> import '../table-col-sort-button.js'; import { css, html, LitElement } from 'lit-element/lit-element.js'; import { tableStyles } from '../table-wrapper.js'; const url = new URL(window.location.href); const type = url.searchParams.get('type') === 'light' ? 'light' : 'default'; class TestTableVisualDiff extends LitElement { static get styles() { return [tableStyles, css` .d2l-visual-diff { margin-bottom: 300px; } `]; } render() { return html` <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="standard-thead"> <table class="d2l-table"> <thead> <tr> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> </thead> <tbody> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr> <td>Cell 2-A</td> <td>Cell 2-B</td> <td>Cell 2-C</td> </tr> <tr> <td>Cell 3-A</td> <td>Cell 3-B</td> <td>Cell 3-C</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="standard-no-thead-class"> <table class="d2l-table"> <tr class="d2l-table-header"> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr> <td>Cell 2-A</td> <td>Cell 2-B</td> <td>Cell 2-C</td> </tr> <tr> <td>Cell 3-A</td> <td>Cell 3-B</td> <td>Cell 3-C</td> </tr> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="standard-no-thead-attr"> <table class="d2l-table"> <tr header> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr> <td>Cell 2-A</td> <td>Cell 2-B</td> <td>Cell 2-C</td> </tr> <tr> <td>Cell 3-A</td> <td>Cell 3-B</td> <td>Cell 3-C</td> </tr> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="vertical-align"> <table class="d2l-table"> <thead> <tr> <th>Header A</th> <th>Header B<br>line 2</th> <th>Header C</th> </tr> </thead> <tbody> <tr> <td>Cell 1-A</td> <td>Cell 1-B<br>line 2</td> <td>Cell 1-C</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="empty"> <table class="d2l-table"> <thead> <tr> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="one-column"> <table class="d2l-table"> <thead> <tr> <th>Header A</th> </tr> </thead> <tbody> <tr> <td>Cell 1-A</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="one-cell"> <table class="d2l-table"> <tbody> <tr> <td>Cell 1-A</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="no-header-tbody"> <table class="d2l-table"> <tbody> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr> <td>Cell 2-A</td> <td>Cell 2-B</td> <td>Cell 2-C</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="no-header-no-tbody"> <table class="d2l-table"> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr> <td>Cell 2-A</td> <td>Cell 2-B</td> <td>Cell 2-C</td> </tr> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="rowspan"> <table class="d2l-table"> <thead> <tr> <th rowspan="2">Country</th> <th colspan="3">Fruit</th> </tr> <tr> <th>Apples</th> <th>Bananas</th> <th>Pears</th> </tr> </thead> <tbody> <tr> <th>Canada</th> <td>$1.29</td> <td>$0.79</td> <td>$2.41</td> </tr> <tr> <th>Mexico</th> <td>$0.59</td> <td>$0.38</td> <td>$1.99</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="footer"> <table class="d2l-table"> <thead> <tr> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> </thead> <tbody> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> </tbody> <tfoot> <tr> <td>Footer 1-A</td> <td>Footer 1-B</td> <td>Footer 1-C</td> </tr> </tfoot> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="selected-one-row"> <table class="d2l-table"> <thead> <tr> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> </thead> <tbody> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr selected> <td>Cell 2-A</td> <td>Cell 2-B</td> <td>Cell 2-C</td> </tr> <tr> <td>Cell 3-A</td> <td>Cell 3-B</td> <td>Cell 3-C</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="selected-top-bottom"> <table class="d2l-table"> <thead> <tr> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> </thead> <tbody> <tr selected> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr> <td>Cell 2-A</td> <td>Cell 2-B</td> <td>Cell 2-C</td> </tr> <tr selected> <td>Cell 3-A</td> <td>Cell 3-B</td> <td>Cell 3-C</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="selected-all"> <table class="d2l-table"> <thead> <tr> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> </thead> <tbody> <tr selected> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr selected> <td>Cell 2-A</td> <td>Cell 2-B</td> <td>Cell 2-C</td> </tr> <tr selected> <td>Cell 3-A</td> <td>Cell 3-B</td> <td>Cell 3-C</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" no-column-border id="no-column-border"> <table class="d2l-table"> <thead> <tr> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> </thead> <tbody> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr> <td>Cell 2-A</td> <td>Cell 2-B</td> <td>Cell 2-C</td> </tr> <tr> <td>Cell 3-A</td> <td>Cell 3-B</td> <td>Cell 3-C</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="no-column-border-legacy"> <table class="d2l-table" no-column-border> <thead> <tr> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> </thead> <tbody> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> <tr> <td>Cell 2-A</td> <td>Cell 2-B</td> <td>Cell 2-C</td> </tr> <tr> <td>Cell 3-A</td> <td>Cell 3-B</td> <td>Cell 3-C</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="overflow"> <table class="d2l-table"> <thead> <tr> <th rowspan="2" style="width: 1%" class="top"><input type="checkbox"></th> <th rowspan="2">Country</th> <th colspan="5">Fruit Production (tons)</th> </tr> <tr> <th>Apples</th> <th>Oranges</th> <th>Bananas</th> <th>Peaches</th> <th>Grapes</th> </tr> </thead> <tbody> <tr> <td class="down"><input type="checkbox"></td> <th>Canada</th> <td>356,863</td> <td>0</td> <th>0</th> <td>23,239</td> <td class="over">90,911</td> </tr> <tr selected> <td><input type="checkbox" checked></td> <th>Australia</th> <td>308,298</td> <td>398,610</td> <td>354,241</td> <td>80,807</td> <td>1,772,911</td> </tr> <tr> <td><input type="checkbox"></td> <th>Mexico</th> <td>716,931</td> <td>4,603,253</td> <td>2,384,778</td> <td>176,909</td> <td>351,310</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> <div class="d2l-visual-diff"> <d2l-table-wrapper type="${type}" id="col-sort-button"> <table class="d2l-table"> <thead> <tr> <th><d2l-table-col-sort-button>Ascending</d2l-table-col-sort-button></th> <th><d2l-table-col-sort-button desc>Descending</d2l-table-col-sort-button></th> <th><d2l-table-col-sort-button nosort>No Sort</d2l-table-col-sort-button></th> </tr> </thead> <tbody> <tr> <td>Cell 1-A</td> <td>Cell 1-B</td> <td>Cell 1-C</td> </tr> </tbody> </table> </d2l-table-wrapper> </div> `; } } customElements.define('d2l-test-table-visual-diff', TestTableVisualDiff); <|start_filename|>components/switch/test/switch-visibility.test.js<|end_filename|> import '../switch-visibility.js'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-switch-visibility', () => { it('should construct', () => { runConstructor('d2l-switch-visibility'); }); }); <|start_filename|>components/card/test/card-content-meta.test.js<|end_filename|> import '../card-content-meta.js'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; describe('d2l-card-content-meta', () => { it('should construct', () => { runConstructor('d2l-card-content-meta'); }); }); <|start_filename|>components/offscreen/offscreen.js<|end_filename|> import { css, html, LitElement } from 'lit-element/lit-element.js'; import { RtlMixin } from '../../mixins/rtl-mixin.js'; export const offscreenStyles = css` .d2l-offscreen { height: 1px; left: -10000px; overflow: hidden; position: absolute !important; white-space: nowrap; width: 1px; } :host([dir="rtl"]) .d2l-offscreen { left: 0; right: -10000px; } `; /** * A component for positioning content offscreen to only be visible to screen readers. * @slot - Default content placed inside of the component */ class Offscreen extends RtlMixin(LitElement) { static get styles() { return css` :host { height: 1px; left: -10000px; overflow: hidden; position: absolute !important; white-space: nowrap; width: 1px; } :host([dir="rtl"]) { left: 0; right: -10000px; } `; } render() { return html`<slot></slot>`; } } customElements.define('d2l-offscreen', Offscreen); <|start_filename|>components/inputs/test/input-date-range.test.js<|end_filename|> import { aTimeout, expect, fixture, oneEvent } from '@open-wc/testing'; import { getDocumentLocaleSettings } from '@brightspace-ui/intl/lib/common.js'; import { getShiftedEndDate } from '../input-date-range.js'; import { runConstructor } from '../../../tools/constructor-test-helper.js'; const basicFixture = '<d2l-input-date-range label="label text"></d2l-input-date-range>'; const minMaxFixture = '<d2l-input-date-range label="label text" min-value="2020-01-01" max-value="2020-06-01"></d2l-input-date-range>'; function dispatchEvent(elem, eventType) { const e = new Event( eventType, { bubbles: true, composed: false } ); elem.dispatchEvent(e); } function getChildElem(elem, selector) { return elem.shadowRoot.querySelector(selector); } describe('d2l-input-date-range', () => { const documentLocaleSettings = getDocumentLocaleSettings(); documentLocaleSettings.timezone.identifier = 'America/Toronto'; describe('constructor', () => { it('should construct', () => { runConstructor('d2l-input-date-range'); }); }); describe('utility', () => { describe('getShiftedEndDate', () => { it('should return correctly forward shifted end date if valid inputs', () => { const start = '2020-10-26T04:00:00.000Z'; const end = '2020-10-27T04:00:00.000Z'; const prevStartValue = '2020-10-25T04:00:00.000Z'; const newEndValue = '2020-10-28T04:00:00.000Z'; expect(getShiftedEndDate(start, end, prevStartValue)).to.equal(newEndValue); }); it('should return correctly backward shifted end date if valid inputs', () => { const start = '2020-10-24T04:00:00.000Z'; const end = '2020-10-27T04:00:00.000Z'; const prevStartValue = '2020-10-25T04:00:00.000Z'; const newEndValue = '2020-10-26T04:00:00.000Z'; expect(getShiftedEndDate(start, end, prevStartValue)).to.equal(newEndValue); }); it('should return correctly shifted end date if shift causes end date to go to next day', () => { const start = '2020-10-25T11:00:00.000Z'; const end = '2020-10-27T23:30:00.000Z'; const prevStartValue = '2020-10-25T04:00:00.000Z'; const newEndValue = '2020-10-28T06:30:00.000Z'; expect(getShiftedEndDate(start, end, prevStartValue)).to.equal(newEndValue); }); it('should return initial end date if prev start value was after end date', () => { const start = '2020-10-23T04:00:00.000Z'; const end = '2020-10-22T04:00:00.000Z'; const prevStartValue = '2020-10-25T04:00:00.000Z'; expect(getShiftedEndDate(start, end, prevStartValue)).to.equal(end); }); it('should return initial end date if not inclusive and prev start value was equal to end date', () => { const start = '2020-10-20T04:00:00.000Z'; const end = '2020-10-25T04:00:00.000Z'; const prevStartValue = '2020-10-25T04:00:00.000Z'; expect(getShiftedEndDate(start, end, prevStartValue)).to.equal(end); }); it('should return correctly shifted end date if inclusive and prev start value was equal to end date', () => { const start = '2020-10-20T04:00:00.000Z'; const end = '2020-10-25T04:00:00.000Z'; const prevStartValue = '2020-10-25T04:00:00.000Z'; expect(getShiftedEndDate(start, end, prevStartValue, true)).to.equal(start); }); }); }); describe('values', () => { it('should fire "change" event when start value changes', async() => { const elem = await fixture(basicFixture); const inputElem = getChildElem(elem, 'd2l-input-date.d2l-input-date-range-start'); inputElem.value = '2018-02-02'; setTimeout(() => dispatchEvent(inputElem, 'change')); await oneEvent(elem, 'change'); expect(elem.startValue).to.equal('2018-02-02'); }); it('should fire "change" event when end value changes', async() => { const elem = await fixture(basicFixture); const inputElem = getChildElem(elem, 'd2l-input-date.d2l-input-date-range-end'); inputElem.value = '2018-10-31'; setTimeout(() => dispatchEvent(inputElem, 'change')); await oneEvent(elem, 'change'); expect(elem.endValue).to.equal('2018-10-31'); }); it('should default start and end values to undefined', async() => { const elem = await fixture(basicFixture); expect(elem.startValue).to.equal(undefined); expect(elem.endValue).to.equal(undefined); }); describe('validation', () => { it('should be valid if start date and no end date', async() => { const elem = await fixture(minMaxFixture); const inputElem = getChildElem(elem, 'd2l-input-date.d2l-input-date-range-start'); inputElem.value = '2020-03-31'; setTimeout(() => dispatchEvent(inputElem, 'change')); await oneEvent(elem, 'change'); expect(elem.startValue).to.equal('2020-03-31'); expect(elem.invalid).to.be.false; expect(elem.validationError).to.be.null; }); it('should be valid if end date and no start date', async() => { const elem = await fixture(minMaxFixture); const inputElem = getChildElem(elem, 'd2l-input-date.d2l-input-date-range-end'); inputElem.value = '2020-03-31'; setTimeout(() => dispatchEvent(inputElem, 'change')); await oneEvent(elem, 'change'); expect(elem.endValue).to.equal('2020-03-31'); expect(elem.invalid).to.be.false; expect(elem.validationError).to.be.null; }); it('should be valid if start date before end date', async() => { const elem = await fixture(minMaxFixture); await updateStartEnd(elem, '2020-03-31', '2020-05-31'); expect(elem.invalid).to.be.false; expect(elem.validationError).to.be.null; }); it('should be invalid if start date equals end date', async() => { const elem = await fixture(minMaxFixture); await updateStartEnd(elem, '2020-03-31', '2020-03-31'); expect(elem.invalid).to.be.true; expect(elem.validationError).to.equal('Start Date must be before End Date'); }); it('should be invalid if start date after end date', async() => { const elem = await fixture(minMaxFixture); await updateStartEnd(elem, '2020-05-31', '2020-03-31'); expect(elem.invalid).to.be.true; expect(elem.validationError).to.equal('Start Date must be before End Date'); }); async function updateStartEnd(elem, startDate, endDate) { let firedCount = 0; elem.addEventListener('change', () => { firedCount++; }); const inputElemStart = getChildElem(elem, 'd2l-input-date.d2l-input-date-range-start'); inputElemStart.value = startDate; setTimeout(() => dispatchEvent(inputElemStart, 'change')); await oneEvent(elem, 'change'); expect(elem.startValue).to.equal(startDate); const inputElemEnd = getChildElem(elem, 'd2l-input-date.d2l-input-date-range-end'); inputElemEnd.value = endDate; setTimeout(() => dispatchEvent(inputElemEnd, 'change')); await oneEvent(inputElemEnd, 'change'); expect(elem.endValue).to.equal(endDate); await aTimeout(1); expect(firedCount).to.equal(2); } }); }); });
turlodales/core
<|start_filename|>basic_geometry_withvars_p5js/sketch.js<|end_filename|> function setup(){ createCanvas(800,500); } function draw(){ var shapeWidth = 200; var shapeHeight = 200; //clear background white //comment this line out with // to test //background color background(255); rect(20,20,shapeWidth,shapeHeight); ellipse(400,120,shapeWidth,shapeHeight); line(600,20,600, 20 + shapeHeight); triangle(20,240, 20+shapeWidth,240, 110,240 + shapeHeight); arc(400, 240, shapeWidth, shapeHeight, 0, PI); point(600, 260); }
jordanyr/CreativeCoding-Jordan
<|start_filename|>tabs.js<|end_filename|> (function() { Array.prototype.forEach.call(document.getElementsByClassName("mammoth-tabs"), function(tabsElement) { var headings = Array.prototype.map.call(tabsElement.getElementsByClassName("tab"), function(tabElement) { var titleElement = tabElement.children[0]; var title = titleElement.textContent; tabElement.removeChild(titleElement); var element = document.createElement("li"); element.textContent = title; element.addEventListener("click", select, false); function select() { headings.forEach(function(heading) { heading.deselect(); }); element.className = "selected"; tabElement.style.display = "block"; } function deselect() { element.className = ""; tabElement.style.display = "none"; } return { element: element, select: select, deselect: deselect }; }); var headingsElement = document.createElement("ul"); headingsElement.className = "tabs-nav"; headings.forEach(function(heading) { headingsElement.appendChild(heading.element); }); tabsElement.insertBefore(headingsElement, tabsElement.firstChild); headings[0].select(); }); })();
wp-plugins/mammoth-docx-converter
<|start_filename|>src/settings/useMediaHandler.js<|end_filename|> import { useState, useEffect, useCallback } from "react"; export function useMediaHandler(client) { const [{ audioInput, videoInput, audioInputs, videoInputs }, setState] = useState(() => { const mediaHandler = client.getMediaHandler(); return { audioInput: mediaHandler.audioInput, videoInput: mediaHandler.videoInput, audioInputs: [], videoInputs: [], }; }); useEffect(() => { const mediaHandler = client.getMediaHandler(); function updateDevices() { navigator.mediaDevices.enumerateDevices().then((devices) => { const audioInputs = devices.filter( (device) => device.kind === "audioinput" ); const videoInputs = devices.filter( (device) => device.kind === "videoinput" ); setState(() => ({ audioInput: mediaHandler.audioInput, videoInput: mediaHandler.videoInput, audioInputs, videoInputs, })); }); } updateDevices(); mediaHandler.on("local_streams_changed", updateDevices); navigator.mediaDevices.addEventListener("devicechange", updateDevices); return () => { mediaHandler.removeListener("local_streams_changed", updateDevices); navigator.mediaDevices.removeEventListener("devicechange", updateDevices); }; }, []); const setAudioInput = useCallback( (deviceId) => { setState((prevState) => ({ ...prevState, audioInput: deviceId })); client.getMediaHandler().setAudioInput(deviceId); }, [client] ); const setVideoInput = useCallback( (deviceId) => { setState((prevState) => ({ ...prevState, videoInput: deviceId })); client.getMediaHandler().setVideoInput(deviceId); }, [client] ); return { audioInput, audioInputs, setAudioInput, videoInput, videoInputs, setVideoInput, }; } <|start_filename|>Dockerfile<|end_filename|> FROM node:16-buster as builder WORKDIR /src COPY . /src/matrix-video-chat RUN matrix-video-chat/scripts/dockerbuild.sh # App FROM nginxinc/nginx-unprivileged:alpine COPY --from=builder /src/matrix-video-chat/dist /app COPY scripts/default.conf /etc/nginx/conf.d/ USER root RUN rm -rf /usr/share/nginx/html USER 101 <|start_filename|>src/auth/useInteractiveRegistration.js<|end_filename|> import matrix, { InteractiveAuth } from "matrix-js-sdk/src/browser-index"; import { useState, useEffect, useCallback, useRef } from "react"; import { useClient } from "../ClientContext"; import { initClient, defaultHomeserver } from "../matrix-utils"; export function useInteractiveRegistration() { const { setClient } = useClient(); const [state, setState] = useState({ privacyPolicyUrl: "#", loading: false }); const authClientRef = useRef(); useEffect(() => { authClientRef.current = matrix.createClient(defaultHomeserver); authClientRef.current.registerRequest({}).catch((error) => { const privacyPolicyUrl = error.data?.params["m.login.terms"]?.policies?.privacy_policy?.en?.url; const recaptchaKey = error.data?.params["m.login.recaptcha"]?.public_key; if (privacyPolicyUrl || recaptchaKey) { setState((prev) => ({ ...prev, privacyPolicyUrl, recaptchaKey })); } }); }, []); const register = useCallback( async (username, password, recaptchaResponse, passwordlessUser) => { const interactiveAuth = new InteractiveAuth({ matrixClient: authClientRef.current, busyChanged(loading) { setState((prev) => ({ ...prev, loading })); }, async doRequest(auth, _background) { return authClientRef.current.registerRequest({ username, password, auth: auth || undefined, }); }, stateUpdated(nextStage, status) { if (status.error) { throw new Error(error); } if (nextStage === "m.login.terms") { interactiveAuth.submitAuthDict({ type: "m.login.terms", }); } else if (nextStage === "m.login.recaptcha") { interactiveAuth.submitAuthDict({ type: "m.login.recaptcha", response: recaptchaResponse, }); } }, }); const { user_id, access_token, device_id } = await interactiveAuth.attemptAuth(); const client = await initClient({ baseUrl: defaultHomeserver, accessToken: access_token, userId: user_id, deviceId: device_id, }); await client.setDisplayName(username); const session = { user_id, device_id, access_token, passwordlessUser }; if (passwordlessUser) { session.tempPassword = password; } setClient(client, session); return client; }, [] ); return [state, register]; } <|start_filename|>src/home/RegisteredView.module.css<|end_filename|> .form { padding: 0 24px; justify-content: center; max-width: 409px; width: calc(100% - 48px); margin-bottom: 72px; } .fieldRow { margin-bottom: 0; } .button { padding: 0 24px; } .recentCallsTitle { margin-bottom: 32px; } <|start_filename|>src/settings/SettingsModal.module.css<|end_filename|> .settingsModal { width: 774px; height: 480px; } .tabContainer { margin: 27px 16px; } <|start_filename|>src/input/Input.module.css<|end_filename|> .fieldRow { display: flex; margin-bottom: 32px; align-items: center; } .field { display: flex; flex: 1; min-width: 0; position: relative; } .fieldRow.rightAlign { justify-content: flex-end; } .fieldRow > * { margin-right: 24px; } .fieldRow > :last-child { margin-right: 0; } .inputField { border-radius: 4px; transition: border-color 0.25s; border: 1px solid var(--inputBorderColor); } .inputField input { font-weight: 400; font-size: 15px; border: none; border-radius: 4px; padding: 12px 9px 10px 9px; color: var(--textColor1); background-color: var(--bgColor1); flex: 1; min-width: 0; } .inputField.disabled input, .inputField.disabled span { color: var(--textColor2); } .inputField span { padding: 11px 9px; } .inputField span:first-child { padding-right: 0; } .inputField input::placeholder { transition: color 0.25s ease-in 0s; color: transparent; } .inputField input:placeholder-shown:focus::placeholder { transition: color 0.25s ease-in 0.1s; color: var(--textColor2); } .inputField label { transition: font-size 0.25s ease-out 0.1s, color 0.25s ease-out 0.1s, top 0.25s ease-out 0.1s, background-color 0.25s ease-out 0.1s; color: var(--textColor3); background-color: transparent; font-size: 15px; position: absolute; left: 0; top: 0; margin: 9px 8px; padding: 2px; pointer-events: none; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; max-width: calc(100% - 20px); } .inputField:focus-within { border-color: var(--inputBorderColorFocused); } .inputField input:focus { outline: 0; } .inputField input:focus + label, .inputField input:not(:placeholder-shown) + label, .inputField.prefix input + label { background-color: var(--bgColor2); transition: font-size 0.25s ease-out 0s, color 0.25s ease-out 0s, top 0.25s ease-out 0s, background-color 0.25s ease-out 0s; font-size: 10px; top: -13px; padding: 0 2px; pointer-events: auto; } .inputField input:focus + label { color: var(--inputBorderColorFocused); } .checkboxField { display: flex; align-items: flex-start; } .checkboxField label { display: flex; align-items: center; flex-grow: 1; font-size: 13px; } .checkboxField input { outline: 0; appearance: none; -webkit-appearance: none; margin: 0; padding: 0; } .checkbox { display: inline-flex; align-items: center; justify-content: center; position: relative; flex-shrink: 0; height: 16px; width: 16px; border: 1.5px solid rgba(185, 190, 198, 0.5); box-sizing: border-box; border-radius: 4px; margin-right: 10px; } .checkbox svg { display: none; } .checkbox svg * { stroke: #fff; } .checkboxField input[type="checkbox"]:checked + label > .checkbox { background: var(--primaryColor); border-color: var(--primaryColor); } .checkboxField input[type="checkbox"]:checked + label > .checkbox svg { display: flex; } .checkboxField:focus-within .checkbox { border: 1.5px solid var(--inputBorderColorFocused) !important; } .errorMessage { margin: 0; font-size: 13px; color: #ff5b55; font-weight: 600; } <|start_filename|>src/button/index.js<|end_filename|> export * from "./Button"; export * from "./CopyButton"; export * from "./LinkButton"; <|start_filename|>src/room/useSentryGroupCallHandler.js<|end_filename|> import { useEffect } from "react"; import * as Sentry from "@sentry/react"; export function useSentryGroupCallHandler(groupCall) { useEffect(() => { function onHangup(call) { if (call.hangupReason === "ice_failed") { Sentry.captureException(new Error("Call hangup due to ICE failure.")); } } function onError(error) { Sentry.captureException(error); } if (groupCall) { groupCall.on("hangup", onHangup); groupCall.on("error", onError); } return () => { if (groupCall) { groupCall.removeListener("hangup", onHangup); groupCall.removeListener("error", onError); } }; }, [groupCall]); } <|start_filename|>src/profile/useProfile.js<|end_filename|> import { useState, useCallback, useEffect } from "react"; import { getAvatarUrl } from "../matrix-utils"; export function useProfile(client) { const [{ loading, displayName, avatarUrl, error, success }, setState] = useState(() => { const user = client?.getUser(client.getUserId()); return { success: false, loading: false, displayName: user?.displayName, avatarUrl: user && client && getAvatarUrl(client, user.avatarUrl), error: null, }; }); useEffect(() => { const onChangeUser = (_event, { displayName, avatarUrl }) => { setState({ success: false, loading: false, displayName, avatarUrl: getAvatarUrl(client, avatarUrl), error: null, }); }; let user; if (client) { const userId = client.getUserId(); user = client.getUser(userId); user.on("User.displayName", onChangeUser); user.on("User.avatarUrl", onChangeUser); } return () => { if (user) { user.removeListener("User.displayName", onChangeUser); user.removeListener("User.avatarUrl", onChangeUser); } }; }, [client]); const saveProfile = useCallback( async ({ displayName, avatar }) => { if (client) { setState((prev) => ({ ...prev, loading: true, error: null, success: false, })); try { await client.setDisplayName(displayName); let mxcAvatarUrl; if (avatar) { mxcAvatarUrl = await client.uploadContent(avatar); await client.setAvatarUrl(mxcAvatarUrl); } setState((prev) => ({ ...prev, displayName, avatarUrl: mxcAvatarUrl ? getAvatarUrl(client, mxcAvatarUrl) : prev.avatarUrl, loading: false, success: true, })); } catch (error) { setState((prev) => ({ ...prev, loading: false, error, success: false, })); } } else { console.error("Client not initialized before calling saveProfile"); } }, [client] ); return { loading, error, displayName, avatarUrl, saveProfile, success }; } <|start_filename|>src/room/useLoadGroupCall.js<|end_filename|> import { useState, useEffect } from "react"; async function fetchGroupCall( client, roomIdOrAlias, viaServers = undefined, timeout = 5000 ) { const { roomId } = await client.joinRoom(roomIdOrAlias, { viaServers }); return new Promise((resolve, reject) => { let timeoutId; function onGroupCallIncoming(groupCall) { if (groupCall && groupCall.room.roomId === roomId) { clearTimeout(timeoutId); client.removeListener("GroupCall.incoming", onGroupCallIncoming); resolve(groupCall); } } const groupCall = client.getGroupCallForRoom(roomId); if (groupCall) { resolve(groupCall); } client.on("GroupCall.incoming", onGroupCallIncoming); if (timeout) { timeoutId = setTimeout(() => { client.removeListener("GroupCall.incoming", onGroupCallIncoming); reject(new Error("Fetching group call timed out.")); }, timeout); } }); } export function useLoadGroupCall(client, roomId, viaServers) { const [state, setState] = useState({ loading: true, error: undefined, groupCall: undefined, }); useEffect(() => { setState({ loading: true }); fetchGroupCall(client, roomId, viaServers, 30000) .then((groupCall) => setState({ loading: false, groupCall })) .catch((error) => setState({ loading: false, error })); }, [client, roomId]); return state; }
michaelkaye/matrix-video-chat
<|start_filename|>composer.json<|end_filename|> { "name": "doublesecretagency/craft-siteswitcher", "description": "Easily switch between sites on any page of your website.", "type": "craft-plugin", "version": "2.2.0", "keywords": [ "craft", "cms", "craftcms", "craft-plugin", "language-link", "languages", "language-switcher", "sites", "switcher", "multisite", "multi-site", "locales" ], "support": { "docs": "https://github.com/doublesecretagency/craft-siteswitcher/blob/v2/README.md", "issues": "https://github.com/doublesecretagency/craft-siteswitcher/issues" }, "license": "MIT", "authors": [ { "name": "<NAME>", "homepage": "https://www.doublesecretagency.com/plugins" } ], "require": { "craftcms/cms": "^3.0.0" }, "autoload": { "psr-4": { "doublesecretagency\\siteswitcher\\": "src/" } }, "extra": { "name": "Site Switcher", "handle": "site-switcher", "schemaVersion": "0.0.0", "changelogUrl": "https://raw.githubusercontent.com/doublesecretagency/craft-siteswitcher/v2/CHANGELOG.md", "class": "doublesecretagency\\siteswitcher\\SiteSwitcher" } }
nthmedia/craft-siteswitcher
<|start_filename|>css/popup.css<|end_filename|> html{ padding: 0; margin: 0; } .settings{ width: 320px; text-align: left; vertical-align: center; margin: 20px; } #textDecoration, #font{ display: inline-block; width: 150px; } ul{ padding: 20px; margin: 0; } li{ list-style-type: none; line-height: 40px; } h2{ font-size: 30px; color: #666; display: block; text-align: center; margin-bottom: 10px; } input[type="range"]{ width:100px; position: relative; bottom: -5px; } .item_name{ display: inline-block; width: 80px; text-align: right; margin-right: 5px; } input[readonly="readonly"]{ width: 50px; display: inline-block; height: 26px; text-align: center; border-radius: 3px; border: none; background-color: #eee; position: relative; top: -2px; } .myBtn{ display: inline-block; margin:0px auto; } #apply{ background-color: #7af; color: white; } .buttonGroup{ text-align: center; } .slidecontainer { width: 100%; /* Width of the outside container */ } .copyright{ display: block; text-align: center; } /* The slider itself */ .slider { -webkit-appearance: none; /* Override default CSS styles */ appearance: none; width: 100%; /* Full-width */ height: 25px; /* Specified height */ background: #d3d3d3; /* Grey background */ outline: none; /* Remove outline */ opacity: 0.7; /* Set transparency (for mouse-over effects on hover) */ -webkit-transition: .2s; /* 0.2 seconds transition on hover */ transition: opacity .2s; border-radius: 3px; } /* Mouse-over effects */ .slider:hover { opacity: 1; /* Fully shown on mouse-over */ } /* The slider handle (use -webkit- (Chrome, Opera, Safari, Edge) and -moz- (Firefox) to override default look) */ .slider::-webkit-slider-thumb { -webkit-appearance: none; /* Override default look */ appearance: none; width: 25px; /* Set a specific slider handle width */ height: 25px; /* Slider handle height */ background: #4C70AF; /* Green background */ cursor: pointer; /* Cursor on hover */ border-radius: 3px; } .slider::-moz-range-thumb { width: 25px; /* Set a specific slider handle width */ height: 25px; /* Slider handle height */ background: #4C70AF; /* Green background */ cursor: pointer; /* Cursor on hover */ border-radius: 3px; } <|start_filename|>_locales/de/messages.json<|end_filename|> { "appName": { "message": "Twitch Chat Danmaku" }, "appDescription": { "message": "Betten Sie den Chat mit einem Danmaku-Stil in dem Stream ein. Kompatibel mit BetterTTV und anderen Emoticons!" }, "settingsTitle": { "message": "Einstellungen" }, "tipEnable": { "message": "Ein-/ausschalten" }, "lblEnable": { "message": "Danmaku: " }, "tipUsername": { "message": "Zeige der Benutzername des Kommentars" }, "lblUsername": { "message": "Benutzername: " }, "tipDuration": { "message": "Wie lange werden die Danmaku auf dem Bildschirm bleiben" }, "lblDuration": { "message": "Dauer: " }, "tipFontSize": { "message": "Schriftgröße des Danmaku" }, "lblFontSize": { "message": "Schriftgröße: " }, "tipOpacity": { "message": "Die Transparenz des Danmaku" }, "lblOpacity": { "message": "Opazität: " }, "tipApply": { "message": "Übernehmen Sie die aktuellen Einstellungen." }, "lblApply": { "message": "Übernehmen" }, "tipResetToDefault": { "message": "Auf Standardeinstellungen zurücksetzen und anwenden" }, "lblResetToDefault": { "message": "Standardeinstellungen" }, "enable": { "message": "Aktivieren" }, "disable": { "message": "Deaktivieren" }, "show": { "message": "Zeigen" }, "hide": { "message": "Ausblenden" }, "px": { "message": "px", "description": "pixel" }, "s": { "message": "s", "description": "seconds" }, "tipTextDecoration": { "message": "Ändern Sie die Textdekoration (kann sich auf die Leistung auswirken)" }, "lblTextDecoration": { "message": "Text-Stil: " }, "lblNone": { "message": "Nichts" }, "lblShadow": { "message": "Schatten" }, "lblStroke": { "message": "Kante" }, "lblFont": { "message": "Schriftart: " }, "tipFont": { "message": "Stellen Sie die Schriftart des Danmaku ein." }, "lblBold": { "message": "Fett: " }, "tipBold": { "message": "Fett" }, "default": { "message": "Standard" } }
pc035860/TwitchChatDanmaku
<|start_filename|>CSharp/Utilities.cs<|end_filename|> /* Copyright 2014, Google Inc. All Rights Reserved. * * 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 Google.Apis.AdExchangeBuyerII.v2beta1; using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2.Flows; using Google.Apis.Http; using Google.Apis.Json; using Google.Apis.Util.Store; using System.IO; using System.Threading; namespace Google.Apis.AdExchangeBuyer.Examples { public class Utilities { /// <summary> /// Create a new Service for Authorized Buyers Ad Exchange Buyer II API. Note the call to /// ServiceAccount - this is where security configuration takes place and will need to be /// configured before the code will work! /// </summary> /// <returns>A new API Service</returns> public static AdExchangeBuyerIIService GetV2Service() { return new AdExchangeBuyerIIService( new Google.Apis.Services.BaseClientService.Initializer { HttpClientInitializer = ServiceAccount(), ApplicationName = "AdExchange Buyer II DotNet Sample", } ); } /// <summary> /// Uses a JSON KeyFile to authenticate a service account and return credentials for /// accessing the API. /// </summary> /// <returns>Authentication object for API Requests</returns> public static IConfigurableHttpClientInitializer ServiceAccount() { var credentialParameters = NewtonsoftJsonSerializer.Instance .Deserialize<JsonCredentialParameters>(System.IO.File.ReadAllText( ExamplesConfig.ServiceKeyFilePath)); return new ServiceAccountCredential( new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail) { Scopes = new[] { AdExchangeBuyerIIService.Scope.AdexchangeBuyer } }.FromPrivateKey(credentialParameters.PrivateKey)); } /// <summary> /// Extracts info from a JSON file and prompts the user to login and authorize the application. /// Returns credentials for accessing the API. /// Note: After the first authentication a RefreshToken is cached and used for subsequent calls /// via FileDataStore("adxbuyer") /// </summary> /// <returns>Authentication object for API Requests</returns> public static IConfigurableHttpClientInitializer Prompt() { using (var stream = new FileStream(ExamplesConfig.ClientSecretLocation, FileMode.Open, FileAccess.Read)) { return GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { AdExchangeBuyerIIService.Scope.AdexchangeBuyer }, "user", CancellationToken.None, new FileDataStore(ExamplesConfig.FileDataStore)).Result; } } /// <summary> /// Uses hard coded info to authenticate and return credentials. /// Note: All of the parameters required for this method can be retrieved from the JSON /// File and the cache file from the Prompt() method above. /// </summary> /// <returns>Authentication object for API Requests</returns> public static IConfigurableHttpClientInitializer RefreshToken() { var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse { RefreshToken = ExamplesConfig.RefreshToken }; return new UserCredential(new GoogleAuthorizationCodeFlow( new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = ExamplesConfig.ClientId, ClientSecret = ExamplesConfig.ClientSecret }, }), "user", token); } } } <|start_filename|>java/src/main/java/com/google/api/services/samples/adexchangebuyer/cmdline/AdExchangeBuyerIISample.java<|end_filename|> /* * Copyright (c) 2016 Google Inc. * * 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.google.api.services.samples.adexchangebuyer.cmdline; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.adexchangebuyer2.v2beta1.AdExchangeBuyerIIScopes; import com.google.api.services.adexchangebuyer2.v2beta1.AdExchangeBuyerII; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.AcceptProposal; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.CreateAccountLevelFilterSet; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.CreateBidderLevelFilterSet; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.CreateClientBuyer; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.CreateInvitation; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.CreateProposal; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.GetAccountLevelBidMetrics; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.GetAllAccountLevelFilterSets; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.GetAllBidderLevelFilterSets; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.GetAllClientBuyers; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.GetAllClientUsers; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.GetAllInvitations; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.GetAllPublisherProfiles; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.GetBidderLevelBidMetrics; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.ListProposals; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.UpdateClientBuyer; import com.google.api.services.samples.adexchangebuyer.cmdline.v2_x.UpdateClientUser; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; /** * A sample application that runs multiple requests against the Authorized Buyers Ad Exchange * Buyer II API. These include: * <ul> * <li>Get All Client Buyers</li> * <li>Create Client Buyer</li> * <li>Update Client Buyer</li> * <li>Get All Invitations</li> * <li>Create Invitation</li> * <li>Get All Client Users</li> * <li>Update Client User</li> * <li>Create Bidder-level Filter Set</li> * <li>Get all Bidder-level Filter Sets</li> * <li>Get Bidder-level Bid Metrics</li> * <li>Create Account-level Filter Set</li> * <li>Get all Account-level Filter Sets</li> * <li>Get Account-level Bid Metrics</li> * </ul> */ public class AdExchangeBuyerIISample { /** * Be sure to specify the name of your application. If the application name is * {@code null} or blank, the application will log a warning. Suggested format * is "MyCompany-ProductName/1.0". */ private static final String APPLICATION_NAME = ""; /** Full path to JSON Key file - include file name */ private static final java.io.File JSON_FILE = new java.io.File("INSERT_PATH_TO_JSON_FILE"); /** Global instance of the HTTP transport. */ private static HttpTransport httpTransport; /** Global instance of the JSON factory. */ private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static ArrayList<BaseSample> samples; /** Authorizes the installed application to access user's protected data. * @throws IOException * */ private static Credential authorize() throws Exception { return GoogleCredential.fromStream(new FileInputStream(JSON_FILE)) .createScoped(AdExchangeBuyerIIScopes.all()); } /** * Performs all necessary setup steps for running requests against the * Ad Exchange Buyer II API. * * @return An initialized AdExchangeBuyerII service object. */ private static AdExchangeBuyerII initAdExchangeBuyerIIClient(Credential credential) { AdExchangeBuyerII client = new AdExchangeBuyerII.Builder( httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build(); return client; } /** * Initializes the list of available code samples. */ private static void initSamples() { samples = new ArrayList<BaseSample>(); samples.add(new GetAllClientBuyers()); samples.add(new CreateClientBuyer()); samples.add(new UpdateClientBuyer()); samples.add(new GetAllInvitations()); samples.add(new CreateInvitation()); samples.add(new GetAllClientUsers()); samples.add(new UpdateClientUser()); samples.add(new CreateBidderLevelFilterSet()); samples.add(new GetAllBidderLevelFilterSets()); samples.add((new GetBidderLevelBidMetrics())); samples.add(new CreateAccountLevelFilterSet()); samples.add(new GetAllAccountLevelFilterSets()); samples.add(new GetAccountLevelBidMetrics()); samples.add(new GetAllPublisherProfiles()); samples.add(new ListProposals()); samples.add(new CreateProposal()); samples.add(new AcceptProposal()); } /** * Runs all the Ad Exchange Buyer API samples. * * @param args command-line arguments. */ public static void main(String[] args) throws Exception { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); initSamples(); Credential credentials = authorize(); AdExchangeBuyerII adXBuyerIIClient = initAdExchangeBuyerIIClient( credentials); BaseSample sample = null; while ((sample = selectSample()) != null) { try { System.out.printf("%nExecuting sample: %s%n%n", sample.getName()); BaseSample.ClientType clientType = sample.getClientType(); if (clientType == BaseSample.ClientType.ADEXCHANGEBUYERII) { sample.execute(adXBuyerIIClient); } } catch (IOException e) { e.printStackTrace(); } } } /** * Prints the list of available code samples and prompts the user to * select one. * * @return The selected sample or null if the user selected to exit. */ private static BaseSample selectSample() throws IOException { System.out.printf("Samples:%n"); int counter = 1; for (BaseSample sample : samples) { System.out.printf("%d) %s - %s%n", counter++, sample.getName(), sample.getDescription()); } System.out.printf("%d) Exit the program%n", counter++); Integer sampleNumber = null; while (sampleNumber == null) { try { System.out.println("Select a sample number and press enter:"); sampleNumber = Integer.parseInt(Utils.readInputLine()); if (sampleNumber < 1 || sampleNumber > samples.size()) { if (sampleNumber == samples.size() + 1) { return null; } System.out.printf("Invalid number provided, try again%n"); sampleNumber = null; } } catch (NumberFormatException e) { System.out.printf("Invalid number provided, try again%n"); } } return samples.get(sampleNumber - 1); } } <|start_filename|>java/src/main/java/com/google/api/services/samples/adexchangebuyer/cmdline/v2_x/GetAllBidderLevelFilterSets.java<|end_filename|> /* * Copyright (c) 2017 Google Inc. * * 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.google.api.services.samples.adexchangebuyer.cmdline.v2_x; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient; import com.google.api.services.adexchangebuyer2.v2beta1.AdExchangeBuyerII; import com.google.api.services.adexchangebuyer2.v2beta1.model.AbsoluteDateRange; import com.google.api.services.adexchangebuyer2.v2beta1.model.Client; import com.google.api.services.adexchangebuyer2.v2beta1.model.Date; import com.google.api.services.adexchangebuyer2.v2beta1.model.FilterSet; import com.google.api.services.adexchangebuyer2.v2beta1.model.RealtimeTimeRange; import com.google.api.services.adexchangebuyer2.v2beta1.model.RelativeDateRange; import com.google.api.services.samples.adexchangebuyer.cmdline.BaseSample; import java.io.IOException; import java.util.List; /** * This sample illustrates how to retrieve all Bidder-level Filter Sets. */ public class GetAllBidderLevelFilterSets extends BaseSample { @Override public ClientType getClientType() { return ClientType.ADEXCHANGEBUYERII; } @Override public String getName() { return "Get All Bidder-level Filter Sets."; } @Override public String getDescription() { return "Lists Filter Sets associated with the given Bidder."; } @Override public void execute(AbstractGoogleJsonClient client) throws IOException { AdExchangeBuyerII adXClient = (AdExchangeBuyerII) client; String bidderResourceId = getStringInput("bidderResourceId", "Enter the Bidder's resource ID"); String ownerName = String.format("bidders/%s", bidderResourceId); List<FilterSet> allFilterSets = adXClient.bidders().filterSets().list(ownerName).execute() .getFilterSets(); if (allFilterSets != null && allFilterSets.size() > 0) { System.out.println("========================================"); System.out.printf("Listing of Filter Sets associated with Bidder \"%s\"%n", ownerName); System.out.println("========================================"); for (FilterSet filterSet : allFilterSets) { System.out.printf("* Filter Set name: %s%n", filterSet.getName()); AbsoluteDateRange absDateRange = filterSet.getAbsoluteDateRange(); if(absDateRange != null) { System.out.println("AbsoluteDateRange"); System.out.printf("\tStart date: %s%n", convertDateToString(absDateRange.getStartDate())); System.out.printf("\tEnd date: %s%n", convertDateToString(absDateRange.getEndDate())); } RelativeDateRange relDateRange = filterSet.getRelativeDateRange(); if(relDateRange != null) { Integer offset = relDateRange.getOffsetDays(); System.out.println("RelativeDateRange"); System.out.printf("\tOffset days: %s%n", offset != null ? offset : 0); System.out.printf("\tDuration days: %s%n", relDateRange.getDurationDays()); } RealtimeTimeRange rtTimeRange = filterSet.getRealtimeTimeRange(); if(rtTimeRange != null) { System.out.println("RealtimeTimeRange"); System.out.printf("\tStart timestamp: %s%n", rtTimeRange.getStartTimestamp()); } String timeSeriesGranularity = filterSet.getTimeSeriesGranularity(); if(timeSeriesGranularity != null) { System.out.printf("Time series granularity: %s%n", timeSeriesGranularity); } String format = filterSet.getFormat(); if(format != null) { System.out.printf("\tFormat: %s%n", format); } String environment = filterSet.getEnvironment(); if(environment != null) { System.out.printf("Environment: %s%n", environment); } List<String> platforms = filterSet.getPlatforms(); if(platforms != null) { System.out.println("Platforms:"); for(String platform : platforms) { System.out.printf("\t%s%n", platform); } } List<Integer> sellerNetworkIds = filterSet.getSellerNetworkIds(); if(filterSet.getSellerNetworkIds() != null) { System.out.println("Seller network IDS:"); for(Integer sellerNetworkId : sellerNetworkIds) { System.out.printf("\t%d%n", sellerNetworkId); } } } } else { System.out.printf("No Filter Sets were found associated with Bidder \"%s\"%n", ownerName); } } private String convertDateToString(Date date) { return String.format("%d%02d%02d", date.getYear(), date.getMonth(), date.getDay()); } }
googleads/googleads-adxbuyer-examples
<|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/favorites/FavoritesMoviesViewState.kt<|end_filename|> package com.yossisegev.movienight.favorites import com.yossisegev.movienight.entities.Movie /** * Created by <NAME> on 09/02/2018. */ data class FavoritesMoviesViewState( val isLoading: Boolean = true, val isEmpty: Boolean = true, val movies: List<Movie>? = null ) <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/common/BaseViewModel.kt<|end_filename|> package com.yossisegev.movienight.common import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable /** * Created by <NAME> on 15/12/2017. */ open class BaseViewModel: ViewModel() { private val compositeDisposable: CompositeDisposable = CompositeDisposable() protected fun addDisposable(disposable: Disposable) { compositeDisposable.add(disposable) } private fun clearDisposables() { compositeDisposable.clear() } override fun onCleared() { clearDisposables() } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/details/DetailsScope.kt<|end_filename|> package com.yossisegev.movienight.di.details import javax.inject.Scope /** * Created by <NAME> on 14/11/2017. */ @Scope @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class DetailsScope <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/details/VideosAdapter.kt<|end_filename|> package com.yossisegev.movienight.details import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.yossisegev.movienight.R import com.yossisegev.movienight.entities.Video import kotlinx.android.synthetic.main.videos_adapter_row.view.* /** * Created by <NAME> on 12/01/2018. */ class VideosAdapter(private val videos: List<Video>, private val callback: (Video) -> (Unit)) : RecyclerView.Adapter<VideosAdapter.VideoViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): VideoViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.videos_adapter_row, parent, false) return VideoViewHolder(view) } override fun onBindViewHolder(holder: VideoViewHolder?, position: Int) { holder?.bind(videos[position], callback) } override fun getItemCount(): Int { return videos.size } class VideoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(video: Video, callback: (Video) -> Unit) { with(itemView) { video_adapter_name.text = video.name setOnClickListener { callback(video) } } } } } <|start_filename|>data/src/main/kotlin/com/yossisegev/data/api/VideoResult.kt<|end_filename|> package com.yossisegev.data.api import com.yossisegev.data.entities.VideoData /** * Created by <NAME> on 11/01/2018. */ class VideoResult { var results: List<VideoData>? = null } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/favorites/FavoriteMoviesAdapter.kt<|end_filename|> package com.yossisegev.movienight.favorites import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.yossisegev.movienight.R import com.yossisegev.movienight.common.ImageLoader import com.yossisegev.movienight.entities.Movie import kotlinx.android.synthetic.main.favorite_movies_adapter_row.view.* /** * Created by <NAME> on 14/11/2017. */ class FavoriteMoviesAdapter constructor(private val imageLoader: ImageLoader, private val onMovieSelected: (Movie, View) -> Unit) : RecyclerView.Adapter<FavoriteMoviesAdapter.MovieCellViewHolder>() { private var movies: List<Movie> = listOf() override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MovieCellViewHolder { val view = LayoutInflater.from(parent?.context).inflate( R.layout.favorite_movies_adapter_row, parent, false) return MovieCellViewHolder(view) } override fun getItemCount(): Int { return movies.size } override fun onBindViewHolder(holder: MovieCellViewHolder?, position: Int) { val movie = movies[position] holder?.bind(movie, imageLoader, onMovieSelected) } fun setMovies(movies: List<Movie>) { this.movies = movies notifyDataSetChanged() } class MovieCellViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(movie: Movie, imageLoader: ImageLoader, listener: (Movie, View) -> Unit) = with(itemView) { title.text = movie.originalTitle movie.posterPath?.let { imageLoader.load(it, image) } movie.overview?.let { overview.text = movie.overview overview.visibility = View.VISIBLE } ?: run { overview.visibility = View.GONE } setOnClickListener { listener(movie, itemView) } } } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/details/MovieDetailsViewState.kt<|end_filename|> package com.yossisegev.movienight.details import com.yossisegev.domain.entities.Genre import com.yossisegev.movienight.entities.Video /** * Created by <NAME> on 10/01/2018. */ data class MovieDetailsViewState( var isLoading: Boolean = true, var title: String? = null, var overview: String? = null, var videos: List<Video>? = null, var homepage: String? = null, var releaseDate: String? = null, var votesAverage: Double? = null, var backdropUrl: String? = null, var genres: List<String>? = null ) <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/popularmovies/PopularMoviesFragment.kt<|end_filename|> package com.yossisegev.movienight.popularmovies import android.app.ActivityOptions import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.util.Pair import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.Toast import com.yossisegev.movienight.R import com.yossisegev.movienight.common.App import com.yossisegev.movienight.common.BaseFragment import com.yossisegev.movienight.common.ImageLoader import com.yossisegev.movienight.details.MovieDetailsActivity import com.yossisegev.movienight.entities.Movie import kotlinx.android.synthetic.main.fragment_popular_movies.* import javax.inject.Inject /** * Created by <NAME> on 11/11/2017. */ class PopularMoviesFragment : BaseFragment() { @Inject lateinit var factory: PopularMoviesVMFactory @Inject lateinit var imageLoader: ImageLoader private lateinit var viewModel: PopularMoviesViewModel private lateinit var recyclerView: RecyclerView private lateinit var progressBar: ProgressBar private lateinit var popularMoviesAdapter: PopularMoviesAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity?.application as App).createPopularComponenet().inject(this) viewModel = ViewModelProviders.of(this, factory).get(PopularMoviesViewModel::class.java) if (savedInstanceState == null) { viewModel.getPopularMovies() } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel.viewState.observe(this, Observer { if (it != null) handleViewState(it) }) viewModel.errorState.observe(this, Observer { throwable -> throwable?.let { Toast.makeText(activity, throwable.message, Toast.LENGTH_LONG).show() } }) } private fun handleViewState(state: PopularMoviesViewState) { progressBar.visibility = if (state.showLoading) View.VISIBLE else View.GONE state.movies?.let { popularMoviesAdapter.addMovies(it) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return layoutInflater.inflate(R.layout.fragment_popular_movies, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) progressBar = popular_movies_progress popularMoviesAdapter = PopularMoviesAdapter(imageLoader, { movie, view -> navigateToMovieDetailsScreen(movie, view) }) recyclerView = popular_movies_recyclerview recyclerView.layoutManager = GridLayoutManager(activity, 2) recyclerView.adapter = popularMoviesAdapter } override fun onDestroy() { super.onDestroy() (activity?.application as App).releasePopularComponent() } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/modules/DataModule.kt<|end_filename|> package com.yossisegev.movienight.di.modules import android.arch.persistence.room.Room import android.content.Context import com.yossisegev.data.api.Api import com.yossisegev.data.db.MoviesDatabase import com.yossisegev.data.db.RoomFavoritesMovieCache import com.yossisegev.data.mappers.MovieDataEntityMapper import com.yossisegev.data.mappers.MovieEntityDataMapper import com.yossisegev.data.repositories.* import com.yossisegev.domain.MoviesCache import com.yossisegev.domain.MoviesRepository import com.yossisegev.movienight.di.DI import dagger.Module import dagger.Provides import javax.inject.Named import javax.inject.Singleton /** * Created by <NAME> on 13/11/2017. */ @Module @Singleton class DataModule { @Singleton @Provides fun provideRoomDatabase(context: Context): MoviesDatabase { return Room.databaseBuilder( context, MoviesDatabase::class.java, "movies_db").build() } @Provides @Singleton fun provideMovieRepository(api: Api, @Named(DI.inMemoryCache) cache: MoviesCache): MoviesRepository { val cachedMoviesDataStore = CachedMoviesDataStore(cache) val remoteMoviesDataStore = RemoteMoviesDataStore(api) return MoviesRepositoryImpl(cachedMoviesDataStore, remoteMoviesDataStore) } @Singleton @Provides @Named(DI.inMemoryCache) fun provideInMemoryMoviesCache(): MoviesCache { return MemoryMoviesCache() } @Singleton @Provides @Named(DI.favoritesCache) fun provideFavoriteMoviesCache(moviesDatabase: MoviesDatabase, entityDataMapper: MovieEntityDataMapper, dataEntityMapper: MovieDataEntityMapper): MoviesCache { return RoomFavoritesMovieCache(moviesDatabase, entityDataMapper, dataEntityMapper) } } <|start_filename|>data/src/main/kotlin/com/yossisegev/data/mappers/MovieDataEntityMapper.kt<|end_filename|> package com.yossisegev.data.mappers import com.yossisegev.data.entities.MovieData import com.yossisegev.domain.common.Mapper import com.yossisegev.domain.entities.MovieEntity import javax.inject.Inject import javax.inject.Singleton /** * Created by <NAME> on 11/11/2017. */ @Singleton class MovieDataEntityMapper @Inject constructor() : Mapper<MovieData, MovieEntity>() { override fun mapFrom(from: MovieData): MovieEntity { return MovieEntity( id = from.id, voteCount = from.voteCount, voteAverage = from.voteAverage, popularity = from.popularity, adult = from.adult, title = from.title, posterPath = from.posterPath, originalLanguage = from.originalLanguage, backdropPath = from.backdropPath, originalTitle = from.originalTitle, releaseDate = from.releaseDate, overview = from.overview ) } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/entities/Genre.kt<|end_filename|> package com.yossisegev.domain.entities /** * Created by <NAME> on 11/01/2018. */ data class Genre( var id: Int = -1, var name: String? = null ) <|start_filename|>data/src/main/kotlin/com/yossisegev/data/entities/VideoData.kt<|end_filename|> package com.yossisegev.data.entities /** * Created by <NAME> on 11/01/2018. */ data class VideoData( var id: String, var name: String, var key: String? = null, var site: String? = null, var type: String? = null ) <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/search/SearchMoviesModule.kt<|end_filename|> package com.yossisegev.movienight.di.search import com.yossisegev.domain.MoviesRepository import com.yossisegev.domain.usecases.SearchMovie import com.yossisegev.movienight.MovieEntityMovieMapper import com.yossisegev.movienight.common.ASyncTransformer import com.yossisegev.movienight.search.SearchVMFactory import dagger.Module import dagger.Provides /** * Created by <NAME> on 23/02/2018. */ @Module class SearchMoviesModule { @Provides fun provideSearchMovieUseCase(moviesRepository: MoviesRepository): SearchMovie { return SearchMovie(ASyncTransformer(), moviesRepository) } @Provides fun provideSearchVMFactory(useCase: SearchMovie, mapper: MovieEntityMovieMapper): SearchVMFactory { return SearchVMFactory(useCase, mapper) } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/popular/PopularSubComponent.kt<|end_filename|> package com.yossisegev.movienight.di.popular import com.yossisegev.movienight.popularmovies.PopularMoviesFragment import dagger.Subcomponent /** * Created by <NAME> on 23/02/2018. */ @Subcomponent(modules = [PopularMoviesModule::class]) interface PopularSubComponent { fun inject(popularMoviesFragment: PopularMoviesFragment) } <|start_filename|>data/src/main/kotlin/com/yossisegev/data/entities/ReviewData.kt<|end_filename|> package com.yossisegev.data.entities /** * Created by <NAME> on 11/01/2018. */ data class ReviewData( var id: String, var author: String, var content: String? = null ) <|start_filename|>presentation/src/androidTest/kotlin/com/yossisegev/movienight/ChangeHistoryObserver.kt<|end_filename|> package com.yossisegev.movienight import android.arch.lifecycle.Observer import android.util.Log /** * Created by <NAME> on 17/02/2018. */ class ChangeHistoryObserver<T>: Observer<T> { private val changeHistory = mutableListOf<T?>() override fun onChanged(t: T?) { changeHistory.add(t) } fun get(index: Int): T? { return changeHistory[index] } fun log() { changeHistory.map { Log.d(javaClass.simpleName, it.toString()) } } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/favorites/FavoritesSubComponent.kt<|end_filename|> package com.yossisegev.movienight.di.favorites import com.yossisegev.movienight.details.MovieDetailsActivity import com.yossisegev.movienight.favorites.FavoriteMoviesFragment import dagger.Subcomponent /** * Created by <NAME> on 23/02/2018. */ @FavoritesScope @Subcomponent(modules = [FavoriteModule::class]) interface FavoritesSubComponent { fun inject(favoriteMoviesFragment: FavoriteMoviesFragment) } <|start_filename|>data/src/main/kotlin/com/yossisegev/data/db/MoviesDao.kt<|end_filename|> package com.yossisegev.data.db import android.arch.persistence.room.* import com.yossisegev.data.entities.MovieData /** * Created by <NAME> on 20/01/2018. */ @Dao interface MoviesDao { @Query("SELECT * FROM movies") fun getFavorites(): List<MovieData> @Query("SELECT * FROM movies WHERE id=:movieId") fun get(movieId: Int): MovieData? @Query("SELECT * FROM movies WHERE title LIKE :query") fun search(query: String): List<MovieData> @Insert(onConflict = OnConflictStrategy.REPLACE) fun saveMovie(movie: MovieData) @Insert(onConflict = OnConflictStrategy.REPLACE) fun saveAllMovies(movies: List<MovieData>) @Delete fun removeMovie(movie: MovieData) @Query("DELETE FROM movies") fun clear() } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/popular/PopularScope.kt<|end_filename|> package com.yossisegev.movienight.di.popular import javax.inject.Scope /** * Created by <NAME> on 14/11/2017. */ @Scope @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class PopularScope <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/search/SearchFragment.kt<|end_filename|> package com.yossisegev.movienight.search import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.os.Bundle import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast import com.yossisegev.movienight.R import com.yossisegev.movienight.common.App import com.yossisegev.movienight.common.BaseFragment import com.yossisegev.movienight.common.ImageLoader import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.PublishSubject import kotlinx.android.synthetic.main.fragment_search_movies.* import java.util.concurrent.TimeUnit import javax.inject.Inject /** * Created by <NAME> on 11/11/2017. */ class SearchFragment : BaseFragment(), TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { searchSubject.onNext(s.toString()) } @Inject lateinit var factory: SearchVMFactory @Inject lateinit var imageLoader: ImageLoader private lateinit var viewModel: SearchViewModel private lateinit var searchEditText: EditText private lateinit var recyclerView: RecyclerView private lateinit var progressBar: ProgressBar private lateinit var noResultsMessage: TextView private lateinit var searchResultsAdapter: SearchResultsAdapter private lateinit var searchSubject: PublishSubject<String> private val compositeDisposable = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity?.application as App).createSearchComponent().inject(this) viewModel = ViewModelProviders.of(this, factory).get(SearchViewModel::class.java) searchSubject = PublishSubject.create() //TODO: Handle screen rotation during debounce val disposable = searchSubject.debounce(1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe { if (it != searchResultsAdapter.query) { viewModel.search(it) } else { Log.i(javaClass.simpleName, "Same query -> aborting search") } } compositeDisposable.add(disposable) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel.viewState.observe(this, Observer { if (it != null) handleViewState(it) }) viewModel.errorState.observe(this, Observer { throwable -> throwable?.let { Toast.makeText(activity, throwable.message, Toast.LENGTH_LONG).show() } }) } private fun handleViewState(state: SearchViewState) { progressBar.visibility = if (state.isLoading) View.VISIBLE else View.GONE val movies = state.movies ?: listOf() if (state.showNoResultsMessage) { noResultsMessage.visibility = View.VISIBLE noResultsMessage.text = String.format( getString(R.string.search_no_results_message, state.lastSearchedQuery)) } else { noResultsMessage.visibility = View.GONE } searchResultsAdapter.setResults(movies, state.lastSearchedQuery) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return layoutInflater.inflate(R.layout.fragment_search_movies, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) searchEditText = search_movies_edit_text searchEditText.addTextChangedListener(this) progressBar = search_movies_progress noResultsMessage = search_movies_no_results_message searchResultsAdapter = SearchResultsAdapter(imageLoader, { movie, movieView -> showSoftKeyboard(false) navigateToMovieDetailsScreen(movie, movieView) }) recyclerView = search_movies_recyclerview recyclerView.layoutManager = LinearLayoutManager(activity) recyclerView.adapter = searchResultsAdapter searchEditText.requestFocus() showSoftKeyboard(true) } private fun showSoftKeyboard(show: Boolean) { val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager if (show) { imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0) } else { imm.hideSoftInputFromWindow(searchEditText.windowToken,0) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString("lastSearch", searchEditText.text.toString()) } override fun onDestroyView() { super.onDestroyView() showSoftKeyboard(false) compositeDisposable.clear() (activity?.application as App).releaseSearchComponent() } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/common/ImageLoader.kt<|end_filename|> package com.yossisegev.movienight.common import android.widget.ImageView /** * Created by <NAME> on 16/11/2017. */ interface ImageLoader { fun load(url: String, imageView: ImageView, callback: (Boolean) -> Unit) fun load(url: String, imageView: ImageView, fadeEffect: Boolean = true) } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/entities/MovieDetails.kt<|end_filename|> package com.yossisegev.movienight.entities import com.yossisegev.domain.entities.Genre import com.yossisegev.domain.entities.Review /** * Created by <NAME> on 09/01/2018. */ data class MovieDetails( var belongsToCollection: Any? = null, var budget: Int? = null, var homepage: String? = null, var imdbId: String? = null, var overview: String? = null, var revenue: Int? = null, var runtime: Int? = null, var status: String? = null, var tagline: String? = null, var videos: List<Video>? = null, var reviews: List<Review>? = null, var genres: List<String>? = null ) <|start_filename|>data/src/main/kotlin/com/yossisegev/data/api/ReviewsResult.kt<|end_filename|> package com.yossisegev.data.api import com.yossisegev.data.entities.ReviewData /** * Created by <NAME> on 11/01/2018. */ class ReviewsResult { var results: List<ReviewData>? = null } <|start_filename|>domain/src/main/kotlin/com/yossisegev/domain/entities/VideoEntity.kt<|end_filename|> package com.yossisegev.domain.entities /** * Created by <NAME> on 11/01/2018. */ data class VideoEntity( var id: String, var name: String, var youtubeKey: String? = null) { companion object { const val SOURCE_YOUTUBE = "YouTube" const val TYPE_TRAILER = "Trailer" } } <|start_filename|>data/src/main/kotlin/com/yossisegev/data/entities/GenreData.kt<|end_filename|> package com.yossisegev.data.entities /** * Created by <NAME> on 11/01/2018. */ data class GenreData( var id: Int, var name: String ) <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/favorites/FavoriteModule.kt<|end_filename|> package com.yossisegev.movienight.di.favorites import com.yossisegev.domain.MoviesCache import com.yossisegev.domain.usecases.CheckFavoriteStatus import com.yossisegev.domain.usecases.GetFavoriteMovies import com.yossisegev.domain.usecases.RemoveFavoriteMovie import com.yossisegev.domain.usecases.SaveFavoriteMovie import com.yossisegev.movienight.MovieEntityMovieMapper import com.yossisegev.movienight.common.ASyncTransformer import com.yossisegev.movienight.di.DI import com.yossisegev.movienight.favorites.FavoriteMoviesVMFactory import dagger.Module import dagger.Provides import javax.inject.Named /** * Created by <NAME> on 23/02/2018. */ @Module class FavoriteModule { @Provides fun provideGetFavoriteMovies(@Named(DI.favoritesCache) moviesCache: MoviesCache): GetFavoriteMovies { return GetFavoriteMovies(ASyncTransformer(), moviesCache) } @Provides fun provideFavoriteMoviesVMFactory(getFavoriteMovies: GetFavoriteMovies, movieEntityMoveMapper: MovieEntityMovieMapper): FavoriteMoviesVMFactory { return FavoriteMoviesVMFactory(getFavoriteMovies, movieEntityMoveMapper) } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/popularmovies/PopularMoviesAdapter.kt<|end_filename|> package com.yossisegev.movienight.popularmovies import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.yossisegev.movienight.R import com.yossisegev.movienight.common.ImageLoader import com.yossisegev.movienight.entities.Movie import kotlinx.android.synthetic.main.popular_movies_adapter_cell.view.* /** * Created by <NAME> on 14/11/2017. */ class PopularMoviesAdapter constructor(private val imageLoader: ImageLoader, private val onMovieSelected: (Movie, View) -> Unit) : RecyclerView.Adapter<PopularMoviesAdapter.MovieCellViewHolder>() { private val movies: MutableList<Movie> = mutableListOf() override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MovieCellViewHolder { val view = LayoutInflater.from(parent?.context).inflate( R.layout.popular_movies_adapter_cell, parent, false) return MovieCellViewHolder(view) } override fun getItemCount(): Int { return movies.size } override fun onBindViewHolder(holder: MovieCellViewHolder?, position: Int) { val movie = movies[position] holder?.bind(movie, imageLoader, onMovieSelected) } fun addMovies(movies: List<Movie>) { this.movies.addAll(movies) notifyDataSetChanged() } class MovieCellViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(movie: Movie, imageLoader: ImageLoader, listener: (Movie, View) -> Unit) = with(itemView) { title.text = movie.originalTitle movie.posterPath?.let { imageLoader.load(it, image) } setOnClickListener { listener(movie, itemView) } } } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/common/PicassoImageLoader.kt<|end_filename|> package com.yossisegev.movienight.common import android.graphics.Bitmap import android.widget.EdgeEffect import android.widget.ImageView import com.squareup.picasso.Callback import com.squareup.picasso.Picasso /** * Created by <NAME> on 16/11/2017. */ class PicassoImageLoader(private val picasso: Picasso) : ImageLoader { override fun load(url: String, imageView: ImageView, callback: (Boolean) -> Unit) { picasso.load(url).into(imageView, FetchCallback(callback)) } override fun load(url: String, imageView: ImageView, fadeEffect: Boolean) { if (fadeEffect) picasso.load(url).into(imageView) else picasso.load(url).noFade().into(imageView) } private class FetchCallback(val delegate: (Boolean) -> Unit): Callback { override fun onSuccess() { delegate(true) } override fun onError() { delegate(false) } } } <|start_filename|>data/src/main/kotlin/com/yossisegev/data/mappers/DetailsDataMovieEntityMapper.kt<|end_filename|> package com.yossisegev.data.mappers import com.yossisegev.data.entities.DetailsData import com.yossisegev.domain.common.Mapper import com.yossisegev.domain.entities.* import javax.inject.Inject import javax.inject.Singleton /** * Created by <NAME> on 07/01/2018. */ @Singleton class DetailsDataMovieEntityMapper @Inject constructor() : Mapper<DetailsData, MovieEntity>() { override fun mapFrom(from: DetailsData): MovieEntity { val movieEntity = MovieEntity( id = from.id, voteCount = from.voteCount, video = from.video, voteAverage = from.voteAverage, popularity = from.popularity, adult = from.adult, title = from.title, posterPath = from.posterPath, originalTitle = from.originalTitle, backdropPath = from.backdropPath, originalLanguage = from.originalLanguage, releaseDate = from.releaseDate, overview = from.overview ) val details = MovieDetailsEntity() details.overview = from.overview details.budget = from.budget details.homepage = from.homepage details.imdbId = from.imdbId details.revenue = from.revenue details.runtime = from.runtime details.tagline = from.tagline from.genres?.let { val genreEntities = it.map { genreData -> return@map GenreEntity(genreData.id, genreData.name) } details.genres = genreEntities } // Take only YouTube trailers from.videos?.let { val videosEntities = it.results?.filter { videoData -> videoData.site.equals(VideoEntity.SOURCE_YOUTUBE) && videoData.type.equals(VideoEntity.TYPE_TRAILER) //TODO: remove from here? }?.map { videoData -> return@map VideoEntity( id = videoData.id, name = videoData.name, youtubeKey = videoData.key ) } details.videos = videosEntities } from.reviews?.let { val reviewEntities = it.results?.map { reviewData -> return@map ReviewEntity( id = reviewData.id, author = reviewData.author, content = reviewData.content ) } details.reviews = reviewEntities } movieEntity.details = details return movieEntity } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/common/ASyncTransformer.kt<|end_filename|> package com.yossisegev.movienight.common import com.yossisegev.domain.common.Transformer import io.reactivex.Observable import io.reactivex.ObservableSource import io.reactivex.ObservableTransformer import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers /** * Created by <NAME> on 11/11/2017. */ class ASyncTransformer<T> : Transformer<T>() { override fun apply(upstream: Observable<T>): ObservableSource<T> { return upstream.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } } <|start_filename|>data/src/main/kotlin/com/yossisegev/data/api/Api.kt<|end_filename|> package com.yossisegev.data.api import com.yossisegev.data.entities.DetailsData import io.reactivex.Observable import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query /** * Created by <NAME> on 11/11/2017. */ interface Api { @GET("movie/{id}?append_to_response=videos,reviews") fun getMovieDetails(@Path("id") movieId: Int): Observable<DetailsData> @GET("movie/popular") ///movie/now_playing fun getPopularMovies(): Observable<MovieListResult> @GET("search/movie") fun searchMovies(@Query("query") query: String): Observable<MovieListResult> } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/favorites/FavoriteMoviesVMFactory.kt<|end_filename|> package com.yossisegev.movienight.favorites import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import com.yossisegev.domain.common.Mapper import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.usecases.GetFavoriteMovies import com.yossisegev.movienight.entities.Movie /** * Created by <NAME> on 01/01/2018. */ class FavoriteMoviesVMFactory(private val useCase: GetFavoriteMovies, private val mapper: Mapper<MovieEntity, Movie>) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return FavoriteMoviesViewModel(useCase, mapper) as T } } <|start_filename|>data/src/main/kotlin/com/yossisegev/data/db/RoomFavoritesMovieCache.kt<|end_filename|> package com.yossisegev.data.db import com.yossisegev.data.entities.MovieData import com.yossisegev.domain.common.Mapper import com.yossisegev.domain.MoviesCache import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.entities.Optional import io.reactivex.Observable /** * Created by <NAME> on 22/01/2018. */ class RoomFavoritesMovieCache(database: MoviesDatabase, private val entityToDataMapper: Mapper<MovieEntity, MovieData>, private val dataToEntityMapper: Mapper<MovieData, MovieEntity>) : MoviesCache { private val dao: MoviesDao = database.getMoviesDao() override fun clear() { dao.clear() } override fun save(movieEntity: MovieEntity) { dao.saveMovie(entityToDataMapper.mapFrom(movieEntity)) } override fun remove(movieEntity: MovieEntity) { dao.removeMovie(entityToDataMapper.mapFrom(movieEntity)) } override fun saveAll(movieEntities: List<MovieEntity>) { dao.saveAllMovies(movieEntities.map { entityToDataMapper.mapFrom(it) }) } override fun getAll(): Observable<List<MovieEntity>> { return Observable.fromCallable { dao.getFavorites().map { dataToEntityMapper.mapFrom(it) } } } override fun get(movieId: Int): Observable<Optional<MovieEntity>> { return Observable.fromCallable { val movieData = dao.get(movieId) movieData?.let { Optional.of(dataToEntityMapper.mapFrom(it)) } ?: Optional.empty() } } override fun isEmpty(): Observable<Boolean> { return Observable.fromCallable { dao.getFavorites().isEmpty() } } override fun search(query: String): Observable<List<MovieEntity>> { val searchQuery = "%$query%" return Observable.fromCallable { dao.search(searchQuery).map { dataToEntityMapper.mapFrom(it) } } } } <|start_filename|>presentation/src/androidTest/kotlin/com/yossisegev/movienight/PopularMoviesViewModelTests.kt<|end_filename|> package com.yossisegev.movienight import android.arch.lifecycle.Observer import android.support.test.annotation.UiThreadTest import android.support.test.runner.AndroidJUnit4 import com.yossisegev.domain.MoviesRepository import com.yossisegev.domain.common.DomainTestUtils import com.yossisegev.domain.common.TestTransformer import com.yossisegev.domain.usecases.GetPopularMovies import com.yossisegev.movienight.popularmovies.PopularMoviesViewModel import com.yossisegev.movienight.popularmovies.PopularMoviesViewState import io.reactivex.Observable import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito import org.mockito.Mockito.* @Suppress("UNCHECKED_CAST") @RunWith(AndroidJUnit4::class) class PopularMoviesViewModelTests { private val movieEntityMovieMapper = MovieEntityMovieMapper() private lateinit var popularMoviesViewModel: PopularMoviesViewModel private lateinit var moviesRepository: MoviesRepository private lateinit var viewObserver: Observer<PopularMoviesViewState> private lateinit var errorObserver: Observer<Throwable?> @Before @UiThreadTest fun before() { moviesRepository = Mockito.mock(MoviesRepository::class.java) val getPopularMoviesUseCase = GetPopularMovies(TestTransformer(), moviesRepository) popularMoviesViewModel = PopularMoviesViewModel(getPopularMoviesUseCase, movieEntityMovieMapper) viewObserver = mock(Observer::class.java) as Observer<PopularMoviesViewState> errorObserver = mock(Observer::class.java) as Observer<Throwable?> popularMoviesViewModel.viewState.observeForever(viewObserver) popularMoviesViewModel.errorState.observeForever(errorObserver) } @Test @UiThreadTest fun testInitialViewStateShowsLoading() { verify(viewObserver).onChanged(PopularMoviesViewState(showLoading = true, movies = null)) verifyZeroInteractions(viewObserver) } @Test @UiThreadTest fun testShowingMoviesAsExpectedAndStopsLoading() { val movieEntities = DomainTestUtils.generateMovieEntityList() `when`(moviesRepository.getMovies()).thenReturn(Observable.just(movieEntities)) popularMoviesViewModel.getPopularMovies() val movies = movieEntities.map { movieEntityMovieMapper.mapFrom(it) } verify(viewObserver).onChanged(PopularMoviesViewState(showLoading = false, movies = movies)) verify(errorObserver).onChanged(null) } @Test @UiThreadTest fun testShowingErrorMessageWhenNeeded() { val throwable = Throwable("ERROR!") `when`(moviesRepository.getMovies()).thenReturn(Observable.error(throwable)) popularMoviesViewModel.getPopularMovies() verify(viewObserver).onChanged(PopularMoviesViewState(showLoading = false, movies = null)) verify(errorObserver).onChanged(throwable) } } <|start_filename|>data/src/main/kotlin/com/yossisegev/data/db/MoviesDatabase.kt<|end_filename|> package com.yossisegev.data.db import android.arch.persistence.room.Database import android.arch.persistence.room.RoomDatabase import com.yossisegev.data.entities.MovieData /** * Created by <NAME> on 20/01/2018. */ @Database(entities = arrayOf(MovieData::class), version = 1) abstract class MoviesDatabase: RoomDatabase() { abstract fun getMoviesDao(): MoviesDao } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/common/App.kt<|end_filename|> package com.yossisegev.movienight.common import android.app.Application import com.squareup.leakcanary.LeakCanary import com.yossisegev.movienight.R import com.yossisegev.movienight.di.* import com.yossisegev.movienight.di.details.MovieDetailsModule import com.yossisegev.movienight.di.details.MovieDetailsSubComponent import com.yossisegev.movienight.di.favorites.FavoriteModule import com.yossisegev.movienight.di.favorites.FavoritesSubComponent import com.yossisegev.movienight.di.modules.* import com.yossisegev.movienight.di.popular.PopularMoviesModule import com.yossisegev.movienight.di.popular.PopularSubComponent import com.yossisegev.movienight.di.search.SearchMoviesModule import com.yossisegev.movienight.di.search.SearchSubComponent /** * Created by <NAME> on 11/11/2017. */ class App: Application() { lateinit var mainComponent: MainComponent private var popularMoviesComponent: PopularSubComponent? = null private var favoriteMoviesComponent: FavoritesSubComponent? = null private var movieDetailsComponent: MovieDetailsSubComponent? = null private var searchMoviesComponent: SearchSubComponent? = null override fun onCreate() { super.onCreate() if (LeakCanary.isInAnalyzerProcess(this)) { return } LeakCanary.install(this) initDependencies() } private fun initDependencies() { mainComponent = DaggerMainComponent.builder() .appModule(AppModule(applicationContext)) .networkModule(NetworkModule(getString(R.string.api_base_url), getString(R.string.api_key))) .dataModule(DataModule()) .build() } fun createPopularComponenet(): PopularSubComponent { popularMoviesComponent = mainComponent.plus(PopularMoviesModule()) return popularMoviesComponent!! } fun releasePopularComponent() { popularMoviesComponent = null } fun createFavoritesComponent() : FavoritesSubComponent { favoriteMoviesComponent = mainComponent.plus(FavoriteModule()) return favoriteMoviesComponent!! } fun releaseFavoritesComponent() { favoriteMoviesComponent = null } fun createDetailsComponent(): MovieDetailsSubComponent { movieDetailsComponent = mainComponent.plus(MovieDetailsModule()) return movieDetailsComponent!! } fun releaseDetailsComponent() { movieDetailsComponent = null } fun createSearchComponent(): SearchSubComponent { searchMoviesComponent = mainComponent.plus(SearchMoviesModule()) return searchMoviesComponent!! } fun releaseSearchComponent() { searchMoviesComponent = null } } <|start_filename|>presentation/src/androidTest/kotlin/com/yossisegev/movienight/MovieDetailsViewModelTests.kt<|end_filename|> package com.yossisegev.movienight import android.arch.lifecycle.Observer import android.support.test.annotation.UiThreadTest import android.support.test.runner.AndroidJUnit4 import com.yossisegev.domain.MoviesCache import com.yossisegev.domain.MoviesRepository import com.yossisegev.domain.common.DomainTestUtils import com.yossisegev.domain.common.TestTransformer import com.yossisegev.domain.entities.Optional import com.yossisegev.domain.usecases.CheckFavoriteStatus import com.yossisegev.domain.usecases.GetMovieDetails import com.yossisegev.domain.usecases.RemoveFavoriteMovie import com.yossisegev.domain.usecases.SaveFavoriteMovie import com.yossisegev.movienight.details.MovieDetailsViewModel import com.yossisegev.movienight.details.MovieDetailsViewState import io.reactivex.Observable import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.* /** * Created by <NAME> on 19/02/2018. */ @Suppress("UNCHECKED_CAST") @RunWith(AndroidJUnit4::class) class MovieDetailsViewModelTests { private val testMovieId = 100 private val movieEntityMovieMapper = MovieEntityMovieMapper() private lateinit var movieDetailsViewModel: MovieDetailsViewModel private lateinit var moviesRepository: MoviesRepository private lateinit var moviesCache: MoviesCache private lateinit var viewObserver: Observer<MovieDetailsViewState> private lateinit var errorObserver: Observer<Throwable> private lateinit var favoriteStateObserver: Observer<Boolean> @Before @UiThreadTest fun before() { moviesRepository = mock(MoviesRepository::class.java) moviesCache = mock(MoviesCache::class.java) val getMovieDetails = GetMovieDetails(TestTransformer(), moviesRepository) val saveFavoriteMovie = SaveFavoriteMovie(TestTransformer(), moviesCache) val removeFavoriteMovie = RemoveFavoriteMovie(TestTransformer(), moviesCache) val checkFavoriteStatus = CheckFavoriteStatus(TestTransformer(), moviesCache) movieDetailsViewModel = MovieDetailsViewModel( getMovieDetails, saveFavoriteMovie, removeFavoriteMovie, checkFavoriteStatus, movieEntityMovieMapper, testMovieId) viewObserver = mock(Observer::class.java) as Observer<MovieDetailsViewState> favoriteStateObserver = mock(Observer::class.java) as Observer<Boolean> errorObserver = mock(Observer::class.java) as Observer<Throwable> movieDetailsViewModel.viewState.observeForever(viewObserver) movieDetailsViewModel.errorState.observeForever(errorObserver) movieDetailsViewModel.favoriteState.observeForever(favoriteStateObserver) } @Test @UiThreadTest fun showsCorrectDetailsAndFavoriteState() { val movieEntity = DomainTestUtils.getTestMovieEntity(testMovieId) `when`(moviesRepository.getMovie(testMovieId)).thenReturn(Observable.just( Optional.of(movieEntity) )) `when`(moviesCache.get(testMovieId)).thenReturn(Observable.just(Optional.of(movieEntity))) movieDetailsViewModel.getMovieDetails() val video = movieEntityMovieMapper.mapFrom(movieEntity) val expectedDetailsViewState = MovieDetailsViewState( isLoading = false, title = video.title, overview = video.details?.overview, videos = video.details?.videos, homepage = video.details?.homepage, releaseDate = video.releaseDate, backdropUrl = video.backdropPath, votesAverage = video.voteAverage, genres = video.details?.genres) verify(viewObserver).onChanged(expectedDetailsViewState) verify(favoriteStateObserver).onChanged(true) verifyZeroInteractions(errorObserver) } @Test @UiThreadTest fun showsErrorWhenFailsToGetMovieFromRepository() { val movieEntity = DomainTestUtils.getTestMovieEntity(testMovieId) val throwable = Throwable("ERROR!") `when`(moviesRepository.getMovie(testMovieId)).thenReturn(Observable.error(throwable)) `when`(moviesCache.get(testMovieId)).thenReturn(Observable.just(Optional.of(movieEntity))) movieDetailsViewModel.getMovieDetails() verify(errorObserver).onChanged(throwable) verifyZeroInteractions(favoriteStateObserver) } @Test @UiThreadTest fun showsErrorWhenFailsToGetFavoriteState() { val movieEntity = DomainTestUtils.getTestMovieEntity(testMovieId) `when`(moviesRepository.getMovie(testMovieId)).thenReturn(Observable.just(Optional.empty())) `when`(moviesCache.get(testMovieId)).thenReturn(Observable.just(Optional.of(movieEntity))) movieDetailsViewModel.getMovieDetails() verify(errorObserver).onChanged(any(Throwable::class.java)) } @Test @UiThreadTest fun showsErrorWhenGetMovieFromRepositoryReturnsEmptyOptional() { val movieEntity = DomainTestUtils.getTestMovieEntity(testMovieId) val throwable = Throwable("ERROR!") `when`(moviesRepository.getMovie(testMovieId)).thenReturn(Observable.just(Optional.of(movieEntity))) `when`(moviesCache.get(testMovieId)).thenReturn(Observable.error(throwable)) movieDetailsViewModel.getMovieDetails() verify(errorObserver).onChanged(throwable) verifyZeroInteractions(favoriteStateObserver) } @Test @UiThreadTest fun favoriteStateChangesAsExpected() { val movieEntity = DomainTestUtils.getTestMovieEntity(testMovieId) `when`(moviesRepository.getMovie(testMovieId)).thenReturn(Observable.just( Optional.of(movieEntity) )) `when`(moviesCache.get(testMovieId)).thenReturn(Observable.just(Optional.of(movieEntity))) movieDetailsViewModel.getMovieDetails() verify(favoriteStateObserver).onChanged(true) movieDetailsViewModel.favoriteButtonClicked() verify(favoriteStateObserver).onChanged(false) movieDetailsViewModel.favoriteButtonClicked() verify(favoriteStateObserver).onChanged(true) verifyZeroInteractions(errorObserver) } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/details/MovieDetailsViewModel.kt<|end_filename|> package com.yossisegev.movienight.details import android.arch.lifecycle.MutableLiveData import com.yossisegev.domain.common.Mapper import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.usecases.CheckFavoriteStatus import com.yossisegev.domain.usecases.GetMovieDetails import com.yossisegev.domain.usecases.RemoveFavoriteMovie import com.yossisegev.domain.usecases.SaveFavoriteMovie import com.yossisegev.movienight.common.BaseViewModel import com.yossisegev.movienight.common.SingleLiveEvent import com.yossisegev.movienight.entities.Movie import io.reactivex.Observable import io.reactivex.functions.BiFunction /** * Created by <NAME> on 07/01/2018. */ class MovieDetailsViewModel(private val getMovieDetails: GetMovieDetails, private val saveFavoriteMovie: SaveFavoriteMovie, private val removeFavoriteMovie: RemoveFavoriteMovie, private val checkFavoriteStatus: CheckFavoriteStatus, private val mapper: Mapper<MovieEntity, Movie>, private val movieId: Int) : BaseViewModel() { lateinit var movieEntity: MovieEntity var viewState: MutableLiveData<MovieDetailsViewState> = MutableLiveData() var favoriteState: MutableLiveData<Boolean> = MutableLiveData() var errorState: SingleLiveEvent<Throwable> = SingleLiveEvent() init { viewState.value = MovieDetailsViewState(isLoading = true) } fun getMovieDetails() { addDisposable( getMovieDetails.getById(movieId) .map { it.value?.let { movieEntity = it mapper.mapFrom(movieEntity) } ?: run { throw Throwable("Something went wrong :(") } } .zipWith(checkFavoriteStatus.check(movieId), BiFunction<Movie, Boolean, Movie> { movie, isFavorite -> movie.isFavorite = isFavorite return@BiFunction movie }) .subscribe( { onMovieDetailsReceived(it) }, { errorState.value = it } ) ) } fun favoriteButtonClicked() { addDisposable(checkFavoriteStatus.check(movieId).flatMap { when (it) { true -> { removeFavorite(movieEntity) } false -> { saveFavorite(movieEntity) } } }.subscribe({ isFavorite -> favoriteState.value = isFavorite }, { errorState.value = it })) } private fun onMovieDetailsReceived(movie: Movie) { val newViewState = viewState.value?.copy( isLoading = false, title = movie.originalTitle, videos = movie.details?.videos, homepage = movie.details?.homepage, overview = movie.details?.overview, releaseDate = movie.releaseDate, votesAverage = movie.voteAverage, backdropUrl = movie.backdropPath, genres = movie.details?.genres) viewState.value = newViewState favoriteState.value = movie.isFavorite } private fun saveFavorite(movieEntity: MovieEntity): Observable<Boolean> { return saveFavoriteMovie.save(movieEntity) } private fun removeFavorite(movieEntity: MovieEntity): Observable<Boolean> { return removeFavoriteMovie.remove(movieEntity) } } <|start_filename|>domain/src/main/kotlin/com/yossisegev/domain/entities/ReviewEntity.kt<|end_filename|> package com.yossisegev.domain.entities /** * Created by <NAME> on 11/01/2018. */ data class ReviewEntity ( var id: String, var author: String, var content: String? = null ) <|start_filename|>presentation/src/androidTest/kotlin/com/yossisegev/movienight/FavoriteMoviesViewModelTests.kt<|end_filename|> package com.yossisegev.movienight import android.arch.lifecycle.Observer import android.support.test.annotation.UiThreadTest import android.support.test.runner.AndroidJUnit4 import com.yossisegev.domain.MoviesCache import com.yossisegev.domain.common.DomainTestUtils import com.yossisegev.domain.common.TestTransformer import com.yossisegev.domain.usecases.GetFavoriteMovies import com.yossisegev.movienight.favorites.FavoriteMoviesViewModel import com.yossisegev.movienight.favorites.FavoritesMoviesViewState import io.reactivex.Observable import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.* @Suppress("UNCHECKED_CAST") @RunWith(AndroidJUnit4::class) class FavoriteMoviesViewModelTests { private val movieEntityMovieMapper = MovieEntityMovieMapper() private lateinit var favoriteMoviesViewModel: FavoriteMoviesViewModel private lateinit var moviesCache: MoviesCache private lateinit var viewObserver: Observer<FavoritesMoviesViewState> private lateinit var errorObserver: Observer<Throwable?> @Before @UiThreadTest fun before() { moviesCache = mock(MoviesCache::class.java) val getFavoriteMovies = GetFavoriteMovies(TestTransformer(), moviesCache) favoriteMoviesViewModel = FavoriteMoviesViewModel(getFavoriteMovies, movieEntityMovieMapper) viewObserver = mock(Observer::class.java) as Observer<FavoritesMoviesViewState> errorObserver = mock(Observer::class.java) as Observer<Throwable?> favoriteMoviesViewModel.viewState.observeForever(viewObserver) favoriteMoviesViewModel.errorState.observeForever(errorObserver) } @Test @UiThreadTest fun testInitialViewStateShowsLoading() { verify(viewObserver).onChanged(FavoritesMoviesViewState(isLoading = true, isEmpty = true, movies = null)) verifyZeroInteractions(errorObserver) } @Test @UiThreadTest fun testShowingMoviesAsExpectedAndStopsLoading() { val movieEntities = DomainTestUtils.generateMovieEntityList() `when`(moviesCache.getAll()).thenReturn(Observable.just(movieEntities)) val movies = movieEntities.map { movieEntityMovieMapper.mapFrom(it) } favoriteMoviesViewModel.getFavorites() verify(viewObserver).onChanged(FavoritesMoviesViewState(isLoading = false, isEmpty = false, movies = movies)) verify(errorObserver).onChanged(null) } @Test @UiThreadTest fun testShowingEmptyMessage() { `when`(moviesCache.getAll()).thenReturn(Observable.just(mutableListOf())) favoriteMoviesViewModel.getFavorites() verify(viewObserver).onChanged(FavoritesMoviesViewState(isLoading = false, isEmpty = true, movies = mutableListOf())) verify(errorObserver).onChanged(null) } @Test @UiThreadTest fun testShowingErrorWhenNeeded() { val throwable = Throwable("ERROR!") `when`(moviesCache.getAll()).thenReturn(Observable.error(throwable)) favoriteMoviesViewModel.getFavorites() verify(viewObserver).onChanged(FavoritesMoviesViewState(isLoading = false, isEmpty = false, movies = null)) verify(errorObserver).onChanged(throwable) } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/details/ReviewsAdapter.kt<|end_filename|> package com.yossisegev.movienight.details import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.yossisegev.domain.entities.Review import com.yossisegev.movienight.R import kotlinx.android.synthetic.main.cell_reviews_adapter.view.* /** * Created by <NAME> on 12/01/2018. */ class ReviewsAdapter(private val reviews: List<Review>) : RecyclerView.Adapter<ReviewsAdapter.ReviewViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ReviewViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.cell_reviews_adapter, parent, false) return ReviewViewHolder(view) } override fun onBindViewHolder(holder: ReviewViewHolder?, position: Int) { holder?.bind(reviews[position]) } override fun getItemCount(): Int { return reviews.size } class ReviewViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(review: Review) { with(itemView) { reviews_adapter_content.text = "\"${review.content}\"" reviews_adapter_author.text = review.author } } } } <|start_filename|>domain/src/main/kotlin/com/yossisegev/domain/entities/GenreEntity.kt<|end_filename|> package com.yossisegev.domain.entities /** * Created by <NAME> on 11/01/2018. */ data class GenreEntity( var id: Int, var name: String ) <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/MainActivity.kt<|end_filename|> package com.yossisegev.movienight import android.os.Bundle import android.support.design.widget.BottomNavigationView import android.support.v7.app.AppCompatActivity import android.view.MenuItem import android.view.SearchEvent import com.yossisegev.movienight.common.App import com.yossisegev.movienight.favorites.FavoriteMoviesFragment import com.yossisegev.movienight.popularmovies.PopularMoviesFragment import com.yossisegev.movienight.search.SearchFragment import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), BottomNavigationView.OnNavigationItemSelectedListener { private lateinit var navigationBar: BottomNavigationView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(R.id.container, PopularMoviesFragment(), "popular") .commitNow() title = getString(R.string.popular) } navigationBar = bottomNavigationView navigationBar.setOnNavigationItemSelectedListener(this) } override fun onNavigationItemSelected(item: MenuItem): Boolean { if (item.itemId == navigationBar.selectedItemId) { return false } when (item.itemId) { R.id.action_popular -> { supportFragmentManager.beginTransaction() .replace(R.id.container, PopularMoviesFragment(), "popular") .commitNow() title = getString(R.string.popular) } R.id.action_favorites -> { supportFragmentManager.beginTransaction() .replace(R.id.container, FavoriteMoviesFragment(), "favorites") .commitNow() title = getString(R.string.my_favorites) } R.id.action_search -> { supportFragmentManager.beginTransaction() .replace(R.id.container, SearchFragment(), "search") .commitNow() title = getString(R.string.search) } } return true } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/search/SearchResultsAdapter.kt<|end_filename|> package com.yossisegev.movienight.search import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.yossisegev.movienight.R import com.yossisegev.movienight.common.ImageLoader import com.yossisegev.movienight.entities.Movie import kotlinx.android.synthetic.main.search_results_adapter_row.view.* /** * Created by <NAME> on 14/11/2017. */ class SearchResultsAdapter constructor(private val imageLoader: ImageLoader, private val onMovieSelected: (Movie, View) -> Unit) : RecyclerView.Adapter<SearchResultsAdapter.MovieCellViewHolder>() { private var movies: List<Movie> = listOf() var query: String? = null fun setResults(movies: List<Movie>, query: String?) { this.movies = movies this.query = query notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MovieCellViewHolder { val view = LayoutInflater.from(parent?.context).inflate( R.layout.search_results_adapter_row, parent, false) return MovieCellViewHolder(view) } override fun getItemCount(): Int { return movies.size } override fun onBindViewHolder(holder: MovieCellViewHolder?, position: Int) { val movie = movies[position] holder?.bind(movie, imageLoader, onMovieSelected) } class MovieCellViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(movie: Movie, imageLoader: ImageLoader, listener: (Movie, View) -> Unit) = with(itemView) { title.text = movie.originalTitle rating.text = movie.voteAverage.toString() movie.overview?.let { overview.text = movie.overview overview.visibility = View.VISIBLE } ?: run { overview.visibility = View.GONE } movie.posterPath?.let { image.visibility = View.VISIBLE imageLoader.load(it, image) } ?: run { image.visibility == View.INVISIBLE } setOnClickListener { listener(movie, itemView) } } } } <|start_filename|>data/src/test/kotlin/com/yossisegev/data/CachedMoviesDataStoreTests.kt<|end_filename|> package com.yossisegev.data import com.yossisegev.data.repositories.CachedMoviesDataStore import com.yossisegev.data.repositories.MemoryMoviesCache import com.yossisegev.domain.MoviesCache import com.yossisegev.domain.common.DomainTestUtils.Companion.generateMovieEntityList import com.yossisegev.domain.common.DomainTestUtils.Companion.getTestMovieEntity import org.junit.After import org.junit.Before import org.junit.Test /** * Created by <NAME> on 22/01/2018. */ class CachedMoviesDataStoreTests { private lateinit var moviesCache: MoviesCache private lateinit var cachedMoviesDataStore: CachedMoviesDataStore @Before fun before() { moviesCache = MemoryMoviesCache() cachedMoviesDataStore = CachedMoviesDataStore(moviesCache) } @After fun after() { moviesCache.clear() } @Test fun testWhenSavingMoviesInCacheTheyCanBeRetrieved() { moviesCache.saveAll(generateMovieEntityList()) cachedMoviesDataStore.getMovies().test() .assertValue { list -> list.size == 5 } .assertComplete() } @Test fun testSavedMovieCanBeRetrievedUsingId() { moviesCache.save(getTestMovieEntity(1)) cachedMoviesDataStore.getMovieById(1).test() .assertValue { optional -> optional.hasValue() && optional.value?.id == 1 } .assertComplete() } @Test fun testWhenRetrievingIdThatDoesNotExistsReturnEmptyOptional() { moviesCache.saveAll(generateMovieEntityList()) cachedMoviesDataStore.getMovieById(18877).test() .assertValue { optional -> !optional.hasValue() } .assertComplete() } } <|start_filename|>domain/src/main/kotlin/com/yossisegev/domain/usecases/SearchMovie.kt<|end_filename|> package com.yossisegev.domain.usecases import com.yossisegev.domain.MoviesDataStore import com.yossisegev.domain.MoviesRepository import com.yossisegev.domain.common.Transformer import com.yossisegev.domain.entities.MovieEntity import io.reactivex.Observable import io.reactivex.ObservableTransformer /** * Created by <NAME> on 11/02/2018. */ class SearchMovie(transformer: Transformer<List<MovieEntity>>, private val moviesRepository: MoviesRepository) : UseCase<List<MovieEntity>>(transformer) { companion object { private const val PARAM_SEARCH_QUERY = "param:search_query" } fun search(query: String): Observable<List<MovieEntity>> { val data = HashMap<String, String>() data[PARAM_SEARCH_QUERY] = query return observable(data) } override fun createObservable(data: Map<String, Any>?): Observable<List<MovieEntity>> { val query = data?.get(PARAM_SEARCH_QUERY) query?.let { return moviesRepository.search(it as String) } ?: return Observable.just(emptyList()) } } <|start_filename|>presentation/src/test/kotlin/com/yossisegev/movienight/MovieEntityMovieMapperTests.kt<|end_filename|> package com.yossisegev.movienight import com.yossisegev.domain.entities.* import junit.framework.Assert.assertEquals import org.junit.Test /** * Created by <NAME> on 20/02/2018. */ class MovieEntityMovieMapperTests { @Test fun testMappingMovieEntityToMovieReturnsExpectedResult() { val videos = (0..4).map { VideoEntity( id = "ID_$it", name = "Video$it", youtubeKey = "Key$it" ) } val genres = (0..4).map { GenreEntity( id = it, name = "Genre$it" ) } val reviews = (0..4).map { ReviewEntity( id = "ID_$it", author = "Author$it", content = "Content$it" ) } val movieEntity = MovieEntity( id = 1, title = "MovieData", backdropPath = "movieData_backdrop", originalLanguage = "movieData_lan", overview = "movieData_overview", posterPath = "movieData_poster", originalTitle = "Original title of MovieData", releaseDate = "1970-1-1", adult = true, popularity = 10.0, voteAverage = 7.0, video = false, voteCount = 100 ) val movieDetailsEntity = MovieDetailsEntity( overview = "movieData_overview", budget = 6, homepage = "homepage_url", imdbId = "imdb_id", revenue = 80, runtime = 60, tagline = "movie_tag_line", videos = videos, reviews = reviews, genres = genres ) movieEntity.details = movieDetailsEntity val mapper = MovieEntityMovieMapper() val movie = mapper.mapFrom(movieEntity) assertEquals(movieEntity.id, movie.id) assertEquals(movieEntity.title, movie.title) assertEquals(movieEntity.originalTitle, movie.originalTitle) assertEquals(movieEntity.adult, movie.adult) assertEquals(movie.backdropPath, MovieEntityMovieMapper.backdropBaseUrl + movieEntity.backdropPath) assertEquals(movieEntity.releaseDate, movie.releaseDate) assertEquals(movieEntity.popularity, movie.popularity, 0.0) assertEquals(movieEntity.voteAverage, movie.voteAverage, 0.0) assertEquals(movieEntity.voteCount, movie.voteCount) assertEquals(movieEntity.video, movie.video) assertEquals(movie.posterPath, MovieEntityMovieMapper.posterBaseUrl + movieEntity.posterPath) assertEquals(movieEntity.originalLanguage, movie.originalLanguage) assertEquals(movieEntity.details?.videos?.size, movie.details!!.videos!!.size) assertEquals(movie.details!!.videos!![0].url, MovieEntityMovieMapper.youTubeBaseUrl + movieEntity.details!!.videos!![0].youtubeKey) assertEquals(movieEntity.details?.videos?.get(0)?.id, movie.details!!.videos!![0].id) assertEquals(movieEntity.details?.videos?.get(0)?.name, movie.details!!.videos!![0].name) assertEquals(movieEntity.details?.reviews?.size, movie.details!!.reviews!!.size) assertEquals(movieEntity.details?.reviews?.get(0)?.id, movie.details!!.reviews!![0].id) assertEquals(movieEntity.details?.reviews?.get(0)?.author, movie.details!!.reviews!![0].author) assertEquals(movieEntity.details?.reviews?.get(0)?.content, movie.details!!.reviews!![0].content) assertEquals(movieEntity.details?.genres?.size, movie.details!!.genres!!.size) assertEquals(movieEntity.details?.genres?.get(0)?.name, movie.details!!.genres!![0]) assertEquals(movieEntity.details?.tagline, movie.details!!.tagline) assertEquals(movieEntity.details?.runtime, movie.details!!.runtime) assertEquals(movieEntity.details?.revenue, movie.details!!.revenue) assertEquals(movieEntity.details?.imdbId, movie.details!!.imdbId) assertEquals(movieEntity.details?.homepage, movie.details!!.homepage) assertEquals(movieEntity.details?.budget, movie.details!!.budget) assertEquals(movieEntity.details?.overview, movie.details!!.overview) assertEquals(movieEntity.details?.overview, movie.overview) } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/popularmovies/PopularMoviesViewModel.kt<|end_filename|> package com.yossisegev.movienight.popularmovies import android.arch.lifecycle.MutableLiveData import com.yossisegev.domain.common.Mapper import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.usecases.GetPopularMovies import com.yossisegev.movienight.common.BaseViewModel import com.yossisegev.movienight.common.SingleLiveEvent import com.yossisegev.movienight.entities.Movie /** * Created by <NAME> on 11/11/2017. */ class PopularMoviesViewModel(private val getPopularMovies: GetPopularMovies, private val movieEntityMovieMapper: Mapper<MovieEntity, Movie>) : BaseViewModel() { var viewState: MutableLiveData<PopularMoviesViewState> = MutableLiveData() var errorState: SingleLiveEvent<Throwable?> = SingleLiveEvent() init { viewState.value = PopularMoviesViewState() } fun getPopularMovies() { addDisposable(getPopularMovies.observable() .flatMap { movieEntityMovieMapper.observable(it) } .subscribe({ movies -> viewState.value?.let { val newState = this.viewState.value?.copy(showLoading = false, movies = movies) this.viewState.value = newState this.errorState.value = null } }, { viewState.value = viewState.value?.copy(showLoading = false) errorState.value = it })) } } <|start_filename|>domain/src/main/kotlin/com/yossisegev/domain/MoviesRepository.kt<|end_filename|> package com.yossisegev.domain import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.entities.Optional import io.reactivex.Observable /** * Created by <NAME> on 25/01/2018. */ interface MoviesRepository { fun getMovies(): Observable<List<MovieEntity>> fun search(query: String): Observable<List<MovieEntity>> fun getMovie(movieId: Int): Observable<Optional<MovieEntity>> } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/common/SimpleTransitionEndedCallback.kt<|end_filename|> package com.yossisegev.movienight.common import android.transition.Transition /** * Created by <NAME> on 12/01/2018. */ class SimpleTransitionEndedCallback(private var callback: () -> Unit): Transition.TransitionListener { override fun onTransitionEnd(transition: Transition?) { callback() } override fun onTransitionResume(transition: Transition?) { } override fun onTransitionPause(transition: Transition?) { } override fun onTransitionCancel(transition: Transition?) { } override fun onTransitionStart(transition: Transition?) { } } <|start_filename|>domain/src/main/kotlin/com/yossisegev/domain/usecases/UseCase.kt<|end_filename|> package com.yossisegev.domain.usecases import com.yossisegev.domain.common.Transformer import io.reactivex.Observable /** * Created by <NAME> on 11/11/2017. */ abstract class UseCase<T>(private val transformer: Transformer<T>) { abstract fun createObservable(data: Map<String, Any>? = null): Observable<T> fun observable(withData: Map<String, Any>? = null): Observable<T> { return createObservable(withData).compose(transformer) } } <|start_filename|>domain/src/main/kotlin/com/yossisegev/domain/common/Transformer.kt<|end_filename|> package com.yossisegev.domain.common import io.reactivex.ObservableTransformer /** * Created by <NAME> on 20/02/2018. */ abstract class Transformer<T> : ObservableTransformer<T, T> <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/search/SearchViewState.kt<|end_filename|> package com.yossisegev.movienight.search import com.yossisegev.movienight.entities.Movie /** * Created by <NAME> on 11/02/2018. */ data class SearchViewState( val isLoading: Boolean = false, val movies: List<Movie>? = null, val lastSearchedQuery: String? = null, val showNoResultsMessage: Boolean = false ) <|start_filename|>domain/src/test/kotlin/com/yossisegev/domain/UseCasesTests.kt<|end_filename|> package com.yossisegev.domain /** * Created by <NAME> on 06/01/2018. */ import com.yossisegev.domain.common.DomainTestUtils import com.yossisegev.domain.common.DomainTestUtils.Companion.generateMovieEntityList import com.yossisegev.domain.common.TestMoviesCache import com.yossisegev.domain.common.TestTransformer import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.entities.Optional import com.yossisegev.domain.usecases.* import io.reactivex.Observable import junit.framework.Assert.assertNotNull import org.junit.Test import org.mockito.Mockito import org.mockito.Mockito.`when` import org.mockito.Mockito.mock class UseCasesTests { @Test fun getMovieDetailsById() { val movieEntity = DomainTestUtils.getTestMovieEntity(100) val movieRepository = Mockito.mock(MoviesRepository::class.java) val getMovieDetails = GetMovieDetails(TestTransformer(), movieRepository) Mockito.`when`(movieRepository.getMovie(100)).thenReturn(Observable.just(Optional.of(movieEntity))) getMovieDetails.getById(100).test() .assertValue { returnedMovieEntity -> returnedMovieEntity.hasValue() && returnedMovieEntity.value?.id == 100 } .assertComplete() } @Test fun getPopularMovies() { val movieRepository = Mockito.mock(MoviesRepository::class.java) Mockito.`when`(movieRepository.getMovies()).thenReturn(Observable.just(generateMovieEntityList())) val getPopularMovies = GetPopularMovies(TestTransformer(), movieRepository) getPopularMovies.observable().test() .assertValue { results -> results.size == 5 } .assertComplete() } @Test fun getPopularMoviesNoResultsReturnsEmpty() { val movieRepository = Mockito.mock(MoviesRepository::class.java) Mockito.`when`(movieRepository.getMovies()).thenReturn(Observable.just(emptyList())) val getPopularMovies = GetPopularMovies(TestTransformer(), movieRepository) getPopularMovies.observable().test() .assertValue { results -> results.isEmpty() } .assertComplete() } @Test fun saveMovieToFavorites() { val moviesCache = TestMoviesCache() val saveFavoriteMovie = SaveFavoriteMovie(TestTransformer(), moviesCache) val movieEntity = DomainTestUtils.getTestMovieEntity(1) saveFavoriteMovie.save(movieEntity).test() .assertValue { result -> result } .assertComplete() moviesCache.get(movieEntity.id).test() .assertValue { optionalMovieEntity -> optionalMovieEntity.hasValue() && optionalMovieEntity.value?.id == movieEntity.id } } @Test fun getFavoriteMovies() { val moviesCache = Mockito.mock(MoviesCache::class.java) Mockito.`when`(moviesCache.getAll()).thenReturn(Observable.just(generateMovieEntityList())) val getFavoriteMovies = GetFavoriteMovies(TestTransformer(), moviesCache) getFavoriteMovies.observable().test() .assertValue { results -> results.size == 5 } .assertComplete() } @Test fun removeFavoriteMovie() { val moviesCache = TestMoviesCache() val saveFavoriteMovie = SaveFavoriteMovie(TestTransformer(), moviesCache) val removeFavoriteMovies = RemoveFavoriteMovie(TestTransformer(), moviesCache) val movieEntity = DomainTestUtils.getTestMovieEntity(1) saveFavoriteMovie.save(movieEntity) assertNotNull(moviesCache.get(movieEntity.id)) removeFavoriteMovies.remove(movieEntity).test() .assertValue { returnedValue -> !returnedValue } .assertComplete() moviesCache.get(movieEntity.id).test() .assertValue { optionalEntity -> !optionalEntity.hasValue() } } @Test fun searchMovies() { val movieRepository = Mockito.mock(MoviesRepository::class.java) val searchMovie = SearchMovie(TestTransformer(), movieRepository) `when`(movieRepository.search("test query")).thenReturn(Observable.just(generateMovieEntityList())) searchMovie.search("test query").test() .assertComplete() .assertValue { results -> results.size == 5 } } @Test fun testCheckFavoriteStatus() { val movieCache = mock(MoviesCache::class.java) `when`(movieCache.get(99)).thenReturn(Observable.just(Optional.empty())) `when`(movieCache.get(100)).thenReturn(Observable.just(Optional.of(DomainTestUtils.getTestMovieEntity(100)))) val checkFavoriteStatus = CheckFavoriteStatus(TestTransformer(), movieCache) checkFavoriteStatus.check(99).test() .assertValue { result -> !result } .assertComplete() checkFavoriteStatus.check(100).test() .assertValue { result -> result } .assertComplete() } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/entities/Video.kt<|end_filename|> package com.yossisegev.movienight.entities /** * Created by <NAME> on 11/01/2018. */ data class Video ( var id: String, var name: String, var url: String? = null ) <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/MainComponent.kt<|end_filename|> package com.yossisegev.movienight.di import com.yossisegev.movienight.di.modules.* import com.yossisegev.movienight.MainActivity import com.yossisegev.movienight.di.details.MovieDetailsModule import com.yossisegev.movienight.di.details.MovieDetailsSubComponent import com.yossisegev.movienight.di.favorites.FavoriteModule import com.yossisegev.movienight.di.favorites.FavoritesSubComponent import com.yossisegev.movienight.di.popular.PopularMoviesModule import com.yossisegev.movienight.di.popular.PopularSubComponent import com.yossisegev.movienight.di.search.SearchMoviesModule import com.yossisegev.movienight.di.search.SearchSubComponent import dagger.Component import javax.inject.Singleton /** * Created by <NAME> on 11/11/2017. */ @Singleton @Component(modules = [ (AppModule::class), (NetworkModule::class), (DataModule::class) ]) interface MainComponent { fun plus(popularMoviesModule: PopularMoviesModule): PopularSubComponent fun plus(favoriteMoviesModule: FavoriteModule): FavoritesSubComponent fun plus(movieDetailsModule: MovieDetailsModule): MovieDetailsSubComponent fun plus(searchMoviesModule: SearchMoviesModule): SearchSubComponent } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/favorites/FavoriteMoviesFragment.kt<|end_filename|> package com.yossisegev.movienight.favorites import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast import com.yossisegev.movienight.R import com.yossisegev.movienight.common.App import com.yossisegev.movienight.common.BaseFragment import com.yossisegev.movienight.common.ImageLoader import kotlinx.android.synthetic.main.fragment_favorite_movies.* import javax.inject.Inject /** * Created by <NAME> on 11/11/2017. */ class FavoriteMoviesFragment : BaseFragment() { @Inject lateinit var factory: FavoriteMoviesVMFactory @Inject lateinit var imageLoader: ImageLoader private lateinit var viewModel: FavoriteMoviesViewModel private lateinit var recyclerView: RecyclerView private lateinit var progressBar: ProgressBar private lateinit var emptyMessage: TextView private lateinit var favoriteMoviesAdapter: FavoriteMoviesAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity?.application as App).createFavoritesComponent().inject(this) viewModel = ViewModelProviders.of(this, factory).get(FavoriteMoviesViewModel::class.java) } override fun onResume() { super.onResume() viewModel.getFavorites() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel.viewState.observe(this, Observer { if (it != null) handleViewState(it) }) viewModel.errorState.observe(this, Observer { throwable -> throwable?.let { Toast.makeText(activity, it.message, Toast.LENGTH_LONG).show() } }) } private fun handleViewState(state: FavoritesMoviesViewState) { progressBar.visibility = if (state.isLoading) View.VISIBLE else View.GONE emptyMessage.visibility = if (!state.isLoading && state.isEmpty) View.VISIBLE else View.GONE state.movies?.let { favoriteMoviesAdapter.setMovies(it) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return layoutInflater.inflate(R.layout.fragment_favorite_movies, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) progressBar = favorite_movies_progress favoriteMoviesAdapter = FavoriteMoviesAdapter(imageLoader, { movie, view -> navigateToMovieDetailsScreen(movie, view) }) recyclerView = favorite_movies_recyclerview emptyMessage = favorite_movies_empty_message recyclerView.layoutManager = LinearLayoutManager(activity) recyclerView.adapter = favoriteMoviesAdapter } override fun onDestroy() { super.onDestroy() (activity?.application as App).releaseFavoritesComponent() } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/search/SearchScope.kt<|end_filename|> package com.yossisegev.movienight.di.search import javax.inject.Scope /** * Created by <NAME> on 23/02/2018. */ @Scope @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class SearchScope <|start_filename|>data/src/main/kotlin/com/yossisegev/data/repositories/RemoteMoviesDataStore.kt<|end_filename|> package com.yossisegev.data.repositories import com.yossisegev.data.api.Api import com.yossisegev.data.entities.DetailsData import com.yossisegev.data.entities.MovieData import com.yossisegev.data.mappers.DetailsDataMovieEntityMapper import com.yossisegev.data.mappers.MovieDataEntityMapper import com.yossisegev.data.mappers.MovieEntityDataMapper import com.yossisegev.domain.common.Mapper import com.yossisegev.domain.MoviesDataStore import com.yossisegev.domain.entities.MovieDetailsEntity import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.entities.Optional import io.reactivex.Observable /** * Created by <NAME> on 11/11/2017. */ class RemoteMoviesDataStore(private val api: Api) : MoviesDataStore { private val movieDataMapper = MovieDataEntityMapper() private val detailedDataMapper = DetailsDataMovieEntityMapper() override fun search(query: String): Observable<List<MovieEntity>> { return api.searchMovies(query).map { results -> results.movies.map { movieDataMapper.mapFrom(it) } } } override fun getMovies(): Observable<List<MovieEntity>> { return api.getPopularMovies().map { results -> results.movies.map { movieDataMapper.mapFrom(it) } } } override fun getMovieById(movieId: Int): Observable<Optional<MovieEntity>> { return api.getMovieDetails(movieId).flatMap { detailedData -> Observable.just(Optional.of(detailedDataMapper.mapFrom(detailedData))) } } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/search/SearchSubComponent.kt<|end_filename|> package com.yossisegev.movienight.di.search import com.yossisegev.movienight.search.SearchFragment import dagger.Subcomponent /** * Created by <NAME> on 23/02/2018. */ @SearchScope @Subcomponent(modules = [SearchMoviesModule::class]) interface SearchSubComponent { fun inject(searchFragment: SearchFragment) } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/popular/PopularMoviesModule.kt<|end_filename|> package com.yossisegev.movienight.di.popular import com.yossisegev.domain.MoviesRepository import com.yossisegev.domain.usecases.GetPopularMovies import com.yossisegev.movienight.MovieEntityMovieMapper import com.yossisegev.movienight.common.ASyncTransformer import com.yossisegev.movienight.di.popular.PopularScope import com.yossisegev.movienight.popularmovies.PopularMoviesVMFactory import dagger.Module import dagger.Provides /** * Created by <NAME> on 23/02/2018. */ @PopularScope @Module class PopularMoviesModule { @Provides fun provideGetPopularMoviesUseCase(moviesRepository: MoviesRepository): GetPopularMovies { return GetPopularMovies(ASyncTransformer(), moviesRepository) } @Provides fun providePopularMoviesVMFactory(useCase: GetPopularMovies, mapper: MovieEntityMovieMapper): PopularMoviesVMFactory { return PopularMoviesVMFactory(useCase, mapper) } } <|start_filename|>presentation/src/androidTest/kotlin/com/yossisegev/movienight/SearchViewModelTests.kt<|end_filename|> package com.yossisegev.movienight import android.arch.lifecycle.Observer import android.support.test.annotation.UiThreadTest import android.support.test.runner.AndroidJUnit4 import com.yossisegev.domain.MoviesRepository import com.yossisegev.domain.common.DomainTestUtils import com.yossisegev.domain.common.TestTransformer import com.yossisegev.domain.usecases.SearchMovie import com.yossisegev.movienight.search.SearchViewModel import com.yossisegev.movienight.search.SearchViewState import io.reactivex.Observable import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.* @Suppress("UNCHECKED_CAST") @RunWith(AndroidJUnit4::class) class SearchViewModelTests { private val testQuery = "this is a test query" private val movieEntityMovieMapper = MovieEntityMovieMapper() private lateinit var movieRepository: MoviesRepository private lateinit var searchViewModel: SearchViewModel @Before @UiThreadTest fun before() { movieRepository = mock(MoviesRepository::class.java) val searchMovie = SearchMovie(TestTransformer(), movieRepository) searchViewModel = SearchViewModel(searchMovie, movieEntityMovieMapper) } @Test @UiThreadTest fun testInitialViewState() { val viewObserver = mock(Observer::class.java) as Observer<SearchViewState> val errorObserver = mock(Observer::class.java) as Observer<Throwable?> searchViewModel.viewState.observeForever(viewObserver) searchViewModel.errorState.observeForever(errorObserver) verify(viewObserver).onChanged(SearchViewState( isLoading = false, movies = null, showNoResultsMessage = false, lastSearchedQuery = null)) verifyZeroInteractions(errorObserver) } @Test @UiThreadTest fun testSearchWithResultsShowsCorrectViewStates() { val movieEntities = DomainTestUtils.generateMovieEntityList() `when`(movieRepository.search(testQuery)).thenReturn(Observable.just(movieEntities)) val viewObserver = ChangeHistoryObserver<SearchViewState>() val errorObserver = mock(Observer::class.java) as Observer<Throwable?> searchViewModel.viewState.observeForever(viewObserver) searchViewModel.errorState.observeForever(errorObserver) searchViewModel.search(testQuery) val loadingViewState = SearchViewState( isLoading = true, showNoResultsMessage = false, movies = null) val resultsViewState = SearchViewState( isLoading = false, lastSearchedQuery = testQuery, movies = movieEntities.map { movieEntityMovieMapper.mapFrom(it) } ) assertEquals(viewObserver.get(1), loadingViewState) assertEquals(viewObserver.get(2), resultsViewState) verify(errorObserver).onChanged(null) } @Test @UiThreadTest fun testSearchWithNoResultsShowsCorrectViewStates() { `when`(movieRepository.search(testQuery)).thenReturn(Observable.just(emptyList())) val viewObserver = ChangeHistoryObserver<SearchViewState>() val errorObserver = mock(Observer::class.java) as Observer<Throwable?> searchViewModel.viewState.observeForever(viewObserver) searchViewModel.errorState.observeForever(errorObserver) searchViewModel.search(testQuery) val loadingViewState = SearchViewState( isLoading = true, showNoResultsMessage = false, lastSearchedQuery = null, movies = null) val resultsViewState = SearchViewState( isLoading = false, lastSearchedQuery = testQuery, showNoResultsMessage = true, movies = emptyList() ) assertEquals(viewObserver.get(1), loadingViewState) assertEquals(viewObserver.get(2), resultsViewState) verify(errorObserver).onChanged(null) } @Test @UiThreadTest fun testQueryStringIsEmptyShowsCorrectViewStates() { `when`(movieRepository.search(testQuery)).thenReturn(Observable.just(emptyList())) val viewObserver = ChangeHistoryObserver<SearchViewState>() val errorObserver = mock(Observer::class.java) as Observer<Throwable?> searchViewModel.viewState.observeForever(viewObserver) searchViewModel.errorState.observeForever(errorObserver) searchViewModel.search("") val loadingViewState = SearchViewState( isLoading = false, showNoResultsMessage = false, lastSearchedQuery = "", movies = null) assertEquals(viewObserver.get(1), loadingViewState) verify(errorObserver).onChanged(null) } @Test @UiThreadTest fun testErrorShowsCorrectViewStates() { val throwable = Throwable("ERROR!") `when`(movieRepository.search(testQuery)).thenReturn(Observable.error(throwable)) val viewObserver = ChangeHistoryObserver<SearchViewState>() val errorObserver = mock(Observer::class.java) as Observer<Throwable?> searchViewModel.viewState.observeForever(viewObserver) searchViewModel.errorState.observeForever(errorObserver) searchViewModel.search(testQuery) val loadingViewState = SearchViewState( isLoading = false, showNoResultsMessage = false, lastSearchedQuery = testQuery, movies = null) assertEquals(viewObserver.get(2), loadingViewState) verify(errorObserver).onChanged(throwable) } } <|start_filename|>data/src/test/kotlin/com/yossisegev/data/MappersTests.kt<|end_filename|> package com.yossisegev.data import com.yossisegev.data.api.ReviewsResult import com.yossisegev.data.api.VideoResult import com.yossisegev.data.entities.DetailsData import com.yossisegev.data.entities.GenreData import com.yossisegev.data.entities.ReviewData import com.yossisegev.data.entities.VideoData import com.yossisegev.data.mappers.DetailsDataMovieEntityMapper import com.yossisegev.data.mappers.MovieDataEntityMapper import com.yossisegev.data.mappers.MovieEntityDataMapper import com.yossisegev.data.utils.TestsUtils.Companion.getMockedMovieData import com.yossisegev.domain.common.DomainTestUtils import com.yossisegev.domain.entities.VideoEntity import org.junit.Assert.assertEquals import org.junit.Test /** * Created by <NAME> on 20/01/2018. */ class MappersTests { @Test fun testMappingMovieDataToMovieEntityReturnsExpectedResult() { val movieData = getMockedMovieData(40) val mapper = MovieDataEntityMapper() val movieEntity = mapper.mapFrom(movieData) assertEquals(movieEntity.id, movieData.id) assertEquals(movieEntity.title, movieData.title) assertEquals(movieEntity.originalTitle, movieData.originalTitle) assertEquals(movieEntity.adult, movieData.adult) assertEquals(movieEntity.backdropPath, movieData.backdropPath) assertEquals(movieEntity.releaseDate, movieData.releaseDate) assertEquals(movieEntity.popularity, movieData.popularity, 0.0) assertEquals(movieEntity.voteAverage, movieData.voteAverage, 0.0) assertEquals(movieEntity.voteCount, movieData.voteCount) assertEquals(movieEntity.posterPath, movieData.posterPath) assertEquals(movieEntity.originalLanguage, movieData.originalLanguage) assertEquals(movieEntity.overview, movieData.overview) } @Test fun testMappingDetailDataToMovieEntityReturnsExpectedResult() { val videos = (0..6).map { VideoData( id = "ID_$it", name = "Video$it", site = if (it == 4) "Not YouTube" else VideoEntity.SOURCE_YOUTUBE, type = if (it == 2) "Not a trailer" else VideoEntity.TYPE_TRAILER, key = "Key$it" ) } val videoResult = VideoResult() videoResult.results = videos val genres = (0..4).map { GenreData( id = it, name = "Genre$it" ) } val reviews = (0..4).map { ReviewData( id = "ID_$it", author = "Author$it", content = "Content$it" ) } val reviewsResult = ReviewsResult() reviewsResult.results = reviews val detailsData = DetailsData( id = 1, title = "MovieData", backdropPath = "movieData_backdrop", originalLanguage = "movieData_lan", overview = "movieData_overview", posterPath = "movieData_poster", originalTitle = "Original title of MovieData", releaseDate = "1970-1-1", adult = true, popularity = 10.0, voteAverage = 7.0, video = false, voteCount = 100, budget = 6, homepage = "homepage_url", imdbId = "imdb_id", revenue = 80, runtime = 60, tagline = "movie_tag_line" ) detailsData.videos = videoResult detailsData.genres = genres detailsData.reviews = reviewsResult val mapper = DetailsDataMovieEntityMapper() val movieEntity = mapper.mapFrom(detailsData) assertEquals(movieEntity.id, detailsData.id) assertEquals(movieEntity.title, detailsData.title) assertEquals(movieEntity.originalTitle, detailsData.originalTitle) assertEquals(movieEntity.adult, detailsData.adult) assertEquals(movieEntity.backdropPath, detailsData.backdropPath) assertEquals(movieEntity.releaseDate, detailsData.releaseDate) assertEquals(movieEntity.popularity, detailsData.popularity, 0.0) assertEquals(movieEntity.voteAverage, detailsData.voteAverage, 0.0) assertEquals(movieEntity.voteCount, detailsData.voteCount) assertEquals(movieEntity.video, detailsData.video) assertEquals(movieEntity.posterPath, detailsData.posterPath) assertEquals(movieEntity.originalLanguage, detailsData.originalLanguage) assertEquals(movieEntity.overview, detailsData.overview) assertEquals(movieEntity.details?.videos?.size, detailsData.videos!!.results!!.size - 2) // ignoring non youtube/trailer assertEquals(movieEntity.details?.videos?.get(0)?.youtubeKey, detailsData.videos!!.results!![0].key) assertEquals(movieEntity.details?.videos?.get(0)?.id, detailsData.videos!!.results!![0].id) assertEquals(movieEntity.details?.videos?.get(0)?.name, detailsData.videos!!.results!![0].name) assertEquals(movieEntity.details?.reviews?.size, detailsData.reviews!!.results!!.size) assertEquals(movieEntity.details?.reviews?.get(0)?.id, detailsData.reviews!!.results!![0].id) assertEquals(movieEntity.details?.reviews?.get(0)?.author, detailsData.reviews!!.results!![0].author) assertEquals(movieEntity.details?.reviews?.get(0)?.content, detailsData.reviews!!.results!![0].content) assertEquals(movieEntity.details?.genres?.size, detailsData.genres!!.size) assertEquals(movieEntity.details?.genres?.get(0)?.id, detailsData.genres!![0].id) assertEquals(movieEntity.details?.genres?.get(0)?.name, detailsData.genres!![0].name) assertEquals(movieEntity.details?.tagline, detailsData.tagline) assertEquals(movieEntity.details?.runtime, detailsData.runtime) assertEquals(movieEntity.details?.revenue, detailsData.revenue) assertEquals(movieEntity.details?.imdbId, detailsData.imdbId) assertEquals(movieEntity.details?.homepage, detailsData.homepage) assertEquals(movieEntity.details?.budget, detailsData.budget) assertEquals(movieEntity.details?.overview, detailsData.overview) } @Test fun testMappingMovieEntityToMovieReturnsExpectedResult() { val movieEntity = DomainTestUtils.getTestMovieEntity(2) val movieEntityDataMapper = MovieEntityDataMapper() val movieData = movieEntityDataMapper.mapFrom(movieEntity) assertEquals(movieEntity.id, movieData.id) assertEquals(movieEntity.title, movieData.title) assertEquals(movieEntity.originalTitle, movieData.originalTitle) assertEquals(movieEntity.adult, movieData.adult) assertEquals(movieEntity.backdropPath, movieData.backdropPath) assertEquals(movieEntity.releaseDate, movieData.releaseDate) assertEquals(movieEntity.popularity, movieData.popularity, 0.0) assertEquals(movieEntity.voteAverage, movieData.voteAverage, 0.0) assertEquals(movieEntity.voteCount, movieData.voteCount) assertEquals(movieEntity.posterPath, movieData.posterPath) assertEquals(movieEntity.originalLanguage, movieData.originalLanguage) assertEquals(movieEntity.overview, movieData.overview) } } <|start_filename|>domain/src/main/kotlin/com/yossisegev/domain/MoviesDataStore.kt<|end_filename|> package com.yossisegev.domain import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.entities.Optional import io.reactivex.Observable /** * Created by <NAME> on 11/11/2017. */ interface MoviesDataStore { fun getMovieById(movieId: Int): Observable<Optional<MovieEntity>> fun getMovies(): Observable<List<MovieEntity>> fun search(query: String): Observable<List<MovieEntity>> } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/popularmovies/PopularMoviesVMFactory.kt<|end_filename|> package com.yossisegev.movienight.popularmovies import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import com.yossisegev.domain.common.Mapper import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.usecases.GetPopularMovies import com.yossisegev.movienight.entities.Movie /** * Created by <NAME> on 01/01/2018. */ class PopularMoviesVMFactory(private val useCase: GetPopularMovies, private val mapper: Mapper<MovieEntity, Movie>) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return PopularMoviesViewModel(useCase, mapper) as T } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/common/BaseFragment.kt<|end_filename|> package com.yossisegev.movienight.common import android.app.ActivityOptions import android.support.v4.app.Fragment import android.util.Pair import android.view.View import com.yossisegev.movienight.R import com.yossisegev.movienight.details.MovieDetailsActivity import com.yossisegev.movienight.entities.Movie /** * Created by <NAME> on 19/02/2018. */ open class BaseFragment: Fragment() { protected fun navigateToMovieDetailsScreen(movie: Movie, view: View) { var activityOptions: ActivityOptions? = null val imageForTransition: View? = view.findViewById(R.id.image) imageForTransition?.let { val posterSharedElement: Pair<View, String> = Pair.create(it, getString(R.string.transition_poster)) activityOptions = ActivityOptions.makeSceneTransitionAnimation(activity, posterSharedElement) } startActivity(MovieDetailsActivity.newIntent( context!!, movie.id, movie.posterPath), activityOptions?.toBundle()) activity?.overridePendingTransition(0, 0) } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/popularmovies/PopularMoviesViewState.kt<|end_filename|> package com.yossisegev.movienight.popularmovies import com.yossisegev.movienight.entities.Movie /** * Created by <NAME> on 06/01/2018. */ data class PopularMoviesViewState( var showLoading: Boolean = true, var movies: List<Movie>? = null ) <|start_filename|>domain/src/main/kotlin/com/yossisegev/domain/common/TestTransformer.kt<|end_filename|> package com.yossisegev.domain.common import io.reactivex.Observable import io.reactivex.ObservableSource import io.reactivex.ObservableTransformer /** * Created by <NAME> on 13/11/2017. */ class TestTransformer<T>: Transformer<T>() { override fun apply(upstream: Observable<T>): ObservableSource<T> { return upstream } } <|start_filename|>data/src/androidTest/kotlin/com/yossisegev/data/RoomDatabaseTests.kt<|end_filename|> package com.yossisegev.data import android.arch.persistence.room.Room import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import com.yossisegev.data.db.MoviesDao import com.yossisegev.data.db.MoviesDatabase import com.yossisegev.data.utils.TestsUtils import org.junit.After import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.junit.runner.RunWith /** * Created by <NAME> on 19/02/2018. */ @RunWith(AndroidJUnit4::class) class RoomDatabaseTests { private lateinit var database: MoviesDatabase private lateinit var moviesDao: MoviesDao @Before fun before() { database = Room.inMemoryDatabaseBuilder( InstrumentationRegistry.getContext(), MoviesDatabase::class.java).build() moviesDao = database.getMoviesDao() } @After fun after() { database.close() } @Test fun testSingleInsertion() { val movieData = TestsUtils.getMockedMovieData(21) moviesDao.saveMovie(movieData) val result = moviesDao.get(movieData.id) assertNotNull(result) assertEquals(result?.id?.toLong(), movieData.id.toLong()) } @Test fun testMultipleInsertions() { val movieDataList = TestsUtils.generateMovieDataList() moviesDao.saveAllMovies(movieDataList) val movies = moviesDao.getFavorites() assertEquals(movies.size.toLong(), 5) } @Test fun testRemoval() { val movieData = TestsUtils.getMockedMovieData(22) moviesDao.saveMovie(movieData) val movies = moviesDao.getFavorites() assertEquals(movies.size.toLong(), 1) moviesDao.removeMovie(movieData) val movies2 = moviesDao.getFavorites() assertEquals(movies2.size.toLong(), 0) } @Test fun testAllDataIsSaved() { val movieData = TestsUtils.getMockedMovieData(432) moviesDao.saveMovie(movieData) val movies = moviesDao.getFavorites() val (id, voteCount, voteAverage, adult, popularity, title, posterPath, originalLanguage, originalTitle, backdropPath, releaseDate) = movies[0] assertEquals(id.toLong(), movieData.id.toLong()) assertEquals(title, movieData.title) assertEquals(posterPath, movieData.posterPath) assertEquals(backdropPath, movieData.backdropPath) assertEquals(adult, movieData.adult) assertEquals(popularity, movieData.popularity, 0.0) assertEquals(originalLanguage, movieData.originalLanguage) assertEquals(releaseDate, movieData.releaseDate) assertEquals(voteAverage, movieData.voteAverage, 0.0) assertEquals(voteCount.toLong(), movieData.voteCount.toLong()) assertEquals(originalTitle, movieData.originalTitle) } @Test fun testClearTable() { val movieDataList = TestsUtils.generateMovieDataList() moviesDao.saveAllMovies(movieDataList) val movies = moviesDao.getFavorites() assertEquals(movies.size.toLong(), 5) moviesDao.clear() assertTrue(moviesDao.getFavorites().isEmpty()) } @Test fun testSearchingMovieReturnsExpectedResults() { val movieData1 = TestsUtils.getMockedMovieData(150, "Star wars") val movieData2 = TestsUtils.getMockedMovieData(151, "The Star") val movieData3 = TestsUtils.getMockedMovieData(152, "The Starcraft story") val movieData4 = TestsUtils.getMockedMovieData(153, "The hobbit") moviesDao.saveMovie(movieData1) moviesDao.saveMovie(movieData2) moviesDao.saveMovie(movieData3) moviesDao.saveMovie(movieData4) val results = moviesDao.search("%star%") assertTrue(results.size == 3) } } <|start_filename|>domain/src/main/kotlin/com/yossisegev/domain/usecases/RemoveFavoriteMovie.kt<|end_filename|> package com.yossisegev.domain.usecases import com.yossisegev.domain.MoviesCache import com.yossisegev.domain.common.Transformer import com.yossisegev.domain.entities.MovieEntity import io.reactivex.Observable import io.reactivex.ObservableTransformer import java.lang.IllegalArgumentException /** * Created by <NAME> on 21/01/2018. */ class RemoveFavoriteMovie(transformer:Transformer<Boolean>, private val moviesCache: MoviesCache): UseCase<Boolean>(transformer) { companion object { private const val PARAM_MOVIE_ENTITY = "param:movieEntity" } fun remove(movieEntity: MovieEntity): Observable<Boolean> { val data = HashMap<String, MovieEntity>() data[PARAM_MOVIE_ENTITY] = movieEntity return observable(data) } override fun createObservable(data: Map<String, Any>?): Observable<Boolean> { val movieEntity = data?.get(PARAM_MOVIE_ENTITY) movieEntity?.let { return Observable.fromCallable { val entity = it as MovieEntity moviesCache.remove(entity) return@fromCallable false } }?: return Observable.error({ IllegalArgumentException("MovieEntity must be provided.") }) } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/details/MovieDetailsModule.kt<|end_filename|> package com.yossisegev.movienight.di.details import com.yossisegev.domain.MoviesCache import com.yossisegev.domain.MoviesRepository import com.yossisegev.domain.usecases.CheckFavoriteStatus import com.yossisegev.domain.usecases.GetMovieDetails import com.yossisegev.domain.usecases.RemoveFavoriteMovie import com.yossisegev.domain.usecases.SaveFavoriteMovie import com.yossisegev.movienight.MovieEntityMovieMapper import com.yossisegev.movienight.common.ASyncTransformer import com.yossisegev.movienight.details.MovieDetailsVMFactory import com.yossisegev.movienight.di.DI import dagger.Module import dagger.Provides import javax.inject.Named /** * Created by <NAME> on 23/02/2018. */ @Module class MovieDetailsModule { @Provides fun provideRemoveFavoriteMovie(@Named(DI.favoritesCache) moviesCache: MoviesCache): RemoveFavoriteMovie { return RemoveFavoriteMovie(ASyncTransformer(), moviesCache) } @Provides fun provideCheckFavoriteStatus(@Named(DI.favoritesCache) moviesCache: MoviesCache): CheckFavoriteStatus { return CheckFavoriteStatus(ASyncTransformer(), moviesCache) } @Provides fun provideSaveFavoriteMovieUseCase(@Named(DI.favoritesCache) moviesCache: MoviesCache): SaveFavoriteMovie { return SaveFavoriteMovie(ASyncTransformer(), moviesCache) } @Provides fun provideGetMovieDetailsUseCase(moviesRepository: MoviesRepository): GetMovieDetails { return GetMovieDetails(ASyncTransformer(), moviesRepository) } @Provides fun provideMovieDetailsVMFactory(getMovieDetails: GetMovieDetails, saveFavoriteMovie: SaveFavoriteMovie, removeFavoriteMovie: RemoveFavoriteMovie, checkFavoriteStatus: CheckFavoriteStatus, mapper: MovieEntityMovieMapper): MovieDetailsVMFactory { return MovieDetailsVMFactory(getMovieDetails, saveFavoriteMovie, removeFavoriteMovie, checkFavoriteStatus, mapper) } } <|start_filename|>data/src/main/kotlin/com/yossisegev/data/repositories/MoviesRepositoryImpl.kt<|end_filename|> package com.yossisegev.data.repositories import com.yossisegev.domain.MoviesDataStore import com.yossisegev.domain.MoviesRepository import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.entities.Optional import io.reactivex.Observable /** * Created by <NAME> on 25/01/2018. */ class MoviesRepositoryImpl(private val cachedDataStore: CachedMoviesDataStore, private val remoteDataStore: RemoteMoviesDataStore) : MoviesRepository { override fun getMovies(): Observable<List<MovieEntity>> { return cachedDataStore.isEmpty().flatMap { empty -> if (!empty) { return@flatMap cachedDataStore.getMovies() } else { return@flatMap remoteDataStore.getMovies() .doOnNext { movies -> cachedDataStore.saveAll(movies) } } } } override fun search(query: String): Observable<List<MovieEntity>> { return remoteDataStore.search(query) } override fun getMovie(movieId: Int): Observable<Optional<MovieEntity>> { return remoteDataStore.getMovieById(movieId) } } <|start_filename|>domain/src/main/kotlin/com/yossisegev/domain/usecases/GetPopularMovies.kt<|end_filename|> package com.yossisegev.domain.usecases import com.yossisegev.domain.MoviesCache import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.MoviesDataStore import com.yossisegev.domain.MoviesRepository import com.yossisegev.domain.common.Transformer import io.reactivex.Observable import io.reactivex.ObservableTransformer /** * Created by <NAME> on 11/11/2017. */ open class GetPopularMovies(transformer: Transformer<List<MovieEntity>>, private val moviesRepository: MoviesRepository) : UseCase<List<MovieEntity>>(transformer) { override fun createObservable(data: Map<String, Any>?): Observable<List<MovieEntity>> { return moviesRepository.getMovies() } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/di/details/MovieDetailsSubComponent.kt<|end_filename|> package com.yossisegev.movienight.di.details import com.yossisegev.movienight.details.MovieDetailsActivity import dagger.Subcomponent /** * Created by <NAME> on 23/02/2018. */ @DetailsScope @Subcomponent(modules = [MovieDetailsModule::class]) interface MovieDetailsSubComponent { fun inject(movieDetailsActivity: MovieDetailsActivity) } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/details/MovieDetailsActivity.kt<|end_filename|> package com.yossisegev.movienight.details import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.transition.Slide import android.transition.TransitionManager import android.view.View import android.widget.ImageView import android.widget.TextView import android.widget.Toast import co.lujun.androidtagview.TagContainerLayout import com.yossisegev.movienight.R import com.yossisegev.movienight.common.App import com.yossisegev.movienight.common.ImageLoader import com.yossisegev.movienight.common.SimpleTransitionEndedCallback import com.yossisegev.movienight.entities.Video import kotlinx.android.synthetic.main.activity_movie_details.* import kotlinx.android.synthetic.main.details_overview_section.* import kotlinx.android.synthetic.main.details_video_section.* import javax.inject.Inject class MovieDetailsActivity : AppCompatActivity() { @Inject lateinit var factory: MovieDetailsVMFactory @Inject lateinit var imageLoader: ImageLoader private lateinit var detailsViewModel: MovieDetailsViewModel private lateinit var backdropImage: ImageView private lateinit var posterImage: ImageView private lateinit var title: TextView private lateinit var overview: TextView private lateinit var releaseDate: TextView private lateinit var score: TextView private lateinit var videos: RecyclerView private lateinit var videosSection: View private lateinit var backButton: View private lateinit var tagsContainer: TagContainerLayout private lateinit var favoriteButton: FloatingActionButton companion object { private const val MOVIE_ID: String = "extra_movie_id" private const val MOVIE_POSTER_URL: String = "extra_movie_poster_url" fun newIntent(context: Context, movieId: Int, posterUrl: String?): Intent { val i = Intent(context, MovieDetailsActivity::class.java) i.putExtra(MOVIE_ID, movieId) i.putExtra(MOVIE_POSTER_URL, posterUrl) return i } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_movie_details) postponeEnterTransition() window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE and View.SYSTEM_UI_FLAG_FULLSCREEN (application as App).createDetailsComponent().inject(this) factory.movieId = intent.getIntExtra(MOVIE_ID, 0) detailsViewModel = ViewModelProviders.of(this, factory).get(MovieDetailsViewModel::class.java) backButton = details_back_button backButton.setOnClickListener { finish() } favoriteButton = details_favorite_fab favoriteButton.setOnClickListener { detailsViewModel.favoriteButtonClicked() } backdropImage = details_backdrop posterImage = details_poster title = details_title overview = details_overview releaseDate = details_release_date tagsContainer = details_tags score = details_score videos = details_videos videosSection = details_video_section val posterUrl = intent.getStringExtra(MOVIE_POSTER_URL) posterUrl?.let { imageLoader.load(it, posterImage) { startPostponedEnterTransition() } } ?: run { startPostponedEnterTransition() } window.sharedElementEnterTransition.addListener(SimpleTransitionEndedCallback { observeViewState() }) // If we don't have any entering transition if (savedInstanceState != null) { observeViewState() } else { detailsViewModel.getMovieDetails() } } private fun observeViewState() { detailsViewModel.viewState.observe(this, Observer { viewState -> handleViewState(viewState) }) detailsViewModel.favoriteState.observe(this, Observer { favorite -> handleFavoriteStateChange(favorite) }) detailsViewModel.errorState.observe(this, Observer { throwable -> throwable?.let { Toast.makeText(this, throwable.message, Toast.LENGTH_LONG).show() } }) } private fun onVideoSelected(video: Video) { video.url?.let { val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(it)) startActivity(browserIntent) } } private fun handleViewState(state: MovieDetailsViewState?) { if (state == null) return title.text = state.title overview.text = state.overview releaseDate.text = String.format(getString(R.string.release_date_template, state.releaseDate)) score.text = if (state.votesAverage == 0.0) getString(R.string.n_a) else state.votesAverage.toString() state.genres?.let { tagsContainer.tags = state.genres } val transition = Slide() transition.excludeTarget(posterImage, true) transition.duration = 750 TransitionManager.beginDelayedTransition(details_root_view, transition) title.visibility = View.VISIBLE releaseDate.visibility = View.VISIBLE score.visibility = View.VISIBLE details_release_date_layout.visibility = View.VISIBLE details_score_layout.visibility = View.VISIBLE details_overview_section.visibility = View.VISIBLE videosSection.visibility = View.VISIBLE tagsContainer.visibility = View.VISIBLE state.backdropUrl?.let { imageLoader.load(it, backdropImage) } state.videos?.let { val videosAdapter = VideosAdapter(it, this::onVideoSelected) videos.layoutManager = LinearLayoutManager(this) videos.adapter = videosAdapter } ?: run { videosSection.visibility = View.GONE } } private fun handleFavoriteStateChange(favorite: Boolean?) { if (favorite == null) return favoriteButton.visibility = View.VISIBLE favoriteButton.setImageDrawable( if (favorite) ContextCompat.getDrawable(this, R.drawable.ic_favorite_white_36dp) else ContextCompat.getDrawable(this, R.drawable.ic_favorite_border_white_36dp)) } override fun onDestroy() { super.onDestroy() (application as App).releaseDetailsComponent() } } <|start_filename|>presentation/src/main/kotlin/com/yossisegev/movienight/favorites/FavoriteMoviesViewModel.kt<|end_filename|> package com.yossisegev.movienight.favorites import android.arch.lifecycle.MutableLiveData import com.yossisegev.domain.common.Mapper import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.usecases.GetFavoriteMovies import com.yossisegev.movienight.common.BaseViewModel import com.yossisegev.movienight.common.SingleLiveEvent import com.yossisegev.movienight.entities.Movie /** * Created by <NAME> on 09/02/2018. */ class FavoriteMoviesViewModel(private val getFavoriteMovies: GetFavoriteMovies, private val movieEntityMovieMapper: Mapper<MovieEntity, Movie>) : BaseViewModel() { var viewState: MutableLiveData<FavoritesMoviesViewState> = MutableLiveData() var errorState: SingleLiveEvent<Throwable?> = SingleLiveEvent() init { val viewState = FavoritesMoviesViewState() this.viewState.value = viewState } fun getFavorites() { getFavoriteMovies.observable() .flatMap { movieEntityMovieMapper.observable(it) } .subscribe({ movies -> val newViewState = viewState.value?.copy( isEmpty = movies.isEmpty(), isLoading = false, movies = movies) viewState.value = newViewState errorState.value = null }, { viewState.value = viewState.value?.copy(isLoading = false, isEmpty = false) errorState.value = it }) } }
vivekprcs/MovieNight
<|start_filename|>cfgov/unprocessed/apps/teachers-digital-platform/js/sticky.js<|end_filename|> const Stickyfill = require( 'stickyfilljs' ); const sticky = { init: () => { const stickies = document.querySelectorAll( '[data-sticky]' ); Stickyfill.add( stickies ); } }; module.exports = sticky; <|start_filename|>cfgov/templates/modeladmin/create.html<|end_filename|> {% extends "modeladmin/create.html" %} {% block header %} {{ block.super }} {% if instance.english_page or instance.spanish_page %} <div class="row nice-padding" style="margin: 30px 0;"> {% if instance.english_page %} <a href="/admin/pages/{{ instance.english_page.id }}/edit/" class="button button-secondary button-large">EDIT ENGLISH PAGE</a> {% endif %} {% if instance.spanish_page %} <a href="/admin/pages/{{ instance.spanish_page.id }}/edit/" class="button button-secondary button-large">EDIT SPANISH PAGE</a> {% endif %} </div> {% endif %} {% endblock %} <|start_filename|>cfgov/teachers_digital_platform/jinja2/teachers_digital_platform/search-hero-image.html<|end_filename|> {# ========================================================================== TDP Search Hero Image ========================================================================== Description: Create a TDP search hero image molecule. value: Object defined from a StreamField block. value.image: An image object containing the image to be placed adjacent to the text. value.small_image: An image object containing the alternate image for smaller screens when bleeding or overlaying at larger screen sizes. ========================================================================== #} {% set img = image(value.image, 'original') %} {% if value.small_image %} {% set sm_img = image(value.small_image, 'original') %} {% else %} {% set sm_img = image(value.image, 'original') %} {% endif %} <img class="m-search-hero_image" srcset="{{ sm_img.url }}, {{ img.url }} 2x" src="{{ img.url }}" width="498" alt="{{ img.alt }}"> <|start_filename|>cfgov/jinja2/v1/_includes/macros/util/url_parameters.html<|end_filename|> {# ========================================================================== url_parameters() ========================================================================== Description: Builds pagination markup when given: parameters: A dictionary of url parameters. ========================================================================== #} {% macro url_parameters(parameters) %} {%- set ignored_params = ('page', 'partial') -%} {%- for key in parameters.keys() -%} {% if parameters.getlist(key) and key not in ignored_params -%} {%- for value in parameters.getlist(key, []) -%} &amp;{{ key }}={{ value }} {%- endfor -%} {%- endif %} {%- endfor -%} {% endmacro %} <|start_filename|>gulp/tasks/test-unit.js<|end_filename|> const fancyLog = require( 'fancy-log' ); const fsHelper = require( '../utils/fs-helper' ); const gulp = require( 'gulp' ); const minimist = require( 'minimist' ); const spawn = require( 'child_process' ).spawn; const paths = require( '../../config/environment' ).paths; /** * Run JavaScript unit tests. * @param {Function} cb - Callback function to call on completion. */ function testUnitScripts( cb ) { const params = minimist( process.argv.slice( 3 ) ) || {}; /* If --specs=path/to/js/spec flag is added on the command-line, pass the value to mocha to test individual unit test files. */ let specs = params.specs; /* Set path defaults for source files. Remove ./ from beginning of path, which collectCoverageFrom doesn't support. */ const pathSrc = paths.unprocessed.substring( 2 ); // Set regex defaults. let fileTestRegex = 'unit_tests/'; let fileSrcPath = pathSrc + '/'; // If --specs flag is passed, adjust regex defaults. if ( specs ) { fileSrcPath += specs; // If the --specs argument is a file, strip it off. if ( specs.slice( -3 ) === '.js' ) { // TODO: Perform a more robust replacement here. fileSrcPath = fileSrcPath.replace( '-spec', '' ); fileTestRegex += specs; } else { // Ensure there's a trailing slash. if ( specs.slice( -1 ) !== '/' ) { specs += '/'; } fileSrcPath += '**/*.js'; fileTestRegex += specs + '.*-spec.js'; } } else { fileSrcPath += '**/*.js'; fileTestRegex += '.*-spec.js'; } /* The --no-cache flag is needed so the transforms don't cache. If they are cached, preprocessor-handlebars.js can't find handlebars. See https://facebook.github.io/jest/docs/en/troubleshooting.html#caching-issues */ const jestOptions = [ '--no-cache', '--config=jest.config.js', `--collectCoverageFrom=${ fileSrcPath }`, `--testRegex=${ fileTestRegex }` ]; if ( params.ci ) { jestOptions.push( '--maxWorkers=2' ); } spawn( fsHelper.getBinary( 'jest-cli', 'jest.js', '../bin' ), jestOptions, { stdio: 'inherit' } ).once( 'close', code => { if ( code ) { fancyLog( 'Unit tests exited with code ' + code ); process.exit( 1 ); } fancyLog( 'Unit tests done!' ); cb(); } ); } gulp.task( 'test:unit:scripts', testUnitScripts ); gulp.task( 'test:unit', gulp.parallel( 'test:unit:scripts' ) ); <|start_filename|>test/util/simulate-event.js<|end_filename|> /** * @param {string} eventType - The type of event. * @param {HTMLNode} target - Target of the event. * @param {Object} eventOption - Options to add to the event. * @returns {HTMLNode} The target of the event. */ function simulateEvent( eventType, target, eventOption = {} ) { let event; if ( eventType === 'click' ) { event = new MouseEvent( 'click', { bubbles: true, cancelable: true, view: window } ); } else { event = window.document.createEvent( 'Event', eventOption.currentTarget ); } if ( eventOption && eventOption.keyCode ) { event.keyCode = eventOption.keyCode; } event.initEvent( eventType, true, true ); return target.dispatchEvent( event ); } module.exports = { simulateEvent }; <|start_filename|>test/cypress/components/feedback.js<|end_filename|> export class Feedback { open() { cy.visit( '/owning-a-home/feedback' ); } submitComment( comment ) { cy.get( '#comment' ).type( comment ); cy.get( '.content_main' ) .within( () => { cy.get( 'form' ).submit(); } ); } successNotification() { return cy.get( '.content_main' ) .within( () => cy.get( '.m-notification' ) ); } } <|start_filename|>cfgov/jinja2/v1/youth_employment_success/route-questions/miles.html<|end_filename|> {% from 'atoms/checkbox.html' import render as render_checkbox with context %} {% from 'input.html' import render as render_input with context %} <div class="content-l block block__sub m-yes-miles"> <div class="content-l_col content-l_col-1"> {{ render_input({ 'class': 'u-w10pct', 'data_js_name': "miles", 'helperText': 'This can be a rough estimate — don’t worry if it’s not exact.', 'label': 'How many miles do you expect to drive to and from work each day?', 'size': '1-4', 'type': 'text', 'value': '', 'disabled': true, 'data_sanitize': 'number' }) }} {{ render_checkbox({ 'class': 'u-js-only block block__sub-micro', 'label': "I'm not sure, add this to my to-do list to look up later ", 'name': "yes-miles-unsure", 'disabled': true }) }} </div> </div> <|start_filename|>cfgov/unprocessed/apps/teachers-digital-platform/js/utils.js<|end_filename|> const xhr = require( '../../../js/modules/util/ajax-request' ).ajaxRequest; /** * fetch - Wrapper for our ajax request method with callback support * * @param {string} url URL to request * @param {function} cb Success/failure callback */ function fetch( url, cb ) { xhr( 'GET', url, { success: data => cb( null, data ), fail: err => cb( err ) } ); } module.exports = { fetch: fetch }; <|start_filename|>cfgov/unprocessed/apps/ccdb-landing-map/js/landing-map.js<|end_filename|> import Chart from './Chart'; import debounce from 'debounce'; let perCapBtn, rawBtn, isPerCapita = false; /** * Wrapper function around the chart cleanup and chart initialization */ function start() { const el = document.getElementById( 'landing-map' ); const elements = el.querySelectorAll( '*' ); for ( let i = 0; i < elements.length; i++ ) { const node = elements[i]; node.parentNode.removeChild( node ); } const dataUrl = 'https://files.consumerfinance.gov/ccdb/hero-map-3y.json'; // eslint-disable-next-line no-unused-vars const chart = new Chart( { el: el, source: dataUrl, isPerCapita } ); } /** * main entrypoint into landing map page, init the buttons, kick off map */ function init() { perCapBtn = document.getElementsByClassName( 'capita' )[0]; rawBtn = document.getElementsByClassName( 'raw' )[0]; perCapBtn.onclick = () => { perCapBtn.classList.add( 'selected' ); rawBtn.classList.remove( 'selected' ); isPerCapita = true; start(); }; rawBtn.onclick = () => { rawBtn.classList.add( 'selected' ); perCapBtn.classList.remove( 'selected' ); isPerCapita = false; start(); }; window.addEventListener( 'resize', debounce( function() { start(); }, 200 ) ); start(); } export default { init }; <|start_filename|>test/cypress/pages/owning-a-home/explore-rates.js<|end_filename|> export class ExploreRates { open() { cy.visit( '/owning-a-home/explore-rates/' ); } selectState( state ) { cy.get( '#location' ) .select( state ); } graph() { return cy.get( '#chart-section' ) .within( () => cy.get( 'figure:first' ) ); } } <|start_filename|>cfgov/paying_for_college/jinja2/paying-for-college/college-cost-blocks/macros/financial-item-expandable.html<|end_filename|> {# ========================================================================== Expandable ========================================================================== Description: Create a financial item expandable when given: value: Object with following properties: value.label: Label for expandable header. value.value: Value for expandable header. value.is_editable: Whether expandable contains form elements. Determines the open/close cues. value.note: Additional text for expandable header. value.data_attribute: Data attribute for value element. value.status: Status descriptor for financial item value. Options include warning. ========================================================================== #} {% macro expandable(value) %} <div data-qa-hook="expandable" class="o-expandable o-expandable__padded"> <button class="o-expandable_header o-expandable_target financial-item financial-item__expandable {{ ('financial-item__' + value.status | safe ) if value.status else ''}}" type="button"> <span class="flex-container"> <span class="h4 o-expandable_header-left o-expandable_label"> {{ value.label }} </span> <span class="o-expandable_header-right o-expandable_link"> <span class="financial-item_value" {{ value.data_attribute | safe if value.data_attribute else '' }} > {{ value.value }} </span> <span class="o-expandable_cue o-expandable_cue-open"> <span class="u-visually-hidden-on-mobile"> {{ 'Edit' if value.is_editable else 'Show' }} </span> {{ svg_icon('edit') if value.is_editable else svg_icon('plus-round') }} </span> <span class="o-expandable_cue o-expandable_cue-close"> <span class="u-visually-hidden-on-mobile"> {{ 'Save' if value.is_editable else 'Hide' }} </span> {{ svg_icon('check-round') if value.is_editable else svg_icon('minus-round') }} </span> </span> </span> {% if value.note %} <span class="financial-item_note"> {{ value.note | safe }} </span> {% endif %} </button> <div class="o-expandable_content"> {% if caller is defined %} {{ caller() }} {% endif %} </div> </div> {% endmacro %} {% if value %} {{ expandable(value) }} {% endif %} <|start_filename|>cfgov/templates/wagtailadmin/access_denied.html<|end_filename|> {% extends "wagtailadmin/login.html" %} {% load i18n admin_static %} {% block furniture %} <div class="content-wrapper"> <h1>{% trans 'Sorry!' %} <br/> {% trans 'You do not have permission to access this page.' %} </h1> <h2>Perhaps you could try:</h2> <ul> {% for name, url in destinations %} <li><a href="{{url}}"> {{name}}</a></li> {% endfor %} </ul> <p>{% trans 'Otherwise, you may want to' %} <a href="/logout/">{% trans 'LOG OUT ' %}</a></p> </div> {% endblock %} <|start_filename|>test/cypress/pages/find-a-housing-counselor/find-a-housing-counselor.js<|end_filename|> export class FindAHousingCounselor { open() { cy.visit( '/find-a-housing-counselor/' ); } searchZipCode( zipCode ) { cy.get( '#hud_hca_api_query' ).type( zipCode ); cy.get( '.m-form-field-with-button_wrapper' ).within( () => { cy.get( 'button' ).click(); } ); } resultsSection() { return cy.get( '#hud_results-list_container' ); } } <|start_filename|>cfgov/jinja2/v1/youth_employment_success/review/print.html<|end_filename|> <div class="block block__sub u-js-only u-hide-on-print"> <p class="h3">Print or save your plan</p> <p> You can print or save your plan as a PDF to keep track of your options and next steps. </p> <button class="a-btn yes-print-button">Print or save</button> </div> <|start_filename|>test/cypress/pages/consumer-tools/before-you-claim.js<|end_filename|> export class BeforeYouClaim { open() { cy.visit( '/consumer-tools/retirement/before-you-claim/' ); } setBirthDate( month, day, year ) { cy.get( '#bd-month' ).type( month ); cy.get( '#bd-day' ).type( day ); cy.get( '#bd-year' ).type( year ); } setHighestAnnualSalary( salary ) { cy.get( '#salary-input' ).type( salary ); } getEstimate() { cy.get( '#get-your-estimates' ).click(); } claimGraph() { return cy.get( '#claim-canvas' ); } setLanguageToSpanish() { cy.get( '.content-l' ).within( () => { cy.get( 'a' ).first().click(); } ); } } <|start_filename|>test/cypress/components/email-signup.js<|end_filename|> export default class EmailSignup { open() { cy.visit( '/consumer-tools/' ); } signUp( email ) { cy.get( '.o-form__email-signup' ).within( () => { cy.get( 'input:first' ).type( email ); cy.get( 'button:first' ).click(); } ); } successNotification() { return cy.get( '.m-notification_message' ); } } <|start_filename|>test/cypress/pages/credit-cards/agreements-search.js<|end_filename|> export class CreditCardAgreementSearch { open() { cy.visit( '/credit-cards/agreements/' ); } selectIssuer( issuer ) { const element = issuer.split( ' ' ).join( '-' ).toLowerCase(); cy.get( '#issuer_select' ).select( element, { force: true } ); } agreementsList() { return cy.get( '#ccagrsearch' ); } } <|start_filename|>cfgov/jinja2/v1/youth_employment_success/route/index.html<|end_filename|> <div class="yes-routes block block__sub js-no-print"> <div class="content-l block block__flush-top block__flush-bottom"> <div class="u-w80pct"> <div class="content-l_col content-l_col-1"> {% for i in range(2) %} {% with id=i+1 %} {% include "route-option.html" %} {% endwith %} {% endfor %} </div> </div> </div> <div class="content-l_col content-l_col-1 m-yes-route-option block block__flush-bottom u-mt30"> <h2>Are there other ways you can get to work?.</h2> <p> Compare different options to help you figure out a backup plan. </p> <div class="u-js-only"> {% include "youth_employment_success/plus-icon.html" %} <button class="a-btn a-btn__link m-yes-route-option">Add another option</button> </div> </div> </div> <|start_filename|>cfgov/jobmanager/jinja2/jobmanager/job_listing_list.html<|end_filename|> {# ========================================================================== Job Listings List ========================================================================== Description: Creates jobs list when given: value.jobs: List of currently open jobs, where each job has: job.title: Title of open job. job.url: Link to job listing page. job.close_date: Date when open job closes. value.more_jobs_url: Link to page listing all open jobs. ========================================================================== #} <aside class="m-jobs-list" data-qa-hook="openings-section"> {% if value.jobs %} <h3>Current openings</h3> <ul class="m-list m-list__unstyled m-list__links"> {% for job in value.jobs %} <li class="m-list_item"> <a class="m-list_link" href="{{ job.url }}"> {{ job.title }} <span class="m-list_link-subtext"> Closing {% import 'macros/time.html' as time %} {{ time.render(job.close_date, {'date': true}, text_format=True) }} </span> </a> </li> {% endfor %} </ul> <a class="a-btn a-btn__full-on-xs" href="{{ value.more_jobs_url }}"> View all job openings </a> {% else %} <h3 class='short-desc'>There are no current openings at this time.</h3> {% endif %} </aside> <|start_filename|>cfgov/unprocessed/apps/paying-for-college/js/util/analytics.js<|end_filename|> import Analytics from '../../../../js/modules/Analytics'; /** * Sends an event to the dataLayer for Google Tag Manager * @param {string} action - The type of event or action taken * @param {string} label - A value or label for the action */ function sendAnalyticsEvent( action, label ) { const eventData = Analytics.getDataLayerOptions( action, label, 'P4C Financial Path Interaction' ); Analytics.sendEvent( eventData ); } export { sendAnalyticsEvent }; <|start_filename|>cfgov/paying_for_college/jinja2/paying-for-college/college-cost-blocks/macros/secondary-nav.html<|end_filename|> {# ========================================================================== secondary_navigation.render() ========================================================================== Description: Creates markup for secondary navigation. nav_items: The secondary navigation item structure. ========================================================================== #} {% macro render( nav_items ) %} <nav class="o-secondary-navigation" aria-label="Section navigation"> {% set sec_nav_settings = { 'label': _('In this section'), 'is_midtone': true, 'is_bordered': false, 'is_expanded': false } %} {% from 'organisms/expandable.html' import expandable with context %} {% call() expandable(sec_nav_settings) %} <ul class="m-list m-list__unstyled o-secondary-navigation_list o-secondary-navigation_list__parents" role="tablist"> {%- for item in nav_items %} <li class="m-list_item m-list_item__parent" data-nav-is-active="{{item.current if item.current else 'False'}}" data-nav-is-open="False" role="tab"> <a class="m-nav-link m-nav-link__parent" href="#" data-gtm_ignore="true" data-nav_section="{{ item.data }}"> {{ item.title }} </a> {%- if item.children -%} <ul class="m-list m-list__unstyled o-secondary-navigation_list o-secondary-navigation_list__children" role="tablist"> {%- for child in item.children -%} <li class="m-list_item" role="tab"> <a class="m-nav-link" href="#" data-gtm_ignore="true" data-nav_item="{{ child.data }}"> {{ child.title }} </a> </li> {%- endfor %} </ul> {%- endif -%} </li> {%- endfor %} </ul> {% endcall %} </nav> {% endmacro %} <|start_filename|>cfgov/jinja2/v1/youth_employment_success/budget-form.html<|end_filename|> {% from 'line-item.html' import render as render_line_item with context %} <section class="block o-yes-budget"> <h2> Now let's compare your different options for getting to work </h2> <p> First we'll help you figure out your average monthly budget so you have an idea of how much money is available to spend on transportation. Once you've estimated your budget, you can compare different options to see which one best fits your budget and lifestyle. </p> <form id="yes-budget-form" class="block block__sub block__flush-bottom"> <h3> How much money can you spend on getting to work? </h3> <div class="content-l content-l__large-gutters block block__sub"> <div class="content-l_col content-l_col-1-2 u-mobile-reorder"> <div class="content-l u-mobile-reorder__second"> <label for="yes-money-earned" class="a-label h4 content-l_col content-l_col-1 u-hide-on-mobile"> How much money do you receive each month? </label> </div> <div class="u-mobile-reorder__first"> <p id="mobile-earned-label" class="a-label h4 content-l_col-1 u-show-on-mobile"> How much money do you receive each month? </p> <p class="a-label_helper"> Some sources might be: </p> <ul class="a-label_helper"> <li>Primary and additional jobs</li> <li>Government programs</li> <li>Disability benefits</li> <li>Child support</li> <li>Cash gifts or allowances</li> </ul> </div> </div> <div class="content-l_col content-l_col-1-2"> <input type="text" id="yes-money-earned" name="money-earned" class="a-text-input o-yes-budget-earned" disabled placeholder="$" data-sanitize="money"> </div> </div> <div class="content-l content-l__large-gutters block block__sub block__flush-bottom"> <div class="content-l_col content-l_col-1-2"> <div class="content-l u-mobile-reorder__second"> <label for="yes-money-spent" class="a-label content-l_col-1 m-right-justify u-mobile-reorder__first"> How much do you spend each month? <span class="h3 content-r u-hide-on-mobile">(-)</span> </label> </div> <div class="u-mobile-reorder__second"> <p class="a-label_helper"> Don’t include transportation costs, but some other expenses might be: </p> <ul class="a-label_helper"> <li>Rent and utilities</li> <li>Groceries and eating out</li> <li>Credit card bills</li> <li>Student loans</li> <li>Childcare</li> <li>Cell phone</li> </ul> </div> </div> <div class="content-l_col content-l_col-1-2 u-mobile-reorder__third"> <span class="h3 u-show-on-mobile u-mr10">( - )</span> <input type="text" id="yes-money-spent" name="money-spent" class="a-text-input o-yes-budget-spent" disabled="" placeholder="$" data-sanitize="money"> </div> </div> </form> <div class="content-l"> <div class="content-l_col content-l_col-1"> <div class="content-l block block__sub block__flush-bottom"> <div class="content-l_col content-l_col-2-3"> <div class="content_line-bold"></div> <div class="block block__sub-micro block__flush-bottom"> {{ render_line_item({ 'label': 'Total left at the end of the month:', 'target': 'o-yes-budget-remaining' }) }} <div class="content-l"> <p class="content-l_col content-l_col-1 u-mt10"> Estimating your monthly budget is a good place to start, but if you want some tips on how to reduce your expenses so you can set aside more money to pay for necessities and to save for your goal, use the <a href="https://files.consumerfinance.gov/f/documents/cfpb_your-money-your-goals_cutting-expenses_tool_2018-11.pdf" rel="noopener noreferrer" target="_blank"> Cutting Expenses tool</a>. </p> </div> </div> </div> </div> </div> </div> </section> <|start_filename|>cfgov/paying_for_college/jinja2/paying-for-college/college-cost-blocks/macros/financial-item-text.html<|end_filename|> {# ========================================================================== Financial Text Item ========================================================================== Description: Outputs inline label and right-aligned value when given: value: Object with the following properties: value.label: Label text. value.helper_text: Label helper text. value.value: Value text. value.type: Item type. Options include 'subtotal' and 'total'. value.status: Item status. Options include 'warning' value.data_attribute: Data attribute for value element. ========================================================================== #} {% macro render( value ) -%} <div class="financial-item {{ 'financial-item__' + ( value.type if value.type else 'text' ) }} {% if value.status %} {{ 'financial-item__' + value.status }} {% endif %}"> <div class="financial-item_label"> <div>{{ value.label | safe }}</div> {%- if value.helper_text -%} <p><small>{{ value.helper_text | safe }}</small></p> {%- endif -%} </div> <div class="financial-item_value"> <span {% if value.data_attribute %}{{ value.data_attribute | safe }}{% endif %}> {{ value.value | safe }} </span> </div> </div> {%- endmacro %} <|start_filename|>test/cypress/pages/consumer-tools/financial-well-being.js<|end_filename|> export class FinancialWellBeing { open() { cy.visit( '/consumer-tools/financial-well-being/' ); } selectQuestion( questionNumber, answer ) { const id = `#question_${ questionNumber }-${ answer.split( ' ' ).join( '-' ) }`.toLowerCase(); cy.get( id ).check( { force: true } ); } selectAge() { cy.get( '#age-18-61' ).check( { force: true } ); } submitButton() { return cy.get( '#submit-quiz' ); } submit() { this.submitButton().click(); } score() { return cy.get( 'figure' ); } } <|start_filename|>test/unit_tests/mocks/chartMock.js<|end_filename|> const chartMock = {}; const props = [ 'renderer', 'g', 'translate', 'add', 'path', 'label', 'attr', 'rect', 'addClass', 'text' ]; for ( let i = 0; i < props.length; i++ ) { const propName = props[i]; chartMock[propName] = jest.fn( () => chartMock ); } export default chartMock; <|start_filename|>cfgov/jinja2/v1/_includes/ask/how-to.html<|end_filename|> {# ========================================================================== HowTo block ========================================================================== Description: Implements Google's recommended elements of HowTo schema (see https://developers.google.com/search/docs/data-types/how-to) when given: value: Object defined from a Streamfield block. value.title: Main title for the HowTo. Marked up as the HowTo's `name` field. value.description: Text overview of the HowTo. Marked up as the HowTo's `description` field. value.steps: List of steps in the HowTo. Marked up as HowToStep objects. value.steps.step.title: Title of an individual step. Marked up as the HowToStep's `name` field. value.steps.step.step_content: StreamBlock containing the step content. Marked up as the HowToStep's `text` field. ========================================================================== #} <div itemscope itemtype="http://schema.org/HowTo" class="schema-block schema-block__how-to"> {%- if value.title %} <h2 itemprop="name" class="schema-block_title"> {{ value.title }} </h2> {% endif -%} {%- if value.description %} <div itemprop="description" class="schema-block_description"> {{ value.description | richtext }} </div> {% endif -%} <ol> {% for step in value.steps %} <li itemprop="step" itemscope itemtype="http://schema.org/HowToStep" class="schema-block_item"> <h3 itemprop="name" class="h4">{{ step.title }}</h3> <div itemprop="text"> {% include_block step.step_content %} </div> </li> {% endfor %} </ol> </div> <|start_filename|>cfgov/jinja2/v1/youth_employment_success/route-questions/driving-cost-estimate.html<|end_filename|> <div class="content-l block block__sub js-driving-estimate"> <div class="content-l_col content-l_col-1 a-label"> <p class="a-label__heading u-mb0"> Average daily cost </p> <small> We've calculated this estimated number for you based on data from <a href="https://www.bts.gov/content/average-cost-owning-and-operating-automobile" rel="noopener noreferrer" target="_blank">Department of Transportation, Bureau of Transportation Statistics</a> about average cost per mile, which includes <ul> <li>gas</li> <li>insurance</li> <li>maintenance costs</li> <li>tires</li> <li>registration and taxes</li> <li>depreciation,</li> <li>finance charges.</li> </ul> </small> </div> </div> <|start_filename|>cfgov/unprocessed/apps/paying-for-college/js/util/promise-request.js<|end_filename|> /* Promise requests are better. */ /** * promiseRequest - A handy function for returning XHR Promises * @param {String} method - The method, ex. POST or GET * @param {String} url - The url to be requested * @returns {Object} Promise of the XHR request */ const promiseRequest = function( method, url ) { const xhr = new XMLHttpRequest(); return new Promise( function( resolve, reject ) { // Completed xhr xhr.onreadystatechange = function() { // Do not run unless xhr is complete if ( xhr.readyState !== 4 ) return; if ( xhr.status >= 200 && xhr.status < 300 ) { resolve( xhr ); } else { reject( new Error( xhr.status + ', ' + xhr.statusText ) ); } }; xhr.open( method, url, true ); xhr.send(); } ); }; export { promiseRequest }; <|start_filename|>cfgov/jinja2/v1/youth_employment_success/route/route-details.html<|end_filename|> {% import 'line-item.html' as line_item with context %} {% macro route_details() %} <div class="content-l u-mb0 yes-route-details"> <div class="content-l_col content-l_col-1 block block__sub-micro block__flush-top js-route-notification u-hidden u-js-only"></div> <div class="content-l_col content-l_col-1"> <p class="h5 u-mt0 u-mb0"> Totals for <span class="js-transportation-type"></span> </p> <div class="content_line-bold u-hide-on-print"></div> <div class="block block__sub-micro u-mb0"> {{ line_item.render({ 'label': 'Money left in your monthly budget', 'target': 'js-budget' }) }} {{ line_item.render({ 'helperText': '<span class="js-average-cost-helper"><br/><small class="a-label a-label_helper">Based on <span class="js-days-per-week"></span> days a week you plan to make this trip</small></span>', 'label': 'Average monthly cost of <span class="js-transportation-type"></span>', 'target': 'js-total-cost' }) }} </div> <div class="content_line-bold"></div> <div class="block block__sub-micro block__flush-bottom"> {{ line_item.render({ 'label': 'Total left in your budget after <span class="js-transportation-type"></span>', 'target': 'js-budget-left' }) }} <div class="block block__sub-micro block__flush-top u-js-only js-route-inline-notification"></div> </div> <div class="block block__sub-micro block__flush-bottom"> <div class="content-l m-hours"> <p class="content-l_col content-l_col-2-3 h4 m-hours_container">Total time to get to work</p> <div class="content-l_col content-l_col-1-3 u-align-right m-hours_container"> <p class="content-l_col content-l_col-1-2 m-hours_data"> <span class="js-time-hours">&mdash;</span> hours </p> <p class="content-l_col content-l_col-1-2 m-minutes_data"> <span class="js-time-minutes">&mdash;</span> minutes </p> </div> </div> </div> {% if caller is defined %} {{ caller() }} {% endif %} </div> </div> {% endmacro %} <|start_filename|>cfgov/jobmanager/jinja2/jobmanager/job_listing_table.html<|end_filename|> {# ========================================================================== Job Listings Table ========================================================================== Description: Creates jobs table when given: value.jobs: List of currently open jobs, where each job has: job.title: Title of open job. job.url: Link to job listing page. job.close_date: Date when open job closes. job.grades: List of job grades, as strings. job.offices: List of offices, where each office has: office.name: Office city name. office.state_id: Office state abbreviation. job.regions: List of regions, where each region has: region.name: Region name. ========================================================================== #} {%- import 'macros/time.html' as time %} {%- set columns = [ 'TITLE', 'GRADE', 'POSTING CLOSES', 'LOCATION' ] %} {%- set rows = [] %} {%- for job in value.jobs %} {% if ( job.offices | length ) + ( job.regions | length ) > 1 %} {% set location = 'Multiple locations' %} {% elif job.regions %} {% set location = job.regions[0].name %} {% elif job.offices %} {% set location = job.offices[0].name ~ ', ' ~ job.offices[0].state_id %} {% endif %} {% do rows.append( [ '<a href="' ~ job.url ~ '">' ~ job.title ~ '</a>', job.grades | join( ', ' ), time.render( job.close_date, { 'date' : true }, text_format=True ), location | default ( '' ) ] ) %} {% endfor %} {%- with value = { 'data': [ columns ] + rows, 'has_data': not not rows, 'empty_table_msg': 'There are no current openings at this time.', 'first_row_is_table_header': true, 'is_stacked': true } %} {% include '_includes/organisms/table.html' %} {% endwith %} <|start_filename|>test/cypress/pages/data-research/prepaid-agreements-search.js<|end_filename|> export class PrepaidAgreementsSearch { open() { cy.visit( '/data-research/prepaid-accounts/search-agreements/' ); } searchByTerm( term ) { cy.get( '#searchText' ).type( term ); this.searchForm().submit(); } searchForm() { return cy.get( '.search_wrapper' ).find( 'form' ); } selectField( field ) { cy.get( '#search_field' ).select( field ); } selectIssuer( issuer ) { cy.get( '#issuer_name' ).type( issuer ); cy.get( `input[value="${ issuer }"]` ).check( { force: true } ); } filtersForm() { return cy.get( '.content_sidebar' ).find( 'form' ); } applyFilters() { this.filtersForm().submit(); } filters() { return cy.get( '.filters_tags' ); } expandProductFilters() { cy.get( 'span' ).contains( 'Prepaid product type' ).click(); } selectProductType( product ) { this.filtersForm().find( `input[value="${ product }"]` ).check( { force: true } ); } expandCurrentStatusFilters() { cy.get( 'span' ).contains( 'Current status' ).click(); } selectStatus( status ) { this.filtersForm().find( `input[value="${ status }"]` ).check( { force: true } ); } } <|start_filename|>cfgov/paying_for_college/jinja2/paying-for-college/college-cost-blocks/macros/financial-item-input.html<|end_filename|> {# ========================================================================== Financial item input ========================================================================== Description: Builds right-aligned input with inline label. value: Object with the following properties: value.data_attribute: Data attribute for input element. value.helper_text: Label helper text. value.label: Name of the field. value.id: Input id. value.value: Input value. ========================================================================== #} {% macro render( value ) -%} {% set ht_id = 'ht_' ~ value.id %} <div class="financial-item"> <div class="financial-item_label"> <label class="a-label a-label__heading" for="{{ value.id }}"> {{ value.label }} </label> {%- if value.helper_text -%} <p id="{{ ht_id }}"><small>{{ value.helper_text | safe }}</small></p> {%- endif -%} </div> <div class="financial-item_value"> <input class="a-text-input" type="text" autocomplete="off" id="{{ value.id if value.id else '' }}" name="{{ value.id if value.id else '' }}" value="{{ value.value if value.value else '' }}" {{ ('aria-describedby="' ~ ht_id ~ '"') | safe if value.helper_text else '' }} {{ value.data_attribute | safe if value.data_attribute else ''}}> </div> </div> {%- endmacro %} <|start_filename|>cfgov/jinja2/v1/youth_employment_success/goals.html<|end_filename|> {% import "goals/goal.html" as textarea with context %} {% import 'atoms/radio-button.html' as radio_button with context %} {% set labels = ['3 to 6 months', '6 to 9 months', '9 months to 1 year', '1 year or more'] %} <h1>Planning how you’ll get to work</h1> <p class="lead-paragraph u-mt0">Getting to work on time is important for keeping your job. Having a plan and a backup option is a good idea in case you get into a bind. We'll help you figure out your best option for getting to work, how to budget for it, and what to do if you need a backup plan. </p> <p class="u-mb0">Meet Mya and Frankie. They’ll help you think about your plan.</p> <div class="content-l block block__sub block__flush-top"> <div class="content-l_col-1-2 block block__sub block__flush-bottom"> <img src="/static/apps/youth-employment-success/img/Mya_transportation_tool.png" alt="" class="u-hide-on-print"> <p class="h2 u-mt15">Mya plans to bike to work</p> <p class="u-mt20"> Mya decided to bike to work because there’s a bikeshare near her school. Bikeshares allow you to borrow a bike from different self-service bike stations around the city. Mya heads straight to work from class &mdash; some days she has time to walk, but usually she’s in a rush and biking is faster. </p> <p class="h3"> Mya’s long-term goal </p> <p>Mya wants to buy an annual bikeshare membership since her youth employment program offers a special rate and it’d be a better deal than paying per ride. The $60 annual membership works out to a little over $1 per week (over 52 weeks in a year). In order to save money for this, Mya will walk to work two days a week for the next few months.</p> </div> <div class="content-l_col-1-2 block block__sub block__flush-bottom"> <img src="/static/apps/youth-employment-success/img/Frankie_transportation_tool.png" alt="" class="u-hide-on-print"> <p class="h2 u-mt15">Frankie plans to take the bus</p> <p class="u-mt20">Frankie doesn’t live near public transportation, so he usually gets a ride to the closest bus stop. The bus ride is about 25 minutes long, so he leaves his house at 7:10 a.m. to allow enough time to get dropped off, ride the bus, and arrive at work before his 8 a.m. shift starts.</p> <p class="h3"> Frankie’s long-term goal </p> <p>Frankie will take the bus five days a week, but over the next year, he will save up to buy a car so he doesn’t have to rely on friends and family for rides to the bus stop. While he's saving up for a car, he will buy a $50 monthly bus pass because it’s more cost-effective than paying $2 each way for a bus ticket.</p> </div> </div> <div class="block block__flush-bottom"> <h2> Now let's think through your long-term goal. </h2> <p> Figuring out your long-term goal may help you figure out the best way to get to work now while you’re working towards your goal. </p> <form class="block u-mt30 js-yes-goals"> <div class="block block__sub"> {{ textarea.render({ 'disabled': true, 'fieldClass': 'js-long-term-goal', 'helperText': 'For example, your long-term goal could be saving up for an annual bus pass over the next few months or saving up to buy a car in the next year.', 'label': 'What’s your long-term goal?', 'labelClass': "h4", 'name': 'longTermGoal', 'required': true }) }} </div> <div class="block block__sub"> {{ textarea.render({ 'disabled': true, 'fieldClass': 'js-goal-importance', 'helperText': 'Maybe this goal will help you save money in the long run, or maybe it’s a more reliable option than your current way of getting to work.', 'label': "Why is this goal important to you?", 'labelClass': "h4", 'name': 'goalImportance', 'required': true }) }} </div> <div class="block block__sub"> <span class="h4 u-mb0"> When do you hope to reach your goal? </span> <p class="u-mt0"> <small>Don't worry if you don't reach your goal by this date. It’s a goal to work towards, but don't stress if it doesn't happen.</small> </p> <div class="u-w80pct"> {% for label in labels | batch(2) %} <div class="block block__sub-micro"> {{ radio_button.render({ 'class': 'content-l content-l_col-1-2 m-form-field__lg-target', 'name': "goalTimeline", 'label': label[0], 'value': label[0] }) }} {% if label[1] %} {{ radio_button.render({ 'class': 'content-l_col-1-2 m-form-field__lg-target', 'name': "goalTimeline", 'label': label[1], 'value': label[1] }) }} {% endif %} </div> {% endfor %} </div> </div> <div class="block block__flush-top"> {{ textarea.render({ 'disabled': true, 'fieldClass': 'js-goal-steps', 'helperText': 'Now work backwards &mdash; what are some steps you could take to achieve your goal during your intended timeline? Make sure your steps are realistic and specific. For example, Mya’s first step is "Over the next six months, I’ll take the bus instead of using a rideshare in order to save $400 to put towards a car down payment."', 'label': "What are some steps you could take to reach your goal?", 'labelClass': "h4", 'name': 'goalSteps', 'required': true }) }} </div> </form> </div> <|start_filename|>test/cypress/pages/data-research/mortgage-performance-trends.js<|end_filename|> export class MortgagePerformanceTrends { open() { cy.visit( '/data-research/mortgage-performance-trends/mortgages-30-89-days-delinquent/' ); } selectLocationType( location ) { const id = `#mp-line-chart_geo-${ location.split( ' ' ).slice( 0, 1 ).join( '' ) }`.toLowerCase(); cy.get( id ).click( { force: true } ); } selectStateForDelinquencyTrends( state ) { cy.get( '#mp-line-chart-state' ).select( state ); } selectStateForDelinquencyRatesPerMonth( state ) { cy.get( '#mp-map-state' ).select( state ); } selectMonth( month ) { cy.get( '#mp-map-month' ).select( month ); } selectYear( year ) { cy.get( '#mp-map-year' ).select( year ); } mapTitle() { return cy.get( '#mp-map-title' ); } } <|start_filename|>cfgov/templates/registration/logged_out.html<|end_filename|> {% extends "wagtailadmin/login.html" %} {% load i18n admin_static %} {% block furniture %} <div class="content-wrapper"> <h1>You've logged out of the consumerfinance.gov editorial tools. </h1> <h2><a href="/login/">log back in</a></h2> </div> {% endblock %} <|start_filename|>cfgov/legacy/static/nemo/_/c/woff.css<|end_filename|> /***** WEBFONTS *****/ /* * CSS as specified in the following article until IE8 support is dropped: * http://coding.smashingmagazine.com/2013/02/14/setting-weights-and-styles-at-font-face-declaration/ * * Only the esential variants are on, by default. Uncomment any others if * you determine that you truly need them. * * Formats: * .woff - Modern browsers * .ttf - Safari, Android, iOS * .svg - Legacy iOS */ @font-face { font-family: "Avenir Next"; src: url("../f/f26faddb-86cc-4477-a253-1e1287684336.woff") format("woff"), url("../f/6de0ce4d-9278-467b-b96f-c1f5f0a4c375.ttf") format("truetype"), url("../f/9fd4ea0c-b19a-4b21-9fdf-37045707dd78.svg#9fd4ea0c-b19a-4b21-9fdf-37045707dd78") format("svg"); font-weight: 200; font-style: normal; } @font-face { font-family: "Avenir Next"; src: url("../f/8344e877-560d-44d4-82eb-9822766676f9.woff") format("woff"), url("../f/3a561c83-40d4-4868-8255-e8455eb009c4.ttf") format("truetype"), url("../f/3966f856-9dcf-48e7-88e7-7400f1b7d619.svg#3966f856-9dcf-48e7-88e7-7400f1b7d619") format("svg"); font-weight: 200; font-style: italic; } @font-face { font-family: "Avenir Next"; src: url("../f/1e9892c0-6927-4412-9874-1b82801ba47a.woff") format("woff"), url("../f/46cf1067-688d-4aab-b0f7-bd942af6efd8.ttf") format("truetype"), url("../f/52a192b1-bea5-4b48-879f-107f009b666f.svg#52a192b1-bea5-4b48-879f-107f009b666f") format("svg"); font-weight: 400; font-style: normal; } @font-face { font-family: "Avenir Next"; src: url("../f/92b66dbd-4201-4ac2-a605-4d4ffc8705cc.woff") format("woff"), url("../f/18839597-afa8-4f0b-9abb-4a30262d0da8.ttf") format("truetype"), url("../f/1de7e6f4-9d4d-47e7-ab23-7d5cf10ab585.svg#1de7e6f4-9d4d-47e7-ab23-7d5cf10ab585") format("svg"); font-weight: 400; font-style: italic; } @font-face { font-family: "Avenir Next"; src: url("../f/f26faddb-86cc-4477-a253-1e1287684336.woff") format("woff"), url("../f/63a74598-733c-4d0c-bd91-b01bffcd6e69.ttf") format("truetype"), url("../f/a89d6ad1-a04f-4a8f-b140-e55478dbea80.svg#a89d6ad1-a04f-4a8f-b140-e55478dbea80") format("svg"); font-weight: 500; font-style: normal; } @font-face { font-family: "Avenir Next"; src: url("../f/8344e877-560d-44d4-82eb-9822766676f9.woff") format("woff"), url("../f/b28b01d9-78c5-46c6-a30d-9a62c8f407c5.ttf") format("truetype"), url("../f/ed4d3c45-af64-4992-974b-c37cd12a9570.svg#ed4d3c45-af64-4992-974b-c37cd12a9570") format("svg"); font-weight: 500; font-style: italic; } @font-face { font-family: "Avenir Next"; src: url("../f/91b50bbb-9aa1-4d54-9159-ec6f19d14a7c.woff") format("woff"), url("../f/a0f4c2f9-8a42-4786-ad00-fce42b57b148.ttf") format("truetype"), url("../f/99affa9a-a5e9-4559-bd07-20cf0071852d.svg#99affa9a-a5e9-4559-bd07-20cf0071852d") format("svg"); font-weight: 600; font-style: normal; } @font-face { font-family: "Avenir Next"; src: url("../f/bc350df4-3100-4ce1-84ce-4a5363dbccfa.woff") format("woff"), url("../f/bc13ae80-cd05-42b4-b2a9-c123259cb166.ttf") format("truetype"), url("../f/4862b373-2643-46b1-b0b5-88537c52d15c.svg#4862b373-2643-46b1-b0b5-88537c52d15c") format("svg"); font-weight: 600; font-style: italic; } @font-face { font-family: "Avenir Next"; src: url("../f/b8e906a1-f5e8-4bf1-8e80-82c646ca4d5f.woff") format("woff"), url("../f/890bd988-5306-43ff-bd4b-922bc5ebdeb4.ttf") format("truetype"), url("../f/ed104d8c-7f39-4e8b-90a9-4076be06b857.svg#ed104d8c-7f39-4e8b-90a9-4076be06b857") format("svg"); font-weight: 700; font-style: normal; } @font-face { font-family: "Avenir Next"; src: url("../f/25e83bf5-47e3-4da7-98b1-755efffb0089.woff") format("woff"), url("../f/4112ec87-6ded-438b-83cf-aaff98f7e987.ttf") format("truetype"), url("../f/ab1835cb-df6f-4d8d-b8ee-3075f5ba758d.svg#ab1835cb-df6f-4d8d-b8ee-3075f5ba758d") format("svg"); font-weight: 700; font-style: italic; } @font-face { font-family: "Avenir Next"; src: url("../f/b8e906a1-f5e8-4bf1-8e80-82c646ca4d5f.woff") format("woff"), url("../f/045d1654-97f2-4ff0-9d24-21ba9dfee219.ttf") format("truetype"), url("../f/3c111f4f-c9f7-45d4-b35f-4f4ed018842f.svg#3c111f4f-c9f7-45d4-b35f-4f4ed018842f") format("svg"); font-weight: 800; font-style: normal; } @font-face { font-family: "Avenir Next"; src: url("../f/25e83bf5-47e3-4da7-98b1-755efffb0089.woff") format("woff"), url("../f/2b4885a7-fc02-4aa0-b998-5b008a589c80.ttf") format("truetype"), url("../f/9b40a6ef-0ef5-49c0-aa8d-5ba7e8e7d9b7.svg#9b40a6ef-0ef5-49c0-aa8d-5ba7e8e7d9b7") format("svg"); font-weight: 800; font-style: italic; } /* * This CSS resource incorporates links to font software which is * the valuable copyrighted property of Monotype Imaging and/or * its suppliers. You may not attempt to copy, install, redistribute, convert, * modify or reverse engineer this font software. Please contact Monotype Imaging * with any questions regarding Web Fonts: http://webfonts.fonts.com */ <|start_filename|>cfgov/regulations3k/jinja2/regulations3k/inline_interps.html<|end_filename|> {#- Part 1004 (Reg D) houses interps in Appendix A instead of Supplement I like every other reg -#} {%- set interp_location = 'Appendix A' if regulation and regulation.part_number == '1004' else 'Supplement I' -%} <div data-qa-hook="expandable" class="o-expandable o-expandable__padded o-expandable__background o-expandable__border inline-interpretation"> <button class="o-expandable_header o-expandable_target"{% if section_title %} data-section="{{ section_title }}"{% endif %}> <span class="o-expandable_header-left o-expandable_label"> Official interpretation {% if section_title %}of {{ section_title }}{% endif %} </span> <span class="o-expandable_header-right o-expandable_link"> <span class="o-expandable_cue o-expandable_cue-open"> <span class="u-visually-hidden-on-mobile"> {{ _('Show') }} </span> <svg viewBox="0 0 1000 1200" class="cf-icon-svg"><path d="M500 105.2c-276.1 0-500 223.9-500 500s223.9 500 500 500 500-223.9 500-500-223.9-500-500-500zm263.1 550.7H549.6v213.6c0 27.6-22.4 50-50 50s-50-22.4-50-50V655.9H236c-27.6 0-50-22.4-50-50s22.4-50 50-50h213.6V342.3c0-27.6 22.4-50 50-50s50 22.4 50 50v213.6h213.6c27.6 0 50 22.4 50 50s-22.5 50-50.1 50z"/></svg> </span> <span class="o-expandable_cue o-expandable_cue-close"> <span class="u-visually-hidden-on-mobile"> {{ _('Hide') }} </span> <svg viewBox="0 0 1000 1200" class="cf-icon-svg"><path d="M500 105.2c-276.1 0-500 223.9-500 500s223.9 500 500 500 500-223.9 500-500-223.9-500-500-500zm263.1 550.7H236c-27.6 0-50-22.4-50-50s22.4-50 50-50h527.1c27.6 0 50 22.4 50 50s-22.4 50-50 50z"/></svg> </span> </span> </button> <div class="o-expandable_content"> {{ contents }} <p><a href="{{ url }}">See interpretation of {% if section_title %}{{ section_title }}{% else %}this section{% endif %} in {{ interp_location }}</a></p> </div> </div> <|start_filename|>cfgov/paying_for_college/jinja2/paying-for-college/college-cost-blocks/macros/number-callout.html<|end_filename|> {# ========================================================================== Number callout ========================================================================== Description: Outputs a header and number when given: value: Object with the following properties: value.header: Header text value.value: Value value.data_attribute: Data attribute for value container value.additional_classes: Additional classes for callout ========================================================================== #} {% macro render( value ) -%} <div class="number-callout {{ value.additional_classes if value.additional_classes else '' }}"> <div class="number-callout_header">{{ value.header }}</div> <div class="number-callout_value"> <span {{ value.data_attribute | safe if value.data_attribute else '' }}> {{ value.value if value.value else '' }} </span> </div> </div> {%- endmacro %} <|start_filename|>cfgov/unprocessed/apps/teachers-digital-platform/js/scroll.js<|end_filename|> const smoothscroll = require( 'smoothscroll-polyfill' ); const scrollIntoView = require( '../../../js/modules/util/scroll' ).scrollIntoView; const scroll = { init: () => { let jumplinks = document.querySelectorAll( '[data-scroll]' ); smoothscroll.polyfill(); // IE doesn't support forEach w/ node lists so convert it to an array. jumplinks = Array.prototype.slice.call( jumplinks ); jumplinks.forEach( function( jumplink ) { jumplink.addEventListener( 'click', function( event ) { const target = document.querySelector( jumplink.hash ); // Disable default browser behavior. event.preventDefault(); // Scroll smoothly to the target. scrollIntoView( target, { behavior: 'smooth', block: 'start', offset: 0 } ); // Update url hash. if ( history.pushState ) { history.pushState( null, null, jumplink.hash ); } else { location.hash = jumplink.hash; } // Wait half a second for scrolling to finish. setTimeout( function() { // Make sure focus is set to the target. target.setAttribute( 'tabindex', '-1' ); target.focus( { preventScroll: true } ); }, 500 ); }, false ); } ); } }; module.exports = scroll;
flacoman91/consumerfinance.gov
<|start_filename|>Dockerfile<|end_filename|> FROM scratch EXPOSE 9624 USER 1000 COPY pactbroker_exporter /bin/pactbroker_exporter ENTRYPOINT ["pactbroker_exporter"] <|start_filename|>main.go<|end_filename|> package main import ( "crypto/tls" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "sync" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/common/log" "github.com/prometheus/common/version" "gopkg.in/alecthomas/kingpin.v2" ) const ( namespace = "pactbroker" ) // Exporter structure type Exporter struct { uri string mutex sync.RWMutex fetch func(endpoint string) (io.ReadCloser, error) pactBrokerUp, pactBrokerPacticipants prometheus.Gauge pactBrokerPacts *prometheus.GaugeVec totalScrapes prometheus.Counter } // NewExporter function func NewExporter(uri string, timeout time.Duration) (*Exporter, error) { u, err := url.Parse(uri) if err != nil { return nil, err } var fetch func(endpoint string) (io.ReadCloser, error) switch u.Scheme { case "http", "https", "file": fetch = fetchHTTP(uri, timeout) default: return nil, fmt.Errorf("unsupported scheme: %q", u.Scheme) } return &Exporter{ uri: uri, fetch: fetch, pactBrokerUp: prometheus.NewGauge( prometheus.GaugeOpts{ Namespace: namespace, Name: "up", Help: "The current health status of the server (1 = UP, 0 = DOWN).", }, ), pactBrokerPacts: prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: namespace, Name: "pacts", Help: "The current number of pacts per pacticipant.", }, []string{"name"}, ), pactBrokerPacticipants: prometheus.NewGauge( prometheus.GaugeOpts{ Namespace: namespace, Name: "pacticipants", Help: "The current number of pacticipants.", }, ), totalScrapes: prometheus.NewCounter( prometheus.CounterOpts{ Namespace: namespace, Name: "total_scrapes", Help: "The total number of scrapes.", }, ), }, nil } // Describe function of Exporter func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { e.mutex.Lock() defer e.mutex.Unlock() ch <- e.totalScrapes.Desc() ch <- e.pactBrokerPacticipants.Desc() ch <- e.pactBrokerUp.Desc() e.pactBrokerPacts.Describe(ch) } // Collect function of Exporter func (e *Exporter) Collect(ch chan<- prometheus.Metric) { e.mutex.Lock() defer e.mutex.Unlock() up := e.scrape(ch) ch <- prometheus.MustNewConstMetric(e.pactBrokerUp.Desc(), prometheus.GaugeValue, up) e.pactBrokerPacts.Collect(ch) } type pacticipants struct { Embedded struct { Pacticipants []struct { Name string `json:"name"` } `json:"pacticipants"` } `json:"_embedded"` } type pacts struct { Links struct { Pbpacts []struct { Name string `json:"name"` } `json:"pb:pacts"` } `json:"_links"` } func (e *Exporter) scrape(ch chan<- prometheus.Metric) (up float64) { e.totalScrapes.Inc() var p pacticipants body, err := e.fetch("/pacticipants") if err != nil { log.Errorf("Can't scrape Pack: %v", err) return 0 } defer body.Close() bodyAll, err := ioutil.ReadAll(body) if err != nil { return 0 } _ = json.Unmarshal([]byte(bodyAll), &p) ch <- prometheus.MustNewConstMetric(e.pactBrokerPacticipants.Desc(), prometheus.GaugeValue, float64(len(p.Embedded.Pacticipants))) for _, pacticipant := range p.Embedded.Pacticipants { var bodyPact io.ReadCloser var pacts pacts bodyPact, err = e.fetch("/pacts/provider/" + pacticipant.Name) if err != nil { log.Errorf("Can't scrape Pack: %v", err) return 0 } defer bodyPact.Close() pactsAll, err := ioutil.ReadAll(bodyPact) if err != nil { return 0 } _ = json.Unmarshal([]byte(pactsAll), &pacts) e.pactBrokerPacts.WithLabelValues(pacticipant.Name).Set(float64(len(pacts.Links.Pbpacts))) } return 1 } func fetchHTTP(uri string, timeout time.Duration) func(endpoint string) (io.ReadCloser, error) { tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} client := http.Client{ Timeout: timeout, Transport: tr, } return func(endpoint string) (io.ReadCloser, error) { resp, err := client.Get(uri + endpoint) if err != nil { return nil, err } if !(resp.StatusCode >= 200 && resp.StatusCode < 300) { resp.Body.Close() return nil, fmt.Errorf("HTTP status %d", resp.StatusCode) } return resp.Body, nil } } func main() { var ( listenAddress = kingpin.Flag("web.listen-address", "Address to listen on for web interface and telemetry.").Default(":9624").Envar("PB_EXPORTER_WEB_LISTEN_ADDRESS").String() metricsPath = kingpin.Flag("web.telemetry-path", "Path under which to expose metrics.").Default("/metrics").Envar("PB_EXPORTER_WEB_TELEMETRY_PATH").String() uri = kingpin.Flag("pactbroker.uri", "URI of Pact Broker.").Default("http://localhost:9292").Envar("PB_EXPORTER_PACTBROKER_URI").String() timeout = kingpin.Flag("pactbroker.timeout", "Scrape timeout").Default("5s").Envar("PB_EXPORTER_PACTBROKER_TIMEOUT").Duration() ) log.AddFlags(kingpin.CommandLine) kingpin.Version(version.Print("pactbroker_exporter")) kingpin.HelpFlag.Short('h') kingpin.Parse() log.Infoln("Starting pactbroker_exporter", version.Info()) log.Infoln("Build context", version.BuildContext()) exporter, err := NewExporter(*uri, *timeout) if err != nil { log.Fatal(err) } prometheus.MustRegister(exporter) prometheus.MustRegister(version.NewCollector("pactexporter")) http.Handle(*metricsPath, promhttp.Handler()) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`<html><head><title>Pact Broker Exporter</title></head><body><h1>Pact Broker Exporter</h1><p><a href='` + *metricsPath + `'>Metrics</a></p></body></html>`)) }) log.Infoln("Listening on", *listenAddress) log.Fatal(http.ListenAndServe(*listenAddress, nil)) }
pperzyna/pactbroker_exporter
<|start_filename|>node_modules/gif.js/src/gif.worker.coffee<|end_filename|> GIFEncoder = require './GIFEncoder.js' renderFrame = (frame) -> encoder = new GIFEncoder frame.width, frame.height if frame.index is 0 encoder.writeHeader() else encoder.firstFrame = false encoder.setTransparent frame.transparent encoder.setRepeat frame.repeat encoder.setDelay frame.delay encoder.setQuality frame.quality encoder.setDither frame.dither encoder.setGlobalPalette frame.globalPalette encoder.addFrame frame.data encoder.finish() if frame.last if frame.globalPalette == true frame.globalPalette = encoder.getGlobalPalette() stream = encoder.stream() frame.data = stream.pages frame.cursor = stream.cursor frame.pageSize = stream.constructor.pageSize if frame.canTransfer transfer = (page.buffer for page in frame.data) self.postMessage frame, transfer else self.postMessage frame self.onmessage = (event) -> renderFrame event.data
sweeneyngo/petsoup
<|start_filename|>cuda-torch/cuda_v8.0/Dockerfile<|end_filename|> # Start with cuDNN base image FROM nvidia/cuda:8.0-cudnn5-devel-ubuntu16.04 MAINTAINER <NAME> <<EMAIL>> # Install git, apt-add-repository and dependencies for iTorch RUN apt-get update && apt-get install -y \ git \ software-properties-common \ libssl-dev \ libzmq3-dev \ python-dev \ python-pip \ sudo # Install Jupyter Notebook for iTorch RUN pip install --upgrade pip RUN pip install jupyter # Run Torch7 installation scripts RUN git clone https://github.com/torch/distro.git /root/torch --recursive && cd /root/torch && \ bash install-deps && \ ./install.sh -b # Export environment variables manually ENV LUA_PATH='/root/.luarocks/share/lua/5.1/?.lua;/root/.luarocks/share/lua/5.1/?/init.lua;/root/torch/install/share/lua/5.1/?.lua;/root/torch/install/share/lua/5.1/?/init.lua;./?.lua;/root/torch/install/share/luajit-2.1.0-beta1/?.lua;/usr/local/share/lua/5.1/?.lua;/usr/local/share/lua/5.1/?/init.lua' ENV LUA_CPATH='/root/.luarocks/lib/lua/5.1/?.so;/root/torch/install/lib/lua/5.1/?.so;./?.so;/usr/local/lib/lua/5.1/?.so;/usr/local/lib/lua/5.1/loadall.so' ENV PATH=/root/torch/install/bin:$PATH ENV LD_LIBRARY_PATH=/root/torch/install/lib:$LD_LIBRARY_PATH ENV DYLD_LIBRARY_PATH=/root/torch/install/lib:$DYLD_LIBRARY_PATH ENV LUA_CPATH='/root/torch/install/lib/?.so;'$LUA_CPATH # Install iTorch RUN luarocks install itorch # Set ~/torch as working directory WORKDIR /root/torch
guilhermemg/dockerfiles
<|start_filename|>manifest.json<|end_filename|> { "name": "AudioViz", "version": "1.0.0", "description": "Audio visualizer", "author": "Vap0r1ze#0126", "license": "MIT", "permissions": [ "use_eud" ] }
ADoesGit/audioviz
<|start_filename|>cmd/kafka-proxy/server.go<|end_filename|> package server import ( "fmt" "github.com/grepplabs/kafka-proxy/config" "github.com/grepplabs/kafka-proxy/proxy" "github.com/oklog/run" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "net" "net/http" _ "net/http/pprof" "os" "os/exec" "os/signal" "syscall" "time" "errors" "strings" "github.com/grepplabs/kafka-proxy/pkg/apis" localauth "github.com/grepplabs/kafka-proxy/plugin/local-auth/shared" tokeninfo "github.com/grepplabs/kafka-proxy/plugin/token-info/shared" tokenprovider "github.com/grepplabs/kafka-proxy/plugin/token-provider/shared" "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-plugin" "github.com/grepplabs/kafka-proxy/pkg/registry" // built-in plugins _ "github.com/grepplabs/kafka-proxy/pkg/libs/googleid-info" _ "github.com/grepplabs/kafka-proxy/pkg/libs/googleid-provider" "github.com/spf13/viper" ) var ( c = new(config.Config) bootstrapServersMapping = make([]string, 0) externalServersMapping = make([]string, 0) dialAddressMapping = make([]string, 0) ) var Server = &cobra.Command{ Use: "server", Short: "Run the kafka-proxy server", PreRunE: func(cmd *cobra.Command, args []string) error { SetLogger() if err := c.InitSASLCredentials(); err != nil { return err } if err := c.InitBootstrapServers(getOrEnvStringSlice(bootstrapServersMapping, "BOOTSTRAP_SERVER_MAPPING")); err != nil { return err } if err := c.InitExternalServers(getOrEnvStringSlice(externalServersMapping, "EXTERNAL_SERVER_MAPPING")); err != nil { return err } if err := c.InitDialAddressMappings(getOrEnvStringSlice(dialAddressMapping, "DIAL_ADDRESS_MAPPING")); err != nil { return err } if err := c.Validate(); err != nil { return err } return nil }, Run: Run, } func getOrEnvStringSlice(value []string, envKey string) []string { if len(bootstrapServersMapping) != 0 { return value } return strings.Fields(os.Getenv(envKey)) } func init() { initFlags() } func initFlags() { // proxy Server.Flags().StringVar(&c.Proxy.DefaultListenerIP, "default-listener-ip", "127.0.0.1", "Default listener IP") Server.Flags().StringVar(&c.Proxy.DynamicAdvertisedListener, "dynamic-advertised-listener", "", "Advertised address for dynamic listeners. If empty, default-listener-ip is used") Server.Flags().StringArrayVar(&bootstrapServersMapping, "bootstrap-server-mapping", []string{}, "Mapping of Kafka bootstrap server address to local address (host:port,host:port(,advhost:advport))") Server.Flags().StringArrayVar(&externalServersMapping, "external-server-mapping", []string{}, "Mapping of Kafka server address to external address (host:port,host:port). A listener for the external address is not started") Server.Flags().StringArrayVar(&dialAddressMapping, "dial-address-mapping", []string{}, "Mapping of target broker address to new one (host:port,host:port). The mapping is performed during connection establishment") Server.Flags().BoolVar(&c.Proxy.DisableDynamicListeners, "dynamic-listeners-disable", false, "Disable dynamic listeners.") Server.Flags().IntVar(&c.Proxy.DynamicSequentialMinPort, "dynamic-sequential-min-port", 0, "If set to non-zero, makes the dynamic listener use a sequential port starting with this value rather than a random port every time.") Server.Flags().IntVar(&c.Proxy.RequestBufferSize, "proxy-request-buffer-size", 4096, "Request buffer size pro tcp connection") Server.Flags().IntVar(&c.Proxy.ResponseBufferSize, "proxy-response-buffer-size", 4096, "Response buffer size pro tcp connection") Server.Flags().IntVar(&c.Proxy.ListenerReadBufferSize, "proxy-listener-read-buffer-size", 0, "Size of the operating system's receive buffer associated with the connection. If zero, system default is used") Server.Flags().IntVar(&c.Proxy.ListenerWriteBufferSize, "proxy-listener-write-buffer-size", 0, "Sets the size of the operating system's transmit buffer associated with the connection. If zero, system default is used") Server.Flags().DurationVar(&c.Proxy.ListenerKeepAlive, "proxy-listener-keep-alive", 60*time.Second, "Keep alive period for an active network connection. If zero, keep-alives are disabled") Server.Flags().BoolVar(&c.Proxy.TLS.Enable, "proxy-listener-tls-enable", false, "Whether or not to use TLS listener") Server.Flags().StringVar(&c.Proxy.TLS.ListenerCertFile, "proxy-listener-cert-file", "", "PEM encoded file with server certificate") Server.Flags().StringVar(&c.Proxy.TLS.ListenerKeyFile, "proxy-listener-key-file", "", "PEM encoded file with private key for the server certificate") Server.Flags().StringVar(&c.Proxy.TLS.ListenerKeyPassword, "proxy-listener-key-password", "", "Password to decrypt rsa private key") Server.Flags().StringVar(&c.Proxy.TLS.CAChainCertFile, "proxy-listener-ca-chain-cert-file", "", "PEM encoded CA's certificate file. If provided, client certificate is required and verified") Server.Flags().StringSliceVar(&c.Proxy.TLS.ListenerCipherSuites, "proxy-listener-cipher-suites", []string{}, "List of supported cipher suites") Server.Flags().StringSliceVar(&c.Proxy.TLS.ListenerCurvePreferences, "proxy-listener-curve-preferences", []string{}, "List of curve preferences") Server.Flags().StringSliceVar(&c.Proxy.TLS.ClientCert.Subjects, "proxy-listener-tls-required-client-subject", []string{}, "Required client certificate subject common name; example; s:/CN=[value]/C=[state]/C=[DE,PL] or r:/CN=[^val.{2}$]/C=[state]/C=[DE,PL]; check manual for more details") // local authentication plugin Server.Flags().BoolVar(&c.Auth.Local.Enable, "auth-local-enable", false, "Enable local SASL/PLAIN authentication performed by listener - SASL handshake will not be passed to kafka brokers") Server.Flags().StringVar(&c.Auth.Local.Command, "auth-local-command", "", "Path to authentication plugin binary") Server.Flags().StringVar(&c.Auth.Local.Mechanism, "auth-local-mechanism", "PLAIN", "SASL mechanism used for local authentication: PLAIN or OAUTHBEARER") Server.Flags().StringArrayVar(&c.Auth.Local.Parameters, "auth-local-param", []string{}, "Authentication plugin parameter") Server.Flags().StringVar(&c.Auth.Local.LogLevel, "auth-local-log-level", "trace", "Log level of the auth plugin") Server.Flags().DurationVar(&c.Auth.Local.Timeout, "auth-local-timeout", 10*time.Second, "Authentication timeout") Server.Flags().BoolVar(&c.Auth.Gateway.Client.Enable, "auth-gateway-client-enable", false, "Enable gateway client authentication") Server.Flags().StringVar(&c.Auth.Gateway.Client.Command, "auth-gateway-client-command", "", "Path to authentication plugin binary") Server.Flags().StringArrayVar(&c.Auth.Gateway.Client.Parameters, "auth-gateway-client-param", []string{}, "Authentication plugin parameter") Server.Flags().StringVar(&c.Auth.Gateway.Client.LogLevel, "auth-gateway-client-log-level", "trace", "Log level of the auth plugin") Server.Flags().StringVar(&c.Auth.Gateway.Client.Method, "auth-gateway-client-method", "", "Authentication method") Server.Flags().Uint64Var(&c.Auth.Gateway.Client.Magic, "auth-gateway-client-magic", 0, "Magic bytes sent in the handshake") Server.Flags().DurationVar(&c.Auth.Gateway.Client.Timeout, "auth-gateway-client-timeout", 10*time.Second, "Authentication timeout") Server.Flags().BoolVar(&c.Auth.Gateway.Server.Enable, "auth-gateway-server-enable", false, "Enable proxy server authentication") Server.Flags().StringVar(&c.Auth.Gateway.Server.Command, "auth-gateway-server-command", "", "Path to authentication plugin binary") Server.Flags().StringArrayVar(&c.Auth.Gateway.Server.Parameters, "auth-gateway-server-param", []string{}, "Authentication plugin parameter") Server.Flags().StringVar(&c.Auth.Gateway.Server.LogLevel, "auth-gateway-server-log-level", "trace", "Log level of the auth plugin") Server.Flags().StringVar(&c.Auth.Gateway.Server.Method, "auth-gateway-server-method", "", "Authentication method") Server.Flags().Uint64Var(&c.Auth.Gateway.Server.Magic, "auth-gateway-server-magic", 0, "Magic bytes sent in the handshake") Server.Flags().DurationVar(&c.Auth.Gateway.Server.Timeout, "auth-gateway-server-timeout", 10*time.Second, "Authentication timeout") // kafka Server.Flags().StringVar(&c.Kafka.ClientID, "kafka-client-id", "kafka-proxy", "An optional identifier to track the source of requests") Server.Flags().IntVar(&c.Kafka.MaxOpenRequests, "kafka-max-open-requests", 256, "Maximal number of open requests pro tcp connection before sending on it blocks") Server.Flags().DurationVar(&c.Kafka.DialTimeout, "kafka-dial-timeout", 15*time.Second, "How long to wait for the initial connection") Server.Flags().DurationVar(&c.Kafka.WriteTimeout, "kafka-write-timeout", 30*time.Second, "How long to wait for a transmit") Server.Flags().DurationVar(&c.Kafka.ReadTimeout, "kafka-read-timeout", 30*time.Second, "How long to wait for a response") Server.Flags().DurationVar(&c.Kafka.KeepAlive, "kafka-keep-alive", 60*time.Second, "Keep alive period for an active network connection. If zero, keep-alives are disabled") Server.Flags().IntVar(&c.Kafka.ConnectionReadBufferSize, "kafka-connection-read-buffer-size", 0, "Size of the operating system's receive buffer associated with the connection. If zero, system default is used") Server.Flags().IntVar(&c.Kafka.ConnectionWriteBufferSize, "kafka-connection-write-buffer-size", 0, "Sets the size of the operating system's transmit buffer associated with the connection. If zero, system default is used") // http://kafka.apache.org/protocol.html#protocol_api_keys Server.Flags().IntSliceVar(&c.Kafka.ForbiddenApiKeys, "forbidden-api-keys", []int{}, "Forbidden Kafka request types. The restriction should prevent some Kafka operations e.g. 20 - DeleteTopics") Server.Flags().BoolVar(&c.Kafka.Producer.Acks0Disabled, "producer-acks-0-disabled", false, "Assume fire-and-forget is never sent by the producer. Enabling this parameter will increase performance") // TLS Server.Flags().BoolVar(&c.Kafka.TLS.Enable, "tls-enable", false, "Whether or not to use TLS when connecting to the broker") Server.Flags().BoolVar(&c.Kafka.TLS.InsecureSkipVerify, "tls-insecure-skip-verify", false, "It controls whether a client verifies the server's certificate chain and host name") Server.Flags().StringVar(&c.Kafka.TLS.ClientCertFile, "tls-client-cert-file", "", "PEM encoded file with client certificate") Server.Flags().StringVar(&c.Kafka.TLS.ClientKeyFile, "tls-client-key-file", "", "PEM encoded file with private key for the client certificate") Server.Flags().StringVar(&c.Kafka.TLS.ClientKeyPassword, "tls-client-key-password", "", "Password to decrypt rsa private key") Server.Flags().StringVar(&c.Kafka.TLS.CAChainCertFile, "tls-ca-chain-cert-file", "", "PEM encoded CA's certificate file") //Same TLS client cert tls-same-client-cert-enable Server.Flags().BoolVar(&c.Kafka.TLS.SameClientCertEnable, "tls-same-client-cert-enable", false, "Use only when mutual TLS is enabled on proxy and broker. It controls whether a proxy validates if proxy client certificate exactly matches brokers client cert (tls-client-cert-file)") // SASL by Proxy Server.Flags().BoolVar(&c.Kafka.SASL.Enable, "sasl-enable", false, "Connect using SASL") Server.Flags().StringVar(&c.Kafka.SASL.Username, "sasl-username", "", "SASL user name") Server.Flags().StringVar(&c.Kafka.SASL.Password, "sasl-password", "", "SASL user password") Server.Flags().StringVar(&c.Kafka.SASL.JaasConfigFile, "sasl-jaas-config-file", "", "Location of JAAS config file with SASL username and password") Server.Flags().StringVar(&c.Kafka.SASL.Method, "sasl-method", "PLAIN", "SASL method to use (PLAIN, SCRAM-SHA-256, SCRAM-SHA-512") // SASL by Proxy plugin Server.Flags().BoolVar(&c.Kafka.SASL.Plugin.Enable, "sasl-plugin-enable", false, "Use plugin for SASL authentication") Server.Flags().StringVar(&c.Kafka.SASL.Plugin.Command, "sasl-plugin-command", "", "Path to authentication plugin binary") Server.Flags().StringVar(&c.Kafka.SASL.Plugin.Mechanism, "sasl-plugin-mechanism", "OAUTHBEARER", "SASL mechanism used for proxy authentication: PLAIN or OAUTHBEARER") Server.Flags().StringArrayVar(&c.Kafka.SASL.Plugin.Parameters, "sasl-plugin-param", []string{}, "Authentication plugin parameter") Server.Flags().StringVar(&c.Kafka.SASL.Plugin.LogLevel, "sasl-plugin-log-level", "trace", "Log level of the auth plugin") Server.Flags().DurationVar(&c.Kafka.SASL.Plugin.Timeout, "sasl-plugin-timeout", 10*time.Second, "Authentication timeout") // Web Server.Flags().BoolVar(&c.Http.Disable, "http-disable", false, "Disable HTTP endpoints") Server.Flags().StringVar(&c.Http.ListenAddress, "http-listen-address", "0.0.0.0:9080", "Address that kafka-proxy is listening on") Server.Flags().StringVar(&c.Http.MetricsPath, "http-metrics-path", "/metrics", "Path on which to expose metrics") Server.Flags().StringVar(&c.Http.HealthPath, "http-health-path", "/health", "Path on which to health endpoint") // Debug Server.Flags().BoolVar(&c.Debug.Enabled, "debug-enable", false, "Enable Debug endpoint") Server.Flags().StringVar(&c.Debug.ListenAddress, "debug-listen-address", "0.0.0.0:6060", "Debug listen address") // Logging Server.Flags().StringVar(&c.Log.Format, "log-format", "text", "Log format text or json") Server.Flags().StringVar(&c.Log.Level, "log-level", "info", "Log level debug, info, warning, error, fatal or panic") Server.Flags().StringVar(&c.Log.LevelFieldName, "log-level-fieldname", "@level", "Log level fieldname for json format") Server.Flags().StringVar(&c.Log.TimeFiledName, "log-time-fieldname", "@timestamp", "Time fieldname for json format") Server.Flags().StringVar(&c.Log.MsgFiledName, "log-msg-fieldname", "@message", "Message fieldname for json format") // Connect through Socks5 or HTTP CONNECT to Kafka Server.Flags().StringVar(&c.ForwardProxy.Url, "forward-proxy", "", "URL of the forward proxy. Supported schemas are socks5 and http") viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) viper.AutomaticEnv() // read in environment variables that match } func Run(_ *cobra.Command, _ []string) { logrus.Infof("Starting kafka-proxy version %s", config.Version) var localPasswordAuthenticator apis.PasswordAuthenticator var localTokenAuthenticator apis.TokenInfo if c.Auth.Local.Enable { switch c.Auth.Local.Mechanism { case "PLAIN": var err error factory, ok := registry.GetComponent(new(apis.PasswordAuthenticatorFactory), c.Auth.Local.Command).(apis.PasswordAuthenticatorFactory) if ok { logrus.Infof("Using built-in '%s' PasswordAuthenticator for local PasswordAuthenticator", c.Auth.Local.Command) localPasswordAuthenticator, err = factory.New(c.Auth.Local.Parameters) if err != nil { logrus.Fatal(err) } } else { client := NewPluginClient(localauth.Handshake, localauth.PluginMap, c.Auth.Local.LogLevel, c.Auth.Local.Command, c.Auth.Local.Parameters) defer client.Kill() rpcClient, err := client.Client() if err != nil { logrus.Fatal(err) } raw, err := rpcClient.Dispense("passwordAuthenticator") if err != nil { logrus.Fatal(err) } localPasswordAuthenticator, ok = raw.(apis.PasswordAuthenticator) if !ok { logrus.Fatal(errors.New("unsupported PasswordAuthenticator plugin type")) } } case "OAUTHBEARER": var err error factory, ok := registry.GetComponent(new(apis.TokenInfoFactory), c.Auth.Local.Command).(apis.TokenInfoFactory) if ok { logrus.Infof("Using built-in '%s' TokenInfo for local TokenAuthenticator", c.Auth.Local.Command) localTokenAuthenticator, err = factory.New(c.Auth.Local.Parameters) if err != nil { logrus.Fatal(err) } } else { client := NewPluginClient(tokeninfo.Handshake, tokeninfo.PluginMap, c.Auth.Local.LogLevel, c.Auth.Local.Command, c.Auth.Local.Parameters) defer client.Kill() rpcClient, err := client.Client() if err != nil { logrus.Fatal(err) } raw, err := rpcClient.Dispense("tokenInfo") if err != nil { logrus.Fatal(err) } localTokenAuthenticator, ok = raw.(apis.TokenInfo) if !ok { logrus.Fatal(errors.New("unsupported TokenInfo plugin type")) } } default: logrus.Fatal(errors.New("unsupported local auth mechanism")) } } var saslTokenProvider apis.TokenProvider if c.Kafka.SASL.Plugin.Enable { switch c.Kafka.SASL.Plugin.Mechanism { case "OAUTHBEARER": var err error factory, ok := registry.GetComponent(new(apis.TokenProviderFactory), c.Kafka.SASL.Plugin.Command).(apis.TokenProviderFactory) if ok { logrus.Infof("Using built-in '%s' TokenProvider for sasl authentication", c.Kafka.SASL.Plugin.Command) saslTokenProvider, err = factory.New(c.Kafka.SASL.Plugin.Parameters) if err != nil { logrus.Fatal(err) } } else { client := NewPluginClient(tokenprovider.Handshake, tokenprovider.PluginMap, c.Kafka.SASL.Plugin.LogLevel, c.Kafka.SASL.Plugin.Command, c.Kafka.SASL.Plugin.Parameters) defer client.Kill() rpcClient, err := client.Client() if err != nil { logrus.Fatal(err) } raw, err := rpcClient.Dispense("tokenProvider") if err != nil { logrus.Fatal(err) } saslTokenProvider, ok = raw.(apis.TokenProvider) if !ok { logrus.Fatal(errors.New("unsupported TokenProvider plugin type")) } } default: logrus.Fatal(errors.New("unsupported sasl auth mechanism")) } } var gatewayTokenProvider apis.TokenProvider if c.Auth.Gateway.Client.Enable { var err error factory, ok := registry.GetComponent(new(apis.TokenProviderFactory), c.Auth.Gateway.Client.Command).(apis.TokenProviderFactory) if ok { logrus.Infof("Using built-in '%s' TokenProvider for Gateway Client", c.Auth.Gateway.Client.Command) gatewayTokenProvider, err = factory.New(c.Auth.Gateway.Client.Parameters) if err != nil { logrus.Fatal(err) } } else { client := NewPluginClient(tokenprovider.Handshake, tokenprovider.PluginMap, c.Auth.Gateway.Client.LogLevel, c.Auth.Gateway.Client.Command, c.Auth.Gateway.Client.Parameters) defer client.Kill() rpcClient, err := client.Client() if err != nil { logrus.Fatal(err) } raw, err := rpcClient.Dispense("tokenProvider") if err != nil { logrus.Fatal(err) } gatewayTokenProvider, ok = raw.(apis.TokenProvider) if !ok { logrus.Fatal(errors.New("unsupported TokenProvider plugin type")) } } } var gatewayTokenInfo apis.TokenInfo if c.Auth.Gateway.Server.Enable { var err error factory, ok := registry.GetComponent(new(apis.TokenInfoFactory), c.Auth.Gateway.Server.Command).(apis.TokenInfoFactory) if ok { logrus.Infof("Using built-in '%s' TokenInfo for Gateway Server", c.Auth.Gateway.Server.Command) gatewayTokenInfo, err = factory.New(c.Auth.Gateway.Server.Parameters) if err != nil { logrus.Fatal(err) } } else { client := NewPluginClient(tokeninfo.Handshake, tokeninfo.PluginMap, c.Auth.Gateway.Server.LogLevel, c.Auth.Gateway.Server.Command, c.Auth.Gateway.Server.Parameters) defer client.Kill() rpcClient, err := client.Client() if err != nil { logrus.Fatal(err) } raw, err := rpcClient.Dispense("tokenInfo") if err != nil { logrus.Fatal(err) } gatewayTokenInfo, ok = raw.(apis.TokenInfo) if !ok { logrus.Fatal(errors.New("unsupported TokenInfo plugin type")) } } } var g run.Group { // All active connections are stored in this variable. connset := proxy.NewConnSet() prometheus.MustRegister(proxy.NewCollector(connset)) listeners, err := proxy.NewListeners(c) if err != nil { logrus.Fatal(err) } connSrc, err := listeners.ListenInstances(c.Proxy.BootstrapServers) if err != nil { logrus.Fatal(err) } proxyClient, err := proxy.NewClient(connset, c, listeners.GetNetAddressMapping, localPasswordAuthenticator, localTokenAuthenticator, saslTokenProvider, gatewayTokenProvider, gatewayTokenInfo) if err != nil { logrus.Fatal(err) } g.Add(func() error { logrus.Print("Ready for new connections") return proxyClient.Run(connSrc) }, func(error) { proxyClient.Close() }) } { cancelInterrupt := make(chan struct{}) g.Add(func() error { c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) select { case sig := <-c: return fmt.Errorf("received signal %s", sig) case <-cancelInterrupt: return nil } }, func(error) { close(cancelInterrupt) }) } if !c.Http.Disable { httpListener, err := net.Listen("tcp", c.Http.ListenAddress) if err != nil { logrus.Fatal(err) } g.Add(func() error { return http.Serve(httpListener, NewHTTPHandler()) }, func(error) { httpListener.Close() }) } if c.Debug.Enabled { // https://golang.org/pkg/net/http/pprof/ // https://jvns.ca/blog/2017/09/24/profiling-go-with-pprof/ debugListener, err := net.Listen("tcp", c.Debug.ListenAddress) if err != nil { logrus.Fatal(err) } g.Add(func() error { return http.Serve(debugListener, http.DefaultServeMux) }, func(error) { debugListener.Close() }) } err := g.Run() logrus.Info("Exit ", err) } func NewHTTPHandler() http.Handler { m := http.NewServeMux() m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte( `<html> <head> <title>kafka-proxy service</title> </head> <body> <h1>Kafka Proxy</h1> <p><a href='` + c.Http.MetricsPath + `'>Metrics</a></p> </body> </html>`)) }) m.HandleFunc(c.Http.HealthPath, func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`OK`)) }) m.Handle(c.Http.MetricsPath, promhttp.Handler()) return m } func SetLogger() { if c.Log.Format == "json" { formatter := &logrus.JSONFormatter{ FieldMap: logrus.FieldMap{ logrus.FieldKeyTime: c.Log.TimeFiledName, logrus.FieldKeyLevel: c.Log.LevelFieldName, logrus.FieldKeyMsg: c.Log.MsgFiledName, }, TimestampFormat: time.RFC3339, } logrus.SetFormatter(formatter) } else { logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true}) } level, err := logrus.ParseLevel(c.Log.Level) if err != nil { logrus.Errorf("Couldn't parse log level: %s", c.Log.Level) level = logrus.InfoLevel } logrus.SetLevel(level) } func NewPluginClient(handshakeConfig plugin.HandshakeConfig, plugins map[string]plugin.Plugin, logLevel string, command string, params []string) *plugin.Client { jsonFormat := false if c.Log.Format == "json" { jsonFormat = true } logger := hclog.New(&hclog.LoggerOptions{ Output: os.Stdout, Level: hclog.LevelFromString(logLevel), Name: "plugin", JSONFormat: jsonFormat, TimeFormat: time.RFC3339, }) return plugin.NewClient(&plugin.ClientConfig{ HandshakeConfig: handshakeConfig, Plugins: plugins, Logger: logger, Cmd: exec.Command(command, params...), AllowedProtocols: []plugin.Protocol{ plugin.ProtocolNetRPC, plugin.ProtocolGRPC}, }) }
p53/kafka-proxy
<|start_filename|>Bubble-Sort.cpp<|end_filename|> #include <cstdio> #include <cstdlib> using namespace std; int data[1000]; void bubble_sort(int *d, int n) { for (int k = 1; k < n; k++) { for (int i = 1; i < n; i++) { if (d[i] < d[i - 1]) { int temp = d[i]; d[i] = d[i - 1]; d[i - 1] = temp; } } } } int main() { for (int i = 0; i < 1000; i++) { data[i] = rand(); } bubble_sort(data, 1000); for (int i = 0; i < 1000; i++) { printf("%d\n", data[i]); } return 0; }
white-WB/CLRS
<|start_filename|>formapi/templates/formapi/api/form.html<|end_filename|> {% extends 'formapi/base.html' %} {% block content %} <div class="span8"> <div class="hero-unit"> <h3>Call</h3> <p><strong>API version:</strong> {{ version }}</p> <p><strong>Name:</strong> {{ call }}</p> {%comment %}<p><strong>Url:</strong> {% url "api_view" version call %}</p>{% endcomment %} <h4>Description</h4> <p>{{ docstring }}</p> <h3>Test Form</h3> <form action="#" method="post"> <p><label for="id_key">key:</label> <input type="text" name="key" id="id_key"/></p> <p><label for="id_sign">sign:</label><input type="text" name="sign" id="id_sign"/></p> {{ form.as_p }} <input type="submit" value="Submit" /> </form> </div> </div> {% endblock %} <|start_filename|>formapi/templates/formapi/api/discover.html<|end_filename|> {% extends 'formapi/base.html' %} {% block content %} <div class="span8"> <div class="hero-unit"> <h1>API Calls</h1> <p>The sidebar shows the api calls sorted by api version.</p> </div> </div><!--/span--> {% endblock %}
beshrkayali/django-formapi
<|start_filename|>minisched/initialize.go<|end_filename|> package minisched import ( "fmt" "k8s.io/apimachinery/pkg/util/sets" "github.com/sanposhiho/mini-kube-scheduler/minisched/plugins/score/nodenumber" "github.com/sanposhiho/mini-kube-scheduler/minisched/queue" "github.com/sanposhiho/mini-kube-scheduler/minisched/waitingpod" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/informers" clientset "k8s.io/client-go/kubernetes" "k8s.io/kubernetes/pkg/scheduler/framework" "k8s.io/kubernetes/pkg/scheduler/framework/plugins/nodeunschedulable" ) type Scheduler struct { SchedulingQueue *queue.SchedulingQueue client clientset.Interface waitingPods map[types.UID]*waitingpod.WaitingPod filterPlugins []framework.FilterPlugin preScorePlugins []framework.PreScorePlugin scorePlugins []framework.ScorePlugin permitPlugins []framework.PermitPlugin } // ======= // funcs for initialize // ======= func New( client clientset.Interface, informerFactory informers.SharedInformerFactory, ) (*Scheduler, error) { sched := &Scheduler{ client: client, waitingPods: map[types.UID]*waitingpod.WaitingPod{}, } filterP, err := createFilterPlugins(sched) if err != nil { return nil, fmt.Errorf("create filter plugins: %w", err) } sched.filterPlugins = filterP preScoreP, err := createPreScorePlugins(sched) if err != nil { return nil, fmt.Errorf("create pre score plugins: %w", err) } sched.preScorePlugins = preScoreP scoreP, err := createScorePlugins(sched) if err != nil { return nil, fmt.Errorf("create score plugins: %w", err) } sched.scorePlugins = scoreP permitP, err := createPermitPlugins(sched) if err != nil { return nil, fmt.Errorf("create permit plugins: %w", err) } sched.permitPlugins = permitP events, err := eventsToRegister(sched) if err != nil { return nil, fmt.Errorf("create gvks: %w") } sched.SchedulingQueue = queue.New(events) addAllEventHandlers(sched, informerFactory, unionedGVKs(events)) return sched, nil } func createFilterPlugins(h waitingpod.Handle) ([]framework.FilterPlugin, error) { // nodeunschedulable is FilterPlugin. nodeunschedulableplugin, err := createNodeUnschedulablePlugin() if err != nil { return nil, fmt.Errorf("create nodeunschedulable plugin: %w", err) } // We use nodeunschedulable plugin only. filterPlugins := []framework.FilterPlugin{ nodeunschedulableplugin.(framework.FilterPlugin), } return filterPlugins, nil } func createPreScorePlugins(h waitingpod.Handle) ([]framework.PreScorePlugin, error) { // nodenumber is FilterPlugin. nodenumberplugin, err := createNodeNumberPlugin(h) if err != nil { return nil, fmt.Errorf("create nodenumber plugin: %w", err) } // We use nodenumber plugin only. preScorePlugins := []framework.PreScorePlugin{ nodenumberplugin.(framework.PreScorePlugin), } return preScorePlugins, nil } func createScorePlugins(h waitingpod.Handle) ([]framework.ScorePlugin, error) { // nodenumber is FilterPlugin. nodenumberplugin, err := createNodeNumberPlugin(h) if err != nil { return nil, fmt.Errorf("create nodenumber plugin: %w", err) } // We use nodenumber plugin only. filterPlugins := []framework.ScorePlugin{ nodenumberplugin.(framework.ScorePlugin), } return filterPlugins, nil } func createPermitPlugins(h waitingpod.Handle) ([]framework.PermitPlugin, error) { // nodenumber is PermitPlugin. nodenumberplugin, err := createNodeNumberPlugin(h) if err != nil { return nil, fmt.Errorf("create nodenumber plugin: %w", err) } // We use nodenumber plugin only. permitPlugins := []framework.PermitPlugin{ nodenumberplugin.(framework.PermitPlugin), } return permitPlugins, nil } func eventsToRegister(h waitingpod.Handle) (map[framework.ClusterEvent]sets.String, error) { nunschedulablePlugin, err := createNodeUnschedulablePlugin() if err != nil { return nil, fmt.Errorf("create node unschedulable plugin: %w", err) } nnumberPlugin, err := createNodeNumberPlugin(h) if err != nil { return nil, fmt.Errorf("create node number plugin: %w", err) } clusterEventMap := make(map[framework.ClusterEvent]sets.String) nunschedulablePluginEvents := nunschedulablePlugin.(framework.EnqueueExtensions).EventsToRegister() registerClusterEvents(nunschedulablePlugin.Name(), clusterEventMap, nunschedulablePluginEvents) nnumberPluginEvents := nnumberPlugin.(framework.EnqueueExtensions).EventsToRegister() registerClusterEvents(nunschedulablePlugin.Name(), clusterEventMap, nnumberPluginEvents) return clusterEventMap, nil } func registerClusterEvents(name string, eventToPlugins map[framework.ClusterEvent]sets.String, evts []framework.ClusterEvent) { for _, evt := range evts { if eventToPlugins[evt] == nil { eventToPlugins[evt] = sets.NewString(name) } else { eventToPlugins[evt].Insert(name) } } } func unionedGVKs(m map[framework.ClusterEvent]sets.String) map[framework.GVK]framework.ActionType { gvkMap := make(map[framework.GVK]framework.ActionType) for evt := range m { if _, ok := gvkMap[evt.Resource]; ok { gvkMap[evt.Resource] |= evt.ActionType } else { gvkMap[evt.Resource] = evt.ActionType } } return gvkMap } // ===== // initialize plugins // ===== // // we only use nodeunschedulable and nodenumber // Original kube-scheduler is implemented so that we can select which plugins to enable var ( nodeunschedulableplugin framework.Plugin nodenumberplugin framework.Plugin ) func createNodeUnschedulablePlugin() (framework.Plugin, error) { if nodeunschedulableplugin != nil { return nodeunschedulableplugin, nil } p, err := nodeunschedulable.New(nil, nil) nodeunschedulableplugin = p return p, err } func createNodeNumberPlugin(h waitingpod.Handle) (framework.Plugin, error) { if nodenumberplugin != nil { return nodenumberplugin, nil } p, err := nodenumber.New(nil, h) nodenumberplugin = p return p, err } <|start_filename|>k8sapiserver/k8sapiserver.go<|end_filename|> package k8sapiserver import ( "context" "fmt" "net" "net/http" "net/http/httptest" "time" "github.com/google/uuid" "golang.org/x/xerrors" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/wait" authauthenticator "k8s.io/apiserver/pkg/authentication/authenticator" "k8s.io/apiserver/pkg/authentication/authenticatorfactory" authenticatorunion "k8s.io/apiserver/pkg/authentication/request/union" "k8s.io/apiserver/pkg/authentication/user" "k8s.io/apiserver/pkg/authorization/authorizerfactory" authorizerunion "k8s.io/apiserver/pkg/authorization/union" "k8s.io/apiserver/pkg/endpoints/openapi" genericapiserver "k8s.io/apiserver/pkg/server" "k8s.io/apiserver/pkg/server/options" serverstorage "k8s.io/apiserver/pkg/server/storage" "k8s.io/apiserver/pkg/storage/storagebackend" utilflowcontrol "k8s.io/apiserver/pkg/util/flowcontrol" "k8s.io/client-go/informers" clientset "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" "k8s.io/component-base/version" "k8s.io/klog/v2" openapicommon "k8s.io/kube-openapi/pkg/common" "k8s.io/kube-openapi/pkg/validation/spec" "k8s.io/kubernetes/pkg/api/legacyscheme" "k8s.io/kubernetes/pkg/controlplane" "k8s.io/kubernetes/pkg/kubeapiserver" kubeletclient "k8s.io/kubernetes/pkg/kubelet/client" generated "github.com/sanposhiho/mini-kube-scheduler/k8sapiserver/openapi" ) // StartAPIServer starts API server, and it make panic when a error happen. func StartAPIServer(etcdURL string) (*restclient.Config, func(), error) { h := &APIServerHolder{Initialized: make(chan struct{})} s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { <-h.Initialized h.M.GenericAPIServer.Handler.ServeHTTP(w, req) })) c := NewControlPlaneConfigWithOptions(s.URL, etcdURL) _, _, closeFn, err := startAPIServer(c, s, h) if err != nil { return nil, nil, xerrors.Errorf("start API server: %w", err) } cfg := &restclient.Config{ Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}, QPS: 5000.0, Burst: 5000, } shutdownFunc := func() { klog.Infof("destroying API server") closeFn() s.Close() klog.Infof("destroyed API server") } return cfg, shutdownFunc, nil } func defaultOpenAPIConfig() *openapicommon.Config { openAPIConfig := genericapiserver.DefaultOpenAPIConfig(generated.GetOpenAPIDefinitions, openapi.NewDefinitionNamer(legacyscheme.Scheme)) openAPIConfig.Info = &spec.Info{ InfoProps: spec.InfoProps{ Title: "Kubernetes", Version: "unversioned", }, } openAPIConfig.DefaultResponse = &spec.Response{ ResponseProps: spec.ResponseProps{ Description: "Default Response.", }, } openAPIConfig.GetDefinitions = generated.GetOpenAPIDefinitions return openAPIConfig } //nolint:funlen func NewControlPlaneConfigWithOptions(serverURL, etcdURL string) *controlplane.Config { etcdOptions := options.NewEtcdOptions(storagebackend.NewDefaultConfig(uuid.New().String(), nil)) etcdOptions.StorageConfig.Transport.ServerList = []string{etcdURL} storageConfig := kubeapiserver.NewStorageFactoryConfig() storageConfig.APIResourceConfig = serverstorage.NewResourceConfig() completedStorageConfig, err := storageConfig.Complete(etcdOptions) if err != nil { panic(err) } storageFactory, err := completedStorageConfig.New() if err != nil { panic(err) } genericConfig := genericapiserver.NewConfig(legacyscheme.Codecs) kubeVersion := version.Get() if len(kubeVersion.Major) == 0 { kubeVersion.Major = "1" } if len(kubeVersion.Minor) == 0 { kubeVersion.Minor = "22" } genericConfig.Version = &kubeVersion genericConfig.SecureServing = &genericapiserver.SecureServingInfo{Listener: fakeLocalhost443Listener{}} err = etcdOptions.ApplyWithStorageFactoryTo(storageFactory, genericConfig) if err != nil { panic(err) } cfg := &controlplane.Config{ GenericConfig: genericConfig, ExtraConfig: controlplane.ExtraConfig{ APIResourceConfigSource: controlplane.DefaultAPIResourceConfigSource(), StorageFactory: storageFactory, KubeletClientConfig: kubeletclient.KubeletClientConfig{Port: 10250}, APIServerServicePort: 443, MasterCount: 1, }, } // set the loopback client config cfg.GenericConfig.LoopbackClientConfig = &restclient.Config{QPS: 50, Burst: 100, ContentConfig: restclient.ContentConfig{NegotiatedSerializer: legacyscheme.Codecs}} cfg.GenericConfig.LoopbackClientConfig.Host = serverURL privilegedLoopbackToken := uuid.New().String() // wrap any available authorizer tokens := make(map[string]*user.DefaultInfo) tokens[privilegedLoopbackToken] = &user.DefaultInfo{ Name: user.APIServerUser, UID: uuid.New().String(), Groups: []string{user.SystemPrivilegedGroup}, } tokenAuthenticator := authenticatorfactory.NewFromTokens(tokens, cfg.GenericConfig.Authentication.APIAudiences) cfg.GenericConfig.Authentication.Authenticator = authenticatorunion.New(tokenAuthenticator, authauthenticator.RequestFunc(alwaysEmpty)) tokenAuthorizer := authorizerfactory.NewPrivilegedGroups(user.SystemPrivilegedGroup) cfg.GenericConfig.Authorization.Authorizer = authorizerunion.New(tokenAuthorizer, authorizerfactory.NewAlwaysAllowAuthorizer()) cfg.GenericConfig.LoopbackClientConfig.BearerToken = <PASSWORD>LoopbackToken cfg.GenericConfig.PublicAddress = net.ParseIP("192.168.10.4") cfg.GenericConfig.SecureServing = &genericapiserver.SecureServingInfo{Listener: fakeLocalhost443Listener{}} cfg.GenericConfig.OpenAPIConfig = defaultOpenAPIConfig() return cfg } type fakeLocalhost443Listener struct{} func (fakeLocalhost443Listener) Accept() (net.Conn, error) { return nil, nil } func (fakeLocalhost443Listener) Close() error { return nil } func (fakeLocalhost443Listener) Addr() net.Addr { return &net.TCPAddr{ IP: net.IPv4(127, 0, 0, 1), Port: 443, } } // startAPIServer starts a kubernetes API server and an httpserver to handle api requests. //nolint:funlen func startAPIServer(controlPlaneConfig *controlplane.Config, s *httptest.Server, apiServerReceiver *APIServerHolder) (*controlplane.Instance, *httptest.Server, func(), error) { var m *controlplane.Instance stopCh := make(chan struct{}) closeFn := func() { if m != nil { if err := m.GenericAPIServer.RunPreShutdownHooks(); err != nil { klog.Errorf("failed to run pre-shutdown hooks for api server: %v", err) } } close(stopCh) s.Close() } clientset, err := clientset.NewForConfig(controlPlaneConfig.GenericConfig.LoopbackClientConfig) if err != nil { return nil, nil, nil, xerrors.Errorf("create clientset: %w", err) } controlPlaneConfig.ExtraConfig.VersionedInformers = informers.NewSharedInformerFactory(clientset, controlPlaneConfig.GenericConfig.LoopbackClientConfig.Timeout) controlPlaneConfig.GenericConfig.FlowControl = utilflowcontrol.New( controlPlaneConfig.ExtraConfig.VersionedInformers, clientset.FlowcontrolV1beta1(), controlPlaneConfig.GenericConfig.MaxRequestsInFlight+controlPlaneConfig.GenericConfig.MaxMutatingRequestsInFlight, controlPlaneConfig.GenericConfig.RequestTimeout/4, ) controlPlaneConfig.ExtraConfig.ServiceIPRange = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(24, 32)} m, err = controlPlaneConfig.Complete().New(genericapiserver.NewEmptyDelegate()) if err != nil { // We log the error first so that even if closeFn crashes, the error is shown klog.Errorf("error in bringing up the apiserver: %v", err) closeFn() return nil, nil, nil, fmt.Errorf("bringing up the apiserver: %w", err) } apiServerReceiver.SetAPIServer(m) m.GenericAPIServer.PrepareRun() m.GenericAPIServer.RunPostStartHooks(stopCh) cfg := *controlPlaneConfig.GenericConfig.LoopbackClientConfig cfg.ContentConfig.GroupVersion = &schema.GroupVersion{} privilegedClient, err := restclient.RESTClientFor(&cfg) if err != nil { closeFn() return nil, nil, nil, xerrors.Errorf("create restclient: %w", err) } var lastHealthContent []byte err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() result := privilegedClient.Get().AbsPath("/healthz").Do(ctx) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } lastHealthContent, _ = result.Raw() return false, nil }) if err != nil { closeFn() klog.Errorf("last health content: %q", string(lastHealthContent)) return nil, nil, nil, xerrors.Errorf("last health content: %w", err) } return m, s, closeFn, nil } // alwaysEmpty simulates "no authentication" for old tests. func alwaysEmpty(_ *http.Request) (*authauthenticator.Response, bool, error) { return &authauthenticator.Response{ User: &user.DefaultInfo{ Name: "", }, }, true, nil } // APIServerHolder implements. type APIServerHolder struct { Initialized chan struct{} M *controlplane.Instance } // SetAPIServer assigns the current API server. func (h *APIServerHolder) SetAPIServer(m *controlplane.Instance) { h.M = m close(h.Initialized) } <|start_filename|>minisched/eventhandler.go<|end_filename|> package minisched import ( "fmt" "k8s.io/kubernetes/pkg/scheduler/framework" v1 "k8s.io/api/core/v1" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/informers" "k8s.io/client-go/tools/cache" ) func addAllEventHandlers( sched *Scheduler, informerFactory informers.SharedInformerFactory, gvkMap map[framework.GVK]framework.ActionType, ) { // unscheduled pod informerFactory.Core().V1().Pods().Informer().AddEventHandler( cache.FilteringResourceEventHandler{ FilterFunc: func(obj interface{}) bool { switch t := obj.(type) { case *v1.Pod: return !assignedPod(t) default: return false } }, Handler: cache.ResourceEventHandlerFuncs{ // Consider only adding. AddFunc: sched.addPodToSchedulingQueue, }, }, ) buildEvtResHandler := func(at framework.ActionType, gvk framework.GVK, shortGVK string) cache.ResourceEventHandlerFuncs { funcs := cache.ResourceEventHandlerFuncs{} if at&framework.Add != 0 { evt := framework.ClusterEvent{Resource: gvk, ActionType: framework.Add, Label: fmt.Sprintf("%vAdd", shortGVK)} funcs.AddFunc = func(_ interface{}) { sched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(evt) } } if at&framework.Update != 0 { evt := framework.ClusterEvent{Resource: gvk, ActionType: framework.Update, Label: fmt.Sprintf("%vUpdate", shortGVK)} funcs.UpdateFunc = func(_, _ interface{}) { sched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(evt) } } if at&framework.Delete != 0 { evt := framework.ClusterEvent{Resource: gvk, ActionType: framework.Delete, Label: fmt.Sprintf("%vDelete", shortGVK)} funcs.DeleteFunc = func(_ interface{}) { sched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(evt) } } return funcs } for gvk, at := range gvkMap { switch gvk { case framework.Node: informerFactory.Core().V1().Nodes().Informer().AddEventHandler( buildEvtResHandler(at, framework.Node, "Node"), ) //case framework.CSINode: //case framework.CSIDriver: //case framework.CSIStorageCapacity: //case framework.PersistentVolume: //case framework.PersistentVolumeClaim: //case framework.StorageClass: //case framework.Service: //default: } } } // assignedPod selects pods that are assigned (scheduled and running). func assignedPod(pod *v1.Pod) bool { return len(pod.Spec.NodeName) != 0 } func (sched *Scheduler) addPodToSchedulingQueue(obj interface{}) { pod := obj.(*v1.Pod) if err := sched.SchedulingQueue.Add(pod); err != nil { utilruntime.HandleError(fmt.Errorf("unable to queue %T: %v", obj, err)) } } <|start_filename|>minisched/minisched.go<|end_filename|> package minisched import ( "context" "fmt" "math/rand" "time" "github.com/sanposhiho/mini-kube-scheduler/minisched/waitingpod" "k8s.io/apimachinery/pkg/types" "k8s.io/kubernetes/pkg/scheduler/framework" "k8s.io/klog/v2" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/wait" ) // ====== // main logic // ====== func (sched *Scheduler) Run(ctx context.Context) { wait.UntilWithContext(ctx, sched.scheduleOne, 0) } func (sched *Scheduler) scheduleOne(ctx context.Context) { klog.Info("minischeduler: Try to get pod from queue....") pod := sched.SchedulingQueue.NextPod() klog.Info("minischeduler: Start schedule: pod name:" + pod.Name) state := framework.NewCycleState() // get nodes nodes, err := sched.client.CoreV1().Nodes().List(ctx, metav1.ListOptions{}) if err != nil { klog.Error(err) sched.ErrorFunc(pod, err) return } klog.Info("minischeduler: Get Nodes successfully") klog.Info("minischeduler: got nodes: ", nodes) // filter fasibleNodes, err := sched.RunFilterPlugins(ctx, state, pod, nodes.Items) if err != nil { klog.Error(err) sched.ErrorFunc(pod, err) return } klog.Info("minischeduler: ran filter plugins successfully") klog.Info("minischeduler: fasible nodes: ", fasibleNodes) // pre score status := sched.RunPreScorePlugins(ctx, state, pod, fasibleNodes) if !status.IsSuccess() { klog.Error(status.AsError()) sched.ErrorFunc(pod, err) return } klog.Info("minischeduler: ran pre score plugins successfully") // score score, status := sched.RunScorePlugins(ctx, state, pod, fasibleNodes) if !status.IsSuccess() { klog.Error(status.AsError()) sched.ErrorFunc(pod, err) return } klog.Info("minischeduler: ran score plugins successfully") klog.Info("minischeduler: score results", score) nodename, err := sched.selectHost(score) if err != nil { klog.Error(err) sched.ErrorFunc(pod, err) return } klog.Info("minischeduler: pod " + pod.Name + " will be bound to node " + nodename) status = sched.RunPermitPlugins(ctx, state, pod, nodename) if status.Code() != framework.Wait && !status.IsSuccess() { klog.Error(status.AsError()) sched.ErrorFunc(pod, err) return } go func() { ctx := ctx status := sched.WaitOnPermit(ctx, pod) if !status.IsSuccess() { klog.Error(status.AsError()) sched.ErrorFunc(pod, err) return } if err := sched.Bind(ctx, nil, pod, nodename); err != nil { klog.Error(err) sched.ErrorFunc(pod, err) return } klog.Info("minischeduler: Bind Pod successfully") }() } func (sched *Scheduler) RunFilterPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodes []v1.Node) ([]*v1.Node, error) { feasibleNodes := make([]*v1.Node, 0, len(nodes)) diagnosis := framework.Diagnosis{ NodeToStatusMap: make(framework.NodeToStatusMap), UnschedulablePlugins: sets.NewString(), } // TODO: consider about nominated pod for _, n := range nodes { n := n nodeInfo := framework.NewNodeInfo() nodeInfo.SetNode(&n) status := framework.NewStatus(framework.Success) for _, pl := range sched.filterPlugins { status = pl.Filter(ctx, state, pod, nodeInfo) if !status.IsSuccess() { status.SetFailedPlugin(pl.Name()) diagnosis.UnschedulablePlugins.Insert(status.FailedPlugin()) break } } if status.IsSuccess() { feasibleNodes = append(feasibleNodes, nodeInfo.Node()) } } if len(feasibleNodes) == 0 { return nil, &framework.FitError{ Pod: pod, Diagnosis: diagnosis, } } return feasibleNodes, nil } func (sched *Scheduler) RunPreScorePlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status { for _, pl := range sched.preScorePlugins { status := pl.PreScore(ctx, state, pod, nodes) if !status.IsSuccess() { return status } } return nil } func (sched *Scheduler) RunScorePlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) (framework.NodeScoreList, *framework.Status) { scoresMap := sched.createPluginToNodeScores(nodes) for index, n := range nodes { for _, pl := range sched.scorePlugins { score, status := pl.Score(ctx, state, pod, n.Name) if !status.IsSuccess() { return nil, status } scoresMap[pl.Name()][index] = framework.NodeScore{ Name: n.Name, Score: score, } if pl.ScoreExtensions() != nil { status := pl.ScoreExtensions().NormalizeScore(ctx, state, pod, scoresMap[pl.Name()]) if !status.IsSuccess() { return nil, status } } } } // TODO: plugin weight result := make(framework.NodeScoreList, 0, len(nodes)) for i := range nodes { result = append(result, framework.NodeScore{Name: nodes[i].Name, Score: 0}) for j := range scoresMap { result[i].Score += scoresMap[j][i].Score } } return result, nil } func (sched *Scheduler) RunPermitPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (status *framework.Status) { pluginsWaitTime := make(map[string]time.Duration) statusCode := framework.Success for _, pl := range sched.permitPlugins { status, timeout := pl.Permit(ctx, state, pod, nodeName) if !status.IsSuccess() { // reject if status.IsUnschedulable() { klog.InfoS("Pod rejected by permit plugin", "pod", klog.KObj(pod), "plugin", pl.Name(), "status", status.Message()) status.SetFailedPlugin(pl.Name()) return status } // wait if status.Code() == framework.Wait { pluginsWaitTime[pl.Name()] = timeout statusCode = framework.Wait continue } // other errors err := status.AsError() klog.ErrorS(err, "Failed running Permit plugin", "plugin", pl.Name(), "pod", klog.KObj(pod)) return framework.AsStatus(fmt.Errorf("running Permit plugin %q: %w", pl.Name(), err)).WithFailedPlugin(pl.Name()) } } if statusCode == framework.Wait { waitingPod := waitingpod.NewWaitingPod(pod, pluginsWaitTime) sched.waitingPods[pod.UID] = waitingPod msg := fmt.Sprintf("one or more plugins asked to wait and no plugin rejected pod %q", pod.Name) klog.InfoS("One or more plugins asked to wait and no plugin rejected pod", "pod", klog.KObj(pod)) return framework.NewStatus(framework.Wait, msg) } return nil } // WaitOnPermit will block, if the pod is a waiting pod, until the waiting pod is rejected or allowed. func (sched *Scheduler) WaitOnPermit(ctx context.Context, pod *v1.Pod) *framework.Status { waitingPod := sched.waitingPods[pod.UID] if waitingPod == nil { return nil } defer delete(sched.waitingPods, pod.UID) klog.InfoS("Pod waiting on permit", "pod", klog.KObj(pod)) s := waitingPod.GetSignal() if !s.IsSuccess() { if s.IsUnschedulable() { klog.InfoS("Pod rejected while waiting on permit", "pod", klog.KObj(pod), "status", s.Message()) s.SetFailedPlugin(s.FailedPlugin()) return s } err := s.AsError() klog.ErrorS(err, "Failed waiting on permit for pod", "pod", klog.KObj(pod)) return framework.AsStatus(fmt.Errorf("waiting on permit for pod: %w", err)).WithFailedPlugin(s.FailedPlugin()) } return nil } func (sched *Scheduler) Bind(ctx context.Context, state *framework.CycleState, p *v1.Pod, nodeName string) error { binding := &v1.Binding{ ObjectMeta: metav1.ObjectMeta{Namespace: p.Namespace, Name: p.Name, UID: p.UID}, Target: v1.ObjectReference{Kind: "Node", Name: nodeName}, } err := sched.client.CoreV1().Pods(binding.Namespace).Bind(ctx, binding, metav1.CreateOptions{}) if err != nil { return err } return nil } // ============ // util funcs // ============ func (sched *Scheduler) ErrorFunc(pod *v1.Pod, err error) { podInfo := &framework.QueuedPodInfo{ PodInfo: framework.NewPodInfo(pod), } if fitError, ok := err.(*framework.FitError); ok { // Inject UnschedulablePlugins to PodInfo, which will be used later for moving Pods between queues efficiently. podInfo.UnschedulablePlugins = fitError.Diagnosis.UnschedulablePlugins klog.V(2).InfoS("Unable to schedule pod; no fit; waiting", "pod", klog.KObj(pod), "err", err) } else { klog.ErrorS(err, "Error scheduling pod; retrying", "pod", klog.KObj(pod)) } if err := sched.SchedulingQueue.AddUnschedulable(podInfo); err != nil { klog.ErrorS(err, "Error occurred") } } func (sched *Scheduler) GetWaitingPod(uid types.UID) *waitingpod.WaitingPod { return sched.waitingPods[uid] } func (sched *Scheduler) selectHost(nodeScoreList framework.NodeScoreList) (string, error) { if len(nodeScoreList) == 0 { return "", fmt.Errorf("empty priorityList") } maxScore := nodeScoreList[0].Score selected := nodeScoreList[0].Name cntOfMaxScore := 1 for _, ns := range nodeScoreList[1:] { if ns.Score > maxScore { maxScore = ns.Score selected = ns.Name cntOfMaxScore = 1 } else if ns.Score == maxScore { cntOfMaxScore++ if rand.Intn(cntOfMaxScore) == 0 { // Replace the candidate with probability of 1/cntOfMaxScore selected = ns.Name } } } return selected, nil } func (sched *Scheduler) createPluginToNodeScores(nodes []*v1.Node) framework.PluginToNodeScores { pluginToNodeScores := make(framework.PluginToNodeScores, len(sched.scorePlugins)) for _, pl := range sched.scorePlugins { pluginToNodeScores[pl.Name()] = make(framework.NodeScoreList, len(nodes)) } return pluginToNodeScores } <|start_filename|>minisched/plugins/score/nodenumber/nodenumber.go<|end_filename|> package nodenumber import ( "context" "strconv" "time" "github.com/sanposhiho/mini-kube-scheduler/minisched/waitingpod" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/kubernetes/pkg/scheduler/framework" ) // NodeNumber is a plugin that favors nodes that has the same number suffix as number suffix of pod name. // And it will delay the binding of pod by {node suffix number} seconds. // For example: // When schedule a pod named Pod1, a Node named Node9 gets a higher score than a node named Node1. // And if it is decided that Pod1 will go to Node9, this plugin delay the binding by 9 seconds. // // IMPORTANT NOTE: this plugin only handle single digit numbers only. type NodeNumber struct { h waitingpod.Handle } var _ framework.ScorePlugin = &NodeNumber{} var _ framework.PreScorePlugin = &NodeNumber{} var _ framework.PermitPlugin = &NodeNumber{} // Name is the name of the plugin used in the plugin registry and configurations. const Name = "NodeNumber" const preScoreStateKey = "PreScore" + Name // Name returns name of the plugin. It is used in logs, etc. func (pl *NodeNumber) Name() string { return Name } // preScoreState computed at PreScore and used at Score. type preScoreState struct { podSuffixNumber int } // Clone implements the mandatory Clone interface. We don't really copy the data since // there is no need for that. func (s *preScoreState) Clone() framework.StateData { return s } func (pl *NodeNumber) PreScore(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status { podNameLastChar := pod.Name[len(pod.Name)-1:] podnum, err := strconv.Atoi(podNameLastChar) if err != nil { // return success even if its suffix is non-number. return nil } s := &preScoreState{ podSuffixNumber: podnum, } state.Write(preScoreStateKey, s) return nil } func (pl *NodeNumber) EventsToRegister() []framework.ClusterEvent { return []framework.ClusterEvent{ {Resource: framework.Node, ActionType: framework.Add}, } } // Score invoked at the score extension point. func (pl *NodeNumber) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) { data, err := state.Read(preScoreStateKey) if err != nil { return 0, framework.AsStatus(err) } s := data.(*preScoreState) nodeNameLastChar := nodeName[len(nodeName)-1:] nodenum, err := strconv.Atoi(nodeNameLastChar) if err != nil { // return success even if its suffix is non-number. return 0, nil } if s.podSuffixNumber == nodenum { // if match, node get high score. return 10, nil } return 0, nil } // ScoreExtensions of the Score plugin. func (pl *NodeNumber) ScoreExtensions() framework.ScoreExtensions { return nil } func (pl *NodeNumber) Permit(ctx context.Context, state *framework.CycleState, p *v1.Pod, nodeName string) (*framework.Status, time.Duration) { nodeNameLastChar := nodeName[len(nodeName)-1:] nodenum, err := strconv.Atoi(nodeNameLastChar) if err != nil { // return allow(success) even if its suffix is non-number. return nil, 0 } // allow pod after {nodenum} seconds time.AfterFunc(time.Duration(nodenum)*time.Second, func() { wp := pl.h.GetWaitingPod(p.GetUID()) wp.Allow(pl.Name()) }) timeout := time.Duration(10) * time.Second return framework.NewStatus(framework.Wait, ""), timeout } // New initializes a new plugin and returns it. func New(_ runtime.Object, h waitingpod.Handle) (framework.Plugin, error) { return &NodeNumber{h: h}, nil } <|start_filename|>minisched/waitingpod/waitingpod.go<|end_filename|> package waitingpod import ( "fmt" "sync" "time" "k8s.io/apimachinery/pkg/types" v1 "k8s.io/api/core/v1" "k8s.io/kubernetes/pkg/scheduler/framework" ) type Handle interface { // GetWaitingPod returns a waiting pod given its UID. GetWaitingPod(uid types.UID) *WaitingPod } // WaitingPod represents a pod waiting in the permit phase. type WaitingPod struct { pod *v1.Pod pendingPlugins map[string]*time.Timer s chan *framework.Status mu sync.RWMutex } // NewWaitingPod returns a new WaitingPod instance. func NewWaitingPod(pod *v1.Pod, pluginsMaxWaitTime map[string]time.Duration) *WaitingPod { wp := &WaitingPod{ pod: pod, // by using non-blocking send to this channel. This channel has a buffer of size 1 // to ensure that non-blocking send will not be ignored - possible situation when // receiving from this channel happens after non-blocking send. s: make(chan *framework.Status, 1), } wp.pendingPlugins = make(map[string]*time.Timer, len(pluginsMaxWaitTime)) // The time.AfterFunc calls wp.Reject which iterates through pendingPlugins map. Acquire the // lock here so that time.AfterFunc can only execute after NewWaitingPod finishes. wp.mu.Lock() defer wp.mu.Unlock() for k, v := range pluginsMaxWaitTime { plugin, waitTime := k, v wp.pendingPlugins[plugin] = time.AfterFunc(waitTime, func() { msg := fmt.Sprintf("rejected due to timeout after waiting %v at plugin %v", waitTime, plugin) wp.Reject(plugin, msg) }) } return wp } // GetPod returns a reference to the waiting pod. func (w *WaitingPod) GetPod() *v1.Pod { return w.pod } // GetSignal returns a signal from plugin // It blocks until get signal func (w *WaitingPod) GetSignal() *framework.Status { return <-w.s } // GetPendingPlugins returns a list of pending permit plugin's name. func (w *WaitingPod) GetPendingPlugins() []string { w.mu.RLock() defer w.mu.RUnlock() plugins := make([]string, 0, len(w.pendingPlugins)) for p := range w.pendingPlugins { plugins = append(plugins, p) } return plugins } // Allow declares the waiting pod is allowed to be scheduled by plugin pluginName. // If this is the last remaining plugin to allow, then a success signal is delivered // to unblock the pod. func (w *WaitingPod) Allow(pluginName string) { w.mu.Lock() defer w.mu.Unlock() if timer, exist := w.pendingPlugins[pluginName]; exist { timer.Stop() delete(w.pendingPlugins, pluginName) } // Only signal success status after all plugins have allowed if len(w.pendingPlugins) != 0 { return } // The select clause works as a non-blocking send. // If there is no receiver, it's a no-op (default case). select { case w.s <- framework.NewStatus(framework.Success, ""): default: } } // Reject declares the waiting pod unschedulable. func (w *WaitingPod) Reject(pluginName, msg string) { w.mu.RLock() defer w.mu.RUnlock() for _, timer := range w.pendingPlugins { timer.Stop() } // The select clause works as a non-blocking send. // If there is no receiver, it's a no-op (default case). select { case w.s <- framework.NewStatus(framework.Unschedulable, msg).WithFailedPlugin(pluginName): default: } } <|start_filename|>minisched/queue/queue.go<|end_filename|> package queue import ( "sync" "time" "k8s.io/klog/v2" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/kubernetes/pkg/scheduler/framework" v1 "k8s.io/api/core/v1" ) type SchedulingQueue struct { lock sync.RWMutex activeQ []*framework.QueuedPodInfo podBackoffQ []*framework.QueuedPodInfo unschedulableQ map[string]*framework.QueuedPodInfo clusterEventMap map[framework.ClusterEvent]sets.String } func New(clusterEventMap map[framework.ClusterEvent]sets.String) *SchedulingQueue { return &SchedulingQueue{ activeQ: []*framework.QueuedPodInfo{}, podBackoffQ: []*framework.QueuedPodInfo{}, unschedulableQ: map[string]*framework.QueuedPodInfo{}, clusterEventMap: clusterEventMap, } } func (s *SchedulingQueue) Add(pod *v1.Pod) error { s.lock.Lock() defer s.lock.Unlock() podInfo := s.newQueuedPodInfo(pod) s.activeQ = append(s.activeQ, podInfo) return nil } // PreEnqueueCheck is a function type. It's used to build functions that // run against a Pod and the caller can choose to enqueue or skip the Pod // by the checking result. type PreEnqueueCheck func(pod *v1.Pod) bool // MoveAllToActiveOrBackoffQueue moves all pods from unschedulableQ to activeQ or backoffQ. // This function adds all pods and then signals the condition variable to ensure that // if Pop() is waiting for an item, it receives the signal after all the pods are in the // queue and the head is the highest priority pod. func (s *SchedulingQueue) MoveAllToActiveOrBackoffQueue(event framework.ClusterEvent) { s.lock.Lock() defer s.lock.Unlock() unschedulablePods := make([]*framework.QueuedPodInfo, 0, len(s.unschedulableQ)) for _, pInfo := range s.unschedulableQ { unschedulablePods = append(unschedulablePods, pInfo) } s.movePodsToActiveOrBackoffQueue(unschedulablePods, event) } // NOTE: this function assumes lock has been acquired in caller func (s *SchedulingQueue) movePodsToActiveOrBackoffQueue(podInfoList []*framework.QueuedPodInfo, event framework.ClusterEvent) { for _, pInfo := range podInfoList { // If the event doesn't help making the Pod schedulable, continue. // Note: we don't run the check if pInfo.UnschedulablePlugins is nil, which denotes // either there is some abnormal error, or scheduling the pod failed by plugins other than PreFilter, Filter and Permit. // In that case, it's desired to move it anyways. if len(pInfo.UnschedulablePlugins) != 0 && !s.podMatchesEvent(pInfo, event) { continue } if isPodBackingoff(pInfo) { s.podBackoffQ = append(s.podBackoffQ, pInfo) } else { s.activeQ = append(s.activeQ, pInfo) } delete(s.unschedulableQ, keyFunc(pInfo)) } } func (s *SchedulingQueue) NextPod() *v1.Pod { // wait for len(s.activeQ) == 0 { } p := s.activeQ[0] s.activeQ = s.activeQ[1:] return p.Pod } // this function is the similar to AddUnschedulableIfNotPresent on original kube-scheduler. func (s *SchedulingQueue) AddUnschedulable(pInfo *framework.QueuedPodInfo) error { s.lock.Lock() defer s.lock.Unlock() // Refresh the timestamp since the pod is re-added. pInfo.Timestamp = time.Now() // add or update s.unschedulableQ[keyFunc(pInfo)] = pInfo klog.Info("queue: pod added to unschedulableQ: "+pInfo.Pod.Name+". This pod is unscheduled by ", pInfo.UnschedulablePlugins) return nil } func (s *SchedulingQueue) Update(oldPod, newPod *v1.Pod) error { // TODO: implement panic("not implemented") return nil } func (s *SchedulingQueue) Delete(pod *v1.Pod) error { // TODO: implement panic("not implemented") return nil } // AssignedPodAdded is called when a bound pod is added. Creation of this pod // may make pending pods with matching affinity terms schedulable. func (s *SchedulingQueue) AssignedPodAdded(pod *v1.Pod) { // TODO: implement panic("not implemented") } // AssignedPodUpdated is called when a bound pod is updated. Change of labels // may make pending pods with matching affinity terms schedulable. func (s *SchedulingQueue) AssignedPodUpdated(pod *v1.Pod) { // TODO: implement panic("not implemented") } // flushBackoffQCompleted Moves all pods from backoffQ which have completed backoff in to activeQ func (s *SchedulingQueue) flushBackoffQCompleted() { // TODO: implement panic("note implemented") } // flushUnschedulableQLeftover moves pods which stay in unschedulableQ longer than unschedulableQTimeInterval // to backoffQ or activeQ. func (s *SchedulingQueue) flushUnschedulableQLeftover() { // TODO: implement panic("note implemented") } // ===== // utils // ===== func keyFunc(pInfo *framework.QueuedPodInfo) string { return pInfo.Pod.Name + "_" + pInfo.Pod.Namespace } func (s *SchedulingQueue) newQueuedPodInfo(pod *v1.Pod, unschedulableplugins ...string) *framework.QueuedPodInfo { now := time.Now() return &framework.QueuedPodInfo{ PodInfo: framework.NewPodInfo(pod), Timestamp: now, InitialAttemptTimestamp: now, UnschedulablePlugins: sets.NewString(unschedulableplugins...), } } // This is achieved by looking up the global clusterEventMap registry. func (s *SchedulingQueue) podMatchesEvent(podInfo *framework.QueuedPodInfo, clusterEvent framework.ClusterEvent) bool { if clusterEvent.IsWildCard() { return true } for evt, nameSet := range s.clusterEventMap { // Firstly verify if the two ClusterEvents match: // - either the registered event from plugin side is a WildCardEvent, // - or the two events have identical Resource fields and *compatible* ActionType. // Note the ActionTypes don't need to be *identical*. We check if the ANDed value // is zero or not. In this way, it's easy to tell Update&Delete is not compatible, // but Update&All is. evtMatch := evt.IsWildCard() || (evt.Resource == clusterEvent.Resource && evt.ActionType&clusterEvent.ActionType != 0) // Secondly verify the plugin name matches. // Note that if it doesn't match, we shouldn't continue to search. if evtMatch && intersect(nameSet, podInfo.UnschedulablePlugins) { return true } } return false } func intersect(x, y sets.String) bool { if len(x) > len(y) { x, y = y, x } for v := range x { if y.Has(v) { return true } } return false } // isPodBackingoff returns true if a pod is still waiting for its backoff timer. // If this returns true, the pod should not be re-tried. func isPodBackingoff(podInfo *framework.QueuedPodInfo) bool { boTime := getBackoffTime(podInfo) return boTime.After(time.Now()) } // getBackoffTime returns the time that podInfo completes backoff func getBackoffTime(podInfo *framework.QueuedPodInfo) time.Time { duration := calculateBackoffDuration(podInfo) backoffTime := podInfo.Timestamp.Add(duration) return backoffTime } const ( podInitialBackoffDuration = 1 * time.Second podMaxBackoffDuration = 10 * time.Second ) // calculateBackoffDuration is a helper function for calculating the backoffDuration // based on the number of attempts the pod has made. func calculateBackoffDuration(podInfo *framework.QueuedPodInfo) time.Duration { duration := podInitialBackoffDuration for i := 1; i < podInfo.Attempts; i++ { // Use subtraction instead of addition or multiplication to avoid overflow. if duration > podMaxBackoffDuration-duration { return podMaxBackoffDuration } duration += duration } return duration }
shopetan/mini-kube-scheduler
<|start_filename|>Makefile<|end_filename|> PWD = $(shell pwd) index: cat ./tests/docs.xml | docker run -i \ -v $(PWD)/tests/sphinx.conf:/opt/sphinx/conf/sphinx.conf \ -v $(PWD)/tests/data:/opt/sphinx/index \ macbre/docker-sphinxsearch \ indexer --config /opt/sphinx/conf/sphinx.conf test_index start: docker run --detach --rm \ -v $(PWD)/tests/sphinx.conf:/opt/sphinx/conf/sphinx.conf \ -v $(PWD)/tests/data:/opt/sphinx/index \ -p 36307:36307 \ --name sphinx_test \ macbre/docker-sphinxsearch query: mysql -h0 -P36307 -e 'show tables' mysql -h0 -P36307 -e "select * from test_index where match('tags')"
macbre/docker-sphinxsearch
<|start_filename|>Samples/Polylines/Prevent Polylines from Crossing the Anti-Merdian.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript'> var map, originalLocations, line; function GetMap() { map = new Microsoft.Maps.Map('#myMap', { center: new Microsoft.Maps.Location(0, 0), zoom: 1 }); //Load the Spatial Math module. Microsoft.Maps.loadModule("Microsoft.Maps.SpatialMath"); //Create array of locations for a polyline that would cross the anti-merdian. originalLocations = [ new Microsoft.Maps.Location(36.218156, -115.254462), new Microsoft.Maps.Location(-33.893142, 151.127501), new Microsoft.Maps.Location(43.707167, -79.386728) ]; //Create a polyline to render on the map. line = new Microsoft.Maps.Polyline(originalLocations); map.entities.push(line); } function updatePolyline(crossAntiMerdian) { if (crossAntiMerdian) { //Allowed to cross the anti-merdian, let the map render the polyline as it normally would. In this case update the poolyline with the original locations. line.setLocations(originalLocations); } else { //Don't cross the anti-merdian, calculate visual midpoints for each segment of the polyline. var locs = line.getLocations(); var newLocs = [locs[0]]; for (var i = 1; i < locs.length; i++) { //Calculate global pixel values of current and last location at zoom level 19. var p1 = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(locs[i - 1], 19); var p2 = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(locs[i], 19); //Calculate mid-point pixel value. var midPoint = new Microsoft.Maps.Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2); //Convert midPoint into location at zoom level 19 and add to array. newLocs.push(Microsoft.Maps.SpatialMath.Tiles.globalPixelToLocation(midPoint, 19)); //Add current location. newLocs.push(locs[i]); } //Update the line with the new locations. line.setLocations(newLocs); } } </script> <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[YOUR_BING_MAPS_KEY]' async defer></script> </head> <body> <div id="myMap" style="position:relative;width:500px;height:500px;"></div> <br/> Allow crossing anti-merdian: <input type="button" value="No" onclick="updatePolyline(false)" /> <input type="button" value="Yes" onclick="updatePolyline(true)" /> <fieldset style="width:800px;margin-top:10px;"> <legend>Prevent Polylines from Crossing the Anti-Merdian Sample</legend> By default, polylines will render such that they take the shortest path between two points. This means that sometimes the shortest path is to cross the anti-merdian (180/-180 longitude). This is spatially accurate however sometimes it may be designered to show the map centered at (0,0) and all lines within within a single map view without crossing the anti-merdian. This sample shows how to modify polylines sby adding an additional midpoint location to each segment of the polyline which is visually accurate to keep the lines looking striaght. This is not spatially accurate. </fieldset> </body> </html> <|start_filename|>Samples/Other/RequireJS/index.js<|end_filename|> requirejs.config({ 'paths': { 'jquery': '//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.0.min', 'async': '//cdnjs.cloudflare.com/ajax/libs/requirejs-plugins/1.0.3/async' } }); require( [ 'jquery', 'async!https://www.bing.com/mapspreview/sdk/mapcontrol' //Alternatively: 'async!https://www.bing.com/mapspreview/sdk/mapcontrol?key=[YOUR_BING_MAPS_KEY]' ], function () { var map = new Microsoft.Maps.Map('#myMap', { credentials: bingMapsKey }); } ); <|start_filename|>Samples/Data Binning Layers/DataBinning_Bivariate.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript'> var map; function GetMap() { map = new Microsoft.Maps.Map('#myMap', {}); //Generate 10,000 random pushpins within the current map view. var pins = Microsoft.Maps.TestDataGenerator.getPushpins(10000, map.getBounds()); //Add a custom metadata value to each pushpin to simulate real data. for (var i = 0, len = pins.length; i < len; i++) { pins[i].metadata = { sales: Math.random() * 100 }; } //Load the Data Binning module. Microsoft.Maps.loadModule('Microsoft.Maps.DataBinning', function () { //Create the data binning layer. Specify a callback for both the color and scale. var layer = new Microsoft.Maps.DataBinningLayer(pins, { dataBinType: Microsoft.Maps.DataBinType.hexagon, aggregationProperty: 'sales', //Specify the name of the custom property to aggregate over. colorCallback: CustomBinColorLogic, scaleCallback: CustomBinScalingLogic }); map.layers.insert(layer); }); } function CustomBinColorLogic(bin, min, max) { //Specify custom logic to colorize a data bin based on the information it contains. //In this case, calculate twhat percentage the sum of this bin is compared to the max bin sum. //If the value is geater than 75% make the bin green, >50% yellow, below 50% red. var percentageSum = bin.metrics.sum / max.sum * 100; if (percentageSum >= 75) { //Green return 'rgba(0,255,0,0.5)'; } else if (percentageSum > 50) { //Yellow return 'rgba(255,255,0,0.5)'; } else { //Red return 'rgba(255,0,0,0.5)'; } } function CustomBinScalingLogic(bin, min, max) { //Specify custom logic to scale a data bin based on the information it contains. //In this case, scale the size of the bin based on the number of pushpins in the bin //relative to the maximum pushpins in a single bin in the layer. return bin.metrics.count / max.count; } </script> <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[YOUR_BING_MAPS_KEY]' async defer></script> </head> <body> <div id="myMap" style="position:relative;width:800px;height:600px;"></div> <fieldset style="width:800px;margin-top:10px;"> <legend>Bivariate Data Binning Sample</legend> In this example, each pushpin in the data set has a custom 'sales' metadata value which is assigned a random number. The color of each data bin is based on the total realtive sum of sales in all pushpins the data bin contains. The scale of each data bin is based on the total number of pushpins in each bin. This is an example of a bivariate data binning layer which uses two types of visualizations to represent two variables; color and scale. If we assume that each pushpin represented a customer. A data bin that is red would indicate that the total sales in that area is low, however, if the bin was also small, this would indicate that there isn't a lot of pushpins in that data bin which could explain why the total sales in that bin is low. </fieldset> </body> </html> <|start_filename|>Samples/Clustering/SpiderClusters/SpiderClusterManager.js<|end_filename|> /* * Copyright(c) 2017 Microsoft Corporation. All rights reserved. * * This code is licensed under the MIT License (MIT). * * 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. */ var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /// <reference path="../../Common/typings/MicrosoftMaps/Microsoft.Maps.d.ts"/> /** * An extened pushpin which is used to represent an individual pushpin in the spider cluster. */ var SpiderPushpin = (function (_super) { __extends(SpiderPushpin, _super); function SpiderPushpin() { return _super !== null && _super.apply(this, arguments) || this; } return SpiderPushpin; }(Microsoft.Maps.Pushpin)); /** * Adds a clustering layer to the map which expands clusters into a spiral spider layout. */ var SpiderClusterManager = (function () { /********************** * Constructor ***********************/ /** * @constructor * A cluster manager that expands clusters when selectd into a spiral layout. * @param map A map instance to add the cluster layer to. * @param data An array of pushpins to cluster in the layer. * @param options A combination of SpiderClusterManager and Cluster options. */ function SpiderClusterManager(map, data, options) { var _this = this; this._events = []; this._options = { circleSpiralSwitchover: 9, minCircleLength: 30, minSpiralAngleSeperation: 25, spiralDistanceFactor: 5, stickStyle: { strokeColor: 'black', strokeThickness: 2 }, stickHoverStyle: { strokeColor: 'red' }, pinSelected: null, pinUnselected: null }; this._map = map; this._data = data; this._clusterLayer = new Microsoft.Maps.ClusterLayer(data, options); map.layers.insert(this._clusterLayer); this._spiderLayer = new Microsoft.Maps.Layer(); map.layers.insert(this._spiderLayer); this.setOptions(options); this._events.push(Microsoft.Maps.Events.addHandler(map, 'click', function (e) { _this.hideSpiderCluster(); })); this._events.push(Microsoft.Maps.Events.addHandler(map, 'viewchangestart', function (e) { _this.hideSpiderCluster(); })); this._events.push(Microsoft.Maps.Events.addHandler(this._clusterLayer, 'click', function (e) { _this._layerClickEvent(e); })); this._events.push(Microsoft.Maps.Events.addHandler(this._spiderLayer, 'mouseover', function (e) { if (e.primitive instanceof SpiderPushpin) { e.primitive.stick.setOptions(_this._options.stickHoverStyle); } })); this._events.push(Microsoft.Maps.Events.addHandler(this._spiderLayer, 'mouseout', function (e) { if (e.primitive instanceof SpiderPushpin) { e.primitive.stick.setOptions(_this._options.stickStyle); } })); this._events.push(Microsoft.Maps.Events.addHandler(this._spiderLayer, 'click', function (e) { _this._layerClickEvent(e); })); } /********************** * Public Functions ***********************/ /** * Disposes the SpiderClusterManager and releases it's resources. */ SpiderClusterManager.prototype.dispose = function () { this._spiderLayer.clear(); this._map.layers.remove(this._spiderLayer); this._spiderLayer = null; for (var i = 0, len = this._events.length; i < len; i++) { Microsoft.Maps.Events.removeHandler(this._events[i]); } this._events = null; }; /** * Gets the base ClusterLayer used by the SpiderClusterManager. * @returns The base ClusterLayer used by the SpiderClusterManager. */ SpiderClusterManager.prototype.getClusterLayer = function () { return this._clusterLayer; }; /** * Collapses any open spider clusters. */ SpiderClusterManager.prototype.hideSpiderCluster = function () { //Show cluster and hide spider. if (this._currentCluster) { this._currentCluster.setOptions({ visible: true }); this._spiderLayer.clear(); this._currentCluster = null; } }; /** * Sets the options used to customize how the SpiderClusterManager renders clusters. * @param options The options used to customize how the SpiderClusterManager renders clusters. */ SpiderClusterManager.prototype.setOptions = function (options) { this.hideSpiderCluster(); if (options) { if (typeof options.circleSpiralSwitchover === 'number') { this._options.circleSpiralSwitchover = options.circleSpiralSwitchover; } if (typeof options.minSpiralAngleSeperation === 'number') { this._options.minSpiralAngleSeperation = options.minSpiralAngleSeperation; } if (typeof options.spiralDistanceFactor === 'number') { this._options.spiralDistanceFactor = options.spiralDistanceFactor; } if (typeof options.minCircleLength === 'number') { this._options.minCircleLength = options.minCircleLength; } if (options.stickHoverStyle) { this._options.stickHoverStyle = options.stickHoverStyle; } if (options.stickStyle) { this._options.stickStyle = options.stickStyle; } if (options.pinSelected) { this._options.pinSelected = options.pinSelected; } if (options.pinUnselected) { this._options.pinUnselected = options.pinUnselected; } if (typeof options.visible === 'boolean') { this._options.visible = options.visible; } this._clusterLayer.setOptions(options); } }; /** * Expands a cluster into it's open spider layout. * @param cluster The cluster to show in it's open spider layout.. */ SpiderClusterManager.prototype.showSpiderCluster = function (cluster) { this.hideSpiderCluster(); this._currentCluster = cluster; if (cluster && cluster.containedPushpins) { //Create spider data. var pins = cluster.containedPushpins; var center = cluster.getLocation(); var centerPoint = this._map.tryLocationToPixel(center, Microsoft.Maps.PixelReference.control); var point; var loc; var pin; var stick; var angle = 0; var makeSpiral = pins.length > this._options.circleSpiralSwitchover; var legPixelLength; var stepAngle; var stepLength; if (makeSpiral) { legPixelLength = this._options.minCircleLength / Math.PI; stepLength = 2 * Math.PI * this._options.spiralDistanceFactor; } else { stepAngle = 2 * Math.PI / pins.length; legPixelLength = (this._options.spiralDistanceFactor / stepAngle / Math.PI / 2) * pins.length; if (legPixelLength < this._options.minCircleLength) { legPixelLength = this._options.minCircleLength; } } for (var i = 0, len = pins.length; i < len; i++) { //Calculate spider pin location. if (makeSpiral) { angle += this._options.minSpiralAngleSeperation / legPixelLength + i * 0.0005; legPixelLength += stepLength / angle; } else { angle = stepAngle * i; } point = new Microsoft.Maps.Point(centerPoint.x + legPixelLength * Math.cos(angle), centerPoint.y + legPixelLength * Math.sin(angle)); loc = this._map.tryPixelToLocation(point, Microsoft.Maps.PixelReference.control); //Create stick to pin. stick = new Microsoft.Maps.Polyline([center, loc], this._options.stickStyle); this._spiderLayer.add(stick); //Create pin in spiral that contains same metadata as parent pin. pin = new SpiderPushpin(loc); pin.metadata = pins[i].metadata; pin.stick = stick; pin.parentPin = pins[i]; pin.setOptions(this._getBasicPushpinOptions(pins[i])); this._spiderLayer.add(pin); } //Hide Cluster this._currentCluster.setOptions({ visible: false }); } }; /********************** * Private Functions ***********************/ /** * Click event handler for when a shape in the cluster layer is clicked. * @param e The mouse event argurment from the click event. */ SpiderClusterManager.prototype._layerClickEvent = function (e) { if (e.primitive instanceof Microsoft.Maps.ClusterPushpin) { if (this._options.pinUnselected) { this._options.pinUnselected(); } this.showSpiderCluster(e.primitive); } else { if (this._options.pinSelected) { var pin = e.primitive; if (e.primitive instanceof SpiderPushpin) { this._options.pinSelected(pin.parentPin, this._currentCluster); } else { this._options.pinSelected(pin, null); } } this.hideSpiderCluster(); } }; /** * Creates a copy of a pushpins basic options. * @param pin Pushpin to copy options from. * @returns A copy of a pushpins basic options. */ SpiderClusterManager.prototype._getBasicPushpinOptions = function (pin) { return { anchor: pin.getAnchor(), color: pin.getColor(), icon: pin.getIcon(), roundClickableArea: pin.getRoundClickableArea(), text: pin.getText(), textOffset: pin.getTextOffset() }; }; return SpiderClusterManager; }()); //Load Custering module which is a dependancy. Microsoft.Maps.loadModule('Microsoft.Maps.Clustering', function () { Microsoft.Maps.moduleLoaded('SpiderClusterManager'); }); //# sourceMappingURL=SpiderClusterManager.js.map <|start_filename|>Samples/Custom Overlays/CanvasLayer/CanvasOverlayModule.js<|end_filename|> /* * Copyright(c) 2017 Microsoft Corporation. All rights reserved. * * This code is licensed under the MIT License (MIT). * * 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. */ var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /// <reference path="../../Common/typings/MicrosoftMaps/Microsoft.Maps.d.ts"/> var CanvasOverlay = (function (_super) { __extends(CanvasOverlay, _super); /********************** * Constructor ***********************/ /** * @contructor * @param drawCallback A callback function that is triggered when the canvas is ready to be rendered for the current map view. */ function CanvasOverlay(drawCallback) { var _this = _super.call(this) || this; _this._drawCallback = drawCallback; return _this; } /********************** * Overridden functions ***********************/ /** * CanvasOverlay added to map, load canvas. */ CanvasOverlay.prototype.onAdd = function () { //Create a canvas for rendering. this._canvas = document.createElement('canvas'); this._canvas.style.position = 'absolute'; this._canvas.style.left = '0px'; this._canvas.style.top = '0px'; //Add the canvas to the overlay. this.setHtmlElement(this._canvas); }; ; /** * CanvasOverlay loaded, attach map events for updating canvas. */ CanvasOverlay.prototype.onLoad = function () { var self = this; var map = self.getMap(); //Get the current map view information. this._zoomStart = map.getZoom(); this._centerStart = map.getCenter(); //Redraw the canvas. self._redraw(); //When the map moves, move the canvas accordingly. self._viewChangeEvent = Microsoft.Maps.Events.addHandler(map, 'viewchange', function (e) { if (map.getMapTypeId() === Microsoft.Maps.MapTypeId.streetside) { //Don't show the canvas if the map is in Streetside mode. self._canvas.style.display = 'none'; } else { //Re-drawing the canvas as it moves would be too slow. Instead, scale and translate canvas element. var zoomCurrent = map.getZoom(); var centerCurrent = map.getCenter(); //Calculate map scale based on zoom level difference. var scale = Math.pow(2, zoomCurrent - self._zoomStart); //Calculate the scaled dimensions of the canvas. var newWidth = map.getWidth() * scale; var newHeight = map.getHeight() * scale; //Calculate offset of canvas based on zoom and center offsets. var pixelPoints = map.tryLocationToPixel([self._centerStart, centerCurrent], Microsoft.Maps.PixelReference.control); var centerOffsetX = pixelPoints[1].x - pixelPoints[0].x; var centerOffsetY = pixelPoints[1].y - pixelPoints[0].y; var x = (-(newWidth - map.getWidth()) / 2) - centerOffsetX; var y = (-(newHeight - map.getHeight()) / 2) - centerOffsetY; //Update the canvas CSS position and dimensions. self._updatePosition(x, y, newWidth, newHeight); } }); //When the map stops moving, render new data on the canvas. self._viewChangeEndEvent = Microsoft.Maps.Events.addHandler(map, 'viewchangeend', function (e) { self.updateCanvas(); }); //Update the position of the overlay when the map is resized. self._mapResizeEvent = Microsoft.Maps.Events.addHandler(this.getMap(), 'mapresize', function (e) { self.updateCanvas(); }); }; CanvasOverlay.prototype.updateCanvas = function () { var map = this.getMap(); //Only render the canvas if it isn't in streetside mode. if (map.getMapTypeId() !== Microsoft.Maps.MapTypeId.streetside) { this._canvas.style.display = ''; //Reset CSS position and dimensions of canvas. this._updatePosition(0, 0, map.getWidth(), map.getHeight()); //Redraw the canvas. this._redraw(); //Get the current map view information. this._zoomStart = map.getZoom(); this._centerStart = map.getCenter(); } }; /** * When the CanvasLayer is removed from the map, release resources. */ CanvasOverlay.prototype.onRemove = function () { this.setHtmlElement(null); this._canvas = null; //Remove all event handlers from the map. Microsoft.Maps.Events.removeHandler(this._viewChangeEvent); Microsoft.Maps.Events.removeHandler(this._viewChangeEndEvent); }; /********************** * Private Functions ***********************/ /** * Simple function for updating the CSS position and dimensions of the canvas. * @param x The horizontal offset position of the canvas. * @param y The vertical offset position of the canvas. * @param w The width of the canvas. * @param h The height of the canvas. */ CanvasOverlay.prototype._updatePosition = function (x, y, w, h) { //Update CSS position. this._canvas.style.left = x + 'px'; this._canvas.style.top = y + 'px'; //Update CSS dimensions. this._canvas.style.width = w + 'px'; this._canvas.style.height = h + 'px'; }; /** * Redraws the canvas for the current map view. */ CanvasOverlay.prototype._redraw = function () { //Clear canvas by updating dimensions. This also ensures canvas stays the same size as the map. this._canvas.width = this.getMap().getWidth(); this._canvas.height = this.getMap().getHeight(); //Call the drawing callback function if specified. if (this._drawCallback) { this._drawCallback(this._canvas); } }; return CanvasOverlay; }(Microsoft.Maps.CustomOverlay)); //Call the module loaded function. Microsoft.Maps.moduleLoaded('CanvasOverlayModule'); //# sourceMappingURL=CanvasOverlayModule.js.map <|start_filename|>Samples/Other/Solar Terminator/SolarTerminatorModule.js<|end_filename|> /* * Copyright(c) 2017 Microsoft Corporation. All rights reserved. * * This code is licensed under the MIT License (MIT). * * 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. */ var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /// <reference path="../../Common/typings/MicrosoftMaps/Microsoft.Maps.d.ts"/> var SolarTerminator = (function (_super) { __extends(SolarTerminator, _super); /********************** * Constructor ***********************/ /** * @contructor */ function SolarTerminator(dateTime, options) { var _this = _super.call(this, [], options || { strokeColor: 'rgba(0,0,0,0)', fillColor: 'rgba(0,0,0,0.7)' }) || this; _this.radiansToDegrees = 180 / Math.PI; _this.degreesToRadians = Math.PI / 180; _this.setLocations(_this.computeTerminatorLocations()); return _this; } /********************** * Public Functions ***********************/ SolarTerminator.prototype.getSunLocation = function () { //Calculate approximate longitude value of sun based on UTC time. var lon = 180 - (this.dateTime.getUTCHours() + this.dateTime.getUTCMinutes() / 60 + this.dateTime.getMilliseconds() / 3600) / 24 * 360; return new Microsoft.Maps.Location(this.sunEquatorialPosition.delta, lon); }; SolarTerminator.prototype.getDateTime = function () { return this.dateTime; }; SolarTerminator.prototype.setDateTime = function (dateTime) { this.dateTime = dateTime; this.setLocations(this.computeTerminatorLocations()); }; /********************** * Private Functions ***********************/ SolarTerminator.prototype.computeTerminatorLocations = function () { this.dateTime = this.dateTime || new Date(); var julianDay = this.getJulian(this.dateTime); var gst = this.getGMST(this.dateTime); var latLng = []; var ha, lat, lng; var sunEclPos = this.getSunEclipticPosition(julianDay); var eclObliq = this.getEclipticObliquity(julianDay); var sunEqPos = this.getSunEquatorialPosition(sunEclPos.lambda, eclObliq); this.sunEquatorialPosition = sunEqPos; for (var i = 0; i <= 360; i++) { lng = -180 + i; ha = this.getHourAngle(lng, sunEqPos, gst); lat = this.getLatitude(ha, sunEqPos); latLng[i + 1] = new Microsoft.Maps.Location(lat, lng); } if (sunEqPos.delta < 0) { latLng[0] = new Microsoft.Maps.Location(90, -180); latLng[latLng.length] = new Microsoft.Maps.Location(90, 180); } else { latLng[0] = new Microsoft.Maps.Location(-90, -180); latLng[latLng.length] = new Microsoft.Maps.Location(-90, 180); } return latLng; }; SolarTerminator.prototype.getJulian = function (date) { //Calculate the present UTC Julian Date. Function is valid after the beginning of the UNIX epoch 1970-01-01 and ignores leap seconds. return (date.getTime() / 86400000) + 2440587.5; }; SolarTerminator.prototype.getGMST = function (date) { //Calculate Greenwich Mean Sidereal Time according to http://aa.usno.navy.mil/faq/docs/GAST.php var julianDay = this.getJulian(date); var d = julianDay - 2451545.0; // Low precision equation is good enough for our purposes. return (18.697374558 + 24.06570982441908 * d) % 24; }; SolarTerminator.prototype.getSunEclipticPosition = function (julianDay) { //Compute the position of the Sun in ecliptic coordinates at julianDay. Following http://en.wikipedia.org/wiki/Position_of_the_Sun // Days since start of J2000.0 var n = julianDay - 2451545.0; // mean longitude of the Sun var L = (280.460 + 0.9856474 * n) % 360; // mean anomaly of the Sun var g = (357.528 + 0.9856003 * n) % 360; // ecliptic longitude of Sun var lambda = L + 1.915 * Math.sin(g * this.degreesToRadians) + 0.02 * Math.sin(2 * g * this.degreesToRadians); // distance from Sun in AU var R = 1.00014 - 0.01671 * Math.cos(g * this.degreesToRadians) - 0.0014 * Math.cos(2 * g * this.degreesToRadians); return { lambda: lambda, R: R }; }; SolarTerminator.prototype.getEclipticObliquity = function (julianDay) { // Following the short term expression in http://en.wikipedia.org/wiki/Axial_tilt#Obliquity_of_the_ecliptic_.28Earth.27s_axial_tilt.29 // Julian centuries since J2000.0 var n = julianDay - 2451545.0; var T = n / 36525; //epsilon return 23.43929111 - T * (46.836769 / 3600 - T * (0.0001831 / 3600 + T * (0.00200340 / 3600 - T * (0.576e-6 / 3600 - T * 4.34e-8 / 3600)))); }; SolarTerminator.prototype.getSunEquatorialPosition = function (sunEclLng, eclObliq) { //Compute the Sun's equatorial position from its ecliptic position. Inputs are expected in degrees. Outputs are in degrees as well. var alpha = Math.atan(Math.cos(eclObliq * this.degreesToRadians) * Math.tan(sunEclLng * this.degreesToRadians)) * this.radiansToDegrees; var delta = Math.asin(Math.sin(eclObliq * this.degreesToRadians) * Math.sin(sunEclLng * this.degreesToRadians)) * this.radiansToDegrees; var lQuadrant = Math.floor(sunEclLng / 90) * 90; var raQuadrant = Math.floor(alpha / 90) * 90; alpha += (lQuadrant - raQuadrant); return { alpha: alpha, delta: delta }; }; SolarTerminator.prototype.getHourAngle = function (lng, sunPos, gst) { //Compute the hour angle of the sun for a longitude on Earth. Return the hour angle in degrees. return (gst + lng / 15) * 15 - sunPos.alpha; }; SolarTerminator.prototype.getLatitude = function (ha, sunPos) { /* For a given hour angle and sun position, compute the latitude of the terminator in degrees. */ return Math.atan(-Math.cos(ha * this.degreesToRadians) / Math.tan(sunPos.delta * this.degreesToRadians)) * this.radiansToDegrees; }; return SolarTerminator; }(Microsoft.Maps.Polygon)); //Call the module loaded function. Microsoft.Maps.moduleLoaded('SolarTerminatorModule'); //# sourceMappingURL=SolarTerminatorModule.js.map <|start_filename|>Samples/Test Data Generator/TestDataGenerator_CreatePushpins.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript'> var map; function GetMap() { map = new Microsoft.Maps.Map('#myMap', {}); // getPushpins(num?: number, bounds?: LocationRect, options?: IPushpinOptions) var pushpins = Microsoft.Maps.TestDataGenerator.getPushpins(3, map.getBounds()); map.entities.push(pushpins); } </script> <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[YOUR_BING_MAPS_KEY]' async defer></script> </head> <body> <div id="myMap" style="position:relative;width:800px;height:600px;"></div> <fieldset style="width:800px;margin-top:10px;"> <legend>TestDataGenerator Create Pushpins Sample</legend> This sample shows how to use the TestDataGenerator to create random pushpins using the getPushpins function. <a href="https://msdn.microsoft.com/en-us/library/mt712874.aspx">TestDataGenerator documentation</a> </fieldset> </body> </html> <|start_filename|>Samples/Tile Layers/TileLayer_XYZoom.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript'> var map; function GetMap() { map = new Microsoft.Maps.Map('#myMap', { center: new Microsoft.Maps.Location(40.75, -99.47), zoom: 4 }); //Weather radar tiles from Iowa Environmental Mesonet of Iowa State University var weatherTileLayer = new Microsoft.Maps.TileLayer({ mercator: new Microsoft.Maps.TileSource({ uriConstructor: 'https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-900913/{zoom}/{x}/{y}.png' }) }); map.layers.insert(weatherTileLayer); } </script> <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[YOUR_BING_MAPS_KEY]' async defer></script> </head> <body> <div id="myMap" style="position:relative;width:800px;height:600px;"></div> <fieldset style="width:800px;margin-top:10px;"> <legend>TileLayer - X/Y/Zoom Sample</legend> This sample shows how to create a simple tile layer which points to a set of tiles which use the x, y, zoom tiling system. The source of this tile layer is a weather radar overlay from the <a href="http://mesonet.agron.iastate.edu/ogc/">Iowa Environmental Mesonet of Iowa State University</a>. </fieldset> </body> </html> <|start_filename|>Samples/BingMapsCredentials.js<|end_filename|> //This file provides a Bing Maps key that is used by all the samples. //Update this value with your Bing Maps key. var YourBingMapsKey = 'YOUR_BING_MAPS_KEY'; //Get your own Bing Maps key at https://www.bingmapsportal.com <|start_filename|>Samples/Article Samples/SimpleStoreLocator/js/Locator.js<|end_filename|> var map, dataLayer, infobox, searchManager; // URL to the data source that powers the locator. var dataSourceUrl = 'https://spatial.virtualearth.net/REST/v1/data/515d38d4d4e348d9a61c615f59704174/CoffeeShops/CoffeeShop'; // A setting for specifying the distance units displayed. Possible values are 'km' and 'mi'. var distanceUnits = 'km'; function GetMap() { // Load the map. map = new Microsoft.Maps.Map('#myMap', { zoom: 3 }); // Create a layer to load pushpins to. dataLayer = new Microsoft.Maps.Layer(); // Add a click event to the data layer to display an infobox. Microsoft.Maps.Events.addHandler(dataLayer, 'click', function (e) { displayInfobox(e.primitive); }); map.layers.insert(dataLayer); // Create a global infobox control. infobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0, 0), { visible: false, offset: new Microsoft.Maps.Point(0, 20), height: 170, width: 230 }); infobox.setMap(map); // Load the Search, Spatial Data Service and Spatial Math modules. Microsoft.Maps.loadModule(['Microsoft.Maps.Search', 'Microsoft.Maps.SpatialDataService', 'Microsoft.Maps.SpatialMath'], function () { searchManager = new Microsoft.Maps.Search.SearchManager(map); }); document.getElementById('searchBtn').onclick = performSearch; document.getElementById('searchBox').onkeypress = function (e) { if (e.which == 13) { performSearch(); } }; } function performSearch() { clearMap(); // Create a request to geocode the users search. var geocodeRequest = { where: document.getElementById('searchBox').value, count: 1, callback: function (r) { if (r && r.results && r.results.length > 0 && r.results[0].location) { findNearbyLocations(r.results[0].location); } else { showErrorMsg('Unable to geocode query'); } }, errorCallback: function () { showErrorMsg('Unable to geocode query'); } }; // Geocode the users search. searchManager.geocode(geocodeRequest); } // A simple function for displaying error messages in the app. function showErrorMsg(msg) { document.getElementById('resultsPanel').innerHTML = '<span class="errorMsg">' + msg + '</span>'; } // A simple function for clearing the map and results panel. function clearMap() { dataLayer.clear(); infobox.setOptions({ visible: false }); document.getElementById('resultsPanel').innerHTML = ''; } // A function that searches for nearby locations against the data source. function findNearbyLocations(location) { // Create the query to get the 10 closest stores that are within 20KM of the specified location. var queryOptions = { queryUrl: dataSourceUrl, spatialFilter: { spatialFilterType: 'nearby', location: location, radius: 20 }, top: 10 }; //Process the query. Microsoft.Maps.SpatialDataService.QueryAPIManager.search(queryOptions, map, function (results) { // Create an array to store the coordinates of all the location results. var locs = []; // Create an array to store the HTML used to generate the list of results. // By using an array to concatenate strings is much more efficient than using +. var listItems = []; //Loop through results and add to map for (var i = 0; i < results.length; i++) { results[i].setOptions({ icon: 'images/red_pin.png', text: (i + 1) + '' }); // Add the location of the pushpin to the array of locations locs.push(results[i].getLocation()); // Create the HTML for a single list item for the result. listItems.push('<table class="listItem"><tr><td rowspan="3"><span>', (i + 1), '.</span></td>'); //Get metadata for location var metadata = results[i].metadata; // Store the result ID as a property of the name. This will allow us to relate the list item to the pushpin on the map. listItems.push('<td><a class="title" href="javascript:void(0);" rel="', metadata.ID, '">', metadata.Name, '</a></td>'); listItems.push('<td>', convertSdsDistance(metadata.__Distance), ' ', distanceUnits, '</td></tr>'); listItems.push('<tr><td colspan="2" class="listItem-address">', metadata.AddressLine, '<br/>', metadata.Locality, ', '); listItems.push(metadata.AdminDistrict, '<br/>', metadata.PostalCode, '</td></tr>'); listItems.push('<tr><td colspan="2"><a target="_blank" href="http://bing.com/maps/default.aspx?rtp=~pos.', metadata.Latitude, '_', metadata.Longitude, '_', encodeURIComponent(metadata.Name), '">Directions</a></td></tr>'); listItems.push('</table>'); } // Add the pushpins to the map. dataLayer.add(results); // Use the array of locations from the results to set the map view to show all locations. if (locs.length > 1) { map.setView({ bounds: Microsoft.Maps.LocationRect.fromLocations(locs), padding: 80 }); } else { map.setView({ center: locs[0], zoom: 15 }); } var resultsPanel = document.getElementById('resultsPanel'); // Add the list items to the results panel. resultsPanel.innerHTML = listItems.join(''); // Add a click event to the title of each list item. var resultItems = resultsPanel.getElementsByClassName('title'); for (var i = 0; i < resultItems.length; i++) { resultItems[i].onclick = resultClicked; } }); } function resultClicked(e) { // Get the ID of the selected location var id = e.target.getAttribute('rel'); //Loop through all the pins in the data layer and find the pushpin for the location. var pins = dataLayer.getPrimitives(); for (var i = 0; i < pins.length; i++) { var pin = pins[i]; if (pin.metadata.ID != id) { pin = null; } else { break; } } // If a pin is found with a matching ID, then center the map on it and show it's infobox. if (pin) { // Offset the centering to account for the infobox. map.setView({ center: pin.getLocation(), zoom: 17 }); displayInfobox(pin); } } // Takes a pushpin and generates the content for the infobox from the Metadata and displays the infobox. function displayInfobox(pin) { var metadata = pin.metadata; var desc = ['<table>']; desc.push('<tr><td colspan="2">', metadata.AddressLine, ', ', metadata.Locality, ', '); desc.push(metadata.AdminDistrict, ', ', metadata.PostalCode, '</td></tr>'); desc.push('<tr><td><b>Hours:</b></td><td>', formatTime(metadata.Open), ' - ', formatTime(metadata.Close), '</td></tr>'); desc.push('<tr><td><b>Store Type:</b></td><td>', metadata.StoreType, '</td></tr>'); desc.push('<tr><td><b>Has Wifi:</b></td><td>', (metadata.IsWiFiHotSpot) ? 'Yes' : 'No', '</td></tr>'); desc.push('<tr><td colspan="2"><a target="_blank" href="http://bing.com/maps/default.aspx?rtp=~pos.', metadata.Latitude, '_', metadata.Longitude, '_', encodeURIComponent(metadata.Name), '">Directions</a></td></tr>'); desc.push('</table>'); infobox.setOptions({ visible: true, location: pin.getLocation(), title: metadata.Name, description: desc.join('') }); } // Formats a time in 1000 hours to hh:mm AM/PM format function formatTime(val) { var minutes = val % 100; var hours = Math.round(val / 100); if (minutes == 0) { minutes = '00'; } if (hours > 12) { return (hours - 12) + ':' + minutes + 'PM'; } else { return hours + ':' + minutes + 'AM'; } } function convertSdsDistance(distance) { var toUnits; switch (distanceUnits.toLowerCase()) { case 'mi': case 'miles': toUnits = Microsoft.Maps.SpatialMath.DistanceUnits.Miles; break; case 'km': case 'kilometers': default: toUnits = Microsoft.Maps.SpatialMath.DistanceUnits.Kilometers; break; } //Convert distance to disired units. var d = Microsoft.Maps.SpatialMath.convertDistance(distance, Microsoft.Maps.SpatialMath.DistanceUnits.Kilometers, toUnits); //Round to to 2 decimal places. d = Math.round(d * 100) / 100; return d; } //# sourceMappingURL=Locator.js.map <|start_filename|>Samples/Default.aspx.cs<|end_filename|> using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Text; using System.Web.Configuration; using System.Web.UI.WebControls; namespace Samples { public partial class Default : System.Web.UI.Page { private List<string> PageNames; private List<string> DuplicatePageNames; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BingMapsKey = WebConfigurationManager.AppSettings["BingMapsKey"]; NumberOfSamples = 0; PageNames = new List<string>(); DuplicatePageNames = new List<string>(); var sampleList = new StringBuilder("["); var welcomeNode = new TreeNode("Welcome") { SelectAction = TreeNodeSelectAction.Select }; welcomeNode.NavigateUrl = string.Format("javascript:loadSample('{0}', '{1}', '{2}')", welcomeNode.Text, "welcome.html", null); sampleList.AppendFormat("{{label:'{0}',category:'',action:function(){{{1}}}}},", welcomeNode.Text, welcomeNode.NavigateUrl.Replace("javascript:", "")); SampleTreeView.Nodes.Add(welcomeNode); PageNames.Add(welcomeNode.Text); DirectoryInfo directory = null; directory = new DirectoryInfo(Server.MapPath("~")); foreach (var dir in directory.GetDirectories()) { //Only add folders that don't have "- Private" in the name. if (!dir.Name.Contains("- Private")) { var categoryNode = new TreeNode(dir.Name) { SelectAction = TreeNodeSelectAction.Expand }; var dirs = dir.GetDirectories(); if (dirs.Length > 0) { foreach (var d in dirs) { AddSampleNodes(dir, d, categoryNode, sampleList); } } AddSampleNodes(dir, null, categoryNode, sampleList); if (categoryNode.ChildNodes != null && categoryNode.ChildNodes.Count > 0) { SampleTreeView.Nodes.Add(categoryNode); SortTreeNodes(categoryNode.ChildNodes); } } } var externalNode = new TreeNode("External Samples") { SelectAction = TreeNodeSelectAction.Select }; externalNode.NavigateUrl = string.Format("javascript:loadSample('{0}', '{1}', '{2}')", externalNode.Text, "ExternalSamples.html", null); SampleTreeView.Nodes.Add(externalNode); PageNames.Add(externalNode.Text); if (DuplicatePageNames.Count > 0) { var sb = new StringBuilder("Warning: Duplicate sample names found:"); foreach(var dn in DuplicatePageNames) { sb.AppendFormat("\\r\\n{0}", dn); } WarningMessage += sb.ToString(); } sampleList.Append("]"); SampleList = sampleList.ToString(); } } public string WarningMessage { get; set; } public int NumberOfSamples { get; set; } public string SampleList { get; set; } public string BingMapsKey { get; set; } private void AddSampleNodes(DirectoryInfo dir, DirectoryInfo dir2, TreeNode parentNode, StringBuilder sampleList) { FileInfo[] files; if (dir2 == null) { files = dir.GetFiles("*.html"); } else { files = dir2.GetFiles("*.html"); } if (files.Length > 0) { string path, sourcePath; foreach (FileInfo fi in files) { if (!fi.Name.Contains("- Private")) { if (dir2 != null) { path = dir.Name + "/" + dir2.Name + "/" + fi.Name.ToString(); sourcePath = dir.Name + "/" + dir2.Name; } else { path = dir.Name + "/" + fi.Name.ToString(); sourcePath = path; } string name = fi.Name.Replace(".html", "").Replace("'", "\\'"); var fileNode = new TreeNode(name) { SelectAction = TreeNodeSelectAction.SelectExpand, NavigateUrl = string.Format("javascript:loadSample('{0}', '{1}', '{2}')", name, path, sourcePath) }; parentNode.ChildNodes.Add(fileNode); if (PageNames.Contains(name)) { DuplicatePageNames.Add(name); } else { PageNames.Add(name); sampleList.AppendFormat("{{label:'{0}',category:'{1}',action:function(){{{2}}}}},", fileNode.Text, dir.Name, fileNode.NavigateUrl.Replace("javascript:", "")); } NumberOfSamples++; } } } } private void SortTreeNodes(TreeNodeCollection treeNodes) { var sorted = true; foreach (TreeNode treeNode in treeNodes) { SortTreeNodes(treeNode.ChildNodes); } do { sorted = true; for (var i = 0; i < treeNodes.Count - 1; i++) { var treeNode1 = treeNodes[i]; var treeNode2 = treeNodes[i + 1]; if (treeNode1.Text.CompareTo(treeNode2.Text) > 0) { treeNodes.RemoveAt(i + 1); treeNodes.RemoveAt(i); treeNodes.AddAt(i, treeNode2); treeNodes.AddAt(i + 1, treeNode1); sorted = false; } } } while (!sorted); } } } <|start_filename|>Samples/GeoXml/GeoXmlLayer - Cross Domain/GeoXmlProxyService.ashx.cs<|end_filename|> using System; using System.IO; using System.Net; using System.Text; using System.Web; namespace Samples.GeoXml { /// <summary> /// This Proxy is not required if the file being used in your application is hosted on the same domain as the web application. /// If accessing files from else where this proxy is needed to get around cross domain access issues. /// </summary> public class GeoXmlProxyService : IHttpHandler { public void ProcessRequest(HttpContext context) { string url = context.Request.QueryString["url"]; //Setup response caching for 5 minutes (adjust as you see fit). SetCacheHeaders(DateTime.UtcNow.AddMinutes(5), context); //Add CORs allowed origin. context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); //Generate response HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); var contentType = response.Headers["Content-Type"]; context.Response.ContentType = contentType; if (IsCompressedContentType(contentType)) { using (var stream = response.GetResponseStream()) { context.Response.BufferOutput = false; byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { context.Response.OutputStream.Write(buffer, 0, bytesRead); } } } else { //Assume the response is text or XML. StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.ASCII); context.Response.Write(stream.ReadToEnd()); } } catch { //Unable to read URL. Return a null response. context.Response.Write(null); } context.ApplicationInstance.CompleteRequest(); } public bool IsReusable { get { return true; } } #region Methods private bool IsCompressedContentType(string contentType) { return (string.Compare(contentType, "application/vnd.google-earth.kmz") == 0 || string.Compare(contentType, "application/zip") == 0 || string.Compare(contentType, "application/octet-stream") == 0); } protected void SetCacheHeaders(DateTime length, HttpContext context) { if (length != null) { context.Response.Cache.SetExpires(length); context.Response.Cache.SetValidUntilExpires(true); context.Response.Cache.SetCacheability(HttpCacheability.Public); } else { //If no cache length specified, disable caching. context.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1)); context.Response.Cache.SetValidUntilExpires(false); context.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches); context.Response.Cache.SetCacheability(HttpCacheability.NoCache); context.Response.Cache.SetNoStore(); } } #endregion } } <|start_filename|>Samples/SiteResources/default.js<|end_filename|> var githubProjectUrl = 'https://github.com/Microsoft/BingMapsV8CodeSamples/blob/master/Samples/'; var currentSampleElm; function loadSample(name, path, sourcePath) { var sampleNode = getSampleNode(name); if (sampleNode) { if (currentSampleElm) { currentSampleElm.classList.remove('selectedNode'); } currentSampleElm = sampleNode; currentSampleElm.classList.add('selectedNode'); } window.location.hash = encodeURIComponent(name); //Download HTML for sample. var xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", path, false); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4) { var sampleHtml = xmlHttp.responseText; sampleHtml = sampleHtml.replace(/\[YOUR_BING_MAPS_KEY\]/gi, BingMapsKey); var iframe = document.getElementById('displayWindow'); var doc = iframe.document; if (iframe.contentDocument) { doc = iframe.contentDocument; // For NS6 } else if (iframe.contentWindow) { doc = iframe.contentWindow.document; // For IE5.5 and IE6 } doc.open(); doc.writeln(sampleHtml); doc.close(); if (sourcePath && sourcePath != '') { document.getElementById('sourceCodeLinkPanel').style.display = ''; document.getElementById('newWindowLink').onclick = function () { var win = window.open(); win.document.write(sampleHtml); }; document.getElementById('sourceCodeLink').href = githubProjectUrl + sourcePath; } else { document.getElementById('sourceCodeLinkPanel').style.display = 'none'; } iframe.focus(); } } xmlHttp.send(); } var spaceRx = /\s/g; function getSampleNode(name) { name = decodeURIComponent(name); var sampleLinks = document.getElementById('SampleTreeView').getElementsByTagName('a'); for (var i = 0; i < sampleLinks.length; i++) { if (sampleLinks[i].innerText === name) { return sampleLinks[i]; } } return null; } function getSamplesParent(sampleElm) { return sampleElm.parentNode.parentNode.parentNode.parentNode.parentNode.id; } function loadSampleByHash(hash) { var redirect = sampleRedirects[hash]; if (redirect) { hash = redirect; } var sampleNode = getSampleNode(hash); if (sampleNode) { currentSampleElm = sampleNode; currentSampleElm.classList.add('selectedNode'); window.location = sampleNode.href; var childNodesArg = getSamplesParent(sampleNode); var parentId = childNodesArg.replace('Nodes', ''); var nodeIndex = parentId.charAt(parentId.length - 1); if (/[0-9]+/.test(nodeIndex)) { TreeView_ToggleNode(SampleTreeView_Data, nodeIndex, document.getElementById(parentId), ' ', document.getElementById(childNodesArg)); } } } window.onload = function () { if (WarningMessage) { alert(WarningMessage); } var hash = window.location.hash; if (hash) { hash = hash.replace('#', ''); loadSampleByHash(hash); } return false; }; $(function () { $.widget("custom.catcomplete", $.ui.autocomplete, { _create: function () { this._super(); this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)"); }, _renderMenu: function (ul, items) { var that = this, currentCategory = ""; $.each(items, function (index, item) { var li; if (item.category != currentCategory) { ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>"); currentCategory = item.category; } li = that._renderItemData(ul, item); if (item.category) { li.attr("aria-label", item.category + " : " + item.label); } }); } }); SampleList.sort(function (a, b) { var nameA = a.label.toLowerCase(), nameB = b.label.toLowerCase(); if (nameA < nameB) return -1; if (nameA > nameB) return 1; return 0; //default return value (no sorting) }); $("#searchTbx").autocomplete({ delay: 0, source: SampleList, delay: 0, select: function (event, ui) { if (ui && ui.item && ui.item.action) { ui.item.action(); } } }).click(function () { $(this).val(''); }); $("#searchTbx").val('Search the samples'); }); var sampleRedirects = { 'CustomOverlay_HtmlPushpinLayer': 'Html%20Pushpin%20Layer', 'QueryAPI_Nearby': 'Find%20Nearby%20Search%20-%20Query%20API', 'CustomOverlay_CanvasLayer': 'Canvas%20Layer', "Map_ContextMenu": "Context%20Menu", "Map_KeyEvents": "Map%20Key%20Events", "Map_LazyLoading": "Lazy%20Loading%20the%20Map", "GeoJson_LocalFile": "GeoJson%20Drag%20and%20Drop", "Autosuggest_AddressForm": "Fill%20Address%20Form%20with%20Autosuggest", "Autosuggest_DefaultUI": "Autosugges%20with%20Map", "GeoXmlLayer%20-%20Local%20Data": "GeoXmlLayer%20-%20Same%20Domain", "Business%20Search%20Module": "POI%20Search%20Module", "GeoData_ChoroplethMap": "GeoData%20Choropleth%20Map", "DrawingTools_CustomToolbar": "Fully%20Custom%Drawing%20Toolbar", "QueryAPI%20-%20Load%20all%20results%20(parallel)": "Load%20all%20results%20(parallel)", "QueryAPI%20-%20Load%20all%20results%20(recursive)": "Load%20all%20results%20(recursive)", "QueryAPI_AlongRoute": "Search%20Along%20a%20Route", "QueryAPI_BasicIntersection": "Basic%20Intersection%20Search%20Query", "QueryAPI_ChoroplethMap": "Search%20Result%20Choropleth%20Map", "QueryAPI_DrawSearchArea": "Draw%20Search%20Area", "QueryAPI_FindByProperty": "Find%20By%20Property%20Query", "QueryAPI_Intersection": "Intersection%20Query", "QueryAPI_Paging": "Paging%20Search%20Results", "QueryAPI_SortByDrivingDistance": "Sort%20Query%20Results%20By%20Driving%20Distance", "Map_WithAngular1": "Basic%20Angular%201.6%20Map", "Pushpin%20Bar%20Chart%20(inline%20SVG)": "Bar%20Chart%20Pushpins%20(inline%20SVG)", "RestServices_jQuery": "RestServices_jQuery_JSONP", "Infobox_Custom": "Custom%20Infobox%20HTML%20Content", "Pushpin_DragEvents": "Draggable%20Pushpin", "Clustering_Basic": "Basic%20Clustering", "Clustering_Customization": "Cluster%20Layer%20Customizations", "Pushpin_FontBasedIcons": "Font%20Based%20Pushpin%20Icons", "Pushpin_DynamicCircles": "Scaled%20Circle%20(Bubbles)%20Pushpins" }; <|start_filename|>Samples/SiteResources/default.css<|end_filename|> body, html { font-family: Arial, Helvetica, sans-serif; } .header { position:relative; width: 100%; height: 50px; color: white; background-color: #333; } .pageLinks { position:absolute; right: 10px; top: 15px; } .subTitle { color: white; font-size: 24px; position: absolute; top: 11px; } .footer { position:fixed; width: calc(100% - 30px); height: 30px; color: gray; padding-left:30px; background-color: #333; line-height:30px; font-size:14px; } .header a, .header a:visited, .footer a, .footer a:visited{ color: gray; text-decoration: none; margin:0 5px; font-size: 14px; } .header a:hover, .footer a:hover { color: white; } .copyrights { position:absolute; right:30px; } .content { position:relative; width: 100%; height: calc(100vh - 80px); } .subpageContent{ font-size:14px; } .subpageContent a, .subpageContent:visited{ color: #00abec; } .subpageContent a:hover{ color: teal; } #sampleTreeContainer { width: 350px; float: left; height: calc(100vh - 90px); overflow-y:scroll; overflow-x:hidden; padding:5px; } .categoryNode { color: black; font-size:16px; } .sampleNode, #tableOfContents a, #tableOfContents a:visited { color: black; font-size:14px; text-decoration: none; } .sampleListHover, #tableOfContents a:hover { color: #00abec; } .selectedNode { color: teal; text-decoration: none; } #displayWindow { display:block; width: calc(100% - 360px); border: none; height: calc(100vh - 80px); float:left; } #sourceCodeLinkPanel { position: absolute; top: 10px; right: 30px; } .blueAnchorButton{ padding: 5px 10px; background-color: white; border: 1px solid #00abec; border-radius: 10px; color: #00abec; } .blueAnchorButton, .blueAnchorButton:visited { color: #00abec; text-decoration: none; } .blueAnchorButton:hover { background-color: #00abec; color: white !important; } #searchTbx { margin-bottom: 10px; margin-left: 10px; width: 300px; } .ui-autocomplete { font-size:12px; font-weight: bold; padding: .2em .4em; margin: .8em 0 .2em; line-height: 1.5; max-height: 50%; overflow-y: auto; overflow-x: hidden; } <|start_filename|>Samples/Tools/SVG Pushpin Maker/SVG Pushpin Maker.css<|end_filename|> body, html { padding:0; margin:0; } h2 { margin: 10px 0 0 0; font-size: 20px; } h3 { margin: 15px 0 10px 0; font-size: 16px; } .sidePanel { border-right: 1px solid #000; font-family: arial; float: left; position: relative; width: 400px; padding: 5px; height: calc(100vh - 10px); overflow-y:auto; } .rightPanel { margin-left: 10px; float: left; position: relative; width: calc(100vw - 450px); height: calc(100vh); } #myMap { margin-top:50px; position:relative; float:left; width: 100%; height: calc(100% - 418px); } #svgList, #symbolList { overflow-y: auto; height: 150px; padding: 5px; border: 1px solid #000; } .svgListItem { display: inline-block; cursor: pointer; padding: 5px; } .svgListItem:hover, .selectdItem { background-color:#aad0ff; } #svgOutput { position:relative; float:left; height: 352px; margin-top: 10px; width: 100%; } #svgList, #symbolList { background: url(/Common/images/backgroundGrid.png) repeat; } <|start_filename|>Samples/Ground Overlays/SVG Ground Overlay.html<|end_filename|> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script> var map, overlay; function GetMap() { map = new Microsoft.Maps.Map('#myMap', { center: new Microsoft.Maps.Location(51, 7), zoom: 9 }); overlay = new Microsoft.Maps.GroundOverlay({ bounds: Microsoft.Maps.LocationRect.fromEdges(52.552, 5.834, 50.315, 9.481), imageUrl: 'https://upload.wikimedia.org/wikipedia/commons/f/f1/North_Rhine-Westphalia_location_map_06.svg', backgroundColor: 'white' }); map.layers.insert(overlay); } </script> <script async defer src="https://bing.com/api/maps/mapcontrol?callback=GetMap&key=[YOUR_BING_MAPS_KEY]"></script> </head> <body> <div id="myMap" style="position:relative;width:800px;height:600px;"></div> <fieldset style="width:800px;margin-top:10px;"> <legend>SVG Ground Overlay Sample</legend> This sample shows how using an SVG as a ground overlay ensures that no matter how much you zoom into the ground overlay, it stays crisp and clear. However, a ground overlay is only as accurate as the scale at which it was drawn. The ground overlay in this sample is sourced from <a href="https://commons.wikimedia.org/wiki/File:North_Rhine-Westphalia_location_map_06.svg/overlay.kml">Wikimedia Commons</a>. </fieldset> </body> </html> <|start_filename|>Samples/Map/Map inside of a tabbed panel.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript'> var map; function GetMap() { if (document.getElementById('MapContainer').style.display !== 'none') { map = new Microsoft.Maps.Map('#myMap', {}); } } function OpenTab(tabName) { //Get all tab contents. var x = document.getElementsByClassName('tabContents'); //Hide all tab contents. for (var i = 0; i < x.length; i++) { if (x[i].id === tabName) { x[i].style.display = 'block'; //Load the map if it isn't already loaded. if (!map) { GetMap(); } } else { x[i].style.display = 'none'; } } } </script> <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[YOUR_BING_MAPS_KEY]' async defer></script> <style> .tabBar { width: 100%; overflow: hidden; background-color: #000; } .tabButton { border: none; color: #000 !important; display: inline-block; padding: 8px 16px; vertical-align: middle; overflow: hidden; text-decoration: none; text-align: center; cursor: pointer; float: left; padding: 8px 16px; margin-right:5px; } .tabButton:hover { color: #000 !important; background-color: #ccc !important } </style> </head> <body> <div class="tabBar"> <button class="tabButton" onclick="OpenTab('Sample_Info')">Sample Info</button> <button class="tabButton" onclick="OpenTab('MapContainer')">Map</button> </div> <div id="Sample_Info" class="tabContents"> <h2>Map inside of a tabbed panel Sample</h2> <p> When the map is initially loaded, it does some calculations to determine its dimensions. If the map is in a hidden tab, it will have width and height of 0 which will result in the map not loading. It is also a best practice to delay the loading of the map until it's tab is displayed. This will result in Bing Maps transactions only being generated once the map is actually being viewed by the user, which can help reduce costs. It also reduces the resources used by the page until the map is needed. <br/><br/> If you want to further optimize this code you can also delay the loading of the Bing Maps API by <a href="https://bingmapsv8samples.azurewebsites.net/#Lazy%20Loading%20the%20Map">lazy loading the map</a>. </p> </div> <div id="MapContainer" class="tabContents" style="display:none"> <h2>Map</h2> <p><div id="myMap" style="position:relative;width:100%;height:600px;"></div></p> </div> </body> </html> <|start_filename|>Samples/Map/Map in liteMode.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript'> var map; function GetMap() { map = new Microsoft.Maps.Map('#myMap', { liteMode: true }); } </script> <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[YOUR_BING_MAPS_KEY]' async defer></script> </head> <body> <div id="myMap" style="position:relative;width:800px;height:600px;"></div> <fieldset style="width:800px;margin-top:10px;"> <legend>Map in liteMode Sample</legend> This sample shows how to put the map into liteMode. When liteMode is set to true vector labels are disabled and are rendered directly on the map tiles like previous versions of Bing Maps. The provides a performance boost, but also means labels will appear behind the data and that there is no label collision detection. Find out more about vector labels <a href="https://msdn.microsoft.com/en-us/library/mt750538.aspx" target="_blank">here</a>. </fieldset> </body> </html> <|start_filename|>Samples/Other/Solar Terminator/DayNightTerminatorModule.js<|end_filename|> /* * Copyright(c) 2017 Microsoft Corporation. All rights reserved. * * This code is licensed under the MIT License (MIT). * * 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. */ var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// <reference path="../../Common/typings/MicrosoftMaps/Microsoft.Maps.d.ts"/> var DayNightTerminator = (function (_super) { __extends(DayNightTerminator, _super); /********************** * Constructor ***********************/ /** * @contructor */ function DayNightTerminator(dateTime, options) { _super.call(this, [], options || { strokeColor: 'rgba(0,0,0,0)', fillColor: 'rgba(0,0,0,0.5)' }); this._R2D = 180 / Math.PI; this._D2R = Math.PI / 180; this.setLocations(this.computeLocations()); } /********************** * Public Functions ***********************/ DayNightTerminator.prototype.getDateTime = function () { return this.dateTime; }; DayNightTerminator.prototype.setDateTime = function (dateTime) { this.dateTime = dateTime; this.setLocations(this.computeLocations()); }; /********************** * Private Functions ***********************/ DayNightTerminator.prototype.computeLocations = function () { this.dateTime = this.dateTime || new Date(); var julianDay = this.getJulian(this.dateTime); var gst = this.getGMST(this.dateTime); var latLng = []; var ha, lat, lng; var sunEclPos = this._sunEclipticPosition(julianDay); var eclObliq = this._eclipticObliquity(julianDay); var sunEqPos = this._sunEquatorialPosition(sunEclPos.lambda, eclObliq); for (var i = 0; i <= 360; i++) { lng = -180 + i; ha = this._hourAngle(lng, sunEqPos, gst); lat = this._latitude(ha, sunEqPos); latLng[i + 1] = new Microsoft.Maps.Location(lat, lng); } if (sunEqPos.delta < 0) { latLng[0] = new Microsoft.Maps.Location(90, -179.999999); latLng[latLng.length] = new Microsoft.Maps.Location(90, 179.999999); } else { latLng[0] = new Microsoft.Maps.Location(-90, -179.999999); latLng[latLng.length] = new Microsoft.Maps.Location(-90, 179.999999); } return latLng; }; DayNightTerminator.prototype.getJulian = function (date) { /* Calculate the present UTC Julian Date. Function is valid after * the beginning of the UNIX epoch 1970-01-01 and ignores leap * seconds. */ return (date.getTime() / 86400000) - (date.getTimezoneOffset() / 1440) + 2440587.5; }; DayNightTerminator.prototype.getGMST = function (date) { /* Calculate Greenwich Mean Sidereal Time according to http://aa.usno.navy.mil/faq/docs/GAST.php */ var julianDay = this.getJulian(date); var d = julianDay - 2451545.0; // Low precision equation is good enough for our purposes. return (18.697374558 + 24.06570982441908 * d) % 24; }; DayNightTerminator.prototype._sunEclipticPosition = function (julianDay) { /* Compute the position of the Sun in ecliptic coordinates at julianDay. Following http://en.wikipedia.org/wiki/Position_of_the_Sun */ // Days since start of J2000.0 var n = julianDay - 2451545.0; // mean longitude of the Sun var L = 280.460 + 0.9856474 * n; L %= 360; // mean anomaly of the Sun var g = 357.528 + 0.9856003 * n; g %= 360; // ecliptic longitude of Sun var lambda = L + 1.915 * Math.sin(g * this._D2R) + 0.02 * Math.sin(2 * g * this._D2R); // distance from Sun in AU var R = 1.00014 - 0.01671 * Math.cos(g * this._D2R) - 0.0014 * Math.cos(2 * g * this._D2R); return { "lambda": lambda, "R": R }; }; DayNightTerminator.prototype._eclipticObliquity = function (julianDay) { // Following the short term expression in // http://en.wikipedia.org/wiki/Axial_tilt#Obliquity_of_the_ecliptic_.28Earth.27s_axial_tilt.29 var n = julianDay - 2451545.0; // Julian centuries since J2000.0 var T = n / 36525; var epsilon = 23.43929111 - T * (46.836769 / 3600 - T * (0.0001831 / 3600 + T * (0.00200340 / 3600 - T * (0.576e-6 / 3600 - T * 4.34e-8 / 3600)))); return epsilon; }; DayNightTerminator.prototype._sunEquatorialPosition = function (sunEclLng, eclObliq) { /* Compute the Sun's equatorial position from its ecliptic * position. Inputs are expected in degrees. Outputs are in * degrees as well. */ var alpha = Math.atan(Math.cos(eclObliq * this._D2R) * Math.tan(sunEclLng * this._D2R)) * this._R2D; var delta = Math.asin(Math.sin(eclObliq * this._D2R) * Math.sin(sunEclLng * this._D2R)) * this._R2D; var lQuadrant = Math.floor(sunEclLng / 90) * 90; var raQuadrant = Math.floor(alpha / 90) * 90; alpha = alpha + (lQuadrant - raQuadrant); return { "alpha": alpha, "delta": delta }; }; DayNightTerminator.prototype._hourAngle = function (lng, sunPos, gst) { /* Compute the hour angle of the sun for a longitude on * Earth. Return the hour angle in degrees. */ var lst = gst + lng / 15; return lst * 15 - sunPos.alpha; }; DayNightTerminator.prototype._latitude = function (ha, sunPos) { /* For a given hour angle and sun position, compute the * latitude of the terminator in degrees. */ var lat = Math.atan(-Math.cos(ha * this._D2R) / Math.tan(sunPos.delta * this._D2R)) * this._R2D; return lat; }; return DayNightTerminator; }(Microsoft.Maps.Polygon)); //Call the module loaded function. Microsoft.Maps.moduleLoaded('DayNightTerminatorModule'); //# sourceMappingURL=DayNightTerminatorModule.js.map <|start_filename|>Samples/GeoXml/GeoXmlLayer - Same Domain.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript'> var map, layer; function GetMap() { map = new Microsoft.Maps.Map('#myMap', { zoom: 1 }); //Load the GeoXml module. Microsoft.Maps.loadModule('Microsoft.Maps.GeoXml', function () { //Create an instance of the GeoXmlLayer. layer = new Microsoft.Maps.GeoXmlLayer(); //Add the layer to the map. map.layers.insert(layer); }); } function readXml(xmlUrl) { //Set the URL of the geo XML file as the data source of the layer. layer.setDataSource(xmlUrl, true); } </script> <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[YOUR_BING_MAPS_KEY]' async defer></script> </head> <body> <div id="myMap" style="position:relative;width:800px;height:600px;"></div> <div style="margin-top:10px;"> GeoRSS: <input type="button" value="Countries" onclick="readXml('/Common/data/georss/Countries.xml');" /> <input type="button" value="Sample File" onclick="readXml('/Common/data/georss/SampleGeoRSS.xml');" /> <input type="button" value="Wifi Locations" onclick="readXml('/Common/data/georss/WifiLocations.xml');" /> <br /> GPX: <input type="button" value="Bike Route" onclick="readXml('/Common/data/gpx/BikeRoute.xml');" /> <input type="button" value="Route 66 Attractions" onclick="readXml('/Common/data/gpx/Route66Attractions.xml');" /> <input type="button" value="UK Tourist Locations" onclick="readXml('/Common/data/gpx/Tourist_locations_UK-England.xml');" /> <br /> KML: <input type="button" value="2007 San Diego Fires" onclick="readXml('/Common/data/kml/2007SanDiegoCountyFires.kml');" /> <input type="button" value="Countries" onclick="readXml('/Common/data/kml/Countries.kml');" /> <input type="button" value="London Tube Lines" onclick="readXml('/Common/data/kml/London%20Tube%20Lines.kml');" /> <input type="button" value="London Tube Stations" onclick="readXml('/Common/data/kml/London%20stations.kml');" /> <input type="button" value="Sample File" onclick="readXml('/Common/data/kml/SampleKml.kml');" /> <input type="button" value="Sample File 2" onclick="readXml('/Common/data/kml/esfr-trip-track-20080407.xml');" /> <input type="button" value="Ground Overlay" onclick="readXml('/Common/data/kml/GroundOverlay.kml');" /> <input type="button" value="Internet Users 2005 Choropleth" onclick="readXml('/Common/data/kml/internet_users_2005_choropleth.kml');" /> <br /> KMZ: <input type="button" value="Recreation Site Point" onclick="readXml('/Common/data/kmz/RecreationSitePoint.kmz');" /> <input type="button" value="Shuckstack fire tower" onclick="readXml('/Common/data/kmz/shuckstack-fire-tower.kmz');" /> <br /> <br /> Layer Options: <br /> <input type="button" onclick="layer.clear();" value="Clear" /> <input type="button" onclick="layer.setVisible(false);" value="Hide" /> <input type="button" onclick="layer.setVisible(true);" value="Show" /> </div> <fieldset style="width:800px;margin-top:10px;"> <legend>GeoXmlLayer - Local Data Sample</legend> This sample shows how to load geospatial XML data from locally hosted files.<br /> <b>Note:</b> Not all file and mime types are enabled in all servers. If using .NET, it is recommended to add the following to the web.config file: <br /> <br /> &lt;system.webServer&gt;<br />&nbsp;&nbsp;&lt;staticContent&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&lt;mimeMap fileExtension=&quot;.json&quot; mimeType=&quot;application/json&quot; /&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&lt;mimeMap fileExtension=&quot;.geojson&quot; mimeType=&quot;application/json&quot; /&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&lt;mimeMap fileExtension=&quot;.gpx&quot; mimeType=&quot;application/xml&quot; /&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&lt;mimeMap fileExtension=&quot;.georss&quot; mimeType=&quot;application/xml&quot; /&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&lt;mimeMap fileExtension=&quot;.kml&quot; mimeType=&quot;application/vnd.google-earth.kml+xml&quot; /&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&lt;mimeMap fileExtension=&quot;.kmz&quot; mimeType=&quot;application/vnd.google-earth.kmz&quot; /&gt;<br />&nbsp;&nbsp;&lt;/staticContent&gt;<br/>&lt;system.webServer&gt; </fieldset> </body> </html> <|start_filename|>Samples/Clustering/Basic Clustering.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type="text/javascript"> var map, clusterLayer; function GetMap() { map = new Microsoft.Maps.Map('#myMap', {}); //Load the Clustering module. Microsoft.Maps.loadModule("Microsoft.Maps.Clustering", function () { //Generate 1,000 random pushpins in the map view. var pins = Microsoft.Maps.TestDataGenerator.getPushpins(1000, map.getBounds()); //Create a ClusterLayer and add it to the map. clusterLayer = new Microsoft.Maps.ClusterLayer(pins); map.layers.insert(clusterLayer); }); } </script> <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[YOUR_BING_MAPS_KEY]' async defer></script> </head> <body> <div id="myMap" style="position:relative;width:800px;height:600px;"></div> <fieldset style="width:800px;margin-top:10px;"> <legend>Basic Clustering Sample</legend> This sample shows how to implement basic pushpin clustering into your app. Zoom in and notice how the clusters break apart into their individual pushpins. Zoom out and see the pushpins group together into clusters. Clustering helps keep the map uncluttered while also reducing the number of objects being rendered which improves performance. </fieldset> </body> </html> <|start_filename|>Samples/Welcome.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <link type="text/css" rel="stylesheet" href="SiteResources/default.css" /> <script> window.onload = function () { document.getElementById('numberOfSamples').innerText = window.parent.NumberOfSamples; }; </script> </head> <body> <div class="subpageContent" style="max-width:800px;margin:10px;"> <h2>Welcome to the Bing Maps V8 Code Sample project </h2> This is a collection of code samples for the Bing Maps V8 web control which have been made open source on Github. These samples have been collected from a number of different sources. Some of these samples where created to assist developers on the <a href="https://social.msdn.microsoft.com/Forums/en-US/home?category=bingmaps">Bing Maps forums</a> many were created for the <a href="http://blogs.bing.com/maps" target="_blank">Bing Maps blog</a>, <a href="https://msdn.microsoft.com/en-us/library/mt712542.aspx" target="_blank">MSDN Documentation</a> and <a href="http://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk" target="_blank">Interactive SDK</a> while others were submitted by Bing Maps community developers. Be sure to also take a look at the list of <a href="javascript:window.parent.loadSample('External Samples', 'ExternalSamples.html');">external samples</a> as well. <br /> <br /> # of samples: <span id="numberOfSamples"></span> <br /> <br /> <iframe src="https://ghbtns.com/github-btn.html?user=Microsoft&repo=BingMapsV8CodeSamples&type=star&count=true" frameborder="0" scrolling="0" style="width:100px;height:20px"></iframe> <br /> <br /> <a href="https://github.com/Microsoft/BingMapsV8CodeSamples" class="blueAnchorButton" target="_blank">Open GitHub Project</a> </div> </body> </html> <|start_filename|>Samples/Search/POI Search/PoiSearchModule.js<|end_filename|> /* * Copyright(c) 2017 Microsoft Corporation. All rights reserved. * * This code is licensed under the MIT License (MIT). * * 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. */ var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /// <reference path="../../Common/typings/MicrosoftMaps/Microsoft.Maps.d.ts"/> var Microsoft; (function (Microsoft) { var Maps; (function (Maps) { var Search; (function (Search) { /** * Represents a search result pushpin. */ var IPoiPushpin = (function (_super) { __extends(IPoiPushpin, _super); function IPoiPushpin() { return _super !== null && _super.apply(this, arguments) || this; } return IPoiPushpin; }(Microsoft.Maps.Pushpin)); Search.IPoiPushpin = IPoiPushpin; /** * A list of all entity types. * Entity Types as defined here: https://msdn.microsoft.com/en-us/library/hh478191.aspx */ Search._entityTypeSynonyms = [ //Petrol/Gasoline Station - 5540 { id: '5540', syn: [ ['gasstation', 'servicestation', 'gas', 'petro', 'petrostation', 'gasoline', 'gasolinestation'], ['76'], ['7eleven'], ['chevron'], ['arco'], ['costco'], ['shell'], ['hess'], ['valero'], ['sunoco'], ['bp', 'britishpetrolum'], ['exxonmobil', 'exxon'], ] }, //Restaurant - 5800 { id: '5800', syn: [ ['food', 'restaurant', 'cuisine'], ['beer', 'pub', 'tavern', 'taproom', 'cocktail', 'wine'], ['italian', 'pizza', 'pizzeria', 'trattoria', 'ristorante'], ['sub', 'sandwich', 'deli'], ['mexican', 'taco', 'burrito'], ['bakery', 'bakeries'], ['chinese'], ['thai'], ['bbq', 'barbeque'], ['kfc', 'kentuckyfriedchicken'], ['mcdonalds'], ['burgerking'], ['subway'], ['pizzahut'], ['dominos'], ['tacobell'], ['papajohns'], ['dairyqueen'], ['baskinrobbins'], ['littlecaesars'], ['krispykreme'], ['wendys'], ['chipotle'], ['tacodelmar'] ] }, //Nightlife - 5813 { id: '5813', syn: [ ['beer', 'pub', 'disco', 'cocktaillounge', 'nightclub', 'beerhouse', 'tavern', 'taproom', 'cocktail', 'wine'] ] }, //Shopping - 6512 { id: '5813', syn: [ ['mall', 'shoppingcenter', 'stripmall', 'marketplace', 'store'], ['walmart', 'walmartsuperstore'], ['costco'], ['thehomedepot', 'homedepot'], ['walgreens'], ['cvscaremark'], ['target'], ['lowes'], ['macys'], ['bestbuy'], ['sears'], ['kohls'], ['meijer'], ['nordstrom'], ['gap'] ] }, //Grocery Store - 5400 { id: '5400', syn: [ ['grocerystore', 'groceries', 'food'], ['fredmeyer'], ['safeway'], ['tescos'], ['wholefoods'], ['tescos'], ['aldi'], ['traderjoes'], ['kroger'], ['costco'], ['albertsons'], ['walmart'], ['marksandspencer'] ] }, //Clothing Store - 9537 { id: '9537', syn: [ ['clothingstore', 'store'], ['walmart', 'walmartsuperstore'], ['costco'], ['target'], ['macys'], ['sears'], ['kohls'], ['meijer'], ['nordstrom'], ['gap'] ] }, //Department Store - 9545 { id: '9545', syn: [ ['departmentstore', 'store'], ['walmart', 'walmartsuperstore'], ['target'], ['macys'], ['sears'], ['kohls'], ['meijer'], ['nordstrom'] ] }, //Rental Car Agency - 7510 { id: '7510', syn: [ ['carrentalagency', 'carrental', 'rentalcaragency'], ['hertzrentacar', 'hertzcarrental'], ['enterpriserentacar', 'enterprisecarrental'], ['budgetrentacar', 'budgetcarrental'], ['aviscarrental'], ['alamorentacar'] ] }, //Hotel - 7011 { id: '7011', syn: [ ['motel', 'inn', 'hostel', 'lodging', 'lodge', 'accommodation'], ['marriottinternational', 'marriott'], ['wyndham', 'wyndhamhotel'], ['intercontientalhotel', 'intercontiental'] ] }, //Cinema - 7832 { id: '7832', syn: [ ['cinema', 'movie', 'theater', 'theatre'], ['cineplexodeon', 'cineplex'], ['cinemarktheater', 'cinemark'], ['ipictheater', 'ipic'] ] }, //Auto Service & Maintenance - 7538 { id: '7538', syn: [ ['garage', 'autorepair', 'servicestation', 'autoservice', 'automaintenance'] ] }, //Hospital - 8060 { id: '8060', syn: [ ['medical', 'emergencyroom', 'hospital', 'clinic', 'walkinclinic'] ] }, //Higher Education - 8200 { id: '8200', syn: [ ['university', 'universities', 'college', 'school', 'education'] ] }, //Convenience Store - 9535 { id: '9535', syn: [ ['conveniencestore'], ['7eleven'] ] }, //Pharmacy - 9565 { id: '9565', syn: [ ['pharmacies', 'pharmacy', 'medicine'], ['cvspharmacies', 'cvspharmacy', 'cvs'], ['walgreens'], ['riteaidpharmacies', 'riteaidpharmacy'] ] }, //Place of Worship - 9992 { id: '9992', syn: [ ['churches', 'mosques', 'temples', 'synagogues', 'shrines', 'chapels', 'parhishes'], ['catholic', 'catholicchurch', 'catholicchurches'] ] }, //Coffee Shop - 9996 { id: '9996', syn: [ ['coffee', 'cafe', 'tea', 'caffé', 'coffeeshop', 'donutshop'], ['dunkindonuts'], ['starbucks'], ['timhortons'], ['costacoffeeshops'] ] }, //Winery - 2084 { id: '2084', syn: [['winery', 'wine']] }, //ATM - 3578 { id: '3578', syn: [['atm']] }, //Train Station - 4013 { id: '4013', syn: [['trainstation', 'trains']] }, //Commuter Rail Station - 4100 { id: '4100', syn: [['commuterrailstation']] }, //Bus Station - 4170 { id: '4170', syn: [['busstation', 'busstop']] }, //Named Place - 4444 { id: '4444', syn: [['namedplace']] }, //Ferry Terminal - 4482 { id: '4482', syn: [['ferryterminal']] }, //Marina - 4493 { id: '4493', syn: [['marina']] }, //Public Sports Airport - 4580 { id: '4580', syn: [['publicsportsairport']] }, //Airport - 4581 { id: '4581', syn: [['airport', 'airfield']] }, //Business Facility - 5000 { id: '5000', syn: [['businessfacility']] }, //Auto Dealerships - 5511 { id: '5511', syn: [['autodealerships']] }, //Auto Dealership-Used Cars - 5512 { id: '5512', syn: [['autodealershipusedcars', 'cardealership', 'dealership', 'usedcars', 'usedcardealership']] }, //Motorcycle Dealership - 5571 { id: '5571', syn: [['motorcycledealership']] }, //Historical Monument - 5999 { id: '5999', syn: [['historicalmonument']] }, //Bank - 6000 { id: '6000', syn: [['bank']] }, //Ski Resort - 7012 { id: '7012', syn: [['skiresort']] }, //Other Accommodation - 7013 { id: '7013', syn: [['otheraccommodation']] }, //Ski Lift - 7014 { id: '7014', syn: [['skilift']] }, //Tourist Information - 7389 { id: '7389', syn: [['touristinformation']] }, //Parking Lot - 7520 { id: '7520', syn: [['parkinglot']] }, //Parking Garage/House - 7521 { id: '7521', syn: [['parkinggaragehouse']] }, //Park & Ride - 7522 { id: '7522', syn: [['park&ride']] }, //Rest Area - 7897 { id: '7897', syn: [['restarea']] }, //Performing Arts - 7929 { id: '7929', syn: [['performingarts']] }, //Bowling Centre - 7933 { id: '7933', syn: [['bowlingcentre']] }, //Sports Complex - 7940 { id: '7940', syn: [['sportscomplex']] }, //Park/Recreation Area - 7947 { id: '7947', syn: [['parkrecreationarea']] }, //Casino - 7985 { id: '7985', syn: [['casino']] }, //Convention/Exhibition Centre - 7990 { id: '7990', syn: [['conventionexhibitioncentre']] }, //Golf Course - 7992 { id: '7992', syn: [['golfcourse']] }, //Civic/Community Centre - 7994 { id: '7994', syn: [['civiccommunitycentre', 'communitycentre', 'communitycenter']] }, //Amusement Park - 7996 { id: '7996', syn: [['amusementpark']] }, //Sports Centre - 7997 { id: '7997', syn: [['sportscentre']] }, //Ice Skating Rink - 7998 { id: '7998', syn: [['iceskatingrink']] }, //Tourist Attraction - 7999 { id: '7999', syn: [['touristattraction']] }, //School - 8211 { id: '8211', syn: [['school', 'gradeschool', 'elementaryschool', 'middleschool']] }, //Library - 8231 { id: '8231', syn: [['library', 'books']] }, //Museum - 8410 { id: '8410', syn: [['museum']] }, //Automobile Club - 8699 { id: '8699', syn: [['automobileclub']] }, //City Hall - 9121 { id: '9121', syn: [['cityhall']] }, //Court House - 9211 { id: '9211', syn: [['courthouse']] }, //Police Station - 9221 { id: '9221', syn: [['policestation']] }, //Campground - 9517 { id: '9517', syn: [['campground']] }, //Truck Stop/Plaza - 9522 { id: '9522', syn: [['truckstopplaza', 'truckstop']] }, //Government Office - 9525 { id: '9525', syn: [['governmentoffice']] }, //Post Office - 9530 { id: '9530', syn: [['postoffice']] }, //Home Specialty Store - 9560 { id: '9560', syn: [['homespecialtystore']] }, //Specialty Store - 9567 { id: '9567', syn: [['specialtystore']] }, //Sporting Goods Store - 9568 { id: '9568', syn: [['sportinggoodsstore']] }, //Medical Service - 9583 { id: '9583', syn: [['medicalservice']] }, //Residential Area/Building - 9590 { id: '9590', syn: [['residentialareabuilding']] }, //Cemetery - 9591 { id: '9591', syn: [['cemetery']] }, //Highway Exit - 9592 { id: '9592', syn: [['highwayexit']] }, //Transportation Service - 9593 { id: '9593', syn: [['transportationservice']] }, //Weigh Station - 9710 { id: '9710', syn: [['weighstation']] }, //Cargo Centre - 9714 { id: '9714', syn: [['cargocentre']] }, //Military Base - 9715 { id: '9715', syn: [['militarybase']] }, //Animal Park - 9718 { id: '9718', syn: [['animalpark']] }, //Truck Dealership - 9719 { id: '9719', syn: [['truckdealership', 'truck']] }, //Home Improvement & Hardware Store - 9986 { id: '9986', syn: [['homeimprovement', 'hardwarestore']] }, //Consumer Electronics Store - 9987 { id: '9987', syn: [ ['consumerelectronicsstore', 'electronics'], ['bestbuy'], ['att'] ] }, //Office Supply & Services Store - 9988 { id: '9988', syn: [ ['officesupply', 'officesupplies'], ['staples'] ] }, //Industrial Zone - 9991 { id: '9991', syn: [['industrialzone']] }, //Embassy - 9993 { id: '9993', syn: [['embassy']] }, //County Council - 9994 { id: '9994', syn: [['countycouncil']] }, //Bookstore - 9995 { id: '9995', syn: [['bookstore']] }, //Hamlet - 9998 { id: '9998', syn: [['hamlet']] }, //Border Crossing - 9999 { id: '9999', syn: [['bordercrossing']] } ]; /** * A search manager that performs poi/business search queries. */ var PoiSearchManager = (function () { /** * A search manager that performs business search queries. * @param map A map instance to retreive a session key from and use to perform a query. */ function PoiSearchManager(map) { this._navteqNA = 'https://spatial.virtualearth.net/REST/v1/data/f22876ec257b474b82fe2ffcb8393150/NavteqNA/NavteqPOIs'; this._navteqEU = 'https://spatial.virtualearth.net/REST/v1/data/c2ae584bbccc4916a0acf75d1e6947b4/NavteqEU/NavteqPOIs'; //Words used to connect a "what" with a "where". this._connectingWords = [" in ", " near ", " around ", " by ", "nearby"]; this._naPhoneRx = /([0-9]{3}-)([0-9]{3})([0-9]{4})/gi; this._ukPhoneRx = /([0-9]{2}-)([0-9]{4})([0-9]{4})/gi; this._fuzzyRx = /([-,.'\s]|s$)/gi; this._map = map; } /** * Performs a business search based on the specified request options and returns the results to the request options callback function. * @param request The business search request. */ PoiSearchManager.prototype.search = function (request) { var _this = this; if ((request.query && request.what) || !request.callback) { if (this.debug) { console.log('Invalid request'); } return; } if (!this._searchManager) { this._searchManager = new Microsoft.Maps.Search.SearchManager(this._map); } var self = this; if (!this._sessionKey) { this._map.getCredentials(function (c) { self._sessionKey = c; self.search(request); }); return; } request.count = (request.count > 0 && request.count <= 25) ? request.count : 25; request.searchRadius = (request.searchRadius > 0 && request.searchRadius <= 250) ? request.searchRadius : 25; request.matchConfidence = request.matchConfidence || Microsoft.Maps.Search.MatchConfidence.medium; if (request.query) { this._splitQueryString(request); } if (request.what) { request.what = request.what.toLowerCase().replace('-', ' ').replace("'", ''); } if (request.where) { if (request.where === 'me' || request.where === 'my location') { //Request the user's location navigator.geolocation.getCurrentPosition(function (position) { var loc = new Microsoft.Maps.Location(position.coords.latitude, position.coords.longitude); self._performPoiSearch(request, [{ address: null, bestView: new Microsoft.Maps.LocationRect(loc, 0.001, 0.001), entityType: 'userLocation', location: loc, locations: null, matchCode: null, matchConfidence: null, name: null }]); }); } else { this._searchManager.geocode({ where: request.where, callback: function (r) { if (r && r.results && r.results.length > 0) { _this._performPoiSearch(request, r.results); } else if (request.callback) { request.callback({ responseSummary: { errorMessage: "No geocode results for 'where'." } }, request.userData); } }, errorCallback: function (e) { request.callback({ responseSummary: { errorMessage: "No geocode results for 'where'." } }, request.userData); } }); } } else { this._performPoiSearch(request, null); } }; /** * Splits a free form query string into a what and where values. * @param request The request containing the free form query string. */ PoiSearchManager.prototype._splitQueryString = function (request) { var query = request.query.toLowerCase(); if (query.indexOf('find ') === 0 || query.indexOf('get ') === 0) { query = query.replace('find ', '').replace('get ', ''); } for (var i = 0; i < this._connectingWords.length; i++) { if (query.indexOf(this._connectingWords[i]) > 0) { var vals = query.split(this._connectingWords[i]); if (vals.length >= 2) { request.what = vals[0].trim(); request.where = vals[1].trim(); break; } else if (vals.length == 1) { request.what = vals[0].trim(); break; } } } if (!request.what) { request.what = request.query; } }; /** * Searches for business points of interests. * @param request The search request. * @param places An array of geocoded locations based on the "where" value of the request. */ PoiSearchManager.prototype._performPoiSearch = function (request, places) { var _this = this; var searchRegion; var alternateSearchRegions; if (places && places.length > 0) { searchRegion = places[0]; if (places.length > 1) { alternateSearchRegions = places.slice(1); } } else { searchRegion = { bestView: this._map.getBounds(), entityType: 'map', location: this._map.getCenter() }; } var self = this; var result = { alternateSearchRegions: alternateSearchRegions, searchRegion: searchRegion, searchResults: [], bestView: searchRegion.bestView }; var what = null; var whatRx = null; var synonyms = null; var filter = null; if (request.what) { //Remove dashes, single quotes, and trailing "s" from what and name values. what = request.what.replace(this._fuzzyRx, ''); if (what.indexOf('restaurant') > 0) { what = what.replace('restaurant', ''); } if (what.indexOf('cuisine') > 0) { what = what.replace('cuisine', ''); } if (what.indexOf('food') > 0) { what = what.replace('food', ''); } synonyms = this._getSynonums(what); filter = this._createPoiFilter(what, synonyms); whatRx = new RegExp('^(.*\\s)?' + what + '(\\s.*)?$', 'gi'); } if (this.debug) { console.log('Data source: ' + ((searchRegion.location.longitude < -26) ? 'NavteqNA' : 'NavteqEU')); if (filter) { console.log('Filter: ' + filter.toString()); } } //Request the top 250 results for the query and then filter them down afterwards. Microsoft.Maps.SpatialDataService.QueryAPIManager.search({ top: 250, queryUrl: (searchRegion.location.longitude < -26) ? this._navteqNA : this._navteqEU, inlineCount: true, spatialFilter: { spatialFilterType: 'nearby', location: searchRegion.location, radius: 25 }, filter: filter }, this._map, function (r, inlineCount) { if (r && r.length > 0) { var locs = []; var confidence; if (what && _this.debug) { console.log('Filtered out results\r\nEntityTypeID\tName'); } for (var i = 0; i < r.length; i++) { var s = r[i]; if (what) { confidence = _this._fuzzyPoiMatch(whatRx, r[i].metadata, synonyms); //Filter results client side. if (confidence === request.matchConfidence || request.matchConfidence === Microsoft.Maps.Search.MatchConfidence.low || request.matchConfidence === Microsoft.Maps.Search.MatchConfidence.unknown || (request.matchConfidence === Microsoft.Maps.Search.MatchConfidence.medium && confidence === Microsoft.Maps.Search.MatchConfidence.high)) { self._convertSearchResult(r[i]); s.metadata.matchConfidence = confidence; result.searchResults.push(s); locs.push(s.getLocation()); } else if (_this.debug) { console.log(r[i].metadata.EntityTypeID + '\t' + r[i].metadata.Name); } } else { self._convertSearchResult(r[i]); s.metadata.matchConfidence = Microsoft.Maps.Search.MatchConfidence.unknown; result.searchResults.push(s); locs.push(s.getLocation()); } if (result.searchResults.length >= request.count) { break; } } if (locs.length > 1) { result.bestView = Microsoft.Maps.LocationRect.fromLocations(locs); } else if (locs.length === 1) { result.bestView = new Microsoft.Maps.LocationRect(locs[0], 0.001, 0.001); } } if (result.searchResults.length === 0 && !request.where && request.what) { //If no results where found and a where hasn't been provided, but a what has. Try geocoding the what as ti may be a location. _this._searchManager.geocode({ where: request.what, callback: function (r) { if (r && r.results && r.results.length > 0) { result.searchRegion = r.results[0]; result.bestView = r.results[0].bestView; if (r.results.length > 1) { result.alternateSearchRegions = r.results.slice(1); } } if (request.callback) { request.callback(result, request.userData); } }, errorCallback: function (e) { if (request.callback) { request.callback(result, request.userData); } } }); } else if (request.callback) { request.callback(result, request.userData); } }); }; /** * Performs a fuzzy match between the "what" parameter of the request and the metadata of a result. * @param what The "what" parameter of the request. * @param metadata The metadata of a result. */ PoiSearchManager.prototype._fuzzyPoiMatch = function (whatRx, metadata, synonyms) { //Remove dashes, single quotes, and trailing "s" from name value. var lowerName = (metadata.Name) ? metadata.Name.toLowerCase().replace(this._fuzzyRx, '') : ''; var eid = metadata.EntityTypeID; //Check to see if the name matches the what query. if (whatRx.test(lowerName)) { return Microsoft.Maps.Search.MatchConfidence.high; } if (synonyms) { for (var i = 0; i < synonyms.length; i++) { for (var j = 0; j < synonyms[i].syn.length; j++) { for (var k = 0; k < synonyms[i].syn[j].length; k++) { if (lowerName.indexOf(synonyms[i].syn[j][k]) > -1) { return Microsoft.Maps.Search.MatchConfidence.high; } } } } } return Microsoft.Maps.Search.MatchConfidence.low; }; /** * Creates a filter for the Bing Spatial Data Services Query API based on the "what" parameter of the request. * @param what The "what" parameter of the request. */ PoiSearchManager.prototype._createPoiFilter = function (what, synonyms) { if (what) { var ids = []; if (synonyms) { for (var i = 0; i < synonyms.length; i++) { ids.push(synonyms[i].id); } } if (ids.length > 0) { return new Microsoft.Maps.SpatialDataService.Filter('EntityTypeID', Microsoft.Maps.SpatialDataService.FilterCompareOperator.isIn, ids); } } return null; }; /** * Converts a result from a NAVTEQ data source into a search result. * @param shape The shape result from the NAVTEQ data source. */ PoiSearchManager.prototype._convertSearchResult = function (shape) { var m = shape.metadata; var phone = m.Phone || ''; if (this._naPhoneRx.test(m.Phone)) { phone = m.Phone.replace(this._naPhoneRx, '$1$2-$3'); } else if (this._ukPhoneRx.test(m.Phone)) { phone = m.Phone.replace(this._ukPhoneRx, '$1$2-$3'); } var metadata = { id: m.EntityID, entityTypeId: m.EntityTypeID, address: m.AddressLine, adminDistrict: m.AdminDistrict, district: m.AdminDistrict2, city: m.Locality, country: m.CountryRegion, postalCode: m.PostalCode, name: m.DisplayName, phone: phone, matchConfidence: Microsoft.Maps.Search.MatchConfidence.unknown, distance: m.__distance }; shape.metadata = metadata; }; /** * Finds all synonums associated with the "what" value. * @param what What the user is looking for. */ PoiSearchManager.prototype._getSynonums = function (what) { var synonums = []; var syns = Microsoft.Maps.Search._entityTypeSynonyms; for (var i = 0; i < syns.length; i++) { var synonum = { id: syns[i].id, syn: [] }; for (var j = 0; j < syns[i].syn.length; j++) { if (syns[i].syn[j].indexOf(what) > -1) { synonum.syn.push(syns[i].syn[j]); } else { for (var k = 0; k < syns[i].syn[j].length; k++) { if (syns[i].syn[j][k].indexOf(what) > -1 && Math.abs(syns[i].syn[j][k].length - what.length) < 2) { synonum.syn.push(syns[i].syn[j]); break; } } } } if (synonum.syn.length > 0) { synonums.push(synonum); } } return synonums; }; return PoiSearchManager; }()); Search.PoiSearchManager = PoiSearchManager; })(Search = Maps.Search || (Maps.Search = {})); })(Maps = Microsoft.Maps || (Microsoft.Maps = {})); })(Microsoft || (Microsoft = {})); //Load dependancies Microsoft.Maps.loadModule(['Microsoft.Maps.Search', 'Microsoft.Maps.SpatialDataService'], function () { Microsoft.Maps.moduleLoaded('PoiSearchModule'); }); //# sourceMappingURL=PoiSearchModule.js.map <|start_filename|>Samples/Other/Angular16/app.js<|end_filename|> var ngBingMaps = angular.module('ngBingMaps', []); ngBingMaps.controller('MainCtrl', function ($scope) { $scope.title = "Bing Maps V8 with Angular 1.6 Sample"; $scope.center = [43.000, 13.0000]; $scope.pushpins = [{ latitude: 43.000, longitude: 13.0000, text: 'hi', color: 'red' }, { latitude: 43.0005, longitude: 13.0005, text: 'ok', color: 'blue' }]; $scope.onPushpinClick = function (pin) { alert(pin.color + ' pin clicked'); }; }); <|start_filename|>Samples/Map/Map Localization/Map Localization.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript'> function LoadMap() { var urOptions = document.getElementById("urOptions"); var userRegion = urOptions.options[urOptions.selectedIndex].value; var mktOptions = document.getElementById("mktOptions"); var mkt = mktOptions.options[mktOptions.selectedIndex].value; var langOptions = document.getElementById("langOptions"); var lang = langOptions.options[langOptions.selectedIndex].value; document.getElementById('mapContainer').src = '/Map/Map%20Localization/IframableLocalizedMap%20-%20Private.html?setLang=' + lang + '&setMkt=' + mkt + '&UR=' + userRegion + '&key=' + '[YOUR_BING_MAPS_KEY]'; } </script> </head> <body> User Region: <select id="urOptions"> <option value="AR">Argentina (AR)</option> <option value="BH">Bahrain (BH)</option> <option value="CN">China (CN)</option> <option value="EG">Egypt (EG)</option> <option value="IN">India (IN)</option> <option value="IL">Israel (IL)</option> <option value="JO">Jordon (JO)</option> <option value="KR">Korea (KR)</option> <option value="KW">Kuwait (KW)</option> <option value="MA">Morocco (MA)</option> <option value="OM">Oman (OM)</option> <option value="PK">Pakistan (PK)</option> <option value="QA">Qatar (QA)</option> <option value="SA">Saudi Arabia (SA)</option> <option value="AE">UAE (AE)</option> <option value="US" selected="selected">US</option> </select> Market/Language: <select id="mktOptions"> <option value="ar-SA">Arabic - Saudi Arabia (ar-SA)</option> <option value="eu">Basque (eu)</option> <option value="bg">Bulgarian (bg)</option> <option value="bg-BG">Bulgarian - Bulgaria (bg-BG)</option> <option value="ca">Catalan Spanish (ca)</option> <option value="ku-Arab">Central Kurdish (ku-Arab)</option> <option value="zh-CN">Chinese - China (zh-CN)</option> <option value="zh-HK">Chinese - Hong Kong (zh-HK)</option> <option value="zh-Hans">Chinese - Simplified (zh-Hans)</option> <option value="zh-TW">Chinese - Taiwan (zh-TW)</option> <option value="zh-Hant">Chinese - Traditional (zh-Hant)</option> <option value="cs">Czech (cs)</option> <option value="cs-CZ">Czech - Czech Republic (cs-CZ)</option> <option value="da">Danish (da)</option> <option value="da-DK">Danish - Denmark (da-DK)</option> <option value="nl-BE">Dutch - Belgium (nl-BE)</option> <option value="nl">Dutch - Netherlands (nl)</option> <option value="nl-NL">Dutch - Netherlands (nl-NL)</option> <option value="en-AU">English - Australia (en-AU)</option> <option value="en-CA">English - Canada (en-CA)</option> <option value="en-IN">English - India (en-IN)</option> <option value="en-GB">English - United Kingdom (en-GB)</option> <option value="en-US" selected="selected">English - United States (en-US)</option> <option value="fi">Finnish (fi)</option> <option value="fi-FI">Finnish - Finland (fi-FI)</option> <option value="fr-BE">French - Belgium (fr-BE)</option> <option value="fr-CA">French - Canada (fr-CA)</option> <option value="fr">French - France (fr)</option> <option value="fr-FR">French - France (fr-FR)</option> <option value="fr-CH">French - Switzerland (fr-CH)</option> <option value="gl">Galician (gl)</option> <option value="de">German - Germany (de)</option> <option value="de-DE">German - Germany (de-DE)</option> <option value="el">Greek (el)</option> <option value="he">Hebrew (he)</option> <option value="he-IL">Hebrew - Israel (he-IL)</option> <option value="hi">Hindi (hi)</option> <option value="hi-IN">Hindi - India (hi-IN)</option> <option value="hu">Hungarian (hu)</option> <option value="hu-HU">Hungarian - Hungary (hu-HU)</option> <option value="is">Icelandic (is)</option> <option value="is-IS">Icelandic - Iceland (is-IS)</option> <option value="it">Italian - Italy (it)</option> <option value="it-IT">Italian - Italy (it-IT)</option> <option value="ja">Japanese (ja)</option> <option value="ja-JP">Japanese - Japan (ja-JP)</option> <option value="ko">Korean (ko)</option> <option value="Ko-KR">Korean - Korea (Ko-KR)</option> <option value="ky-Cyrl">Kyrgyz (ky-Cyrl)</option> <option value="lv">Latvian (lv)</option> <option value="lv-LV">Latvian - Latvia (lv-LV)</option> <option value="lt">Lithuanian (lt)</option> <option value="lt-LT">Lithuanian - Lithuania (lt-LT)</option> <option value="nb">Norwegian - Bokmål (nb)</option> <option value="nb-NO">Norwegian - Bokmal - Norway (nb-NO)</option> <option value="nn">Norwegian - Nynorsk (nn)</option> <option value="pl">Polish (pl)</option> <option value="pl-PL">Polish - Poland (pl-PL)</option> <option value="pt-BR">Portuguese - Brazil (pt-BR)</option> <option value="pt-PT">Portuguese - Portugal (pt-PT)</option> <option value="ru">Russian (ru)</option> <option value="ru-RU">Russian - Russia (ru-RU)</option> <option value="es-MX">Spanish - Mexico (es-MX)</option> <option value="es">Spanish - Spain (es)</option> <option value="es-ES">Spanish - Spain (es-ES)</option> <option value="es-US">Spanish - United States (es-US)</option> <option value="sv">Swedish - Sweden (sv)</option> <option value="sv-SE">Swedish - Sweden (sv-SE)</option> <option value="tt-Cyrl">Tatar - Cyrillic (tt-Cyrl)</option> <option value="th">Thai (th)</option> <option value="th-TH">Thai - Thailand (th-TH)</option> <option value="tr">Turkish (tr)</option> <option value="tr-TR">Turkish - Turkey (tr-TR)</option> <option value="uk">Ukrainian (uk)</option> <option value="uk-UA">Ukrainian - Ukraine (uk-UA)</option> <option value="ug-Arab">Uyghur (ug-Arab)</option> <option value="ca-ES-valencia">Valencian (ca-ES-valencia)</option> <option value="vi">Vietnamese (vi)</option> <option value="vi-VN">Vietnamese - Vietnam (vi-VN)</option> </select> Language: <select id="langOptions"> <option value="ar-SA">Arabic - Saudi Arabia (ar-SA)</option> <option value="eu">Basque (eu)</option> <option value="bg">Bulgarian (bg)</option> <option value="bg-BG">Bulgarian - Bulgaria (bg-BG)</option> <option value="ca">Catalan Spanish (ca)</option> <option value="ku-Arab">Central Kurdish (ku-Arab)</option> <option value="zh-CN">Chinese - China (zh-CN)</option> <option value="zh-HK">Chinese - Hong Kong (zh-HK)</option> <option value="zh-Hans">Chinese - Simplified (zh-Hans)</option> <option value="zh-TW">Chinese - Taiwan (zh-TW)</option> <option value="zh-Hant">Chinese - Traditional (zh-Hant)</option> <option value="cs">Czech (cs)</option> <option value="cs-CZ">Czech - Czech Republic (cs-CZ)</option> <option value="da">Danish (da)</option> <option value="da-DK">Danish - Denmark (da-DK)</option> <option value="nl-BE">Dutch - Belgium (nl-BE)</option> <option value="nl">Dutch - Netherlands (nl)</option> <option value="nl-NL">Dutch - Netherlands (nl-NL)</option> <option value="en-AU">English - Australia (en-AU)</option> <option value="en-CA">English - Canada (en-CA)</option> <option value="en-IN">English - India (en-IN)</option> <option value="en-GB">English - United Kingdom (en-GB)</option> <option value="en-US" selected="selected">English - United States (en-US)</option> <option value="fi">Finnish (fi)</option> <option value="fi-FI">Finnish - Finland (fi-FI)</option> <option value="fr-BE">French - Belgium (fr-BE)</option> <option value="fr-CA">French - Canada (fr-CA)</option> <option value="fr">French - France (fr)</option> <option value="fr-FR">French - France (fr-FR)</option> <option value="fr-CH">French - Switzerland (fr-CH)</option> <option value="gl">Galician (gl)</option> <option value="de">German - Germany (de)</option> <option value="de-DE">German - Germany (de-DE)</option> <option value="el">Greek (el)</option> <option value="he">Hebrew (he)</option> <option value="he-IL">Hebrew - Israel (he-IL)</option> <option value="hi">Hindi (hi)</option> <option value="hi-IN">Hindi - India (hi-IN)</option> <option value="hu">Hungarian (hu)</option> <option value="hu-HU">Hungarian - Hungary (hu-HU)</option> <option value="is">Icelandic (is)</option> <option value="is-IS">Icelandic - Iceland (is-IS)</option> <option value="it">Italian - Italy (it)</option> <option value="it-IT">Italian - Italy (it-IT)</option> <option value="ja">Japanese (ja)</option> <option value="ja-JP">Japanese - Japan (ja-JP)</option> <option value="ko">Korean (ko)</option> <option value="Ko-KR">Korean - Korea (Ko-KR)</option> <option value="ky-Cyrl">Kyrgyz (ky-Cyrl)</option> <option value="lv">Latvian (lv)</option> <option value="lv-LV">Latvian - Latvia (lv-LV)</option> <option value="lt">Lithuanian (lt)</option> <option value="lt-LT">Lithuanian - Lithuania (lt-LT)</option> <option value="nb">Norwegian - Bokmål (nb)</option> <option value="nb-NO">Norwegian - Bokmal - Norway (nb-NO)</option> <option value="nn">Norwegian - Nynorsk (nn)</option> <option value="pl">Polish (pl)</option> <option value="pl-PL">Polish - Poland (pl-PL)</option> <option value="pt-BR">Portuguese - Brazil (pt-BR)</option> <option value="pt-PT">Portuguese - Portugal (pt-PT)</option> <option value="ru">Russian (ru)</option> <option value="ru-RU">Russian - Russia (ru-RU)</option> <option value="es-MX">Spanish - Mexico (es-MX)</option> <option value="es">Spanish - Spain (es)</option> <option value="es-ES">Spanish - Spain (es-ES)</option> <option value="es-US">Spanish - United States (es-US)</option> <option value="sv">Swedish - Sweden (sv)</option> <option value="sv-SE">Swedish - Sweden (sv-SE)</option> <option value="tt-Cyrl">Tatar - Cyrillic (tt-Cyrl)</option> <option value="th">Thai (th)</option> <option value="th-TH">Thai - Thailand (th-TH)</option> <option value="tr">Turkish (tr)</option> <option value="tr-TR">Turkish - Turkey (tr-TR)</option> <option value="uk">Ukrainian (uk)</option> <option value="uk-UA">Ukrainian - Ukraine (uk-UA)</option> <option value="ug-Arab">Uyghur (ug-Arab)</option> <option value="ca-ES-valencia">Valencian (ca-ES-valencia)</option> <option value="vi">Vietnamese (vi)</option> <option value="vi-VN">Vietnamese - Vietnam (vi-VN)</option> </select> <input type="button" value="Load Map" onclick="LoadMap()" /> <br /> <iframe id="mapContainer" src="about:blank" style="width:100%;height:calc(100vh - 200px);" frameborder="0" scrolling="no"></iframe> </body> </html> <|start_filename|>Samples/Rest Services/RestServices_jQuery_JSONP.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script> <script type='text/javascript'> function geocode() { var query = document.getElementById('input').value; var geocodeRequest = "https://dev.virtualearth.net/REST/v1/Locations?query=" + encodeURIComponent(query) + "&key=" + '[YOUR_BING_MAPS_KEY]'; CallRestService(geocodeRequest, GeocodeCallback); } function GeocodeCallback(response) { var output = document.getElementById('output'); if (response && response.resourceSets && response.resourceSets.length > 0 && response.resourceSets[0].resources) { var results = response.resourceSets[0].resources; var html = ['<table><tr><td>Name</td><td>Latitude</td><td>Longitude</td></tr>']; for (var i = 0; i < results.length; i++) { html.push('<tr><td>', results[i].name, '</td><td>', results[i].point.coordinates[0], '</td><td>', results[i].point.coordinates[1], '</td></tr>'); } html.push('</table>'); output.innerHTML = html.join(''); } else { output.innerHTML = "No results found."; } } function CallRestService(requestUrl, callback) { $.ajax({ url: requestUrl, dataType: "jsonp", jsonp: "jsonp", success: function (r) { callback(r); }, error: function (e) { alert(e.statusText); } }); } </script> </head> <body> <input type="text" id="input" value="New York"/> <input type="button" onClick="geocode()" value="Search" /><br/> <div id="output" style="height:150px;"></div> <fieldset style="width:800px;margin-top:10px;"> <legend>REST Services jQuery JSONP Sample</legend> This sample shows how to call the Bing Maps REST services using jQuery and a JSONP request.<br /><br /> The Bing Maps REST services were initially released many years ago before browsers supported cross domain requests using <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing">CORS</a>. To get around this <a href="https://en.wikipedia.org/wiki/JSONP">JSONP</a> requests where made which would tell the server to wrap the response with a JavaScript function. JSONP requests would then be loaded like a JavaScript file rather than queries like a API. The Bing Maps REST services now support CORS as well. </fieldset> </body> </html> <|start_filename|>Samples/Experimental/BasicTileLayer/BasicTileLayerModule.js<|end_filename|> /* * Copyright(c) 2017 Microsoft Corporation. All rights reserved. * * This code is licensed under the MIT License (MIT). * * 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. */ var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /// <reference path="../../Common/typings/MicrosoftMaps/Microsoft.Maps.d.ts"/> /** * A reusable class for overlaying HTML elements as pushpins on the map. */ var BasicTileLayer = (function (_super) { __extends(BasicTileLayer, _super); /********************** * Constructor ***********************/ /** * @constructor */ function BasicTileLayer(options) { var _this = _super.call(this) || this; /********************** * Private Properties ***********************/ /** A variable to store the viewchange event handler id. */ _this._viewChangeEventHandler = null; /** A variable to store the viewchangeend event handler id. */ _this._viewChangeEndEventHandler = null; /** A variable to store the map resize event handler id. */ _this._mapResizeEventHandler = null; /** A variable to store a reference to the container for the HTML pushpins. */ _this._container = null; _this._tileLayerOptions = { visible: true, mercator: null, opacity: 1, zIndex: 0, downloadTimeout: 10000 }; _this._tiles = []; _this._tileIds = []; if (!options) { throw 'A tile layer options must be specified in a BasicTileLayer.'; } else if (!options.mercator) { throw 'A tile source must be specified in a BasicTileLayer.'; } _this.setOptions(options); return _this; } /********************** * Overridden functions ***********************/ /** * Layer added to map. Setup rendering container. */ BasicTileLayer.prototype.onAdd = function () { //Create a div that will hold the pushpins. this._container = document.createElement('div'); this._container.style.position = 'absolute'; this._container.style.left = '0px'; this._container.style.top = '0px'; this.setHtmlElement(this._container); }; /** * Layer loaded, add map events for updating position of data. */ BasicTileLayer.prototype.onLoad = function () { var _this = this; var map = this.getMap(); this._mapWidth = map.getWidth(); this._mapHeight = map.getHeight(); //Update the position of the pushpin when the view changes. Hide the layer if map changed to streetside. this._viewChangeEventHandler = Microsoft.Maps.Events.addHandler(map, 'viewchange', function (e) { _this._viewChange(); }); this._viewChangeEndEventHandler = Microsoft.Maps.Events.addHandler(map, 'viewchangeend', function (e) { _this._viewChanged(e); }); //Update the position of the overlay when the map is resized. this._mapResizeEventHandler = Microsoft.Maps.Events.addHandler(map, 'mapresize', function (e) { _this._viewChanged(e); }); this.setOptions(this._tileLayerOptions); }; /** * Layer removed from map. Release resources. */ BasicTileLayer.prototype.onRemove = function () { this.setHtmlElement(null); //Remove the event handler that is attached to the map. Microsoft.Maps.Events.removeHandler(this._viewChangeEventHandler); Microsoft.Maps.Events.removeHandler(this._viewChangeEndEventHandler); Microsoft.Maps.Events.removeHandler(this._mapResizeEventHandler); for (var i = 0; i < this._tiles.length; i++) { if (this._tiles[i]) { this._tiles[i] = null; this._tileIds[i] = null; } } this._tiles = null; this._tileIds = null; }; /********************** * Public Functions ***********************/ /** * Retrieves the opacity of the layer. * @returns The opacity of the layer. */ BasicTileLayer.prototype.getOpacity = function () { return this._tileLayerOptions.opacity; }; /** * Retrieves the tile source of the layer. * @returnsTthe tile source of the layer. */ BasicTileLayer.prototype.getTileSource = function () { return this._tileLayerOptions.mercator; }; /** * Retrieves the visibility of the layer. * @returns The visibility of the layer. */ BasicTileLayer.prototype.getVisible = function () { return this._tileLayerOptions.visible; }; /** * Retrieves the ZIndex of the layer. * @returns The ZIndex of the layer. */ BasicTileLayer.prototype.getZIndex = function () { return this._tileLayerOptions.zIndex; }; /** * Sets the opacity of the layer. * @param show The opacity of the layer. */ BasicTileLayer.prototype.setOpacity = function (opacity) { this._tileLayerOptions.opacity = opacity; this._container.style.opacity = opacity.toString(); }; /** * Sets the options of the layer. * @param opt The options of the layer. */ BasicTileLayer.prototype.setOptions = function (opt) { if (opt) { if (typeof opt.opacity === 'number') { this.setOpacity(opt.opacity); } if (typeof opt.visible === 'boolean') { this.setVisible(opt.visible); } if (typeof opt.zIndex === 'number') { this.setZIndex(opt.zIndex); } if (opt.mercator) { this._tileLayerOptions.mercator = new Microsoft.Maps.TileSource({ bounds: opt.mercator.getBounds() || new Microsoft.Maps.LocationRect(new Microsoft.Maps.Location(0, 0), 360, 180), maxZoom: opt.mercator.getMaxZoom() || 21, minZoom: opt.mercator.getMinZoom() || 1, uriConstructor: opt.mercator.getUriConstructor() }); this._reloadTiles(); } } }; /** * Sets the visibility of the layer. * @param show The visibility of the layer. */ BasicTileLayer.prototype.setVisible = function (show) { this._tileLayerOptions.visible = show; if (show) { this._container.style.display = ''; } else { this._container.style.display = 'none'; } }; /** * Sets the zIndex of the layer. * @param idx The zIndex of the layer. */ BasicTileLayer.prototype.setZIndex = function (idx) { this._tileLayerOptions.zIndex = idx; this._container.style.zIndex = idx.toString(); }; /********************** * Private Functions ***********************/ BasicTileLayer.prototype._viewChange = function () { //Hide tile layer when moving the map for now. var zoom = this._map.getZoom(); var self = this; setTimeout(function () { if (self._currentZoom !== zoom) { var scale = Math.pow(2, zoom - self._currentZoom); self._container.style.transform = 'scale(' + scale + ')'; self._container.style.transformOrigin = (self._mapWidth / 2) + 'px ' + (self._mapHeight / 2) + 'px'; self._updatePositions(false); } else { self._container.style.transform = ''; self._updatePositions(false); } }, 0); }; BasicTileLayer.prototype._viewChanged = function (e) { this._mapWidth = this._map.getWidth(); this._mapHeight = this._map.getHeight(); this._container.style.transformOrigin = (this._mapWidth / 2) + 'px ' + (this._mapHeight / 2) + 'px'; var mapType = this._map.getMapTypeId(); if (mapType !== Microsoft.Maps.MapTypeId.streetside && mapType !== Microsoft.Maps.MapTypeId.birdseye && this._tileLayerOptions.visible) { var self = this; setTimeout(function () { self._reloadTiles(); self._container.style.display = ''; }, 0); } }; /** * Reloads all tiles on the layer. */ BasicTileLayer.prototype._reloadTiles = function () { var _this = this; if (!this._container || !this._map) { return; } this._container.style.transform = ''; var center = this._map.getCenter(); var zoom = this._map.getZoom(); if (zoom >= this._tileLayerOptions.mercator.getMinZoom() && zoom <= this._tileLayerOptions.mercator.getMaxZoom()) { var dx = Math.ceil(this._mapWidth / 512) + 1; var dy = Math.ceil(this._mapHeight / 512) + 1; var cpx = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(center, zoom); var topLeftGlobalPixel = new Microsoft.Maps.Point(cpx.x - this._mapWidth / 2, cpx.y - this._mapHeight / 2); this._mapSize = Microsoft.Maps.SpatialMath.Tiles.mapSize(zoom) / 256 - 1; var centerTile = Microsoft.Maps.SpatialMath.Tiles.locationToTile(center, zoom); this._createTile(centerTile.x, centerTile.y, zoom, topLeftGlobalPixel); var minX = Math.max(0, centerTile.x - dx); var maxX = Math.min(centerTile.x + dx, this._mapSize - 1); var minY = Math.max(0, centerTile.y - dy); var maxY = Math.min(centerTile.y + dy, this._mapSize - 1); //for (var x = minX; x <= maxX; x++) { // for (var y = minY; y <= maxY; y++) { // this._createTile(x, y, zoom, topLeftGlobalPixel); // } //} var midX = Math.floor((maxX + minX) / 2); var midY = Math.floor((maxY + minY) / 2); //Load tiles from the middle out. for (var x = 0; x <= maxX - midX; x++) { for (var y = 0; y <= maxY - midY; y++) { if (midX - x >= minX) { if (midY - y >= minY) { this._createTile(midX - x, midY - y, zoom, topLeftGlobalPixel); } if (midY + y <= maxY) { this._createTile(midX - x, midY + y, zoom, topLeftGlobalPixel); } } if (midX + x <= maxX) { if (midY - y >= minY) { this._createTile(midX + x, midY - y, zoom, topLeftGlobalPixel); } if (midY + y <= maxY) { this._createTile(midX + x, midY + y, zoom, topLeftGlobalPixel); } } // this._createTile(x, y, zoom, topLeftGlobalPixel); } } } this._updatePositions(true); if (typeof this._tileDownloadTimer === 'number') { clearTimeout(this._tileDownloadTimer); } this._tileDownloadTimer = setTimeout(function () { _this._removeOldTiles(); }, this._tileLayerOptions.downloadTimeout); this._currentZoom = zoom; this._currentCenter = center; }; BasicTileLayer.prototype._createTile = function (tileX, tileY, zoom, topLeftGlobalPixel) { var tileId = tileX + '_' + tileY + '_' + zoom; var tileIdx = this._tileIds.indexOf(tileId); var tile = null; if (tileIdx > -1) { tile = this._tiles[tileIdx]; } if (!tile) { var self = this; var tileInfo = new Microsoft.Maps.PyramidTileId(tileX, tileY, zoom); var bounds = Microsoft.Maps.SpatialMath.Tiles.tileToLocationRect(tileInfo); if (this._tileLayerOptions.mercator.getBounds().intersects(bounds)) { tileIdx = self._tileIds.length; self._tileIds.push(tileId); self._tiles[tileIdx] = { id: tileId, tileInfo: tileInfo, img: null }; var tileUrl = ''; var urlCon = this._tileLayerOptions.mercator.getUriConstructor(); if (typeof urlCon === "function") { tileUrl = urlCon(tileInfo); } else { tileUrl = urlCon.replace(/{quadkey}/gi, tileInfo.quadKey).replace(/{x}/gi, tileInfo.x.toString()).replace(/{y}/gi, tileInfo.y.toString()).replace(/{zoom}/gi, tileInfo.zoom.toString()) .replace(/{bbox}/gi, bounds.getWest() + ',' + bounds.getSouth() + ',' + bounds.getEast() + ',' + bounds.getNorth()); } var img = new Image(256, 256); img.style.position = 'absolute'; img.style.pointerEvents = 'none'; img.onload = function (image) { if (self._tiles[tileIdx]) { //Set position. img.style.top = (self._tiles[tileIdx].tileInfo.y * 256 - topLeftGlobalPixel.y) + 'px'; img.style.left = (self._tiles[tileIdx].tileInfo.x * 256 - topLeftGlobalPixel.x) + 'px'; self._container.appendChild(img); self._tiles[tileIdx].img = img; } }; img.onerror = function () { self._tiles[tileIdx] = null; }; if (tileUrl !== '') { img.src = tileUrl; } } } else if (tile.img) { //Tile already exists, update its position. tile.img.style.top = (tileY * 256 - topLeftGlobalPixel.y) + 'px'; tile.img.style.left = (tileX * 256 - topLeftGlobalPixel.x) + 'px'; } }; /** * Updates the positions of all tiles in the layer. */ BasicTileLayer.prototype._updatePositions = function (removeTiles) { var center = this._map.getCenter(); var zoom = this._map.getZoom(); var cpx = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(center, zoom); var topLeftGlobalPixel = new Microsoft.Maps.Point(cpx.x - this._mapWidth / 2, cpx.y - this._mapHeight / 2); for (var i = 0; i < this._tiles.length; i++) { if (this._tiles[i]) { if (removeTiles && this._tiles[i].tileInfo.zoom !== zoom) { if (this._tiles[i].img) { this._container.removeChild(this._tiles[i].img); } this._tiles[i] = null; this._tileIds[i] = null; } else if (this._tiles[i].img) { this._tiles[i].img.style.top = (this._tiles[i].tileInfo.y * 256 - topLeftGlobalPixel.y) + 'px'; this._tiles[i].img.style.left = (this._tiles[i].tileInfo.x * 256 - topLeftGlobalPixel.x) + 'px'; } } } }; BasicTileLayer.prototype._removeOldTiles = function () { var currentTiles = []; var currentTileIdx = []; for (var i = 0; i < this._tiles.length; i++) { if (this._tiles[i]) { currentTiles.push(this._tiles[i]); currentTileIdx.push(this._tiles[i].id); } } this._tiles = currentTiles; this._tileIds = currentTileIdx; }; return BasicTileLayer; }(Microsoft.Maps.CustomOverlay)); //Load dependancy module. Microsoft.Maps.loadModule('Microsoft.Maps.SpatialMath', function () { //Call the module loaded function. Microsoft.Maps.moduleLoaded('BasicTileLayerModule'); }); //# sourceMappingURL=BasicTileLayerModule.js.map <|start_filename|>Samples/Other/Angular16/directives.js<|end_filename|> 'use strict'; ngBingMaps.directive('map', [function ($compile) { return { restrict: 'E', controller: ['$scope', function ($scope) { this.buffer_pushpins = []; this.mapHtmlEl = null this.map = null; this.exeFunc = function (func, context, args) { $scope.$parent[func].apply(context, args); } this.addPushpin = function (pushpin) { if (this.map) { this.map.entities.push(pushpin); } else { this.buffer_pushpins.push(pushpin); } } this.removePushpin = function (pushpin) { this.map.entities.remove(pushpin); } this.initializePushpins = function () { for (var i = 0; i < this.buffer_pushpins.length; i++) { var pushpin = this.buffer_pushpins[i]; if (this.map) { this.map.entities.push(pushpin); } } } this.initializeMap = function (scope, elem, attrs) { var map_canvas = document.createElement('div'); map_canvas.style.width = attrs.width; map_canvas.style.height = attrs.height; var _thisCtrl = this; var def_coords = eval(attrs.center); _thisCtrl.map = new Microsoft.Maps.Map(map_canvas, { center: new Microsoft.Maps.Location(def_coords[0], def_coords[1]), mapTypeId: 'a', zoom: 18 }); _thisCtrl.initializePushpins(); $(this.mapHtmlEl).append('<span ng-transclude></span>') this.mapHtmlEl = map_canvas; } this.setCenter = function (position) { var position = eval(position) var _position = new Microsoft.Maps.Location(position[0], position[1]) if (this.map) { this.map.setView({ center: _position }); } } }], scope: { 'center': '@', }, link: function (scope, element, attrs, ctrl) { scope.$watch('center', function (center) { if (center) { ctrl.setCenter(center); } }, false); if (!window.mapScriptLoaded) { //Wait for map API to be loaded before loading map. window.mapScriptLoadCallback = function () { ctrl.initializeMap(scope, element, attrs); element.append(ctrl.mapHtmlEl); window.mapScriptLoaded = true; }; } else { ctrl.initializeMap(scope, element, attrs); element.append(ctrl.mapHtmlEl); } } } }]); ngBingMaps.directive('pushpin', [function ($compile) { return { restrict: 'E', require: '^map', controllerAs: 'pushpin', link: function (scope, element, attrs, mapController) { var getPushpin = function () { var lat = attrs.lat var lng = attrs.lng; var text = attrs.text; var color = attrs.color; var location = new Microsoft.Maps.Location(lat, lng); var pushpin = new Microsoft.Maps.Pushpin(location, { text: text, color: color }); if (attrs.click) { var matches = attrs.click.match(/([^\(]+)\(([^\)]*)\)/); var funcName = matches[1]; var argsStr = matches[2] var args = scope.$eval("[" + argsStr + "]"); var pushpinListener = function () { mapController.exeFunc(funcName, this, args); }; Microsoft.Maps.Events.addHandler(pushpin, 'click', pushpinListener); } return pushpin; }; var loadPushpins = function () { if (window.mapScriptLoaded) { var pushpin = getPushpin(); mapController.addPushpin(pushpin); scope.$on('$destroy', function () { mapController.removePushpin(pushpin); }); } else { setTimeout(loadPushpins, 100); } }; loadPushpins(); } } }]); <|start_filename|>Samples/GeoXml/GeoXml - Read from Url.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript'> var map; var xmlUrl = '/Common/data/georss/SampleGeoRSS.xml'; function GetMap() { map = new Microsoft.Maps.Map('#myMap', {}); //Load the GeoXml module. Microsoft.Maps.loadModule('Microsoft.Maps.GeoXml', function () { //Parse the XML data. Microsoft.Maps.GeoXml.readFromUrl(xmlUrl, null, function (data) { //Do something with the parsed XML data, in this case render it. renderGeoXmlDataSet(data); }); }); } function renderGeoXmlDataSet(data) { //Add all shapes that are not in layers to the map. if (data.shapes) { map.entities.push(data.shapes); } //Add all data layers to the map. if (data.layers) { for (var i = 0, len = data.layers.length; i < len; i++) { map.layers.insert(data.layers[i]); } } //Add all screen overlays to the map. if (data.screenOverlays) { for (var i = 0, len = data.screenOverlays.length; i < len; i++) { map.layers.insert(data.screenOverlays[i]); } } if (data.summary && data.summary.bounds) { //Set the map view to focus show the data. map.setView({ bounds: data.summary.bounds, padding: 30 }); } } </script> <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[YOUR_BING_MAPS_KEY]' async defer></script> </head> <body> <div id="myMap" style="position:relative;width:800px;height:600px;"></div> <fieldset style="width:800px;margin-top:10px;"> <legend>GeoXml - Read from URL Sample</legend> This sample shows how to read a geospatial XML file that is hosted on the same domain as the application. If your data is hosted on another domain, you can use a proxy service similar to the GeoXmlLayer Cross Domain sample. The data is then manually added to the map rather than being loaded through a GeoXmlLayer. This provides the ability to full customize how the data is rendered and also provides the option to simply extract information from the data without having to render it. </fieldset> </body> </html> <|start_filename|>Samples/Article Samples/SimpleStoreLocator/css/Locator.css<|end_filename|> html, body { margin: 0; padding: 0; width: 100%; height: 100%; } .header { width: 100%; height: 80px; background-color: #8f0202; float: left; } .header img { height: 60px; margin-left: 15px; } .sidePanel { padding: 10px; width: 300px; height: calc(100% - 100px); vertical-align: top; float: left; } #searchBox { width: 180px; } .searchBar { height: 50px; } .resultsPanel { width: 280px; overflow-y: auto; overflow-x: hidden; } #myMap { position: relative; width: calc(100% - 320px); height: calc(100% - 80px); float: left; } .errorMsg { color: red; } .listItem { font-size: 12px; font-family: Arial,Helvetica; width: 260px; margin: 5px 0; } .listItem td { vertical-align: top; } .listItem span { font-size: 14px; } .title, .title:link, .title:visited, .title:active { font-size: 14px; color: #8f0202; } .title:hover { color: red; } .infobox-info { color: #000 !important; font-size: 12px !important; padding-top: 0px !important; } <|start_filename|>Samples/ExternalSamples.js<|end_filename|> /** * List of External Bing Maps V8 Samples. * Structure of externalSamples object: * - Categroy name: [ * { title: "Sample Name", href: "URL to sample project", description: "[Optional] Description for the sample" } * ]; * */ var externalSamples = { 'Angular': [ { title: 'Angular Maps (X-Map)', href: 'https://github.com/infusion-code/angular-maps', description: 'Angular Maps (X-Map) is a set of components and services to provide map functionality in angular 2+ apps. X-Maps architecture is provider independent and can be used with Bing, Google, ESRI or any other service enabled mapping provider. X-Map contains a default implementation for Bing Maps.' } ], 'Bots': [ { title: 'Bing Location Control for Microsoft Bot Framework', 'href': 'https://github.com/Microsoft/BotBuilder-Location', description: 'An open-source location picker control for Microsoft Bot Framework powered by Bing Maps REST services. ' } ], 'Mobile': [ { title: 'BingMapAndroid', href: 'https://github.com/LeonidVeremchuk/BingMapAndroid', description: 'An native Android SDK that wraps the Bing Maps V8 control.' } ], 'Other': [ { title: 'DCProperties', href: 'https://github.com/rkgeorge/DCProperties', description: 'Example using Bing Maps v8 SpatialMath Module with the District of Columbia GIS services' } ], 'Desktop': [ { title: 'Using the Bing Maps V8 Web control in a WinForm application', href: 'https://code.msdn.microsoft.com/Using-the-Bing-Maps-V8-Web-07e21f3a' } ] }; //# sourceMappingURL=ExternalSamples.js.map <|start_filename|>Samples/Modules/GpxModule/GPXParserModule.js<|end_filename|> /**************************************************************************** * Author: <NAME> * Website: http://rbrundritt.wordpress.com * Date: January 19th, 2012 * * Source: http://bingmapsv7modules.codeplex.com/ * * Description: * This plugin allows you to import GPX files into Bing Maps. A GPX feed will be downloaded * and parsed into an EntityCollection which can then be added to the map. Additional metadata is * captured and stored in a metadata tag on each shape and on the base EntityCollection thus making * it easy to relate shapes to their metadata. Also note that the base EntityCollection will have * LocationRect property in the metadata if bound information is found in the GPX metadata. This can * be used to set the map view. Also note that the extension tag is not supported. * * Currently supports: * * Feed Tags: * - gpx * - metadata * - wpt * - rte * - trk * * metadata Tags: * - name * - desc * - author * - copyright * - time * - timeSpecified * - keywords * - bounds * - link * ****************************************************************************/ var GPXParser = function () { var _defaultOptions = { pushpinOptions: {}, routeOptions: { //strokeColor: new Microsoft.Maps.Color(200, 255, 165, 0), strokeThickness: 5 }, trackOptions: { //strokeColor: new Microsoft.Maps.Color(200, 255, 165, 0), strokeThickness: 5 } }; /***************** * Private Methods ******************/ //Creates a new object that is a merge of two other objects function mergeObjects(obj1, obj2) { var obj3 = {}; for (var p in obj1) { try { // Property in destination object set; update its value. if (obj1[p].constructor == Object) { obj3[p] = mergeObjects(obj3[p], obj1[p]); } else { obj3[p] = obj1[p]; } } catch (e) { // Property in destination object not set; create it and set its value. obj3[p] = obj1[p]; } } for (var p in obj2) { try { // Property in destination object set; update its value. if (obj2[p].constructor == Object) { obj3[p] = mergeObjects(obj3[p], obj2[p]); } else { obj3[p] = obj2[p]; } } catch (e) { // Property in destination object not set; create it and set its value. obj3[p] = obj2[p]; } } return obj3; } //Method for parsing a GPX file function parseGPX(xmlDoc, options) { var GPX_Collection = new Microsoft.Maps.Layer(); var nodes = xmlDoc.getElementsByTagName("metadata"), i, j, geom, nodeCount, wp; if (nodes.length == 0) { //GPX V1.0 files do not use a metadata tag and instead put the metadata directly in the GPX tag nodes = xmlDoc.getElementsByTagName("gpx"); } if (nodes != null && nodes.length > 0) { GPX_Collection.metadata = parseMetadata(nodes[0]); if (GPX_Collection.metadata.bounds != null && GPX_Collection.metadata.bounds != undefined) { GPX_Collection.metadata.LocationRect = new Microsoft.Maps.LocationRect.fromEdges( GPX_Collection.metadata.bounds.maxlat, //North GPX_Collection.metadata.bounds.minlon, //West GPX_Collection.metadata.bounds.minlat, //South GPX_Collection.metadata.bounds.maxlon //East ); } } nodes = xmlDoc.getElementsByTagName("trk"); nodeCount = nodes.length; for (i = 0; i < nodeCount; i++) { geom = parseTrack(nodes[i], options); for (j = 0; j < geom.length; j++) { GPX_Collection.add(geom[j]); } } nodes = xmlDoc.getElementsByTagName("rte"); nodeCount = nodes.length; for (i = 0; i < nodeCount; i++) { geom = parseRoute(nodes[i], options); if (geom != null) { GPX_Collection.add(geom); } } nodes = xmlDoc.getElementsByTagName("wpt"); nodeCount = nodes.length; for (i = 0; i < nodeCount; i++) { wp = parseWaypoint(nodes[i]); if (wp != null) { geom = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(wp.lat, wp.lon), options.pushpinOptions); geom.metadata = wp; //if (wp.sym != null && wp.sym != undefined && wp.sym != '') { // geom.setOptions({ icon: wp.sym }); //} GPX_Collection.add(geom); } } return GPX_Collection; } function parseRoute(node, options) { var m = { waypoints: [] }, points = []; if (node != null) { var tagName, waypoint; for (var i = 0; i < node.attributes.length; i++) { tagName = node.attributes[i].nodeName; switch (tagName) { case "number": m.number = parseString(node.attributes[i]); break; default: break; } } for (var i = 0; i < node.childNodes.length; i++) { tagName = node.childNodes[i].nodeName; switch (tagName) { case "name": case "cmt": case "desc": case "src": case "type": case "number": m[tagName] = parseString(node.childNodes[i]); break; case "link": if (m.link == null || m.link == undefined) { m.link = []; } m.link.push(parseLink(node.childNodes[i])); break; case "rtept": waypoint = parseWaypoint(node.childNodes[i]); m.waypoints.push(waypoint); //store waypoint metadata points.push(new Microsoft.Maps.Location(waypoint.lat, waypoint.lon)); break; break; default: break; } } } if (points.length >= 2) { var route = new Microsoft.Maps.Polyline(points, options.routeOptions); route.metadata = m; return route; } return null; } function parseTrack(node, options) { var m = {}, segments = []; if (node != null) { var tagName; for (var i = 0; i < node.attributes.length; i++) { tagName = node.attributes[i].nodeName; switch (tagName) { case "number": m.number = parseString(node.attributes[i]); break; default: break; } } for (var i = 0; i < node.childNodes.length; i++) { tagName = node.childNodes[i].nodeName; switch (tagName) { case "name": case "cmt": case "desc": case "src": case "type": case "number": m[tagName] = parseString(node.childNodes[i]); break; case "link": if (m.link == null || m.link == undefined) { m.link = []; } m.link.push(parseLink(node.childNodes[i])); break; case "trkseg": segments.push(parseTrackSegment(node.childNodes[i])); break; default: break; } } } if (segments.length >= 1) { var geoms = [], track; for (var i = 0; i < segments.length; i++) { track = new Microsoft.Maps.Polyline(segments[i].points, options.trackOptions); track.metadata = m; track.metadata.waypoints = segments[i].waypoints; geoms.push(track); } return geoms; } return []; } //return an array of Microsoft.Maps.Location objects. function parseTrackSegment(node) { var metadata = { points: [], waypoints: [] }; if (node != null) { var tagName, waypoint; for (var i = 0; i < node.childNodes.length; i++) { tagName = node.childNodes[i].nodeName; switch (tagName) { case "trkpt": waypoint = parseWaypoint(node.childNodes[i]); metadata.waypoints.push(waypoint); //store waypoint metadata metadata.points.push(new Microsoft.Maps.Location(waypoint.lat, waypoint.lon)); break; default: break; } } } return metadata; } function parseWaypoint(node) { var waypoint = {}; if (node != null) { var tagName; for (var i = 0; i < node.attributes.length; i++) { tagName = node.attributes[i].nodeName; switch (tagName) { case "lat": case "lon": waypoint[tagName] = parseDouble(parseString(node.attributes[i]), 6); break; case "eleSpecified": case "timeSpecified": case "magvarSpecified": case "geoidheightSpecified": case "fixSpecified": case "magvarSpecified": case "hdopSpecified": case "vdopSpecified": case "pdopSpecified": case "ageofdgpsdataSpecified": case "magvarSpecified": waypoint[tagName] = parseBool(parseString(node.attributes[i])); break; case "sat": case "dgpsid": waypoint[tagName] = parseString(node.attributes[i]); break; default: break; } } for (var i = 0; i < node.childNodes.length; i++) { tagName = node.childNodes[i].nodeName; switch (tagName) { case "ele": case "magvar": case "geoidheight": case "hdop": case "vdop": case "pdop": case "ageofdgpsdata": waypoint[tagName] = parseDouble(parseString(node.childNodes[i])); break; case "name": case "cmt": case "desc": case "src": case "sym": case "time": case "type": waypoint[tagName] = parseString(node.childNodes[i]); break; case "link": if (waypoint.link == null || waypoint.link == undefined) { waypoint.link = []; } waypoint.link.push(parseLink(node.childNodes[i])); break; default: break; } } } return waypoint; } function parseMetadata(node) { var metadata = {}; if (node != null) { var tagName; for (var i = 0; i < node.childNodes.length; i++) { tagName = node.childNodes[i].nodeName.toLowerCase(); switch (tagName) { case "name": case "desc": case "time": case "keywords": metadata[tagName] = parseString(node.childNodes[i]); break; case "author": metadata.author = parseAuthor(node.childNodes[i]); break; case "copyright": metadata.copyright = parseCopyright(node.childNodes[i]); break; case "link": if (metadata.link == null || metadata.link == undefined) { metadata.link = []; } metadata.link.push(parseLink(node.childNodes[i])); break; case "bounds": metadata.bounds = parseBounds(node.childNodes[i]); break; default: break; } } } return metadata; } function parseAuthor(node) { var a = {}; if (node != null) { var tagName; for (var i = 0; i < node.childNodes.length; i++) { tagName = node.childNodes[i].nodeName; switch (tagName) { case "name": a.name = parseString(node.childNodes[i]); break; case "email": a.email = parseEmail(node.childNodes[i]); break; case "link": a.link = parseLink(node.childNodes[i]); break; default: break; } } } return a; } function parseEmail(node) { var e = {}; if (node != null) { var tagName; for (var i = 0; i < node.attributes.length; i++) { tagName = node.attributes[i].nodeName; switch (tagName) { case "id": case "domain": e[tagName] = parseString(node.attributes[i]); break; default: break; } } } return e; } function parseCopyright(node) { var cr = {}; if (node != null) { var tagName; for (var i = 0; i < node.attributes.length; i++) { tagName = node.attributes[i].nodeName; switch (tagName) { case "author": cr.author = parseString(node.attributes[i]); break; default: break; } } for (var i = 0; i < node.childNodes.length; i++) { tagName = node.childNodes[i].nodeName; switch (tagName) { case "year": case "license": cr[tagName] = parseString(node.childNodes[i]); break; default: break; } } } return cr; } function parseLink(node) { var link = {}; if (node != null) { var tagName; for (var i = 0; i < node.attributes.length; i++) { tagName = node.attributes[i].nodeName; switch (tagName) { case "href": link.href = parseString(node.attributes[i]); break; default: break; } } for (var i = 0; i < node.childNodes.length; i++) { tagName = node.childNodes[i].nodeName; switch (tagName) { case "text": case "type": link[tagName] = parseString(node.childNodes[i]); break; default: break; } } } return link; } //Consider turing into LocationRect function parseBounds(node) { var b = {}; if (node != null) { var tagName; for (var i = 0; i < node.attributes.length; i++) { tagName = node.attributes[i].nodeName; switch (tagName) { case "minlat": case "minlon": case "maxlat": case "maxlon": b[tagName] = parseDouble(parseString(node.attributes[i]), 6); break; default: break; } } } return b; } function parseDouble(value, maxDecimals) { if (value != null && value != undefined) { try { if (maxDecimals != null) { var multiplier = Math.pow(10, maxDecimals); return Math.round(parseFloat(value) * multiplier) / multiplier; } else { return parseFloat(value); } } catch (e) { } } return 0; } function parseBool(value) { try { switch (value.toLowerCase()) { case "true": case "yes": case "1": return true; case "false": case "no": case "0": case null: return false; default: return Boolean(value); } } catch (e) { } return false; } function parseString(value) { if (value.text) { return value.text; } else if (value.textContent) { return value.textContent; } else if (value.value) { return value.value; } else if (value.nodeValue) { return value.nodeValue; } return value; } /**************** * Public Methods *****************/ this.Parse = function (feed, callback, options) { options = mergeObjects(_defaultOptions, options); var xmlHttp; if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { throw (e); } } } xmlHttp.open("GET", feed, false); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4) { var xmlDoc = xmlHttp.responseXML; callback(parseGPX(xmlDoc, options)); } } xmlHttp.send(); }; }; //Call the Module Loaded method Microsoft.Maps.moduleLoaded('GPXParserModule'); <|start_filename|>Samples/Map/Localize the Map (en-GB).html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript'> var map; function GetMap() { map = new Microsoft.Maps.Map('#myMap', { mapTypeId: Microsoft.Maps.MapTypeId.ordnanceSurvey, center: new Microsoft.Maps.Location(51.552, -0.1586), zoom: 15 }); } </script> <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&setLang=en&setMkt=en-GB&key=[YOUR_BING_MAPS_KEY]' async defer></script> </head> <body> <div id="myMap" style="position:relative;width:800px;height:600px;"></div> <fieldset style="width:800px;margin-top:10px;"> <legend>Localize the Map (en-GB) Sample</legend> This sample shows how to localize the map to the en-GB market and language (British English). In this market the Ordnance Survey map style is available at certain levels. This is a custom map type only available in the UK. </fieldset> </body> </html> <|start_filename|>Samples/Configuration Driven Maps/Load a Configurable Map with Code.html<|end_filename|> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript'> var map; function GetMap() { Microsoft.Maps.ConfigurableMap.createFromConfig('#myMap', 'https://bingmapsisdk.blob.core.windows.net/isdksamples/configmap2.json', false, null, function (mapObj) { //Store a reference to the map object instance. map = mapObj; //You can use the map object to just as you would normally. //To demonstrate this, the following code will change the map view after 5 seconds. setTimeout(function () { //Change the zoom level of the map. map.setView({ zoom: 5 }); }, 5000); }, function (errorMsg) { //An error occured, display it. alert(message); }); } </script> <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[YOUR_BING_MAPS_KEY]&branch=experimental' async defer></script> </head> <body> <div id="myMap" style="position:relative;width:800px;height:600px;"></div> <fieldset style="width:800px;margin-top:10px;"> <legend>Load a Configurable Map with Code Sample</legend> This sample shows how to load a map using a configuration file. This is a good way to jump start development as it saves you the time of writing the code to load each data set individually. It also makes it easier to reuse a map implementation with different data sets simply by loading different configuration files. </fieldset> </body> </html> <|start_filename|>Samples/Modules/DraggableShapes/DraggableShapesModule.js<|end_filename|> /* * Copyright(c) 2017 Microsoft Corporation. All rights reserved. * * This code is licensed under the MIT License (MIT). * * 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. */ /******************************************** * Draggable Shapes Manager * Author: <NAME> * License: MIT *********************************************/ /// <reference path="../../Common/typings/MicrosoftMaps/Microsoft.Maps.d.ts"/> /** * An enumeration which defines how a shape is dragged on the map. */ var DragMethod; (function (DragMethod) { /** Shapes are dragged such that they maintain their Pixel dimensions. */ DragMethod[DragMethod["pixel"] = 0] = "pixel"; /** Shapes are dragged using geospatial accurate projections. The shape may become distorted when moved towards the poles. */ DragMethod[DragMethod["geo"] = 1] = "geo"; })(DragMethod || (DragMethod = {})); /** * A class that makes it easy to make any shape draggable. */ var DraggableShapesManager = (function () { /********************** * Constructor ***********************/ /** * @constructor * @param map The map to add the DraggableShapesManager to. * @param dragMethod The drag method to use. */ function DraggableShapesManager(map, dragMethod) { this._dragMethod = DragMethod.pixel; this._shapes = []; this._map = map; if (typeof dragMethod != 'undefined') { this._dragMethod = dragMethod; } var self = this; //Update the shape as the mouse moves on the map. this._mapMoveEventId = Microsoft.Maps.Events.addHandler(this._map, 'mousemove', function (e) { self._updateShape(e); }); } /********************** * Public Functions ***********************/ /** * Disposes the DraggableShapesManager and releases it's resources. */ DraggableShapesManager.prototype.dispose = function () { Microsoft.Maps.Events.removeHandler(this._mapMoveEventId); this._currentLocation = null; this._currentShape = null; this._currentPoint = null; this._map = null; this._dragMethod = null; for (var i = 0; i < this._shapes.length; i++) { this.disableDraggable(this._shapes[i]); } this._shapes = null; }; /** * Adds draggable functionality to a shape. * @param shape The shape to add draggable functionality to. */ DraggableShapesManager.prototype.makeDraggable = function (shape) { if (this._shapes.indexOf(shape) === -1) { if (shape instanceof Microsoft.Maps.Pushpin) { //Pushpins already support dragging. shape.setOptions({ draggable: true }); } else { var s = shape; if (!s._dragevents) { s._dragevents = []; } var self = this; s._dragevents.push(Microsoft.Maps.Events.addHandler(s, 'mousedown', function (e) { //Lock map so it doesn't move when dragging. self._map.setOptions({ disablePanning: true }); //Set the current draggable shape. self._currentShape = e.target; //Capture the mouse start location and pixel point. self._currentLocation = e.location; self._currentPoint = e.point; })); s._dragevents.push(Microsoft.Maps.Events.addHandler(s, 'mouseup', function (e) { //Unlock map panning. self._map.setOptions({ disablePanning: false }); //Set current shape to null, so that no updates will happen will mouse is up. self._currentShape = null; })); } } }; /** * Removes the draggable functionality of a shape. * @param shape The shape to remove the draggable functionality from. */ DraggableShapesManager.prototype.disableDraggable = function (shape) { if (this._shapes.indexOf(shape) !== -1) { if (shape instanceof Microsoft.Maps.Pushpin) { //Pushpins already support dragging. shape.setOptions({ draggable: false }); } else { var s = shape; if (s._dragevents) { this._clearShapeEvents(s._dragevents); s._dragevents = null; } } this._shapes.splice(this._shapes.indexOf(shape), 1); } }; /** * Gets the drag method currently used by the DraggabeShapesManager. * @returns The drag method currently used by the DraggabeShapesManager. */ DraggableShapesManager.prototype.getDragMethod = function () { return this._dragMethod; }; /** * Sets the drag method used by the DraggabeShapesManager. * @param dragMethod The drag method used by the DraggabeShapesManager. */ DraggableShapesManager.prototype.setDragMethod = function (dragMethod) { if (typeof dragMethod !== 'undefined') { this._dragMethod = dragMethod; } }; /********************** * Private Functions ***********************/ /** * Removes an array of event handler ID's to remove. * @param events An array of event handler ID's to remove. */ DraggableShapesManager.prototype._clearShapeEvents = function (events) { for (var i = 0; i < events.length; i++) { Microsoft.Maps.Events.removeHandler(events[i]); } }; /** * Updates a shapes position as it is being dragged. * @param e The mouse event argument. */ DraggableShapesManager.prototype._updateShape = function (e) { if (this._currentShape) { //As an optimization, only update the shape if the mouse has moved atleast 5 pixels. //This will significantly reduce the number of recalculations and provide much better performance. var dx = this._currentPoint.x - e.point.x; var dy = this._currentPoint.y - e.point.y; if (dx * dx + dy * dy <= 25) { return; } if (this._dragMethod === DragMethod.pixel) { this._pixelAccurateUpdate(e); } else { this._geoAccurateUpdate(e); } } }; /** * Updates the position of a shape as it dragged using a geospatially accurate shift. * @param e The mouse event argument. */ DraggableShapesManager.prototype._geoAccurateUpdate = function (e) { var newLoc = e.location; var currentLocation = this._currentLocation; //Calculate the distance and heading from the last mouse location used to update the shape to the new location. var distance = Microsoft.Maps.SpatialMath.getDistanceTo(currentLocation, newLoc); var heading = Microsoft.Maps.SpatialMath.getHeading(currentLocation, newLoc); if (this._currentShape instanceof Microsoft.Maps.Polygon) { var polygon = this._currentShape; var rings = polygon.getRings(); for (var i = 0, len = rings.length; i < len; i++) { rings[i] = this._shiftLocations(rings[i], heading, distance); } //Update the in rings ina polygon. polygon.setRings(rings); } else if (this._currentShape instanceof Microsoft.Maps.Polyline) { var line = this._currentShape; var locs = line.getLocations(); //Update the locations of a polyline. line.setLocations(this._shiftLocations(locs, heading, distance)); } else if (this._currentShape instanceof Microsoft.Maps.Pushpin) { //Although not needed, for completeness, this supports dragging of pushpins. var pin = this._currentShape; var locs = this._shiftLocations([pin.getLocation()], heading, distance); pin.setLocation(locs[0]); } //Store the new mouse location and point that was used to update the shape. this._currentLocation = newLoc; this._currentPoint = e.point; }; /** * Updates the position of a shape as it dragged using a pixel accurate shift. * @param e The mouse event argument. */ DraggableShapesManager.prototype._pixelAccurateUpdate = function (e) { //Shift the shape based on pixel offset. var newPoint = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(e.location, 19); var point = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(this._currentLocation, 19); var dx = point.x - newPoint.x; var dy = point.y - newPoint.y; if (this._currentShape instanceof Microsoft.Maps.Polygon) { var polygon = this._currentShape; var rings = polygon.getRings(); for (var i = 0, len = rings.length; i < len; i++) { rings[i] = this._pixelShiftLocations(rings[i], dx, dy); } //Update the in rings ina polygon. polygon.setRings(rings); } else if (this._currentShape instanceof Microsoft.Maps.Polyline) { var line = this._currentShape; var locs = line.getLocations(); //Update the locations of a polyline. line.setLocations(this._pixelShiftLocations(locs, dx, dy)); } else if (this._currentShape instanceof Microsoft.Maps.Pushpin) { //Although not needed, for completeness, this supports dragging of pushpins. var pin = this._currentShape; var locs = this._pixelShiftLocations([pin.getLocation()], dx, dy); pin.setLocation(locs[0]); } //Store the new mouse location and point that was used to update the shape. this._currentLocation = e.location; this._currentPoint = e.point; }; /** * Takes an array of locations and shifts them a specified distancein a specified direction. * @param locs The locations to shift. * @param heading The direction to shift the locations. * @param distance The distance to shift the locations. * @returns An array of shifted locations. */ DraggableShapesManager.prototype._shiftLocations = function (locs, heading, distance) { //Based on the distance and heading, shift all locations in the array accordingly. var loc; for (var i = 0, len = locs.length; i < len; i++) { locs[i] = Microsoft.Maps.SpatialMath.getDestination(locs[i], heading, distance); } return locs; }; /** * Takes an rray of locations and shifts them a specified distance in pixels at zoom level 19. * @param locs The locations to shift. * @param dx Horizontal offset distance to shift the locations in pixels at zoom level 19. * @param dy Vertical offset distance to shift the locations in pixels at zoom level 19. * @returns An array of shifted locations. */ DraggableShapesManager.prototype._pixelShiftLocations = function (locs, dx, dy) { var mapWidth19 = Math.pow(2, 19) * 256; //Based on the distance and heading, shift all locations in the array accordingly. for (var i = 0, len = locs.length; i < len; i++) { var p = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(locs[i], 19); p.x -= dx; p.y -= dy; if (p.x < 0) { p.x += mapWidth19; } else if (p.x > mapWidth19) { p.x -= mapWidth19; } locs[i] = Microsoft.Maps.SpatialMath.Tiles.globalPixelToLocation(p, 19); } return locs; }; return DraggableShapesManager; }()); //Load SpatialMath module dependancy. Microsoft.Maps.loadModule('Microsoft.Maps.SpatialMath', function () { Microsoft.Maps.moduleLoaded('DraggableShapesModule'); }); //# sourceMappingURL=DraggableShapesModule.js.map
ConnectionMaster/BingMapsV8CodeSamples
<|start_filename|>frontend_tests/zjsunit/zpage_params.js<|end_filename|> "use strict"; exports.page_params = {}; exports.realm_user_settings_defaults = {}; exports.user_settings = {}; exports.reset = () => { for (const field in exports.page_params) { if (Object.prototype.hasOwnProperty.call(exports.page_params, field)) { delete exports.page_params[field]; } } for (const field in exports.user_settings) { if (Object.prototype.hasOwnProperty.call(exports.user_settings, field)) { delete exports.user_settings[field]; } } for (const field in exports.realm_user_settings_defaults) { if (Object.prototype.hasOwnProperty.call(exports.realm_user_settings_defaults, field)) { delete exports.realm_user_settings_defaults[field]; } } }; <|start_filename|>frontend_tests/node_tests/echo.js<|end_filename|> "use strict"; const {strict: assert} = require("assert"); const MockDate = require("mockdate"); const {mock_esm, zrequire} = require("../zjsunit/namespace"); const {make_stub} = require("../zjsunit/stub"); const {run_test} = require("../zjsunit/test"); const {page_params} = require("../zjsunit/zpage_params"); const markdown = mock_esm("../../static/js/markdown"); const message_lists = mock_esm("../../static/js/message_lists"); const notifications = mock_esm("../../static/js/notifications"); let disparities = []; mock_esm("../../static/js/ui", { show_failed_message_success: () => {}, }); mock_esm("../../static/js/sent_messages", { mark_disparity: (local_id) => { disparities.push(local_id); }, }); const message_store = mock_esm("../../static/js/message_store", { get: () => ({failed_request: true}), update_booleans: () => {}, }); mock_esm("../../static/js/message_list"); message_lists.current = ""; message_lists.home = {view: {}}; const drafts = zrequire("drafts"); const echo = zrequire("echo"); const people = zrequire("people"); run_test("process_from_server for un-echoed messages", () => { const waiting_for_ack = new Map(); const server_messages = [ { local_id: "100.1", }, ]; echo._patch_waiting_for_ack(waiting_for_ack); const non_echo_messages = echo.process_from_server(server_messages); assert.deepEqual(non_echo_messages, server_messages); }); run_test("process_from_server for differently rendered messages", ({override}) => { let messages_to_rerender = []; override(message_lists.home.view, "rerender_messages", (msgs) => { messages_to_rerender = msgs; }); // Test that we update all the booleans and the content of the message // in local echo. const old_value = "old_value"; const new_value = "new_value"; const waiting_for_ack = new Map([ [ "100.1", { content: "<p>A client rendered message</p>", timestamp: old_value, is_me_message: old_value, submessages: old_value, topic_links: old_value, }, ], ]); const server_messages = [ { local_id: "100.1", content: "<p>A server rendered message</p>", timestamp: new_value, is_me_message: new_value, submessages: new_value, topic_links: new_value, }, ]; echo._patch_waiting_for_ack(waiting_for_ack); disparities = []; const non_echo_messages = echo.process_from_server(server_messages); assert.deepEqual(non_echo_messages, []); assert.equal(disparities.length, 1); assert.deepEqual(messages_to_rerender, [ { content: server_messages[0].content, timestamp: new_value, is_me_message: new_value, submessages: new_value, topic_links: new_value, }, ]); }); run_test("build_display_recipient", () => { page_params.user_id = 123; const params = {}; params.realm_users = [ { user_id: 123, full_name: "Iago", email: "<EMAIL>", }, { email: "<EMAIL>", full_name: "Cordelia", user_id: 21, }, ]; params.realm_non_active_users = []; params.cross_realm_bots = []; people.initialize(page_params.user_id, params); let message = { type: "stream", stream: "general", sender_email: "<EMAIL>", sender_full_name: "Iago", sender_id: 123, }; let display_recipient = echo.build_display_recipient(message); assert.equal(display_recipient, "general"); message = { type: "private", private_message_recipient: "<EMAIL>,<EMAIL>", sender_email: "<EMAIL>", sender_full_name: "Iago", sender_id: 123, }; display_recipient = echo.build_display_recipient(message); assert.equal(display_recipient.length, 3); let iago = display_recipient.find((recipient) => recipient.email === "<EMAIL>"); assert.equal(iago.full_name, "Iago"); assert.equal(iago.id, 123); const cordelia = display_recipient.find( (recipient) => recipient.email === "<EMAIL>", ); assert.equal(cordelia.full_name, "Cordelia"); assert.equal(cordelia.id, 21); const hamlet = display_recipient.find((recipient) => recipient.email === "<EMAIL>"); assert.equal(hamlet.full_name, "<EMAIL>"); assert.equal(hamlet.id, undefined); assert.equal(hamlet.unknown_local_echo_user, true); message = { type: "private", private_message_recipient: "<EMAIL>", sender_email: "<EMAIL>", sender_full_name: "Iago", sender_id: 123, }; display_recipient = echo.build_display_recipient(message); assert.equal(display_recipient.length, 1); iago = display_recipient.find((recipient) => recipient.email === "<EMAIL>"); assert.equal(iago.full_name, "Iago"); assert.equal(iago.id, 123); }); run_test("update_message_lists", () => { message_lists.home.view = {}; const stub = make_stub(); const view_stub = make_stub(); message_lists.home.change_message_id = stub.f; message_lists.home.view.change_message_id = view_stub.f; echo.update_message_lists({old_id: 401, new_id: 402}); assert.equal(stub.num_calls, 1); const args = stub.get_args("old", "new"); assert.equal(args.old, 401); assert.equal(args.new, 402); assert.equal(view_stub.num_calls, 1); const view_args = view_stub.get_args("old", "new"); assert.equal(view_args.old, 401); assert.equal(view_args.new, 402); }); run_test("insert_local_message streams", ({override}) => { const fake_now = 555; MockDate.set(new Date(fake_now * 1000)); const local_id_float = 101.01; let apply_markdown_called = false; let add_topic_links_called = false; let insert_message_called = false; override(markdown, "apply_markdown", () => { apply_markdown_called = true; }); override(markdown, "add_topic_links", () => { add_topic_links_called = true; }); override(echo, "insert_message", (message) => { assert.equal(message.display_recipient, "general"); assert.equal(message.timestamp, fake_now); assert.equal(message.sender_email, "<EMAIL>"); assert.equal(message.sender_full_name, "Iago"); assert.equal(message.sender_id, 123); insert_message_called = true; }); const message_request = { type: "stream", stream: "general", sender_email: "<EMAIL>", sender_full_name: "Iago", sender_id: 123, }; echo.insert_local_message(message_request, local_id_float); assert.ok(apply_markdown_called); assert.ok(add_topic_links_called); assert.ok(insert_message_called); }); run_test("insert_local_message PM", ({override}) => { const local_id_float = 102.01; page_params.user_id = 123; const params = {}; params.realm_users = [ { user_id: 123, full_name: "Iago", email: "<EMAIL>", }, ]; params.realm_non_active_users = []; params.cross_realm_bots = []; people.initialize(page_params.user_id, params); let add_topic_links_called = false; let apply_markdown_called = false; let insert_message_called = false; override(echo, "insert_message", (message) => { assert.equal(message.display_recipient.length, 3); insert_message_called = true; }); override(markdown, "apply_markdown", () => { apply_markdown_called = true; }); override(markdown, "add_topic_links", () => { add_topic_links_called = true; }); const message_request = { private_message_recipient: "<EMAIL>,<EMAIL>", type: "private", sender_email: "<EMAIL>", sender_full_name: "Iago", sender_id: 123, }; echo.insert_local_message(message_request, local_id_float); assert.ok(add_topic_links_called); assert.ok(apply_markdown_called); assert.ok(insert_message_called); }); run_test("test reify_message_id", ({override}) => { const local_id_float = 103.01; override(markdown, "apply_markdown", () => {}); override(markdown, "add_topic_links", () => {}); override(echo, "insert_message", () => {}); const message_request = { type: "stream", stream: "general", sender_email: "<EMAIL>", sender_full_name: "Iago", sender_id: 123, draft_id: 100, }; echo.insert_local_message(message_request, local_id_float); let message_store_reify_called = false; let notifications_reify_called = false; let draft_deleted = false; override(message_store, "reify_message_id", () => { message_store_reify_called = true; }); override(notifications, "reify_message_id", () => { notifications_reify_called = true; }); const draft_model = drafts.draft_model; override(draft_model, "deleteDraft", (draft_id) => { assert.ok(draft_id, 100); draft_deleted = true; }); echo.reify_message_id(local_id_float.toString(), 110); assert.ok(message_store_reify_called); assert.ok(notifications_reify_called); assert.ok(draft_deleted); }); MockDate.reset(); <|start_filename|>postcss.config.js<|end_filename|> "use strict"; const path = require("path"); const {media_breakpoints} = require("./static/js/css_variables"); module.exports = ({file}) => ({ plugins: [ (file.basename ?? path.basename(file)) === "night_mode.css" && // Add postcss-import plugin with postcss-prefixwrap to handle // the flatpickr dark theme. We do this because flatpickr themes // are not scoped. See https://github.com/flatpickr/flatpickr/issues/2168. require("postcss-import")({ plugins: [require("postcss-prefixwrap")("%night-mode-block")], }), require("postcss-nested"), require("postcss-extend-rule"), require("postcss-simple-vars")({variables: media_breakpoints}), require("postcss-calc"), require("postcss-media-minmax"), require("autoprefixer"), ], }); <|start_filename|>templates/zerver/for-open-source.html<|end_filename|> {% extends "zerver/portico.html" %} {% set entrypoint = "landing-page" %} (% set OPEN_GRAPH_TITLE = 'Modern chat for open source' %} {% set OPEN_GRAPH_DESCRIPTION = 'Zulip is the only modern team chat app that is ideal for both live and asynchronous conversations. Discuss issues, pull requests and feature ideas, engage with users, answer questions, and onboard new contributors.' %} {% block title %} <title>Zulip: the best group chat for open-source projects</title> {% endblock %} {% block customhead %} <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {% endblock %} {% block portico_content %} {% include 'zerver/landing_nav.html' %} <div class="portico-landing why-page no-slide solutions-page"> <div class="hero bg-pycon"> <div class="bg-dimmer"></div> <div class="content"> <h1 class="center">Zulip for open source projects</h1> <p>Grow your community with thoughtful and inclusive discussion.</p> </div> <div class="hero-text"> <a href="/plans">Zulip Standard</a> is free for open-source projects! Contact <a href="mailto:<EMAIL>"><EMAIL></a> to check whether your organization qualifies, or <a href="/accounts/go/?next=/upgrade%23sponsorship">request sponsorship</a> today. </div> <div class="hero-buttons center"> <a href="/new/" class="button"> {{ _('Create organization') }} </a> <a href="/accounts/go/?next=/upgrade%23sponsorship" class="button"> {{ _('Request sponsorship') }} </a> <a href="https://zulip.readthedocs.io/en/stable/production/install.html" class="button"> {{ _('Self-host Zulip') }} </a> </div> </div> <div class="feature-intro"> <h1 class="center"> Make Zulip the communication hub for your open-source community. </h1> <p> <a href="/hello">Zulip</a> is the only <a href="/features">modern team chat app</a> that is <a href="/why-zulip">ideal</a> for both live and asynchronous conversations. Discuss issues, pull requests and feature ideas, engage with users, answer questions, and onboard new contributors. </p> </div> <div class="feature-container"> <div class="feature-half"> <div class="feature-text"> <h1> Use topics to organize the discussion </h1> <ul> <li> <div class="list-content"> Like email threads, <a href="/help/streams-and-topics">Zulip topics</a> create a separate space for each discussion, so different conversations will never get in each other’s way. </div> </li> <li> <div class="list-content"> Find active conversations, or see what happened while you were away, with the <a href="/help/reading-strategies#recent-topics">Recent Topics</a> view. Read the topics you care about, and skip the rest. </div> </li> <li> <div class="list-content"> Keep discussions orderly by <a href="/help/rename-a-topic">moving</a> or <a href="/help/move-content-to-another-topic">splitting</a> topics when conversations digress. </div> </li> </ul> <blockquote class="twitter-tweet" data-cards="hidden"><p lang="en" dir="ltr">We just moved the Lichess team (~100 persons) to <a href="https://twitter.com/zulip?ref_src=twsrc%5Etfw">@zulip</a>, and I&#39;m loving it. The topics in particular make it vastly superior to slack &amp; discord, when it comes to dealing with many conversations.<br />Zulip is also open-source! <a href="https://t.co/lxHjf3YPMe">https://t.co/lxHjf3YPMe</a></p>&mdash; <NAME> (@ornicar) <a href="https://twitter.com/ornicar/status/1412672302601457664?ref_src=twsrc%5Etfw">July 7, 2021</a></blockquote> <script async src="https://platform.twitter.com/widgets.js"></script> </div> </div> <div class="feature-half"> <div class="feature-image topics-image"> <img alt="" src="/static/images/landing-page/open_source/streams_and_topics_day.png" /> </div> </div> </div> <div class="feature-container alternate-grid"> <div class="feature-half md-hide"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/education/knowledge-repository.svg" /> </div> </div> <div class="feature-half"> <div class="feature-text"> <h1> Lasting knowledge repository </h1> <ul> <li> <div class="list-content"> Permanently link to a <a href="/help/link-to-a-message-or-conversation"> Zulip conversation</a> or a <a href="/help/link-to-a-message-or-conversation#link-to-a-specific-message">message in context</a> from your issue tracker, forum, or anywhere else. </div> </li> <li> <div class="list-content"> With conversations organized by topic, you can review old discussions to understand past work, explanations, and decisions. </div> </li> <li> <div class="list-content"> <a href="https://github.com/zulip/zulip-archive">Publish</a> discussions on the web, letting anyone find previous answers to common questions without making an account. </div> </li> <li> <div class="list-content"> Topics make it easy to find the right conversation with Zulip's <a href="/help/search-for-messages">powerful full-text search</a>. New participants can learn from past discussions as they onboard, with unlimited message history. </div> </li> </ul> <div class="quote"> <blockquote> Choosing Zulip over Slack as our group chat is one of the best decisions we’ve ever made. Zulip makes it easy for our community of 1000 Recursers around the world to stay involved, even years after their batches finish. No other tool has a user experience that scales to a community of our size. </blockquote> <div class="author"><NAME>, founder and CEO, <a href="https://www.recurse.com/">Recurse Center</a></div> </div> </div> </div> <div class="feature-half md-display"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/education/knowledge-repository.svg" /> </div> </div> </div> <div class="feature-container"> <div class="feature-half"> <div class="feature-text"> <h1> Build inclusive communities </h1> <ul> <li> <div class="list-content"> Conversations in Zulip can continue for hours or days, enabling effective discussions between community members around the world. </div> </li> <li> <div class="list-content"> Core contributors can answer a question when they have a few minutes, without digging through dozens of messages. </div> </li> <li> <div class="list-content"> Part-time participants <a href="/help/reading-strategies#recent-topics"> quickly zero in</a> on the conversations they care about. This is not possible with other chat tools like Slack or Discord. </div> </li> <li> <div class="list-content"> Topics provide a safe space to ask a question without interrupting other conversations. </div> </li> <li> <div class="list-content"> Zulip offers dozens of features for <a href="/help/moderating-open-organizations"> moderating discussions</a>. Members can also <a href="/help/mute-a-user">mute</a> anyone they'd rather not interact with. </div> </li> <li> <div class="list-content"> Check out <a href="/for/communities">Zulip for communities</a> to learn more about how Zulip facilitates contributor engagement and inclusion. </div> </li> </ul> <blockquote class="twitter-tweet"><p lang="en" dir="ltr">When we made the switch to <a href="https://twitter.com/zulip?ref_src=twsrc%5Etfw">@zulip</a> a few months ago for chat, never in my wildest dreams did I imagine it was going to become the beating heart of the community, and so quickly. It&#39;s a game changer. 🧑‍💻🗨️👩‍💻</p>&mdash; <NAME> (@mojavelinux) <a href="https://twitter.com/mojavelinux/status/1409702273400201217?ref_src=twsrc%5Etfw">June 29, 2021</a></blockquote><script async src="https://platform.twitter.com/widgets.js"></script> </div> </div> <div class="feature-half"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/open_source/build_inclusive_communities.svg" /> </div> </div> </div> <div class="feature-container alternate-grid"> <div class="feature-half md-hide"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/companies/software-engineer.svg" /> </div> </div> <div class="feature-half"> <div class="feature-text"> <h1> Open ecosystem </h1> <ul> <li> <div class="list-content"> Zulip is <a href="https://github.com/zulip">100% open-source software</a>, with no "open core" catch. We work hard to make it <a href="https://zulip.readthedocs.io/en/latest/production/install.html">easy to set up</a>, <a href="https://zulip.readthedocs.io/en/stable/production/export-and-import.html#backups">backup </a>, and <a href="https://zulip.readthedocs.io/en/stable/production/upgrade-or-modify.html">maintain </a> a self-hosted Zulip installation, where you have full control of your data. </div> </li> <li> <div class="list-content"> Our high quality <a href="/help/export-your-organization">export </a> and <a href="https://zulip.readthedocs.io/en/latest/production/export-and-import.html">import </a> tools ensure that you can always move from <a href="/plans/">Zulip Cloud</a> hosting to your own servers. There is no lock-in. </div> </li> <li> <div class="list-content"> Zulip's <a href="https://chat.zulip.org/api/rest">open API</a> is shared by the official web/desktop, mobile, and terminal clients, with a <a href="https://chat.zulip.org/api/changelog">complete API changelog</a> and <a href="https://zulip.readthedocs.io/en/latest/overview/release-lifecycle.html#compatibility-and-upgrading"> backwards-compatibility policy</a> designed to support developers of third-party clients. </div> </li> <li> <div class="list-content"> Zulip supports mirroring channels with <a href="/integrations/doc/irc">IRC</a>, <a href="/integrations/doc/slack">Slack</a>, and <a href="/integrations/doc/matrix">Matrix</a>, and you can connect to other modern chat protocols using <a href="https://github.com/42wim/matterbridge">Matterbridge</a>. </div> </li> </ul> <div class="quote"> <blockquote> I highly recommend Zulip to other communities. We’re coming from Freenode as our only real-time communication so the difference is night and day. Slack is a no-go for many due to not being FLOSS, and I’m concerned about vendor lock-in if they were to stop being so generous. Slack’s threading model is much worse than Zulip’s IMO. The streams/topics flow is an incredibly intuitive way to keep track of everything that is going on. </blockquote> <div class="author"> <NAME>, <a href="https://mixxx.org/">Mixxx</a> Developer </div> </div> </div> </div> <div class="feature-half md-display"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/companies/software-engineer.svg" /> </div> </div> </div> <div class="feature-container"> <div class="feature-half"> <div class="feature-text"> <h1> Powerful formatting </h1> <ul> <li> <div class="list-content"> <a href="/help/code-blocks">Zulip code blocks</a> come with syntax highlighting for over 250 languages, ability to <a href="/help/code-blocks#default-code-block-language">set a default language</a>, and integrated <a href="/help/code-blocks#code-playgrounds">code playgrounds.</a> </div> </li> <li> <div class="list-content"> <a href="/help/format-your-message-using-markdown#latex">Type LaTeX</a> directly into your Zulip message, and see it beautifully rendered. </div> </li> <li> <div class="list-content"> Enjoy inline image, video and Tweet previews. </div> </li> <li> <div class="list-content"> If you made a mistake, no worries! You can <a href="/help/edit-or-delete-a-message">edit your message</a>, or move it to a different <a href="/help/move-content-to-another-topic">topic</a> or <a href="/help/move-content-to-another-stream">stream</a>. </div> </li> </ul> <div class="quote"> <blockquote> At rust-lang, at Ferrous Systems, and now at Near, Zulip is absolutely invaluable for making technical discussion work! </blockquote> <div class="author"> <a href="https://github.com/matklad/"><NAME></a> , Senior software engineer, NEAR Protocol </div> </div> </div> </div> <div class="feature-half"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/companies/message-formatting-top.png" /> </div> </div> </div> <div class="feature-container alternate-grid"> <div class="feature-half md-hide"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/companies/message-formatting-bottom.png" /> </div> </div> <div class="feature-half"> <div class="feature-text"> <h1> Interactive messaging </h1> <ul> <li> <div class="list-content"> Start a <a href="/help/start-a-call">video call</a> with the click of a button, or plan events without worrying about time zones using <a href="/help/format-your-message-using-markdown#mention-a-time">local times</a>. </div> </li> <li> <div class="list-content"> Use <a href="/help/emoji-reactions">emoji reactions</a> for lightweight interactions. Have fun with <a href="/help/add-custom-emoji">custom emoji</a> and gather feedback with <a href="/help/create-a-poll">polls</a>. </div> </li> <li> <div class="list-content"> Share files or images with <a href="/help/share-and-upload-files">drag-and-drop uploads</a>. </div> </li> <li> <div class="list-content"> Enjoy animated GIFs with Zulip's native <a href="/help/animated-gifs-from-giphy">GIPHY integration</a>. </div> </li> </ul> <div class="quote"> <blockquote> Wikimedia uses Zulip for its participation in open source mentoring programs. Zulip’s threaded discussions help busy organization administrators and mentors stay in close communication with students during all phases of the programs. </blockquote> <div class="author"> &mdash; <NAME>, Developer Advocate, <a href="https://wikimediafoundation.org/">Wikimedia Foundation</a> </div> </div> </div> </div> <div class="feature-half md-display"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/companies/message-formatting-bottom.png" /> </div> </div> </div> <div class="feature-container"> <div class="feature-half"> <div class="feature-text"> <h1> Effective workflows with integrations </h1> <ul> <li> <div class="list-content"> Use topics to manage support workflows, answer questions, and collaborate to investigate issues. <a href="/help/resolve-a-topic">Mark the topic ✓ resolved</a> when done! </div> </li> <li> <div class="list-content"> <a href="/help/add-a-custom-linkifier">Customize Zulip’s markup with linkifiers</a>, so that “TRAC-1234” and “#1234” automatically link to issues or tickets in the tools you use. </div> </li> <li> <div class="list-content"> Native integrations for GitHub, Jira, Twitter, Sentry and <a href="/integrations">hundreds of other tools</a> can initiate new topics, creating lightweight discussion spaces for each issue. </div> </li> <li> <div class="list-content"> Bots can also use a dedicated topic to avoid crowding out conversations. </div> </li> <li> <div class="list-content"> Connect to thousands of tools using <a href="https://zapier.com/apps/zulip/integrations">Zapier</a>. Integrations written for Slack can post into Zulip via the <a href="/integrations/doc/slack_incoming">Slack compatible webhook</a>. </div> </li> <li> <div class="list-content"> Build your own integrations with Zulip’s easy-to-use <a href="/api">RESTful API</a>, <a href="/api/installation-instructions">client bindings</a>, <a href="/api/incoming-webhooks-overview">incoming webhooks</a>, <a href="/api/outgoing-webhooks">outgoing webhooks</a> and <a href="/api/running-bots">interactive bot framework</a>. </div> </li> </ul> </div> </div> <div class="feature-half"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/companies/integrations_with_border.png" /> </div> </div> </div> <div class="feature-container alternate-grid"> <div class="feature-half md-hide"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/education/flexible-administration.svg" /> </div> </div> <div class="feature-half"> <div class="feature-text"> <h1> Flexible administration and moderation </h1> <ul> <li> <div class="list-content"> Invite new members with <a href="/help/invite-new-users">multi-use invite links</a>, or make your community open for anyone to <a href="/help/allow-anyone-to-join-without-an-invitation">join without an invitation</a>. </div> </li> <li> <div class="list-content"> Allow (or require) users to authenticate with <a href="https://zulip.readthedocs.io/en/stable/production/authentication-methods.html"> single sign-on options</a> like <a href="/help/configure-authentication-methods">GitHub or GitLab</a>, instead of with a username and password. </div> </li> <li> <div class="list-content"> Automatically subscribe members to streams <a href="/help/set-default-streams-for-new-users">when they join.</a> </div> </li> <li> <div class="list-content">Manage your community with <a href="/help/stream-permissions#detailed-permissions"> fine-grained permission settings</a> for <a href="/help/roles-and-permissions"> administrators and moderators</a>. </div> </li> </ul> </div> </div> <div class="feature-half md-display"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/education/flexible-administration.svg" /> </div> </div> </div> <div class="feature-container"> <div class="feature-half"> <div class="feature-text"> <h1> When and how you want it </h1> <ul> <li> <div class="list-content"> With <a href="/apps">apps for every platform</a>, you can check Zulip at your computer or on your phone. Zulip works great in a browser, so no download is required. </div> </li> <li><div class="list-content">Zulip alerts you about timely messages with <a href="/help/stream-notifications">fully customizable</a> mobile, email and desktop notifications.</div></li> <li> <div class="list-content"> Mention <a href="/help/mention-a-user-or-group">users</a>, <a href="/help/mention-a-user-or-group#mention-a-user-or-group">groups of users</a> or <a href="/help/pm-mention-alert-notifications#wildcard-mentions">everyone</a> when you need their attention. </div> </li> <li> <div class="list-content"> Use Zulip in your language of choice, with translations into <a href="https://www.transifex.com/zulip/zulip/">17 languages</a>. </div> </li> <li> <div class="list-content"> Zulip is built for scale and works reliably for open organizations with 10,000s of users, with <a href="https://zulip.readthedocs.io/en/stable/production/requirements.html#scalability"> modest hardware</a>. </div> </li> </ul> </div> </div> <div class="feature-half"> <div class="feature-image"> <img alt="" src="/static/images/landing-page/education/mobile.svg" /> </div> </div> </div> <div class="feature-container alternate-grid"> <div class="feature-half md-hide"> <div class="feature-image"> <div class="quote"> <blockquote> The Lean community switched from Gitter to Zulip in early 2018, and never looked back. Zulip’s stream/topic model has been essential for organising research work and simultaneously onboarding newcomers as our community scaled. My experience with both the app and the website is extremely positive! </blockquote> <div class="author"> &mdash; <a href="https://www.imperial.ac.uk/people/k.buzzard"><NAME></a>, Professor of Pure Mathematics at <a href="https://www.imperial.ac.uk/">Imperial College London</a> </div> </div> </div> </div> <div class="feature-half"> <div class="feature-text"> <h1> Make the move today </h1> <ul> <li> <div class="list-content"> The Zulip core developers have decades of combined experience leading and growing open source communities, and we love helping other communities reach their potential. </div> </li> <li> <div class="list-content"> Getting started or moving from another platform is easy! Import your existing organization from <a href="/help/import-from-slack"> Slack</a>, <a href="/help/import-from-mattermost"> Mattermost</a>, <a href="/help/import-from-gitter"> Gitter</a>, or <a href="/help/import-from-rocketchat"> Rocket.Chat</a>. </div> </li> <li> <div class="list-content"> If you have any questions, please contact us at <a href="mailto:<EMAIL>"> <EMAIL></a>. You can also drop by our <a href="/developer-community/">friendly developer community at chat.zulip.org</a> to ask for help or suggest improvements! </div> </li> </ul> </div> </div> <div class="feature-half md-display"> <div class="feature-image"> <div class="quote"> <blockquote> The Lean community switched from Gitter to Zulip in early 2018, and never looked back. Zulip’s stream/topic model has been essential for organising research work and simultaneously onboarding newcomers as our community scaled. My experience with both the app and the website is extremely positive! </blockquote> <div class="author"> &mdash; <a href="https://www.imperial.ac.uk/people/k.buzzard"><NAME></a>, Professor of Pure Mathematics at <a href="https://www.imperial.ac.uk/">Imperial College London</a> </div> </div> </div> </div> </div> <div class="bottom-register-buttons"> <h1> <a href="/plans">Zulip Standard</a> is free for open-source projects! </h1> <div class="bottom-text-large"> <p>Join the hundreds of open-source projects we sponsor.</p> </div> <div class="hero-buttons center"> <a href="/new/" class="button"> {{ _('Create organization') }} </a> <a href="/accounts/go/?next=/upgrade%23sponsorship" class="button"> {{ _('Request sponsorship') }} </a> <a href="https://zulip.readthedocs.io/en/stable/production/install.html" class="button"> {{ _('Self-host Zulip') }} </a> </div> </div> </div> {% endblock %} <|start_filename|>static/js/settings_realm_user_settings_defaults.js<|end_filename|> import $ from "jquery"; import * as overlays from "./overlays"; import {page_params} from "./page_params"; import {realm_user_settings_defaults} from "./realm_user_settings_defaults"; import * as settings_display from "./settings_display"; import * as settings_notifications from "./settings_notifications"; import * as settings_org from "./settings_org"; export const realm_default_settings_panel = {}; export function maybe_disable_widgets() { if (!page_params.is_admin) { $(".organization-box [data-name='organization-level-user-defaults']") .find("input, select") .prop("disabled", true); $(".organization-box [data-name='organization-level-user-defaults']") .find(".play_notification_sound") .addClass("control-label-disabled"); } } export function update_page(property) { if (!overlays.settings_open()) { return; } const container = $(realm_default_settings_panel.container); const value = realm_user_settings_defaults[property]; if (property === "emojiset") { container.find(`input[value=${CSS.escape(value)}]`).prop("checked", true); return; } const input_elem = container.find(`[name=${CSS.escape(property)}]`); settings_org.set_input_element_value(input_elem, value); } export function set_up() { const container = $(realm_default_settings_panel.container); settings_display.set_up(realm_default_settings_panel); settings_notifications.set_up(realm_default_settings_panel); settings_org.register_save_discard_widget_handlers( container, "/json/realm/user_settings_defaults", true, ); maybe_disable_widgets(); } export function initialize() { realm_default_settings_panel.container = "#realm-user-default-settings"; realm_default_settings_panel.settings_object = realm_user_settings_defaults; realm_default_settings_panel.notification_sound_elem = "#realm-default-notification-sound-audio"; realm_default_settings_panel.for_realm_settings = true; } <|start_filename|>templates/zerver/plans.html<|end_filename|> {% extends "zerver/portico.html" %} {% set entrypoint = "landing-page" %} {% block customhead %} <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {% endblock %} {% block portico_content %} {% include 'zerver/gradients.html' %} {% include 'zerver/landing_nav.html' %} <div class="portico-landing plans"> <div class="main"> {% include "zerver/pricing_model.html" %} </div> <div class="discounts-section"> <header> <h1>Special Zulip Cloud Standard pricing</h1> </header> <div class="register-buttons"> <a href="/for/open-source" class="register-now buttton">Open source <p>Free</p></a> <a href="/for/education" class="register-now button">Education <p>85%+ OFF</p></a> <a href="/for/research" class="register-now button">Research <p>Free</p></a> <a href="/for/events" class="register-now button">Academic conferences<p>Free</p></a> <a href="/for/communities" class="register-now button">Non-profits and communities <p>85%+ OFF</p></a> </div> </div> {% include "zerver/faq.html" %} {% include "zerver/compare.html" %} </div> {% endblock %} <|start_filename|>static/js/compose.js<|end_filename|> import $ from "jquery"; import _ from "lodash"; import render_compose from "../templates/compose.hbs"; import * as blueslip from "./blueslip"; import * as channel from "./channel"; import * as compose_actions from "./compose_actions"; import * as compose_error from "./compose_error"; import * as compose_fade from "./compose_fade"; import * as compose_state from "./compose_state"; import * as compose_ui from "./compose_ui"; import * as compose_validate from "./compose_validate"; import * as echo from "./echo"; import * as giphy from "./giphy"; import {$t, $t_html} from "./i18n"; import * as loading from "./loading"; import * as markdown from "./markdown"; import * as notifications from "./notifications"; import {page_params} from "./page_params"; import * as people from "./people"; import * as reminder from "./reminder"; import * as rendered_markdown from "./rendered_markdown"; import * as resize from "./resize"; import * as rows from "./rows"; import * as sent_messages from "./sent_messages"; import * as server_events from "./server_events"; import * as stream_data from "./stream_data"; import * as stream_edit from "./stream_edit"; import * as stream_settings_ui from "./stream_settings_ui"; import * as sub_store from "./sub_store"; import * as transmit from "./transmit"; import * as ui_report from "./ui_report"; import * as upload from "./upload"; import {user_settings} from "./user_settings"; import * as util from "./util"; import * as zcommand from "./zcommand"; // Docs: https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html /* Track the state of the @all warning. The user must acknowledge that they are spamming the entire stream before the warning will go away. If they try to send before explicitly dismissing the warning, they will get an error message too. undefined: no @all/@everyone in message; false: user typed @all/@everyone; true: user clicked YES */ let uppy; export function compute_show_video_chat_button() { const available_providers = page_params.realm_available_video_chat_providers; if (page_params.realm_video_chat_provider === available_providers.disabled.id) { return false; } if ( page_params.realm_video_chat_provider === available_providers.jitsi_meet.id && !page_params.jitsi_server_url ) { return false; } return true; } export function update_video_chat_button_display() { const show_video_chat_button = compute_show_video_chat_button(); $("#below-compose-content .video_link").toggle(show_video_chat_button); $(".message-edit-feature-group .video_link").toggle(show_video_chat_button); } export function clear_invites() { $("#compose_invite_users").hide(); $("#compose_invite_users").empty(); } export function clear_private_stream_alert() { $("#compose_private_stream_alert").hide(); $("#compose_private_stream_alert").empty(); } export function clear_preview_area() { $("#compose-textarea").show(); $("#compose .undo_markdown_preview").hide(); $("#compose .preview_message_area").hide(); $("#compose .preview_content").empty(); $("#compose .markdown_preview").show(); } export function update_fade() { if (!compose_state.composing()) { return; } const msg_type = compose_state.get_message_type(); compose_fade.set_focused_recipient(msg_type); compose_fade.update_all(); } export function abort_xhr() { $("#compose-send-button").prop("disabled", false); uppy.cancelAll(); } export const zoom_token_callbacks = new Map(); export const video_call_xhrs = new Map(); export function abort_video_callbacks(edit_message_id = "") { zoom_token_callbacks.delete(edit_message_id); if (video_call_xhrs.has(edit_message_id)) { video_call_xhrs.get(edit_message_id).abort(); video_call_xhrs.delete(edit_message_id); } } export function empty_topic_placeholder() { return $t({defaultMessage: "(no topic)"}); } export function toggle_enter_sends_ui() { const send_button = $("#compose-send-button"); if (user_settings.enter_sends) { send_button.fadeOut(); } else { send_button.fadeIn(); } } export function create_message_object() { // Topics are optional, and we provide a placeholder if one isn't given. let topic = compose_state.topic(); if (topic === "") { topic = empty_topic_placeholder(); } // Changes here must also be kept in sync with echo.try_deliver_locally const message = { type: compose_state.get_message_type(), content: compose_state.message_content(), sender_id: page_params.user_id, queue_id: page_params.queue_id, stream: "", }; message.topic = ""; if (message.type === "private") { // TODO: this should be collapsed with the code in composebox_typeahead.js const recipient = compose_state.private_message_recipient(); const emails = util.extract_pm_recipients(recipient); message.to = emails; message.reply_to = recipient; message.private_message_recipient = recipient; message.to_user_ids = people.email_list_to_user_ids_string(emails); // Note: The `undefined` case is for situations like the // is_zephyr_mirror_realm case where users may be // automatically created when you try to send a private // message to their email address. if (message.to_user_ids !== undefined) { message.to = people.user_ids_string_to_ids_array(message.to_user_ids); } } else { const stream_name = compose_state.stream_name(); message.stream = stream_name; const sub = stream_data.get_sub(stream_name); if (sub) { message.stream_id = sub.stream_id; message.to = sub.stream_id; } else { // We should be validating streams in calling code. We'll // try to fall back to stream_name here just in case the // user started composing to the old stream name and // manually entered the stream name, and it got past // validation. We should try to kill this code off eventually. blueslip.error("Trying to send message with bad stream name: " + stream_name); message.to = stream_name; } message.topic = topic; } return message; } export function clear_compose_box() { /* Before clearing the compose box, we reset it to the * default/normal size. Note that for locally echoed messages, we * will have already done this action before echoing the message * to avoid the compose box triggering "new message out of view" * notifications incorrectly. */ if (compose_ui.is_full_size()) { compose_ui.make_compose_box_original_size(); } $("#compose-textarea").val("").trigger("focus"); compose_validate.check_overflow_text(); $("#compose-textarea").removeData("draft-id"); compose_ui.autosize_textarea($("#compose-textarea")); $("#compose-send-status").hide(0); $("#compose-send-button").prop("disabled", false); $("#sending-indicator").hide(); } export function send_message_success(local_id, message_id, locally_echoed) { if (!locally_echoed) { clear_compose_box(); } echo.reify_message_id(local_id, message_id); } export function send_message(request = create_message_object()) { if (request.type === "private") { request.to = JSON.stringify(request.to); } else { request.to = JSON.stringify([request.to]); } let local_id; let locally_echoed; const message = echo.try_deliver_locally(request); if (message) { // We are rendering this message locally with an id // like 92l99.01 that corresponds to a reasonable // approximation of the id we'll get from the server // in terms of sorting messages. local_id = message.local_id; locally_echoed = true; } else { // We are not rendering this message locally, but we // track the message's life cycle with an id like // loc-1, loc-2, loc-3,etc. locally_echoed = false; local_id = sent_messages.get_new_local_id(); } request.local_id = local_id; sent_messages.start_tracking_message({ local_id, locally_echoed, }); request.locally_echoed = locally_echoed; function success(data) { send_message_success(local_id, data.id, locally_echoed); } function error(response) { // If we're not local echo'ing messages, or if this message was not // locally echoed, show error in compose box if (!locally_echoed) { compose_error.show(_.escape(response), $("#compose-textarea")); return; } echo.message_send_error(message.id, response); } transmit.send_message(request, success, error); server_events.assert_get_events_running( "Restarting get_events because it was not running during send", ); if (locally_echoed) { clear_compose_box(); } } export function enter_with_preview_open() { if (user_settings.enter_sends) { // If enter_sends is enabled, we attempt to send the message finish(); } else { // Otherwise, we return to the compose box and focus it $("#compose-textarea").trigger("focus"); } } function show_sending_indicator(whats_happening) { $("#sending-indicator").text(whats_happening); $("#sending-indicator").show(); } export function finish() { clear_preview_area(); clear_invites(); clear_private_stream_alert(); notifications.clear_compose_notifications(); const message_content = compose_state.message_content(); // Skip normal validation for zcommands, since they aren't // actual messages with recipients; users only send them // from the compose box for convenience sake. if (zcommand.process(message_content)) { do_post_send_tasks(); clear_compose_box(); return undefined; } $("#compose-send-button").prop("disabled", true).trigger("blur"); if (reminder.is_deferred_delivery(message_content)) { show_sending_indicator($t({defaultMessage: "Scheduling..."})); } else { show_sending_indicator($t({defaultMessage: "Sending..."})); } if (!compose_validate.validate()) { // If the message failed validation, hide the sending indicator. $("#sending-indicator").hide(); return false; } if (reminder.is_deferred_delivery(message_content)) { reminder.schedule_message(); } else { send_message(); } do_post_send_tasks(); return true; } export function do_post_send_tasks() { clear_preview_area(); // TODO: Do we want to fire the event even if the send failed due // to a server-side error? $(document).trigger("compose_finished.zulip"); } export function update_email(user_id, new_email) { let reply_to = compose_state.private_message_recipient(); if (!reply_to) { return; } reply_to = people.update_email_in_reply_to(reply_to, user_id, new_email); compose_state.private_message_recipient(reply_to); } function insert_video_call_url(url, target_textarea) { const link_text = $t({defaultMessage: "Click to join video call"}); compose_ui.insert_syntax_and_focus(`[${link_text}](${url})`, target_textarea); } export function render_and_show_preview(preview_spinner, preview_content_box, content) { function show_preview(rendered_content, raw_content) { // content is passed to check for status messages ("/me ...") // and will be undefined in case of errors let rendered_preview_html; if (raw_content !== undefined && markdown.is_status_message(raw_content)) { // Handle previews of /me messages rendered_preview_html = "<p><strong>" + _.escape(page_params.full_name) + "</strong>" + rendered_content.slice("<p>/me".length); } else { rendered_preview_html = rendered_content; } preview_content_box.html(util.clean_user_content_links(rendered_preview_html)); rendered_markdown.update_elements(preview_content_box); } if (content.length === 0) { show_preview($t_html({defaultMessage: "Nothing to preview"})); } else { if (markdown.contains_backend_only_syntax(content)) { const spinner = preview_spinner.expectOne(); loading.make_indicator(spinner); } else { // For messages that don't appear to contain syntax that // is only supported by our backend Markdown processor, we // render using the frontend Markdown processor (but still // render server-side to ensure the preview is accurate; // if the `markdown.contains_backend_only_syntax` logic is // wrong, users will see a brief flicker of the locally // echoed frontend rendering before receiving the // authoritative backend rendering from the server). const message_obj = { raw_content: content, }; markdown.apply_markdown(message_obj); } channel.post({ url: "/json/messages/render", idempotent: true, data: {content}, success(response_data) { if (markdown.contains_backend_only_syntax(content)) { loading.destroy_indicator(preview_spinner); } show_preview(response_data.rendered, content); }, error() { if (markdown.contains_backend_only_syntax(content)) { loading.destroy_indicator(preview_spinner); } show_preview($t_html({defaultMessage: "Failed to generate preview"})); }, }); } } export function render_compose_box() { $("#compose-container").append( render_compose({ embedded: $("#compose").attr("data-embedded") === "", file_upload_enabled: page_params.max_file_upload_size_mib > 0, giphy_enabled: giphy.is_giphy_enabled(), }), ); } export function initialize() { render_compose_box(); $("#below-compose-content .video_link").toggle(compute_show_video_chat_button()); $( "#stream_message_recipient_stream,#stream_message_recipient_topic,#private_message_recipient", ).on("keyup", update_fade); $( "#stream_message_recipient_stream,#stream_message_recipient_topic,#private_message_recipient", ).on("change", update_fade); $("#compose-textarea").on("keydown", (event) => { compose_ui.handle_keydown(event, $("#compose-textarea").expectOne()); }); $("#compose-textarea").on("keyup", (event) => { compose_ui.handle_keyup(event, $("#compose-textarea").expectOne()); }); $("#compose-textarea").on("input propertychange", () => { compose_validate.check_overflow_text(); }); $("#compose form").on("submit", (e) => { e.preventDefault(); finish(); }); resize.watch_manual_resize("#compose-textarea"); upload.feature_check($("#compose .compose_upload_file")); $("#compose-all-everyone").on("click", ".compose-all-everyone-confirm", (event) => { event.preventDefault(); $(event.target).parents(".compose-all-everyone").remove(); compose_validate.set_user_acknowledged_all_everyone_flag(true); compose_validate.clear_all_everyone_warnings(); finish(); }); $("#compose-announce").on("click", ".compose-announce-confirm", (event) => { event.preventDefault(); $(event.target).parents(".compose-announce").remove(); compose_validate.set_user_acknowledged_announce_flag(true); compose_validate.clear_announce_warnings(); finish(); }); $("#compose-send-status").on("click", ".sub_unsub_button", (event) => { event.preventDefault(); const stream_name = $("#stream_message_recipient_stream").val(); if (stream_name === undefined) { return; } const sub = stream_data.get_sub(stream_name); stream_settings_ui.sub_or_unsub(sub); $("#compose-send-status").hide(); }); $("#compose-send-status").on("click", "#compose_not_subscribed_close", (event) => { event.preventDefault(); $("#compose-send-status").hide(); }); $("#compose_invite_users").on("click", ".compose_invite_link", (event) => { event.preventDefault(); const invite_row = $(event.target).parents(".compose_invite_user"); const user_id = Number.parseInt($(invite_row).data("user-id"), 10); const stream_id = Number.parseInt($(invite_row).data("stream-id"), 10); function success() { const all_invites = $("#compose_invite_users"); invite_row.remove(); if (all_invites.children().length === 0) { all_invites.hide(); } } function failure(error_msg) { clear_invites(); compose_error.show(_.escape(error_msg), $("#compose-textarea")); $(event.target).prop("disabled", true); } function xhr_failure(xhr) { const error = JSON.parse(xhr.responseText); failure(error.msg); } const sub = sub_store.get(stream_id); stream_edit.invite_user_to_stream([user_id], sub, success, xhr_failure); }); $("#compose_invite_users").on("click", ".compose_invite_close", (event) => { const invite_row = $(event.target).parents(".compose_invite_user"); const all_invites = $("#compose_invite_users"); invite_row.remove(); if (all_invites.children().length === 0) { all_invites.hide(); } }); $("#compose_private_stream_alert").on( "click", ".compose_private_stream_alert_close", (event) => { const stream_alert_row = $(event.target).parents(".compose_private_stream_alert"); const stream_alert = $("#compose_private_stream_alert"); stream_alert_row.remove(); if (stream_alert.children().length === 0) { stream_alert.hide(); } }, ); // Click event binding for "Attach files" button // Triggers a click on a hidden file input field $("#compose").on("click", ".compose_upload_file", (e) => { e.preventDefault(); $("#compose .file_input").trigger("click"); }); $("body").on("click", ".video_link", (e) => { e.preventDefault(); let target_textarea; let edit_message_id; if ($(e.target).parents(".message_edit_form").length === 1) { edit_message_id = rows.id($(e.target).parents(".message_row")); target_textarea = $(`#edit_form_${CSS.escape(edit_message_id)} .message_edit_content`); } let video_call_link; const available_providers = page_params.realm_available_video_chat_providers; const show_video_chat_button = compute_show_video_chat_button(); if (!show_video_chat_button) { return; } if ( available_providers.zoom && page_params.realm_video_chat_provider === available_providers.zoom.id ) { abort_video_callbacks(edit_message_id); const key = edit_message_id || ""; const make_zoom_call = () => { video_call_xhrs.set( key, channel.post({ url: "/json/calls/zoom/create", success(res) { video_call_xhrs.delete(key); insert_video_call_url(res.url, target_textarea); }, error(xhr, status) { video_call_xhrs.delete(key); if ( status === "error" && xhr.responseJSON && xhr.responseJSON.code === "INVALID_ZOOM_TOKEN" ) { page_params.has_zoom_token = false; } if (status !== "abort") { ui_report.generic_embed_error( $t_html({defaultMessage: "Failed to create video call."}), ); } }, }), ); }; if (page_params.has_zoom_token) { make_zoom_call(); } else { zoom_token_callbacks.set(key, make_zoom_call); window.open( window.location.protocol + "//" + window.location.host + "/calls/zoom/register", "_blank", "width=800,height=500,noopener,noreferrer", ); } } else if ( available_providers.big_blue_button && page_params.realm_video_chat_provider === available_providers.big_blue_button.id ) { channel.get({ url: "/json/calls/bigbluebutton/create", success(response) { insert_video_call_url(response.url, target_textarea); }, }); } else { const video_call_id = util.random_int(100000000000000, 999999999999999); video_call_link = page_params.jitsi_server_url + "/" + video_call_id; insert_video_call_url(video_call_link, target_textarea); } }); $("#compose").on("click", ".markdown_preview", (e) => { e.preventDefault(); const content = $("#compose-textarea").val(); $("#compose-textarea").hide(); $("#compose .markdown_preview").hide(); $("#compose .undo_markdown_preview").show(); $("#compose .preview_message_area").show(); render_and_show_preview( $("#compose .markdown_preview_spinner"), $("#compose .preview_content"), content, ); }); $("#compose").on("click", ".undo_markdown_preview", (e) => { e.preventDefault(); clear_preview_area(); }); $("#compose").on("click", ".expand_composebox_button", (e) => { e.preventDefault(); compose_ui.make_compose_box_full_size(); }); $("#compose").on("click", ".collapse_composebox_button", (e) => { e.preventDefault(); compose_ui.make_compose_box_original_size(); }); uppy = upload.setup_upload({ mode: "compose", }); $("#compose-textarea").on("focus", () => { compose_actions.update_placeholder_text(); }); $("#stream_message_recipient_topic").on("focus", () => { compose_actions.update_placeholder_text(); }); if (page_params.narrow !== undefined) { if (page_params.narrow_topic !== undefined) { compose_actions.start("stream", {topic: page_params.narrow_topic}); } else { compose_actions.start("stream", {}); } } }
narendrapsgim/zulip
<|start_filename|>app/src/main/java/com/ztech/fakecalllollipop/FakeRingerActivity.java<|end_filename|> package com.ztech.fakecalllollipop; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.*; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.os.Vibrator; import android.provider.CallLog; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.NotificationCompat; import android.telephony.PhoneNumberUtils; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.io.InputStream; import java.util.Locale; public class FakeRingerActivity extends AppCompatActivity { private static final int INCOMING_CALL_NOTIFICATION = 1001; private static final int MISSED_CALL_NOTIFICATION = 1002; private ImageButton callActionButton; private ImageButton answer; private ImageButton decline; private ImageButton text; private ImageButton endCall; private ImageView contactPhoto; private ImageView ring; private TextView callStatus; private TextView callDuration; private RelativeLayout main; private RelativeLayout callActionButtons; private AudioManager audioManager; private long secs; private int duration; private String number; private String name; private String voice; private Ringtone ringtone; private Vibrator vibrator; private PowerManager.WakeLock wakeLock; private NotificationManager notificationManager; private ContentResolver contentResolver; private MediaPlayer voicePlayer; private Resources resources; private int currentRingerMode; private int currentRingerVolume; private String contactImageString; private int currentMediaVolume; final Handler handler = new Handler(); private Runnable hangUP = new Runnable() { @Override public void run() { finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); setContentView(R.layout.activity_fake_ringer); Window window = getWindow(); Intent intent = getIntent(); Bundle extras = intent.getExtras(); PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this); TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber); TextView callerName = (TextView) findViewById(R.id.callerName); final Animation ringExpandAnimation = AnimationUtils.loadAnimation(this, R.anim.ring_expand); final Animation ringShrinkAnimation = AnimationUtils.loadAnimation(this, R.anim.ring_shrink); final Drawable bg2 = getDrawable(R.drawable.answered_bg); contactPhoto = (ImageView)findViewById(R.id.contactPhoto); contentResolver = getContentResolver(); resources = getResources(); audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "Tag"); currentRingerMode = audioManager.getRingerMode(); currentRingerVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING); currentMediaVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); callActionButtons = (RelativeLayout)findViewById(R.id.callActionButtons); callActionButton = (ImageButton) findViewById(R.id.callActionButton); answer = (ImageButton) findViewById(R.id.callActionAnswer); decline = (ImageButton) findViewById(R.id.callActionDecline); text = (ImageButton) findViewById(R.id.callActionText); endCall = (ImageButton) findViewById(R.id.endCall); callStatus = (TextView) findViewById(R.id.callStatus); callDuration = (TextView) findViewById(R.id.callDuration); main = (RelativeLayout) findViewById(R.id.main); ring = (ImageView) findViewById(R.id.ring); name = extras.getString("name"); voice = extras.getString("voice", ""); duration = extras.getInt("duration"); number = extras.getString("number"); contactImageString = extras.getString("contactImage"); int hangUpAfter = extras.getInt("hangUpAfter"); getSupportActionBar().hide(); window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); wakeLock.setReferenceCounted(false); nBuilder.setSmallIcon(R.drawable.ic_call); nBuilder.setOngoing(true); nBuilder.setContentTitle(name); nBuilder.setColor(Color.rgb(4, 137, 209)); nBuilder.setContentText(resources.getString(R.string.incoming_call)); notificationManager.notify(INCOMING_CALL_NOTIFICATION, nBuilder.build()); handler.postDelayed(hangUP, hangUpAfter * 1000); muteAll(); setContactImage(true); callActionButton.setOnTouchListener(new View.OnTouchListener() { float x1 = 0, x2 = 0, y1 = 0, y2 = 0; @Override public boolean onTouch(View v, MotionEvent event) { int a = event.getAction(); if (a == MotionEvent.ACTION_DOWN) { x1 = event.getX(); y1 = event.getY(); ring.startAnimation(ringExpandAnimation); answer.setVisibility(View.VISIBLE); decline.setVisibility(View.VISIBLE); text.setVisibility(View.VISIBLE); callActionButton.setVisibility(View.INVISIBLE); } else if (a == MotionEvent.ACTION_MOVE) { x2 = event.getX(); y2 = event.getY(); if ((x2 - 200) > x1) { callActionButtons.removeView(callActionButton); callActionButtons.removeView(ring); callActionButtons.removeView(answer); callActionButtons.removeView(decline); callActionButtons.removeView(text); audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); handler.removeCallbacks(hangUP); callStatus.setText(""); setContactImage(false); stopRinging(); main.setBackground(bg2); endCall.setVisibility(View.VISIBLE); wakeLock.acquire(); playVoice(); handler.postDelayed(new Runnable() { @Override public void run() { long min = (secs % 3600) / 60; long seconds = secs % 60; String dur = String.format(Locale.US, "%02d:%02d", min, seconds); secs++; callDuration.setText(dur); handler.postDelayed(this, 1000); } }, 10); handler.postDelayed(new Runnable() { @Override public void run() { finish(); } }, duration * 1000); } else if ((x2 + 200) < x1) { finish(); } else if ((y2 + 200) < y1) { finish(); } else if ((y2 - 200) > y1) { finish(); } } else if (a == MotionEvent.ACTION_UP || a == MotionEvent.ACTION_CANCEL) { answer.setVisibility(View.INVISIBLE); decline.setVisibility(View.INVISIBLE); text.setVisibility(View.INVISIBLE); ring.startAnimation(ringShrinkAnimation); callActionButton.setVisibility(View.VISIBLE); } return false; } }); Animation animCallStatusPulse = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.call_status_pulse); callStatus.startAnimation(animCallStatusPulse); number = PhoneNumberUtils.formatNumber(number, "ET"); phoneNumber.setText("Mobile " + number); callerName.setText(name); Uri ringtoneURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); ringtone = RingtoneManager.getRingtone(getApplicationContext(), ringtoneURI); vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); ringtone.play(); long[] pattern = {1000, 1000, 1000, 1000, 1000}; vibrator.vibrate(pattern, 0); } private void setContactImage(boolean tint) { if (!(contactImageString == null)) { Uri contactImageUri = Uri.parse(contactImageString); try { InputStream contactImageStream = contentResolver.openInputStream(contactImageUri); Drawable contactImage = Drawable.createFromStream(contactImageStream, contactImageUri.toString()); if(tint) { contactImage.setTint(getResources().getColor(R.color.contact_photo_tint)); contactImage.setTintMode(PorterDuff.Mode.DARKEN); } contactPhoto.setImageDrawable(contactImage); } catch (Exception e) { } } } private void playVoice() { if (!voice.equals("")) { Uri voiceURI = Uri.parse(voice); voicePlayer = new MediaPlayer(); try { voicePlayer.setDataSource(this, voiceURI); } catch (Exception e) { e.printStackTrace(); } voicePlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL); voicePlayer.prepareAsync(); voicePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); } }); } } private void muteAll() { audioManager.setStreamMute(AudioManager.STREAM_ALARM, true); audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true); } private void unMuteAll() { audioManager.setStreamMute(AudioManager.STREAM_ALARM, false); audioManager.setStreamMute(AudioManager.STREAM_MUSIC, false); } public void onClickEndCall(View view) { stopVoice(); finish(); } private void stopVoice() { if (voicePlayer != null && voicePlayer.isPlaying()) { voicePlayer.stop(); } } private void stopRinging() { vibrator.cancel(); ringtone.stop(); } // adds a missed call to the log and shows a notification private void missedCall() { NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this); nBuilder.setSmallIcon(android.R.drawable.stat_notify_missed_call); nBuilder.setContentTitle(name); nBuilder.setContentText(resources.getString(R.string.missed_call)); nBuilder.setColor(Color.rgb(4, 137, 209)); nBuilder.setAutoCancel(true); Intent showCallLog = new Intent(Intent.ACTION_VIEW); showCallLog.setType(CallLog.Calls.CONTENT_TYPE); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, showCallLog, PendingIntent.FLAG_CANCEL_CURRENT); nBuilder.setContentIntent(pendingIntent); showCallLog.setType(CallLog.Calls.CONTENT_TYPE); notificationManager.notify(MISSED_CALL_NOTIFICATION, nBuilder.build()); CallLogUtilities.addCallToLog(contentResolver, number, 0, CallLog.Calls.MISSED_TYPE, System.currentTimeMillis()); } private void incomingCall() { CallLogUtilities.addCallToLog(contentResolver, number, secs, CallLog.Calls.INCOMING_TYPE, System.currentTimeMillis()); } @Override protected void onDestroy() { super.onDestroy(); stopVoice(); notificationManager.cancel(INCOMING_CALL_NOTIFICATION); if (secs > 0) { incomingCall(); } else { missedCall(); } wakeLock.release(); audioManager.setRingerMode(currentRingerMode); audioManager.setStreamVolume(AudioManager.STREAM_RING, currentRingerVolume, 0); stopRinging(); unMuteAll(); audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentMediaVolume, 0); } @Override public void onBackPressed() { } } <|start_filename|>app/src/main/java/com/ztech/fakecalllollipop/FakeSMSReceiver.java<|end_filename|> package com.ztech.fakecalllollipop; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.graphics.*; import android.net.Uri; import android.support.v7.app.NotificationCompat; import java.io.InputStream; public class FakeSMSReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context); ContentResolver contentResolver = context.getContentResolver(); String contactImage = intent.getStringExtra("contactImage"); String name = intent.getStringExtra("name"); String number = intent.getStringExtra("number"); String message = intent.getStringExtra("message"); Intent showSMS = new Intent(Intent.ACTION_MAIN); showSMS.addCategory(Intent.CATEGORY_DEFAULT); showSMS.setType("vnd.android-dir/mms-sms"); PendingIntent showSMSIntent = PendingIntent.getActivity(context, 0, showSMS, PendingIntent.FLAG_CANCEL_CURRENT); if (contactImage != null && !contactImage.equals("")) { Uri contactImageUri = Uri.parse(contactImage); try { InputStream contactImageStream = contentResolver.openInputStream(contactImageUri); Bitmap icon = BitmapFactory.decodeStream(contactImageStream); icon.setHasMipMap(true); nBuilder.setLargeIcon(FakeSMSReceiver.getCircleBitmap(icon)); } catch (Exception e) { } } if (name == null) { nBuilder.setContentTitle(number); } else { nBuilder.setContentTitle(name); } nBuilder.setDefaults(Notification.DEFAULT_ALL); nBuilder.setSmallIcon(R.drawable.sms, 1); nBuilder.setContentText(message); nBuilder.setPriority(NotificationCompat.PRIORITY_HIGH); nBuilder.setColor(Color.rgb(0, 172, 193)); nBuilder.addAction(R.drawable.ic_reply, "Reply", showSMSIntent); nBuilder.addAction(R.drawable.ic_mark_read, "Read", showSMSIntent); nBuilder.addAction(R.drawable.ic_call, "Call", showSMSIntent); nBuilder.setContentIntent(showSMSIntent); nm.notify(2001, nBuilder.build()); } private static Bitmap getCircleBitmap(Bitmap bitmap) { final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(output); final int color = Color.RED; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawOval(rectF, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); bitmap.recycle(); return output; } } <|start_filename|>app/src/main/java/com/ztech/fakecalllollipop/SelectTimeFragment.java<|end_filename|> package com.ztech.fakecalllollipop; import android.app.Activity; import android.app.Fragment; import android.app.TimePickerDialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TimePicker; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * A simple {@link Fragment} subclass. */ public class SelectTimeFragment extends Fragment { private EditText timeInput; private Calendar calendar = null; private Activity activity; public SelectTimeFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_select_time, container, false); timeInput = (EditText) view.findViewById(R.id.scheduleTimePicker); activity = getActivity(); timeInput.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { calendar = Calendar.getInstance(); int cHour = calendar.get(Calendar.HOUR_OF_DAY); int cMinute = calendar.get(Calendar.MINUTE); TimePickerDialog timePickerDialog = new TimePickerDialog(activity, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, 0); Date scheduleTime = calendar.getTime(); SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a", Locale.US); timeInput.setText(dateFormat.format(scheduleTime)); ((IEventListener) activity).sendTime(calendar); } }, cHour, cMinute, false); timePickerDialog.setCancelable(false); timePickerDialog.show(); } }); return view; } interface IEventListener { public void sendTime(Calendar calendar); } } <|start_filename|>app/src/main/java/com/ztech/fakecalllollipop/LaunchAppViaDialReceiver.java<|end_filename|> package com.ztech.fakecalllollipop; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; public class LaunchAppViaDialReceiver extends BroadcastReceiver { SharedPreferences appSettings; @Override public void onReceive(Context context, Intent intent) { appSettings = context.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE); String numberToDial = appSettings.getString("numberToDial", "111"); String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); if (phoneNumber.equals(numberToDial)) { setResultData(null); Intent appIntent = new Intent(context, ScheduleCallActivity.class); appIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(appIntent); } } } <|start_filename|>app/src/main/java/com/ztech/fakecalllollipop/ScheduleCallActivity.java<|end_filename|> package com.ztech.fakecalllollipop; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Intent; import android.os.Bundle; import android.provider.CallLog; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import java.util.Calendar; public class ScheduleCallActivity extends AppCompatActivity implements SelectTimeFragment.IEventListener, SelectContactFragment.IEventListener { private static final int FILE_SELECT = 1002; private static final int HANA_UP_AFTER = 15; private static final int DURATION = 63; Calendar calendar = null; String contactImage = null; String voice = null; EditText voiceInput = null; RadioGroup callType; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_schedule_call); callType = (RadioGroup)findViewById(R.id.callTypeRadioGroup); voiceInput = (EditText)findViewById(R.id.voiceFileInput); voiceInput.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("audio/*"); startActivityForResult(intent, FILE_SELECT); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.settings_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { Intent intent; switch(menuItem.getItemId()) { case R.id.exitOption: finish(); return true; case R.id.aboutOption: AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle(R.string.about); alertDialogBuilder.setMessage(R.string.about_message); alertDialogBuilder.setIcon(R.mipmap.ic_launcher); alertDialogBuilder.show(); return true; case R.id.settingsOption: intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; case R.id.smsOption: intent = new Intent(this, ScheduleSMSActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(menuItem); } } public void onClickSchedule(View view) { EditText nameInput = (EditText)findViewById(R.id.nameInput); EditText numberInput = (EditText)findViewById(R.id.numberInput); EditText timeInput = (EditText)findViewById(R.id.scheduleTimePicker); EditText durationInput = (EditText)findViewById(R.id.callDurationInput); EditText hangUpAfterInput = (EditText)findViewById(R.id.hangUpAfterInput); String name = nameInput.getText().toString(); String number = numberInput.getText().toString(); String time = timeInput.getText().toString(); String duration = durationInput.getText().toString(); String hangUpAfter = hangUpAfterInput.getText().toString(); if (number.equals("")) { Toast.makeText(this, "Number can't be empty!", Toast.LENGTH_SHORT).show(); return; } if (time.equals("")) { Toast.makeText(this, "Call time can't be empty", Toast.LENGTH_SHORT).show(); return; } if (name.equals("")) { name = getResources().getString(R.string.unknown); } if (duration.equals("")) { duration = Integer.toString(DURATION); } if (hangUpAfter.equals("")) { hangUpAfter = Integer.toString(HANA_UP_AFTER); } RadioButton radioButton = (RadioButton)findViewById(callType.getCheckedRadioButtonId()); int radioButtonIndex = callType.indexOfChild(radioButton); ContentResolver contentResolver = getContentResolver(); if (radioButtonIndex == 0) { Intent intent = new Intent(this, FakeRingerActivity.class); intent.putExtra("name", name); intent.putExtra("number", "Mobile " + number); intent.putExtra("contactImage", contactImage); intent.putExtra("duration", Integer.parseInt(duration)); intent.putExtra("hangUpAfter", Integer.parseInt(hangUpAfter)); intent.putExtra("voice", voice); final int fakeCallID = (int)System.currentTimeMillis(); PendingIntent pendingIntent = PendingIntent.getActivity(this, fakeCallID, intent, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); Toast.makeText(this, "Fake call scheduled", Toast.LENGTH_SHORT).show(); finish(); } else if (radioButtonIndex == 1) { CallLogUtilities.addCallToLog(contentResolver, number, Integer.parseInt(duration), CallLog.Calls.OUTGOING_TYPE, calendar.getTimeInMillis()); Toast.makeText(this, "Fake outgoing call added to log", Toast.LENGTH_SHORT).show(); } else if (radioButtonIndex == 2) { CallLogUtilities.addCallToLog(contentResolver, number, 0, CallLog.Calls.MISSED_TYPE, calendar.getTimeInMillis()); Toast.makeText(this, "Fake missed call added to log", Toast.LENGTH_SHORT).show(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) return; switch (requestCode) { case FILE_SELECT: voice = data.getDataString(); voiceInput.setText(voice); break; } } @Override public void sendTime(Calendar calendar) { this.calendar = calendar; } @Override public void sendContactImage(String contactImage) { this.contactImage = contactImage; } }
zolamk/fake-call-lollipop
<|start_filename|>src/components/vue-cal/i18n/it.json<|end_filename|> { "weekDays": ["Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"], "months": ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"], "years": "Anni", "year": "Anno", "month": "Mese", "week": "Settimana", "day": "Giorno", "today": "Oggi", "noEvent": "No evento", "deleteEvent": "Cancellare", "createEvent": "Creare un evento", "dateFormat": "DDDD d mmmm yyyy" }
Yurgeman/vue-cal
<|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/logs/vm/LogsViewModel.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.logs.vm import android.text.Spannable import androidx.databinding.BaseObservable import androidx.databinding.ObservableBoolean import androidx.databinding.ObservableField import androidx.navigation.NavController import io.stanwood.bitrise.R import io.stanwood.bitrise.data.model.App import io.stanwood.bitrise.data.model.Build import io.stanwood.bitrise.data.net.BitriseService import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.util.extensions.ansiEscapeToSpannable import io.stanwood.bitrise.util.extensions.bundleOf import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import timber.log.Timber class LogsViewModel( private val service: BitriseService, private val token: String, private val router: NavController, private val app: App, private val build: Build, private val mainScope: CoroutineScope ) : BaseObservable() { val isLoading = ObservableBoolean(false) var showLog = ObservableBoolean(false) var log = ObservableField<Spannable>() fun onRefresh() { showLog.set(true) mainScope.launch { try { isLoading.set(true) log.apply { set(fetchLog().ansiEscapeToSpannable()) } } catch (exception: CancellationException) { /* noop */ } catch (exception: Exception) { Timber.e(exception) bundleOf(Properties.MESSAGE to exception.message).apply { router.navigate(R.id.action_error, this) } } finally { isLoading.set(false) } } } private suspend fun fetchLog() = service .getBuildLog(token, app.slug, build.slug) .await() .let { if (it.isArchived) { service.downloadFile(it.expiringRawLogUrl) .await() .charStream() .readText() } else { it.logChunks .asSequence() .sortedBy { logChunk -> logChunk.position } .joinToString { logChunk -> logChunk.chunk } } } } <|start_filename|>app/src/main/java/io/stanwood/bitrise/data/model/Log.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.data.model import com.google.gson.annotations.SerializedName data class Log( @SerializedName("expiring_raw_log_url") val expiringRawLogUrl: String, //https://bitrise-build-log-archives-production.s3.amazonaws.com/build-logs-v2/669403bffbe35909/3247e2920496e846/2194500/3247e2920496e846.log?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOC7N256G7J2W2TQ%2F20171122%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20171122T135458Z&X-Amz-Expires=600&X-Amz-SignedHeaders=host&X-Amz-Signature=611793356be42a86b618f53effa74a4297f3970abc2ebc47b8b1a298a29ae649 @SerializedName("generated_log_chunks_num") val generatedLogChunksNum: Int, //6 @SerializedName("is_archived") val isArchived: Boolean, //true @SerializedName("log_chunks") val logChunks: List<LogChunk>, @SerializedName("timestamp") val timestamp: String //2017-05-30T15:47:39.567+00:00 ) data class LogChunk( @SerializedName("chunk") val chunk: String, @SerializedName("position") val position: Int) <|start_filename|>app/src/main/java/io/stanwood/bitrise/PermissionActivity.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise import android.annotation.SuppressLint import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.appcompat.app.AppCompatActivity import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.suspendCancellableCoroutine import java.util.concurrent.atomic.AtomicInteger import kotlin.coroutines.resume @SuppressLint("Registered") open class PermissionActivity: AppCompatActivity() { private val permissionRequestCounter = AtomicInteger(0) private val uid: Int get() = permissionRequestCounter.getAndIncrement() private val permissionListeners: MutableMap<Int, CancellableContinuation<Boolean>> = mutableMapOf() private fun requestPermissions(vararg permissions: String, continuation: CancellableContinuation<Boolean>) { val isRequestRequired = permissions .map { ContextCompat.checkSelfPermission(this, it) } .any { result -> result == PackageManager.PERMISSION_DENIED } if (isRequestRequired) { ActivityCompat.requestPermissions(this, permissions, uid) } else { continuation.resume(true) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) val isGranted = grantResults.all { result -> result == PackageManager.PERMISSION_GRANTED } permissionListeners .remove(requestCode) ?.resume(isGranted) } suspend fun requestPermissions(vararg permissions: String): Boolean = suspendCancellableCoroutine { continuation -> requestPermissions(*permissions, continuation = continuation) } } <|start_filename|>app/src/main/java/io/stanwood/bitrise/Arguments.kt<|end_filename|> package io.stanwood.bitrise object Arguments { const val ACTIVITY = "activity" const val BUILD = "build" const val APP = "arg_app" const val FRAGMENT_MANAGER = "fragment_manager" const val BRANCH = "branch" const val WORKFLOW = "workflow" const val FAVORITE_APPS = "fav_apps" const val MESSAGE = "arg_message" const val TOKEN = "arg_token" } <|start_filename|>app/src/main/java/io/stanwood/bitrise/data/model/Artifact.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.data.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Artifact( @SerializedName("artifact_type") val artifactType: ArtifactType?, //android-apk @SerializedName("expiring_download_url") val expiringDownloadUrl: String, //https://bitrise-prod-build-storage.s3.amazonaws.com/builds/ddf4134555e833d8/artifacts/3205846/app-debug.apk?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=AKIAIOC7N256G7J2W2TQ%2F20171122%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20171122T135501Z&X-Amz-Expires=600&X-Amz-SignedHeaders=host&X-Amz-Signature=bad4467b83a1d98a6046b59a1b232bb0888decf203e039c9b3798f7b4950b68c @SerializedName("file_size_bytes") val fileSizeBytes: Int, //607185 @SerializedName("is_public_page_enabled") val isPublicPageEnabled: Boolean, //true @SerializedName("public_install_page_url") val publicInstallPageUrl: String?, //https://www.bitrise.io/artifact/3205846/p/300e0121b50985fd631fe304d549006f @SerializedName("slug") val slug: String, //5a9f5da8d5f1057c @SerializedName("title") val title: String //app-debug.apk ): Parcelable <|start_filename|>app/src/main/java/io/stanwood/bitrise/util/extensions/StringExtensions.kt<|end_filename|> package io.stanwood.bitrise.util.extensions import android.graphics.Color import android.graphics.Typeface import android.text.ParcelableSpan import android.text.Spannable import android.text.SpannableString import android.text.style.BackgroundColorSpan import android.text.style.ForegroundColorSpan import android.text.style.StyleSpan import android.text.style.UnderlineSpan import java.util.Stack private val ansiRegex by lazy { Regex("\u001B\\[[;\\d]*m") } fun String.stripAnsiEscapes() = replace(ansiRegex, "") private val red by lazy { Color.parseColor("#f44336") } private val green by lazy { Color.parseColor("#4caf50") } private val yellow by lazy { Color.parseColor("#ffeb3b") } private val blue by lazy { Color.parseColor("#2196f3") } private val magenta by lazy { Color.parseColor("#e91e63") } private val cyan by lazy { Color.parseColor("#00bcd4") } fun getSpan(code: String?): ParcelableSpan? = when(code) { "0" -> null "1" -> StyleSpan(Typeface.BOLD) "3" -> StyleSpan(Typeface.ITALIC) "4" -> UnderlineSpan() "30" -> ForegroundColorSpan(Color.BLACK) "31" -> ForegroundColorSpan(red) "32" -> ForegroundColorSpan(green) "33" -> ForegroundColorSpan(yellow) "34" -> ForegroundColorSpan(blue) "35" -> ForegroundColorSpan(magenta) "36" -> ForegroundColorSpan(cyan) "37" -> ForegroundColorSpan(Color.WHITE) "40" -> BackgroundColorSpan(Color.BLACK) "41" -> BackgroundColorSpan(red) "42" -> BackgroundColorSpan(green) "43" -> BackgroundColorSpan(yellow) "44" -> BackgroundColorSpan(blue) "45" -> BackgroundColorSpan(magenta) "46" -> BackgroundColorSpan(cyan) "47" -> BackgroundColorSpan(Color.WHITE) else -> null } class AnsiInstruction(code: String) { val spans: List<ParcelableSpan> by lazy { listOfNotNull(getSpan(colorCode), getSpan(decorationCode)) } var colorCode: String? = null private set var decorationCode: String? = null private set init { val colorCodes = code .substringAfter('[') .substringBefore('m') .split(';') when (colorCodes.size) { 3 -> { colorCode = colorCodes[1] decorationCode = colorCodes[2] } 2 -> { colorCode = colorCodes[0] decorationCode = colorCodes[1] } 1 -> { decorationCode = colorCodes[0] } } } } data class AnsiSpan( val instruction: AnsiInstruction, val start: Int, val end: Int) fun String.ansiEscapeToSpannable(): Spannable { val spannable = SpannableString(this.stripAnsiEscapes()) val stack = Stack<AnsiSpan>() val spans = mutableListOf<AnsiSpan>() val matches = ansiRegex.findAll(this) var offset = 0 matches.forEach { result -> val stringCode = result.value val start = result.range.endInclusive val end = result.range.endInclusive + 1 val ansiInstruction = AnsiInstruction(stringCode) offset += stringCode.length when (ansiInstruction.decorationCode) { "0" -> { val topInstruction = stack.pop().copy(end = end - offset) spans.add(topInstruction) } else -> { val instruction = AnsiInstruction(stringCode) val span = AnsiSpan( instruction, start - offset, 0 ) stack.push(span) } } } spans.forEach { ansiSpan -> ansiSpan.instruction.spans.forEach { spannable.setSpan(it, ansiSpan.start, ansiSpan.end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) } } return spannable } <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/artifacts/vm/ArtifactItemViewModel.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.artifacts.vm import android.Manifest import android.app.DownloadManager import android.app.DownloadManager.Query import android.app.DownloadManager.Request import android.content.Context import android.content.Intent import android.database.Cursor import androidx.databinding.BaseObservable import androidx.databinding.Bindable import androidx.databinding.ObservableBoolean import androidx.databinding.ObservableInt import android.graphics.drawable.Drawable import android.net.Uri import android.os.Build import android.os.Environment import androidx.core.app.ShareCompat import android.text.format.Formatter import androidx.navigation.NavController import io.stanwood.bitrise.BuildConfig import io.stanwood.bitrise.PermissionActivity import io.stanwood.bitrise.R import io.stanwood.bitrise.data.model.Artifact import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.util.Snacker import io.stanwood.bitrise.util.extensions.bundleOf import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import timber.log.Timber private enum class DownloadStatus { RUNNING, SUCCESS, FAILED } class ArtifactItemViewModel( private val snacker: Snacker, private val activity: PermissionActivity, private val router: NavController, private val artifact: Artifact, private val mainScope: CoroutineScope ) : BaseObservable() { val icon: Drawable? get() = artifact.artifactType?.getIcon(activity.resources) val title: String get() = artifact.title @get:Bindable("downloadedSize", "isDownloading") val size: String get() = when { isAwaitingDownload -> activity.getString(R.string.download_awaiting_message) isDownloading.get() -> { val progress = (downloadedSize.get() / totalSize.get().toFloat() * 100).toInt() val totalSizeFormatted = Formatter.formatShortFileSize(activity, totalSize.get().toLong()) val downloadedSizeFormatted = Formatter.formatShortFileSize(activity, downloadedSize.get().toLong()) "$downloadedSizeFormatted/$totalSizeFormatted ($progress%)" } else -> Formatter.formatShortFileSize(activity, artifact.fileSizeBytes.toLong()) } val totalSize = ObservableInt(0) val downloadedSize = ObservableInt(0) val isDownloading = ObservableBoolean() @get:Bindable("downloadedSize", "isDownloading") val isAwaitingDownload get() = isDownloading.get() && downloadedSize.get() == 0 val isPublishPageEnabled: Boolean get() = artifact.isPublicPageEnabled private val downloadUri: Uri get() = Uri.parse(artifact.expiringDownloadUrl) private val downloadErrorMessage: String get() = activity.getString(R.string.download_error_message, title) private val downloadCancelledMessage: String get() = activity.getString(R.string.download_cancelled_message, title) private val downloadManager: DownloadManager by lazy { activity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager } private var downloadingJob: Job? = null fun stop() { downloadingJob?.cancel() } fun onClick() { if (isDownloading.get()) { downloadingJob?.cancel() return } try { downloadingJob = mainScope.launch { if (activity.requestPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { download() } } } catch (exception: Exception) { onDownloadStop() Timber.e(exception) bundleOf(Properties.MESSAGE to exception.message).apply { router.navigate(R.id.action_error, this) } } } fun onShareClick() { ShareCompat .IntentBuilder .from(activity) .setType("text/plain") .setChooserTitle(R.string.share_public_page_title) .setText(artifact.publicInstallPageUrl) .startChooser() } private suspend fun download() { isDownloading.set(true) val request = Request(downloadUri).apply { setTitle(title) setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title) } downloadManager.apply { val id = enqueue(request) var status = DownloadStatus.RUNNING try { do { val progressQuery = Query().setFilterById(id) query(progressQuery).let { status = updateDownloadProgress(it) } delay(BuildConfig.DOWNLOAD_STATUS_REFRESH_DELAY) } while (status == DownloadStatus.RUNNING) } catch (e: CancellationException) { Timber.d("Download canceled: $title") snacker.show(downloadCancelledMessage) remove(id) return } finally { onDownloadStop() } if (status == DownloadStatus.SUCCESS) { Timber.d("Download completed: $title") installApk(id) } else { Timber.d("Download failed: $title") snacker.show(downloadErrorMessage) } } } private fun updateDownloadProgress(cursor: Cursor): DownloadStatus { cursor.apply { if (moveToFirst()) { val downloadedColIndex = getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR) val totalColIndex = getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES) val statusColIndex = getColumnIndex(DownloadManager.COLUMN_STATUS) downloadedSize.set(getInt(downloadedColIndex)) totalSize.set(getInt(totalColIndex)) return when(getInt(statusColIndex)) { DownloadManager.STATUS_SUCCESSFUL -> DownloadStatus.SUCCESS DownloadManager.STATUS_FAILED -> DownloadStatus.FAILED else -> DownloadStatus.RUNNING } } } return DownloadStatus.FAILED } private fun getDownloadedApkUri(downloadId: Long): Uri { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { downloadManager.getUriForDownloadedFile(downloadId) } else { val query = DownloadManager.Query() query.setFilterById(downloadId) downloadManager.query(query).use { it.moveToFirst() val path = it.getString(it.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)) Uri.parse(path) } } } private fun installApk(downloadId: Long) { val uri = getDownloadedApkUri(downloadId) Intent(Intent.ACTION_VIEW).apply { setDataAndType(uri, "application/vnd.android.package-archive") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } else { flags = Intent.FLAG_ACTIVITY_NEW_TASK } }.let { activity.startActivity(it) } } private fun onDownloadStop() { isDownloading.set(false) totalSize.set(0) downloadedSize.set(0) } } <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/dashboard/ui/DashboardFragment.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.dashboard.ui import android.os.Bundle import androidx.fragment.app.Fragment import androidx.appcompat.app.AppCompatActivity import android.view.* import io.stanwood.bitrise.R import io.stanwood.bitrise.databinding.FragmentDashboardBinding import io.stanwood.bitrise.ui.dashboard.vm.DashboardViewModel import kotlinx.android.synthetic.main.layout_toolbar.* import org.koin.android.ext.android.inject class DashboardFragment : Fragment() { private val viewModel: DashboardViewModel by inject() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = FragmentDashboardBinding.inflate(inflater, container, false).apply { lifecycle.addObserver(viewModel) vm = viewModel }.root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setHasOptionsMenu(true) (activity as? AppCompatActivity)?.setSupportActionBar(toolbar) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.main, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_logout -> viewModel.onLogout() R.id.menu_settings -> viewModel.onGoToSettings() } return super.onOptionsItemSelected(item) } } <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/builds/vm/BuildItemViewModel.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.builds.vm import android.content.res.Resources import android.graphics.drawable.Drawable import androidx.navigation.NavController import io.stanwood.bitrise.R import io.stanwood.bitrise.data.model.App import io.stanwood.bitrise.data.model.Build import io.stanwood.bitrise.data.model.BuildStatus import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.util.extensions.bundleOf import org.joda.time.Duration import org.joda.time.format.PeriodFormatter import java.text.DateFormat class BuildItemViewModel( private val resources: Resources, private val periodFormatter: PeriodFormatter, private val router: NavController, private val build: Build, private val token: String, private val app: App) { val workflow: String get() = build.triggeredWorkflow val color: Int get() = build.status.getColor(resources) val number: String get() = "#${build.number}" val triggeredAt: String get() { val time = DateFormat.getTimeInstance().format(build.triggeredAt) return resources.getString(R.string.build_triggered_at, time) } val duration: String? get() = build.finishedAt?.let { val triggeredAt = build.triggeredAt.time val finishedAt = build.finishedAt.time val duration = Duration(finishedAt - triggeredAt) val period = duration.toPeriod() return periodFormatter.print(period) } val icon: Drawable get() = if (build.pullRequestTargetBranch != null && build.status == BuildStatus.SUCCESS) { resources.getDrawable(R.drawable.ic_pull_request) } else { build.status.getIcon(resources) } val branch: String get() = if (build.pullRequestTargetBranch == null) { build.branch } else { "${build.branch}>${build.pullRequestTargetBranch}" } val isBuildCompleted: Boolean get() = build.status != BuildStatus.IN_PROGRESS fun onClick() { bundleOf( Properties.TOKEN to token, Properties.BUILD to build, Properties.APP to app) .apply { router.navigate(R.id.action_builds_to_build, this) } } } <|start_filename|>app/src/main/java/io/stanwood/bitrise/util/extensions/PreferenceFragmentCompatExtensions.kt<|end_filename|> package io.stanwood.bitrise.util.extensions import androidx.annotation.StringRes import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat fun PreferenceFragmentCompat.findPreference(@StringRes keyResId: Int): Preference { return findPreference(this.getString(keyResId)) } <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/build/vm/BuildViewModel.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.build.vm import android.content.res.Resources import androidx.databinding.ObservableBoolean import androidx.lifecycle.LifecycleObserver import androidx.navigation.NavController import io.stanwood.bitrise.R import io.stanwood.bitrise.data.model.App import io.stanwood.bitrise.data.model.Build import io.stanwood.bitrise.data.model.BuildParams import io.stanwood.bitrise.data.model.BuildStatus import io.stanwood.bitrise.data.model.NewBuildParams import io.stanwood.bitrise.data.net.BitriseService import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.ui.build.ui.FragmentAdapter import io.stanwood.bitrise.util.Snacker import io.stanwood.bitrise.util.extensions.bundleOf import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import timber.log.Timber class BuildViewModel( private val resources: Resources, private val router: NavController, private val service: BitriseService, val adapter: FragmentAdapter, private val snacker: Snacker, private val token: String, private val app: App, private val build: Build, private val mainScope: CoroutineScope): LifecycleObserver { val title: String get() = "${app.title} #${build.number} (${build.triggeredWorkflow})" val isLoading = ObservableBoolean(false) val isCurrentlyRunning get() = build.status == BuildStatus.IN_PROGRESS fun onRestartBuild() { mainScope.launch { try { isLoading.set(true) restartBuild().let { val message = resources.getString(R.string.new_build_started, it.buildNumber) snacker.show(message) router.navigateUp() } } catch (exception: CancellationException) { /* noop */ } catch (exception: Exception) { Timber.e(exception) bundleOf(Properties.MESSAGE to exception.message).apply { router.navigate(R.id.action_error, this) } } finally { isLoading.set(false) } } } private suspend fun restartBuild() = service .startNewBuild(token, app.slug, NewBuildParams(BuildParams(build.branch, build.triggeredWorkflow))) .await() } <|start_filename|>app/src/main/java/io/stanwood/bitrise/data/model/RepoProvider.kt<|end_filename|> package io.stanwood.bitrise.data.model import com.google.gson.annotations.SerializedName enum class RepoProvider { @SerializedName("github") GITHUB } <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/settings/ui/SettingsFragment.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.settings.ui import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.preference.PreferenceFragmentCompat import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.stanwood.bitrise.R import kotlinx.android.synthetic.main.layout_toolbar.* import io.stanwood.bitrise.util.extensions.* import com.google.android.gms.oss.licenses.OssLicensesMenuActivity import android.content.Intent import android.net.Uri import androidx.navigation.fragment.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupWithNavController import io.stanwood.bitrise.BuildConfig class SettingsFragment: PreferenceFragmentCompat() { override fun onCreatePreferences(bundle: Bundle?, s: String?) { addPreferencesFromResource(R.xml.settings) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val currentActivity = activity if (currentActivity is AppCompatActivity) { toolbar.let { //currentActivity.setSupportActionBar(it) } } return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) findNavController().let { toolbar.setupWithNavController(it, AppBarConfiguration(it.graph)) } findPreference(R.string.pref_key_contribute).setOnPreferenceClickListener { onContributeClick() true } findPreference(R.string.pref_key_licenses).setOnPreferenceClickListener { onLicensesClick() true } } private fun onContributeClick() { Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(BuildConfig.REPO_URL) startActivity(this) } } private fun onLicensesClick() { startActivity(Intent(context, OssLicensesMenuActivity::class.java)) } } <|start_filename|>app/src/main/java/io/stanwood/bitrise/di/ApplicationModule.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.di import android.preference.PreferenceManager import androidx.navigation.Navigation import com.google.gson.GsonBuilder import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import io.stanwood.bitrise.BuildConfig import io.stanwood.bitrise.R import io.stanwood.bitrise.data.net.BitriseService import io.stanwood.bitrise.util.Snacker import io.stanwood.bitrise.util.gson.GsonDateFormatAdapter import kotlinx.coroutines.MainScope import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.android.ext.koin.androidApplication import org.koin.dsl.module.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.Date val applicationModule = module { /** * Gson */ single { GsonBuilder() .registerTypeAdapter(Date::class.java, GsonDateFormatAdapter(BuildConfig.API_DATE_TIME_FORMAT)) .create() } /** * OkHttpClient */ single { val interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.BODY OkHttpClient .Builder() .addInterceptor(interceptor) .build() } /** * Retrofit */ single { Retrofit .Builder() .baseUrl(BuildConfig.BITRISE_API_BASE_URL) .client(get()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .addConverterFactory(GsonConverterFactory.create(get())) .build() } /** * BitriseService */ single { get<Retrofit>().create(BitriseService::class.java) } /** * Cicerone */ single { Navigation.findNavController(getProperty(Properties.ACTIVITY), R.id.root) } /** * SharedPreferences */ single { PreferenceManager.getDefaultSharedPreferences(androidApplication()) } /** * Snacker */ single { Snacker( activity = getProperty(Properties.ACTIVITY), layoutResId = R.id.root ) } // Coroutine scope which operates on the main thread single("main") { MainScope() } } <|start_filename|>app/src/main/java/io/stanwood/bitrise/MainActivity.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise import android.content.SharedPreferences import android.os.Bundle import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.di.applicationModule import io.stanwood.bitrise.ui.artifacts.di.artifactsModule import io.stanwood.bitrise.ui.build.di.buildModule import io.stanwood.bitrise.ui.builds.di.buildsModule import io.stanwood.bitrise.ui.dashboard.di.dashboardModule import io.stanwood.bitrise.ui.error.di.errorModule import io.stanwood.bitrise.ui.login.di.loginModule import io.stanwood.bitrise.ui.logs.di.logsModule import io.stanwood.bitrise.ui.newbuild.di.newBuildModule import org.koin.android.ext.android.inject import org.koin.android.ext.android.setProperty import org.koin.android.ext.koin.with import org.koin.error.AlreadyStartedException import org.koin.standalone.StandAloneContext import timber.log.Timber class MainActivity: PermissionActivity() { private val sharedPreferences: SharedPreferences by inject() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } startKoin() setProperty(Properties.ACTIVITY, this) setProperty(Properties.TOKEN, sharedPreferences.getString(Properties.TOKEN, BuildConfig.BITRISE_API_TOKEN) ?: "") setContentView(R.layout.activity_main) } override fun onDestroy() { super.onDestroy() StandAloneContext.closeKoin() } private fun startKoin() { try { StandAloneContext.startKoin(listOf( applicationModule, errorModule, loginModule, dashboardModule, buildsModule, buildModule, logsModule, artifactsModule, newBuildModule)) with application } catch (exception: AlreadyStartedException) { // Can be safely ignored Timber.e(exception) } } } <|start_filename|>app/src/main/java/io/stanwood/bitrise/data/model/App.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.data.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class App( @SerializedName("is_disabled") val isDisabled: Boolean, //false @SerializedName("project_type") val projectType: Platform?, //xamarin @SerializedName("provider") val provider: RepoProvider?, //github @SerializedName("repo_owner") val repoOwner: String, //bitrise-samples @SerializedName("repo_slug") val repoSlug: String, //sample-apps-xamarin-cross-platform @SerializedName("repo_url") val repoUrl: String, //https://github.com/bitrise-samples/sample-apps-xamarin-cross-platform.git @SerializedName("slug") val slug: String, //f46e89061e967f27 @SerializedName("title") val title: String //sample-apps-xamarin-cross-platform ) : Parcelable <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/dashboard/vm/DashboardViewModel.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.dashboard.vm import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import android.content.SharedPreferences import android.content.res.Resources import androidx.databinding.ObservableArrayList import androidx.databinding.ObservableBoolean import androidx.navigation.NavController import io.stanwood.bitrise.R import io.stanwood.bitrise.data.model.App import io.stanwood.bitrise.data.net.BitriseService import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.util.extensions.bundleOf import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import timber.log.Timber class DashboardViewModel(private val router: NavController, private val service: BitriseService, private val token: String, private val sharedPreferences: SharedPreferences, private val resources: Resources, private val mainScope: CoroutineScope): LifecycleObserver { val isLoading = ObservableBoolean(false) val items = ObservableArrayList<AppItemViewModel>() private var deferred: Deferred<Any>? = null private var nextCursor: String? = null private val shouldLoadMoreItems: Boolean get() = !isLoading.get() && nextCursor != null private val favoriteAppsSlugs: Set<String>? get() = sharedPreferences.getStringSet(Properties.FAVORITE_APPS, null) @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun start() { onRefresh() } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun stop() { deferred?.cancel() items.forEach { viewModel -> viewModel.stop() } } fun onRefresh() { deferred?.cancel() items.clear() nextCursor = null loadMoreItems() } @Suppress("UNUSED_PARAMETER") fun onEndOfListReached(itemCount: Int) { if (shouldLoadMoreItems) { loadMoreItems() } } fun onLogout() { sharedPreferences .edit() .remove(Properties.TOKEN) .apply() router.navigate(R.id.action_logout) } fun onGoToSettings() { router.navigate(R.id.action_dashboard_to_settings) } private fun loadMoreItems() { deferred = mainScope.async { try { isLoading.set(true) fetchAllApps() .forEach { viewModel -> viewModel.start() items.add(viewModel) } } catch (exception: CancellationException) { /* noop */ } catch (exception: Exception) { Timber.e(exception) bundleOf(Properties.MESSAGE to exception.message).apply { router.navigate(R.id.action_error, this) } } finally { isLoading.set(false) } } } private suspend fun fetchFavoriteApps(): List<App> = favoriteAppsSlugs ?.map { service .getApp(token, it) .await() .data } ?: emptyList() private suspend fun fetchNonFavoriteApps(): List<App> = service .getApps(token, nextCursor) .await() .apply { nextCursor = paging.nextCursor } .data .filter { !(favoriteAppsSlugs?.contains(it.slug) ?: false) } private suspend fun fetchAllApps() = listOf(if(items.isEmpty()) fetchFavoriteApps() else emptyList(), fetchNonFavoriteApps()) .flatten() .map { app -> AppItemViewModel(service, token, resources, router, sharedPreferences, app, mainScope) } } <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/newbuild/vm/NewBuildViewModel.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.newbuild.vm import android.content.SharedPreferences import android.content.res.Resources import androidx.databinding.BaseObservable import androidx.databinding.Bindable import androidx.databinding.ObservableBoolean import androidx.navigation.NavController import com.google.gson.Gson import com.google.gson.JsonSyntaxException import io.stanwood.bitrise.R import io.stanwood.bitrise.data.model.App import io.stanwood.bitrise.data.model.BuildParams import io.stanwood.bitrise.data.model.NewBuildParams import io.stanwood.bitrise.data.model.NewBuildResponse import io.stanwood.bitrise.data.net.BitriseService import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.util.Snacker import io.stanwood.bitrise.util.extensions.bundleOf import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import retrofit2.HttpException import timber.log.Timber class NewBuildViewModel( private val gson: Gson, private val resources: Resources, private val router: NavController, private val service: BitriseService, private val sharedPreferences: SharedPreferences, private val snacker: Snacker, private val token: String, private val app: App, private val mainScope: CoroutineScope): BaseObservable() { val title: String get() = app.title @get:Bindable var branch: String get() = sharedPreferences.getString(Properties.BRANCH, "") ?: "" set(value) = sharedPreferences.edit().putString(Properties.BRANCH, value).apply() @get:Bindable var workflow: String get() = sharedPreferences.getString(Properties.WORKFLOW, "") ?: "" set(value) = sharedPreferences.edit().putString(Properties.WORKFLOW, value).apply() val isLoading = ObservableBoolean(false) fun onStartNewBuild() { mainScope.launch { try { isLoading.set(true) startNewBuild().let { val message = resources.getString(R.string.new_build_started, it.buildNumber) snacker.show(message) router.navigateUp() } } catch (exception: HttpException) { onError(exception) } finally { isLoading.set(false) } } } fun onError(httpException: HttpException) { val errorBody = httpException.response().errorBody()?.string() val response = try { gson .fromJson(errorBody, NewBuildResponse::class.java) .message } catch (jsonException: JsonSyntaxException) { httpException.message() } Timber.e(response) bundleOf(Properties.MESSAGE to response).apply { router.navigate(R.id.action_error, this) } } private suspend fun startNewBuild() = service .startNewBuild(token, app.slug, NewBuildParams(BuildParams(branch, workflow))) .await() } <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/builds/vm/BuildsViewModel.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.builds.vm import android.content.res.Resources import androidx.databinding.ObservableArrayList import androidx.databinding.ObservableBoolean import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import androidx.navigation.NavController import io.stanwood.bitrise.R import io.stanwood.bitrise.data.model.App import io.stanwood.bitrise.data.model.RepoProvider import io.stanwood.bitrise.data.net.BitriseService import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.util.extensions.bundleOf import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import org.joda.time.format.PeriodFormatter import timber.log.Timber class BuildsViewModel(private val router: NavController, private val service: BitriseService, private val token: String, private val resources: Resources, private val periodFormatter: PeriodFormatter, private val app: App, private val mainScope: CoroutineScope ) : LifecycleObserver { val isLoading = ObservableBoolean(false) val items = ObservableArrayList<BuildItemViewModel>() val title: String get() = app.title val isProvidedByGithub: Boolean get() = app.provider == RepoProvider.GITHUB val repoUrl: String? get() = when(app.provider) { RepoProvider.GITHUB -> "https://github.com/${app.repoOwner}/${app.repoSlug}" else -> null } private var deferred: Deferred<Any>? = null private var nextCursor: String? = null private val shouldLoadMoreItems: Boolean get() = !isLoading.get() && nextCursor != null @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreate() { onRefresh() } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun onResume() { onRefresh() } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { deferred?.cancel() } fun onRefresh() { deferred?.cancel() items.clear() nextCursor = null loadMoreItems() } @Suppress("UNUSED_PARAMETER") fun onEndOfListReached(itemCount: Int) { if (shouldLoadMoreItems) { loadMoreItems() } } fun onStartNewBuild() = bundleOf( Properties.TOKEN to token, Properties.APP to app) .let { router.navigate(R.id.screen_new_build, it) } private fun loadMoreItems() { deferred = mainScope.async { try { isLoading.set(true) fetchItems() .forEach { viewModel -> items.add(viewModel) } } catch (exception: CancellationException) { /* noop */ } catch (exception: Exception) { Timber.e(exception) bundleOf(Properties.MESSAGE to null).apply { router.navigate(R.id.action_error, this) } } finally { isLoading.set(false) } } } private suspend fun fetchItems() = service .getBuilds(token, app.slug, nextCursor) .await() .apply { nextCursor = paging.nextCursor } .data .map { build -> BuildItemViewModel(resources, periodFormatter, router, build, token, app) } } <|start_filename|>app/src/main/java/io/stanwood/bitrise/util/databinding/ViewModelAdapter.java<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.util.databinding; import android.content.Context; import androidx.databinding.DataBindingUtil; import androidx.databinding.ObservableList; import androidx.databinding.ViewDataBinding; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import java.util.List; import io.stanwood.bitrise.BR; public class ViewModelAdapter extends RecyclerView.Adapter<ViewModelAdapter.ViewHolder> { private class ListChangedCallback extends ObservableList.OnListChangedCallback<ObservableList<Object>> { @Override public void onChanged(ObservableList<Object> objects) { notifyDataSetChanged(); } @Override public void onItemRangeChanged(ObservableList<Object> objects, int positionStart, int itemCount) { notifyItemRangeChanged(positionStart, itemCount); } @Override public void onItemRangeInserted(ObservableList<Object> objects, int positionStart, int itemCount) { notifyItemRangeInserted(positionStart, itemCount); } @Override public void onItemRangeMoved(ObservableList<Object> objects, int fromPosition, int toPosition, int itemCount) { notifyDataSetChanged(); } @Override public void onItemRangeRemoved(ObservableList<Object> objects, int positionStart, int itemCount) { notifyItemRangeRemoved(positionStart, itemCount); } } class ViewHolder extends RecyclerView.ViewHolder { private ViewDataBinding binding; public ViewHolder(ViewDataBinding binding) { super(binding.getRoot()); this.binding = binding; } public void bind(Object item) { binding.setVariable(variableId, item); binding.notifyPropertyChanged(BR._all); binding.executePendingBindings(); binding.invalidateAll(); } } @NonNull private List<Object> items; @LayoutRes private int layoutResId; private int variableId; public ViewModelAdapter(@NonNull List<Object> items, @LayoutRes int layoutResId, int variableId) { this.items = items; this.layoutResId = layoutResId; this.variableId = variableId; if (items instanceof ObservableList) { ObservableList observableList = (ObservableList) items; observableList.addOnListChangedCallback(new ListChangedCallback()); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); ViewDataBinding binding = DataBindingUtil.inflate(inflater, layoutResId, parent, false); return new ViewHolder(binding); } @Override public void onBindViewHolder(ViewModelAdapter.ViewHolder holder, int position) { Object item = items.get(position); holder.bind(item); } @Override public int getItemCount() { return items == null ? 0 : items.size(); } } <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/dashboard/vm/AppItemViewModel.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.dashboard.vm import android.content.SharedPreferences import android.content.res.Resources import androidx.databinding.BaseObservable import androidx.databinding.Bindable import android.graphics.drawable.Drawable import androidx.navigation.NavController import io.stanwood.bitrise.BR import io.stanwood.bitrise.R import io.stanwood.bitrise.data.model.App import io.stanwood.bitrise.data.model.Build import io.stanwood.bitrise.data.model.BuildStatus import io.stanwood.bitrise.data.net.BitriseService import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.util.extensions.bundleOf import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import org.ocpsoft.prettytime.PrettyTime import timber.log.Timber class AppItemViewModel( private val service: BitriseService, private val token: String, private val resources: Resources, private val router: NavController, private val sharedPreferences: SharedPreferences, private val app: App, private val mainScope: CoroutineScope ) : BaseObservable() { val title: String get() = app.title val repoOwner: String get() = "${app.repoOwner}/" val icon: Drawable? get() = app.projectType?.getIcon(resources) @get:Bindable val lastBuildTime: String? get() { return if (lastBuild?.status == BuildStatus.IN_PROGRESS) { lastBuild?.status?.getTitle(resources) } else { lastBuild?.finishedAt?.let { PrettyTime().format(it) } } } @get:Bindable val lastBuildWorkflow: String? get() = lastBuild?.triggeredWorkflow @get:Bindable("lastBuildTime") val buildStatusColor: Int get() = lastBuild?.status?.getColor(resources) ?: 0 @get:Bindable("lastBuildTime") val buildStatusIcon: Drawable? get() = lastBuild?.status?.getIcon(resources) @get:Bindable var isFavorite: Boolean get() = sharedPreferences .getStringSet(Properties.FAVORITE_APPS, null) ?.contains(app.slug) ?: false set(value) { val favoriteAppsSlugs = sharedPreferences .getStringSet(Properties.FAVORITE_APPS, null) /** * Please note, that we cannot modify a set returned from SharedPreferences::getStringSet, thus we * have to make a copy. * See <a href="https://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet(java.lang.String,%20java.util.Set<java.lang.String>)">SharedPreferences::getStringSet documentation</a> */ ?.toMutableSet() ?: mutableSetOf() if (value == favoriteAppsSlugs.contains(app.slug)) { return } if (value) { favoriteAppsSlugs.add(app.slug) } else { favoriteAppsSlugs.remove(app.slug) } sharedPreferences .edit() .putStringSet(Properties.FAVORITE_APPS, favoriteAppsSlugs) .apply() } private var deferred: Deferred<Any?>? = null private var lastBuild: Build? = null fun start() { deferred = mainScope.async { try { lastBuild = fetchLastBuild() notifyPropertyChanged(BR.lastBuildTime) notifyPropertyChanged(BR.lastBuildWorkflow) } catch (exception: Exception) { Timber.e(exception) bundleOf(Properties.MESSAGE to exception.message).apply { router.navigate(R.id.action_error, this) } } } } fun stop() { deferred?.cancel() } fun onClick() { bundleOf( Properties.APP to app, Properties.TOKEN to token) .apply { router.navigate(R.id.action_dashboard_to_builds, this) } } private suspend fun fetchLastBuild() = service .getBuilds(token, app.slug, limit = 1) .await() .data .firstOrNull() } <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/artifacts/ui/ArtifactsFragment.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.artifacts.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.ViewGroup import io.stanwood.bitrise.data.model.App import io.stanwood.bitrise.data.model.Build import io.stanwood.bitrise.databinding.FragmentArtifactsBinding import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.ui.artifacts.vm.ArtifactsViewModel import org.koin.android.ext.android.inject import org.koin.core.parameter.parametersOf class ArtifactsFragment : Fragment() { companion object { fun newInstance(token: String, build: Build, app: App) = ArtifactsFragment().apply { arguments = Bundle().apply { putString(Properties.TOKEN, token) putParcelable(Properties.BUILD, build) putParcelable(Properties.APP, app) } } } private val token: String get() = arguments?.getString(Properties.TOKEN) as String private val app: App get() = arguments?.getParcelable(Properties.APP) as App private val build: Build get() = arguments?.getParcelable(Properties.BUILD) as Build private val viewModel: ArtifactsViewModel by inject(parameters = { parametersOf( token, app, build ) }) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = FragmentArtifactsBinding.inflate(inflater, container, false).apply { lifecycle.addObserver(viewModel) vm = viewModel }.root } <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/artifacts/vm/ArtifactsViewModel.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.artifacts.vm import androidx.databinding.BaseObservable import androidx.databinding.ObservableArrayList import androidx.databinding.ObservableBoolean import androidx.databinding.ObservableField import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import androidx.navigation.NavController import io.stanwood.bitrise.PermissionActivity import io.stanwood.bitrise.R import io.stanwood.bitrise.data.model.App import io.stanwood.bitrise.data.model.Artifact import io.stanwood.bitrise.data.model.Build import io.stanwood.bitrise.data.net.BitriseService import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.util.Snacker import io.stanwood.bitrise.util.extensions.bundleOf import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import timber.log.Timber class ArtifactsViewModel( private val snacker: Snacker, private val router: NavController, private val service: BitriseService, private val token: String, private val activity: PermissionActivity, private val app: App, private val build: Build, private val mainScope: CoroutineScope ) : LifecycleObserver, BaseObservable() { val isLoading = ObservableBoolean(false) var log = ObservableField<String>() val items = ObservableArrayList<ArtifactItemViewModel>() private var deferred: Deferred<Any>? = null private var nextCursor: String? = null private val shouldLoadMoreItems: Boolean get() = !isLoading.get() && nextCursor != null @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun start() { onRefresh() } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun stop() { deferred?.cancel() items.forEach { viewModel -> viewModel.stop() } } fun onRefresh() { deferred?.cancel() items.clear() nextCursor = null loadMoreItems() } @Suppress("UNUSED_PARAMETER") fun onEndOfListReached(itemCount: Int) { if (shouldLoadMoreItems) { loadMoreItems() } } private fun loadMoreItems() { deferred = mainScope.async { try { isLoading.set(true) fetchItems() .forEach { viewModel -> items.add(viewModel) } } catch (exception: CancellationException) { /* noop */ } catch (exception: Exception) { Timber.e(exception) bundleOf(Properties.MESSAGE to exception.message).apply { router.navigate(R.id.action_error, this) } } finally { isLoading.set(false) } } } private suspend fun fetchItems() = service .getBuildArtifacts(token, app.slug, build.slug, nextCursor) .await() .apply { nextCursor = paging.nextCursor } .data .map { artifact -> fetchArtifact(artifact) } .map { artifact -> ArtifactItemViewModel(snacker, activity, router, artifact, mainScope) } private suspend fun fetchArtifact(artifact: Artifact) = service .getBuildArtifact(token, app.slug, build.slug, artifact.slug) .await() .data } <|start_filename|>app/src/main/java/io/stanwood/bitrise/data/model/Build.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.data.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize import java.util.* @Parcelize data class Build( @SerializedName("abort_reason") val abortReason: String?, @SerializedName("branch") val branch: String, //master @SerializedName("build_number") val number: Int, //20 @SerializedName("commit_hash") val commitHash: String?, //null @SerializedName("commit_message") val commitMessage: String, //generate an APK @SerializedName("commit_view_url") val commitViewUrl: String?, @SerializedName("environment_prepare_finished_at") val environmentPrepareFinishedAt: Date?, //2017-11-08T13:24:33Z @SerializedName("finished_at") val finishedAt: Date?, //2017-11-08T13:26:54Z @SerializedName("is_on_hold") val isOnHold: Boolean, //false @SerializedName("original_build_params") val originalBuildParams: OriginalBuildParams, @SerializedName("pull_request_id") val pullRequestId: Int, //0 @SerializedName("pull_request_target_branch") val pullRequestTargetBranch: String?, @SerializedName("pull_request_view_url") val pullRequestViewUrl: String?, @SerializedName("slug") val slug: String, //ddf4134555e833d8 @SerializedName("stack_config_type") val stackConfigType: String, //standard1 @SerializedName("stack_identifier") val stackIdentifier: String, //linux-docker-android @SerializedName("started_on_worker_at") val startedOnWorkerAt: String, //2017-11-08T13:24:33Z @SerializedName("status") val status: BuildStatus, @SerializedName("status_text") val statusText: String, //success @SerializedName("tag") val tag: String?, @SerializedName("triggered_at") val triggeredAt: Date, //2017-11-08T13:24:33Z @SerializedName("triggered_by") val triggeredBy: String, //manual-api-demo @SerializedName("triggered_workflow") val triggeredWorkflow: String //gen-apk ): Parcelable <|start_filename|>app/src/main/java/io/stanwood/bitrise/data/net/BitriseService.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.data.net import io.stanwood.bitrise.BuildConfig import io.stanwood.bitrise.data.model.* import kotlinx.coroutines.Deferred import okhttp3.ResponseBody import retrofit2.http.* interface BitriseService { @GET("v0.1/me") fun login(@Header("Authorization") token: String): Deferred<Response<Me>> @GET("v0.1/apps/{APP-SLUG}") fun getApp( @Header("Authorization") token: String, @Path("APP-SLUG") appSlug: String): Deferred<Response<App>> @GET("v0.1/me/apps") fun getApps( @Header("Authorization") token: String, @Query("next") cursor: String? = null, @Query("limit") limit: Int = BuildConfig.DEFAULT_PAGE_SIZE, @Query("sort_by") sortBy: SortBy = SortBy.last_build_at): Deferred<Response<List<App>>> @GET("v0.1/apps/{APP-SLUG}/builds") fun getBuilds( @Header("Authorization") token: String, @Path("APP-SLUG") appSlug: String, @Query("next") cursor: String? = null, @Query("limit") limit: Int = BuildConfig.DEFAULT_PAGE_SIZE): Deferred<Response<List<Build>>> @GET("v0.1/apps/{APP-SLUG}/builds/{BUILD-SLUG}/log") fun getBuildLog( @Header("Authorization") token: String, @Path("APP-SLUG") appSlug: String, @Path("BUILD-SLUG") buildLog: String, @Query("next") cursor: String? = null, @Query("limit") limit: Int? = null): Deferred<Log> @GET fun downloadFile( @Url url: String ): Deferred<ResponseBody> @GET("v0.1/apps/{APP-SLUG}/builds/{BUILD-SLUG}/artifacts") fun getBuildArtifacts( @Header("Authorization") token: String, @Path("APP-SLUG") appSlug: String, @Path("BUILD-SLUG") buildSlug: String, @Query("next") cursor: String? = null, @Query("limit") limit: Int? = null): Deferred<Response<List<Artifact>>> @GET("v0.1/apps/{APP-SLUG}/builds/{BUILD-SLUG}/artifacts/{ARTIFACT-SLUG}") fun getBuildArtifact( @Header("Authorization") token: String, @Path("APP-SLUG") appSlug: String, @Path("BUILD-SLUG") buildSlug: String, @Path("ARTIFACT-SLUG") artifactSlug: String): Deferred<Response<Artifact>> @POST("/v0.1/apps/{APP-SLUG}/builds") fun startNewBuild( @Header("Authorization") token: String, @Path("APP-SLUG") appSlug: String, @Body params: NewBuildParams): Deferred<NewBuildResponse> } <|start_filename|>app/src/main/java/io/stanwood/bitrise/ui/login/vm/LoginViewModel.kt<|end_filename|> /* * Copyright (c) 2018 <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 io.stanwood.bitrise.ui.login.vm import android.content.SharedPreferences import androidx.databinding.Bindable import androidx.databinding.ObservableBoolean import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import androidx.navigation.NavController import io.stanwood.bitrise.BuildConfig import io.stanwood.bitrise.R import io.stanwood.bitrise.data.net.BitriseService import io.stanwood.bitrise.di.Properties import io.stanwood.bitrise.util.databinding.ObservableViewModel import io.stanwood.bitrise.util.extensions.bundleOf import io.stanwood.bitrise.util.extensions.setProperty import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import retrofit2.HttpException import timber.log.Timber import java.net.HttpURLConnection class LoginViewModel( private val service: BitriseService, private val router: NavController, private val sharedPreferences: SharedPreferences, private val mainScope: CoroutineScope ) : LifecycleObserver, ObservableViewModel() { val isError = ObservableBoolean() val isLoading = ObservableBoolean() @get:Bindable var token: String? set(value) { if (value?.isBlank() == true) { /** * Sanity check. We don't want to store an empty or null token. */ return } setProperty(Properties.TOKEN, value) sharedPreferences .edit() .putString(Properties.TOKEN, value) .apply() } get() = sharedPreferences.getString(Properties.TOKEN, BuildConfig.BITRISE_API_TOKEN) private var deferred: Deferred<Any>? = null @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun start() { token?.let { onTokenEntered(it) } } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun stop() { deferred?.cancel() } fun onTokenEntered(newToken: String) { deferred = mainScope.async { tryLogin(newToken) } } private suspend fun tryLogin(newToken: String?) { newToken?.let { try { isLoading.set(true) service .login(it) .await() token = it bundleOf(Properties.TOKEN to token).apply { router.navigate(R.id.action_login_to_dashboard, this) } } catch (exception: Exception) { if (exception is HttpException && exception.code() == HttpURLConnection.HTTP_UNAUTHORIZED) { isError.set(true) } bundleOf(Properties.MESSAGE to exception.message).apply { router.navigate(R.id.action_error, this) } Timber.e(exception) } finally { isLoading.set(false) } } } }
Marchuck/Bitrise_Android
<|start_filename|>RepositoryHelpers/Mapping/MappingHelper.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Dapper.FluentMap; using Dapper.FluentMap.Dommel.Mapping; using Dapper.FluentMap.Mapping; using RepositoryHelpers.Utils; namespace RepositoryHelpers.Mapping { internal static class MappingHelper { public static List<string> GetPrimaryKey(Type type) { var properties = new List<string>(); foreach (var property in type.GetProperties()) { var isKey = property.CustomAttributes.ToList().Any(x => x.GetAttributeName() == Attributes.PrimaryKey); if (!isKey) { var propertyMap = GetFluentPropertyMap(type, property); if (propertyMap != null) isKey = propertyMap.Key; } if (isKey) properties.Add(property.Name); } return properties; } public static string GetIdentityColumn(Type type) { foreach (var property in type.GetProperties()) { var isIdentity = property.CustomAttributes.ToList().Any(x => x.GetAttributeName() == Attributes.Identity); // if is not attribute identity, search Fluent if (!isIdentity) { var propertyMap = GetFluentPropertyMap(type, property); if (propertyMap != null) isIdentity = propertyMap.Identity; } if (isIdentity) return property.Name; } return null; } public static string GetTableName(Type type,DataBaseType dataBaseType) { var table = type.GetCustomAttributes(typeof(Table), true).FirstOrDefault() as Table; var tableNameFluent = GetFluentEntityMap(type)?.TableName; var tableName = string.Empty; if (table != null) tableName = table.TableName; else if (!string.IsNullOrWhiteSpace(tableNameFluent)) tableName = tableNameFluent; else tableName = type.Name; switch (dataBaseType) { case DataBaseType.SqlServer: return $"[{tableName}]"; case DataBaseType.PostgreSQL: return tableName.ToLower(); case DataBaseType.Oracle: default: return tableName; } } public static bool IsIgnored(Type entityType, PropertyInfo property) { var customAttributeData = property.CustomAttributes.ToList(); if (customAttributeData.Any()) { if (customAttributeData.Any(x => x.GetAttributeName() == Attributes.DapperIgnore || x.GetAttributeName() == Attributes.Identity)) return true; } else { var propertyMap = GetFluentPropertyMap(entityType, property); if (propertyMap != null && (propertyMap.Ignored || propertyMap.Identity)) return true; } return false; } private static IDommelEntityMap GetFluentEntityMap(Type entityType) => (IDommelEntityMap)FluentMapper.EntityMaps.FirstOrDefault(map => map.Key == entityType).Value; private static DommelPropertyMap GetFluentPropertyMap(Type entityType, PropertyInfo property) { var entityMap = GetFluentEntityMap(entityType); if (entityMap != null) { var propertyMap = entityMap.PropertyMaps.FirstOrDefault(p => p.PropertyInfo.Name.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)); if (propertyMap != null) { if (propertyMap is DommelPropertyMap) return (DommelPropertyMap)propertyMap; else throw new CustomRepositoryException($"{entityType.Name} class mapping must inherit from DommelEntityMap base class."); } } return null; } } } <|start_filename|>RepositoryHelpers/Mapping/Attributes/Table.cs<|end_filename|> using System; namespace RepositoryHelpers { [AttributeUsage(AttributeTargets.Class)] public sealed class Table : Attribute { public string TableName { get; private set; } public Table(string tableName) => TableName = tableName; } } <|start_filename|>RepositoryHelpers/Mapping/Mapper.cs<|end_filename|> using System; using Dapper.FluentMap; using Dapper.FluentMap.Configuration; namespace RepositoryHelpers.Mapping { public static class Mapper { public static void Initialize(Action<FluentMapConfiguration> configure) => FluentMapper.Initialize(configure); public static bool IsEmptyMapping() => FluentMapper.EntityMaps.IsEmpty; } } <|start_filename|>RepositoryHelpers/Mapping/Attributes/DapperIgnore.cs<|end_filename|> using System; namespace RepositoryHelpers { [AttributeUsage(AttributeTargets.Property)] public sealed class DapperIgnore : Attribute { } } <|start_filename|>RepositoryHelpers/DataBase/Connection.cs<|end_filename|> using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.OracleClient; using System.Data.SqlClient; using Npgsql; using RepositoryHelpers.Utils; namespace RepositoryHelpers.DataBase { public sealed class Connection { public string ConnectionString { get; set; } public DataBaseType Database { get; set; } public IsolationLevel IsolationLevel { get; set; } public Connection() { IsolationLevel = IsolationLevel.ReadCommitted; } internal DbConnection DataBaseConnection { get { switch (Database) { case DataBaseType.SqlServer: return new SqlConnection(this.ConnectionString); case DataBaseType.Oracle: return new OracleConnection(this.ConnectionString); case DataBaseType.PostgreSQL: return new NpgsqlConnection(this.ConnectionString); default: return null; } } } internal DbCommand GetCommand() { switch (Database) { case DataBaseType.SqlServer: return new SqlCommand(); case DataBaseType.Oracle: return new OracleCommand(); case DataBaseType.PostgreSQL: return new NpgsqlCommand(); default: return null; } } internal DbCommand GetCommand(string sql, DbConnection dbConnection) { switch (Database) { case DataBaseType.SqlServer: return new SqlCommand(sql, (SqlConnection)dbConnection); case DataBaseType.Oracle: return new OracleCommand(sql, (OracleConnection)dbConnection); case DataBaseType.PostgreSQL: return new NpgsqlCommand(sql, (NpgsqlConnection)dbConnection); default: return null; } } internal DbDataAdapter GetDataAdapter() { switch (Database) { case DataBaseType.SqlServer: return new SqlDataAdapter(); case DataBaseType.Oracle: return new OracleDataAdapter(); case DataBaseType.PostgreSQL: return new NpgsqlDataAdapter(); default: return null; } } internal object GetParameter(KeyValuePair<string, object> parameter) { switch (Database) { case DataBaseType.SqlServer: return new SqlParameter($"@{parameter.Key}", parameter.Value); case DataBaseType.Oracle: return new OracleParameter($"<EMAIL>}", parameter.Value); case DataBaseType.PostgreSQL: return new NpgsqlParameter($"@{parameter.Key}", parameter.Value); default: return null; } } } } <|start_filename|>RepositoryHelpers/Mapping/Attributes/Attributes.cs<|end_filename|> using System; namespace RepositoryHelpers { internal struct Attributes : IEquatable<Attributes> { public const string DapperIgnore = "REPOSITORYHELPERS.DAPPERIGNORE"; public const string PrimaryKey = "REPOSITORYHELPERS.PRIMARYKEY"; // public const string IdentityIgnore = "REPOSITORYHELPERS.IDENTITYIGNORE"; public const string Identity = "REPOSITORYHELPERS.IDENTITY"; public bool Equals(Attributes other) => base.Equals(other); } } <|start_filename|>RepositoryHelpers/Mapping/Attributes/Identity.cs<|end_filename|> using System; namespace RepositoryHelpers { [AttributeUsage(AttributeTargets.Property)] public sealed class Identity : Attribute { } } <|start_filename|>RepositoryHelpers/DataBaseRepository/LiteDbRepository.cs<|end_filename|> using System.Collections.Generic; using System.Linq; using LiteDB; using RepositoryHelpers.DataBaseRepository.Base; namespace RepositoryHelpers.DataBaseRepository { public sealed class LiteDbRepository<T> where T : ILiteDbRepository { private readonly LiteRepository _liteRepository; public LiteDbRepository(string dataBaseName) { _liteRepository = new LiteRepository(dataBaseName); } public IEnumerable<T> Get() { return _liteRepository.Query<T>().ToEnumerable(); } public void Insert(T item) { _liteRepository.Insert<T>(item); } public void Update(T item) { _liteRepository.Update<T>(item); } public T GetById(int id) { return _liteRepository.Query<T>().Where(x => x.Id == id).ToEnumerable().FirstOrDefault(); } } } <|start_filename|>RepositoryHelpers/DataBaseRepository/Base/ICustomRepository.cs<|end_filename|> using System; using System.Collections.Generic; using System.Data; using System.Threading.Tasks; namespace RepositoryHelpers.DataBaseRepository.Base { internal interface ICustomRepository<T> { string GetConnectionString(); IEnumerable<T> Get(CustomTransaction customTransaction, int? commandTimeout); IEnumerable<T> Get(CustomTransaction customTransaction); IEnumerable<T> Get(); IEnumerable<T> Get(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); IEnumerable<T> Get(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction); IEnumerable<T> Get(string sql, Dictionary<string, object> parameters); IEnumerable<T> Get(string sql); Task<IEnumerable<T>> GetAsync(CustomTransaction customTransaction, int? commandTimeout); Task<IEnumerable<T>> GetAsync(CustomTransaction customTransaction); Task<IEnumerable<T>> GetAsync(); Task<IEnumerable<T>> GetAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); Task<IEnumerable<T>> GetAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction); Task<IEnumerable<T>> GetAsync(string sql, Dictionary<string, object> parameters); Task<IEnumerable<T>> GetAsync(string sql); Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction); Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters); Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map); IEnumerable<TReturn> Get<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); IEnumerable<TReturn> Get<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction); IEnumerable<TReturn> Get<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters); IEnumerable<TReturn> Get<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map); Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction); Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters); Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map); IEnumerable<TReturn> Get<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); IEnumerable<TReturn> Get<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction); IEnumerable<TReturn> Get<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters); IEnumerable<TReturn> Get<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map); Task<IEnumerable<TReturn>> GetAsync<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); Task<IEnumerable<TReturn>> GetAsync<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction); Task<IEnumerable<TReturn>> GetAsync<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters); Task<IEnumerable<TReturn>> GetAsync<TReturn>(string sql, Type[] types, Func<object[], TReturn> map); IEnumerable<TReturn> Get<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); IEnumerable<TReturn> Get<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction); IEnumerable<TReturn> Get<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters); IEnumerable<TReturn> Get<TReturn>(string sql, Type[] types, Func<object[], TReturn> map); Task<T> GetByIdAsync(object id, CustomTransaction customTransaction, int? commandTimeout); Task<T> GetByIdAsync(object id, CustomTransaction customTransaction); Task<T> GetByIdAsync(object id); T GetById(object id, CustomTransaction customTransaction, int? commandTimeout); T GetById(object id, CustomTransaction customTransaction); T GetById(object id); Task<object> InsertAsync(T item, bool identity, CustomTransaction customTransaction, int? commandTimeout); Task<object> InsertAsync(T item, bool identity, CustomTransaction customTransaction); Task<object> InsertAsync(T item, bool identity); object Insert(T item, bool identity, CustomTransaction customTransaction, int? commandTimeout); object Insert(T item, bool identity, CustomTransaction customTransaction); object Insert(T item, bool identity); Task UpdateAsync(T item, CustomTransaction customTransaction, int? commandTimeout); Task UpdateAsync(T item, CustomTransaction customTransaction); Task UpdateAsync(T item); void Update(T item, CustomTransaction customTransaction, int? commandTimeout); void Update(T item, CustomTransaction customTransaction); void Update(T item); Task DeleteAsync(object id, CustomTransaction customTransaction, int? commandTimeout); Task DeleteAsync(object id, CustomTransaction customTransaction); Task DeleteAsync(object id); void Delete(object id, CustomTransaction customTransaction, int? commandTimeout); void Delete(object id, CustomTransaction customTransaction); void Delete(object id); DataSet GetDataSet(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); DataSet GetDataSet(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction); DataSet GetDataSet(string sql, Dictionary<string, object> parameters); Task<int> ExecuteQueryAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); Task<int> ExecuteQueryAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction); Task<int> ExecuteQueryAsync(string sql, Dictionary<string, object> parameters); Task<int> ExecuteQueryAsync(string sql); int ExecuteQuery(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); int ExecuteQuery(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction); int ExecuteQuery(string sql, Dictionary<string, object> parameters); int ExecuteQuery(string sql); Task<string> ExecuteQueryAsync(string sql, Dictionary<string, object> parameters, string identity, CustomTransaction customTransaction, int? commandTimeout); Task<string> ExecuteQueryAsync(string sql, Dictionary<string, object> parameters, string identity, CustomTransaction customTransaction); Task<int> ExecuteProcedureAsync(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); Task<int> ExecuteProcedureAsync(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction); Task<int> ExecuteProcedureAsync(string procedure, Dictionary<string, object> parameters); Task<int> ExecuteProcedureAsync(string procedure); int ExecuteProcedure(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); int ExecuteProcedure(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction); int ExecuteProcedure(string procedure, Dictionary<string, object> parameters); int ExecuteProcedure(string procedure); DataSet GetProcedureDataSet(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); DataSet GetProcedureDataSet(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction); DataSet GetProcedureDataSet(string procedure, Dictionary<string, object> parameters); Task<DataTable> GetProcedureDataTableAsync(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); Task<DataTable> GetProcedureDataTableAsync(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction); Task<DataTable> GetProcedureDataTableAsync(string procedure, Dictionary<string, object> parameters); Task<DataTable> GetProcedureDataTableAsync(string procedure, Dictionary<string, object> parameters, int? commandTimeout); DataTable GetProcedureDataTable(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); DataTable GetProcedureDataTable(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction); DataTable GetProcedureDataTable(string procedure, Dictionary<string, object> parameters); DataTable GetProcedureDataTable(string procedure, Dictionary<string, object> parameters, int? commandTimeout); Task<object> ExecuteScalarAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); Task<object> ExecuteScalarAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction); Task<object> ExecuteScalarAsync(string sql, Dictionary<string, object> parameters); object ExecuteScalar(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout); object ExecuteScalar(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction); object ExecuteScalar(string sql, Dictionary<string, object> parameters); } } <|start_filename|>RepositoryHelpers/DataBaseRepository/CustomRepository.cs<|end_filename|> using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Text; using System.Threading.Tasks; using Dapper; using RepositoryHelpers.DataBase; using RepositoryHelpers.DataBaseRepository.Base; using RepositoryHelpers.Mapping; using RepositoryHelpers.Utils; namespace RepositoryHelpers.DataBaseRepository { public sealed class CustomRepository<T> : ICustomRepository<T> { private readonly Connection _connection; public CustomRepository(Connection connection) { _connection = connection; } #region IDb //DefaultConnection private DbConnection _DBConnection; private DbConnection DBConnection { get { if (_DBConnection == null) _DBConnection = _connection.DataBaseConnection; return _DBConnection; } set { _DBConnection = value; } } //Default Command private DbCommand _DBCommand; public DbCommand DbCommand { set { _DBCommand = value; } get { if (_DBCommand == null) { _DBCommand = _connection.GetCommand(); _DBCommand.Connection = DBConnection; } return _DBCommand; } } public void DisposeDB(bool dispose) { if (dispose) { DBConnection.Close(); _DBConnection.Dispose(); _DBConnection = null; DbCommand.Dispose(); DbCommand = null; } } #endregion #region DAPPER private DbConnection GetConnection(CustomTransaction customTransaction) => customTransaction?.DbCommand?.Connection ?? _connection.DataBaseConnection; /// <summary> /// Update an item asynchronously /// </summary> /// <param name="item"> item to update</param> /// <param name="customTransaction">Has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns></returns> public async Task UpdateAsync(T item, CustomTransaction customTransaction, int? commandTimeout) { if (_connection.Database == DataBaseType.Oracle) throw new NotImplementedDatabaseException(); var isCustomTransaction = customTransaction != null; try { var connection = GetConnection(customTransaction); var sql = new StringBuilder(); var parameters = new Dictionary<string, object>(); var primaryKey = MappingHelper.GetPrimaryKey(typeof(T)); if (!primaryKey.Any()) throw new CustomRepositoryException("Primary key is not defined"); sql.AppendLine($"update {MappingHelper.GetTableName(typeof(T), _connection.Database)} set "); foreach (var p in item.GetType().GetProperties()) { if (item.GetType().GetProperty(p.Name) == null) continue; if (!MappingHelper.IsIgnored(typeof(T), p)) { sql.Append($" {p.Name} = @{p.Name},"); parameters.Add($"@{p.Name}", item.GetType().GetProperty(p.Name)?.GetValue(item)); } else if (primaryKey.Contains(p.Name)) parameters.Add($"@{p.Name}", item.GetType().GetProperty(p.Name)?.GetValue(item)); } sql.Remove(sql.Length - 1, 1); sql.Append($" where"); foreach(var pkcolumn in primaryKey) { sql.Append($" {pkcolumn} = @{pkcolumn} AND"); } sql.Remove(sql.Length - 4, 4); if (isCustomTransaction) await connection.ExecuteAsync(sql.ToString(), parameters, customTransaction.DbCommand.Transaction, commandTimeout); else await connection.ExecuteAsync(sql.ToString(), parameters, commandTimeout: commandTimeout); } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } } /// <summary> /// Update an item asynchronously /// </summary> /// <param name="item"> item to update</param> /// <param name="customTransaction">Has a transaction object</param> /// <returns></returns> public async Task UpdateAsync(T item, CustomTransaction customTransaction) => await UpdateAsync(item, customTransaction, null).ConfigureAwait(false); /// <summary> /// Update an item /// </summary> /// <param name="item"> item to update</param> /// <returns></returns> public async Task UpdateAsync(T item) => await UpdateAsync(item, null, null).ConfigureAwait(false); /// <summary> /// Update an item /// </summary> /// <param name="item"> item to update</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns></returns> public void Update(T item, CustomTransaction customTransaction, int? commandTimeout) => UpdateAsync(item, customTransaction, commandTimeout).Wait(); /// <summary> /// Update an item /// </summary> /// <param name="item"> item to update</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns></returns> public void Update(T item, CustomTransaction customTransaction) => UpdateAsync(item, customTransaction, null).Wait(); /// <summary> /// Update an item /// </summary> /// <param name="item"> item to update</param> /// <returns></returns> public void Update(T item) => UpdateAsync(item, null, null).Wait(); /// <summary> /// Insert an item asynchronously /// </summary> /// <param name="item"> item to insert</param> /// <param name="identity"> Return primary key</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Table Primary key or number of rows affected</returns> public async Task<object> InsertAsync(T item, bool identity, CustomTransaction customTransaction, int? commandTimeout) { if (_connection.Database == DataBaseType.Oracle) throw new NotImplementedDatabaseException(); var isCustomTransaction = customTransaction != null; try { var connection = GetConnection(customTransaction); var sql = new StringBuilder(); var sqlParameters = new StringBuilder(); var parameters = new Dictionary<string, object>(); foreach (var p in item.GetType().GetProperties()) { if (item.GetType().GetProperty(p.Name) == null) continue; if (MappingHelper.IsIgnored(typeof(T), p)) continue; sqlParameters.Append($"@{p.Name},"); parameters.Add($"@{p.Name}", item.GetType().GetProperty(p.Name)?.GetValue(item)); } sqlParameters.Remove(sqlParameters.Length - 1, 1); sql.AppendLine($"insert into {MappingHelper.GetTableName(typeof(T), _connection.Database)} ({sqlParameters.ToString().Replace("@", "")}) "); if (identity) { var identityColumn = MappingHelper.GetIdentityColumn(typeof(T)); if (string.IsNullOrEmpty(identityColumn)) throw new CustomRepositoryException("Identity column is not defined"); if (_connection.Database == DataBaseType.SqlServer) sql.AppendLine($" OUTPUT inserted.{identityColumn} values ({sqlParameters.ToString()}) "); else if (_connection.Database == DataBaseType.PostgreSQL) sql.AppendLine($" values ({sqlParameters.ToString()}) RETURNING {identityColumn} "); object identityObject; if (isCustomTransaction) identityObject = connection.ExecuteScalar(sql.ToString(), parameters, customTransaction.DbCommand.Transaction, commandTimeout); else identityObject = connection.ExecuteScalar(sql.ToString(), parameters, commandTimeout: commandTimeout); return identityObject; } else { sql.AppendLine($" values ({sqlParameters.ToString()}) "); if (isCustomTransaction) return await connection.ExecuteAsync(sql.ToString(), parameters, customTransaction.DbCommand.Transaction, commandTimeout); else return await connection.ExecuteAsync(sql.ToString(), parameters, commandTimeout: commandTimeout); } } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } } /// <summary> /// Insert an item /// </summary> /// <param name="item"> item to insert</param> /// <param name="identity"> Return primary key</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>Table Primary key or number of rows affected</returns> public async Task<object> InsertAsync(T item, bool identity, CustomTransaction customTransaction) => await InsertAsync(item, identity, customTransaction, null).ConfigureAwait(false); /// <summary> /// Insert an item /// </summary> /// <param name="item"> item to insert</param> /// <param name="identity"> Return primary key</param> /// <returns>Table Primary key or number of rows affected</returns> public async Task<object> InsertAsync(T item, bool identity) => await InsertAsync(item, identity, null, null).ConfigureAwait(false); /// <summary> /// Insert an item /// </summary> /// <param name="item"> item to insert</param> /// <param name="identity"> Return primary key</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Table Primary key or number of rows affected</returns> public object Insert(T item, bool identity, CustomTransaction customTransaction, int? commandTimeout) => InsertAsync(item, identity, customTransaction, commandTimeout).Result; /// <summary> /// Insert an item /// </summary> /// <param name="item"> item to insert</param> /// <param name="identity"> Return primary key</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>Table Primary key or number of rows affected</returns> public object Insert(T item, bool identity, CustomTransaction customTransaction) => InsertAsync(item, identity, customTransaction).Result; /// <summary> /// Insert an item /// </summary> /// <param name="item"> item to insert</param> /// <param name="identity"> Return primary key</param> /// <returns>Table Primary key or number of rows affected</returns> public object Insert(T item, bool identity) => InsertAsync(item, identity).Result; /// <summary> /// Get all rows in the table asynchronously /// </summary> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>All rows in the table</returns> public async Task<IEnumerable<T>> GetAsync(CustomTransaction customTransaction, int? commandTimeout) { try { var isCustomTransaction = customTransaction != null; var connection = GetConnection(customTransaction); if (isCustomTransaction) return await connection.QueryAsync<T>($"Select * from {MappingHelper.GetTableName(typeof(T), _connection.Database)} ", transaction: customTransaction.DbCommand.Transaction, commandTimeout: commandTimeout); else return await connection.QueryAsync<T>($"Select * from {MappingHelper.GetTableName(typeof(T), _connection.Database)} ", commandTimeout: commandTimeout); } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } } /// <summary> /// Get all rows in the table /// </summary> /// <param name="customTransaction"> has a transaction object</param> /// <returns>All rows in the table</returns> public async Task<IEnumerable<T>> GetAsync(CustomTransaction customTransaction) => await GetAsync(customTransaction, null).ConfigureAwait(false); /// <summary> /// Get all rows in the table /// </summary> /// <returns>All rows in the table</returns> public async Task<IEnumerable<T>> GetAsync() => await GetAsync(customTransaction: null, commandTimeout: null).ConfigureAwait(false); /// <summary> /// Get all rows in the table /// </summary> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>All rows in the table</returns> public IEnumerable<T> Get(CustomTransaction customTransaction, int? commandTimeout) => GetAsync(customTransaction, commandTimeout).Result; /// <summary> /// Get all rows in the table /// </summary> /// <param name="customTransaction"> has a transaction object</param> /// <returns>All rows in the table</returns> public IEnumerable<T> Get(CustomTransaction customTransaction) => GetAsync(customTransaction).Result; /// <summary> /// Get all rows in the table /// </summary> /// <returns>All rows in the table</returns> public IEnumerable<T> Get() => GetAsync().Result; /// <summary> /// Get the result of a query with parameters asynchronously /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public async Task<IEnumerable<T>> GetAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) { try { var isCustomTransaction = customTransaction != null; var connection = GetConnection(customTransaction); if (isCustomTransaction) return await connection.QueryAsync<T>(sql, parameters, customTransaction.DbCommand.Transaction, commandTimeout); else return await connection.QueryAsync<T>(sql, parameters, commandTimeout: commandTimeout); } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } } /// <summary> /// Get the result of a query with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>List of results</returns> public async Task<IEnumerable<T>> GetAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction) => await GetAsync(sql, parameters, customTransaction, null).ConfigureAwait(false); /// <summary> /// Get the result of a query with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <returns>List of results</returns> public async Task<IEnumerable<T>> GetAsync(string sql, Dictionary<string, object> parameters) => await GetAsync(sql, parameters, null, null).ConfigureAwait(false); /// <summary> /// Get the result of a query without parameters /// </summary> /// <param name="sql">Query</param> /// <returns>List of results</returns> public async Task<IEnumerable<T>> GetAsync(string sql) => await GetAsync(sql, null, null, null).ConfigureAwait(false); /// <summary> /// Get the result of a query with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public IEnumerable<T> Get(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) => GetAsync(sql, parameters, customTransaction, commandTimeout).Result; /// <summary> /// Get the result of a query with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>List of results</returns> public IEnumerable<T> Get(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction) => GetAsync(sql, parameters, customTransaction).Result; /// <summary> /// Get the result of a query with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <returns>List of results</returns> public IEnumerable<T> Get(string sql, Dictionary<string, object> parameters) => GetAsync(sql, parameters).Result; /// <summary> /// Get the result of a query without parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <returns>List of results</returns> public IEnumerable<T> Get(string sql) => GetAsync(sql).Result; /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, string splitOn, int? commandTimeout) { try { var isCustomTransaction = customTransaction != null; var connection = GetConnection(customTransaction); if (isCustomTransaction) return await connection.QueryAsync<TFirst, TSecond, TReturn>(sql, map, parameters, customTransaction.DbCommand.Transaction, splitOn: splitOn, commandTimeout: commandTimeout); else return await connection.QueryAsync<TFirst, TSecond, TReturn>(sql, map, parameters, splitOn: splitOn, commandTimeout: commandTimeout); } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } } /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) => await GetAsync<TFirst, TSecond, TReturn>(sql, map, parameters, customTransaction, "Id", commandTimeout).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction) => await GetAsync<TFirst, TSecond, TReturn>(sql, map, parameters, customTransaction, null).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, string splitOn) => await GetAsync<TFirst, TSecond, TReturn>(sql, map, parameters, null, splitOn, null).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters) => await GetAsync<TFirst, TSecond, TReturn>(sql, map, parameters, null, null).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map) => await GetAsync<TFirst, TSecond, TReturn>(sql, map, null, null, null).ConfigureAwait(false); /// <summary> /// Get the result of a multi-mapping query with parameters and 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, string splitOn, int? commandTimeout) => GetAsync<TFirst, TSecond, TReturn>(sql, map, parameters, customTransaction, splitOn, commandTimeout).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) => GetAsync<TFirst, TSecond, TReturn>(sql, map, parameters, customTransaction, commandTimeout).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction) => GetAsync<TFirst, TSecond, TReturn>(sql, map, parameters, customTransaction).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters, string splitOn) => GetAsync<TFirst, TSecond, TReturn>(sql, map, parameters, splitOn).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, Dictionary<string, object> parameters) => GetAsync<TFirst, TSecond, TReturn>(sql, map, parameters).Result; /// <summary> /// Get the result of a multi-mapping query with 2 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map) => GetAsync<TFirst, TSecond, TReturn>(sql, map).Result; /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, string splitOn, int? commandTimeout) { try { var isCustomTransaction = customTransaction != null; var connection = GetConnection(customTransaction); if (isCustomTransaction) return await connection.QueryAsync<TFirst, TSecond, TThird, TReturn>(sql, map, parameters, customTransaction.DbCommand.Transaction, splitOn: splitOn, commandTimeout: commandTimeout); else return await connection.QueryAsync<TFirst, TSecond, TThird, TReturn>(sql, map, parameters, splitOn: splitOn, commandTimeout: commandTimeout); } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } } /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) => await GetAsync<TFirst, TSecond, TThird, TReturn>(sql, map, parameters, customTransaction, "Id", null).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction) => await GetAsync<TFirst, TSecond, TThird, TReturn>(sql, map, parameters, customTransaction, null).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, string splitOn) => await GetAsync<TFirst, TSecond, TThird, TReturn>(sql, map, parameters, null, splitOn, null).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters) => await GetAsync<TFirst, TSecond, TThird, TReturn>(sql, map, parameters, null, null).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map) => await GetAsync<TFirst, TSecond, TThird, TReturn>(sql, map, null, null, null).ConfigureAwait(false); /// <summary> /// Get the result of a multi-mapping query with parameters and 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, string splitOn, int? commandTimeout) => GetAsync<TFirst, TSecond, TThird, TReturn>(sql, map, parameters, customTransaction, splitOn, commandTimeout).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) => GetAsync<TFirst, TSecond, TThird, TReturn>(sql, map, parameters, customTransaction, commandTimeout).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction) => GetAsync<TFirst, TSecond, TThird, TReturn>(sql, map, parameters, customTransaction).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters, string splitOn) => GetAsync<TFirst, TSecond, TThird, TReturn>(sql, map, parameters, splitOn).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, Dictionary<string, object> parameters) => GetAsync<TFirst, TSecond, TThird, TReturn>(sql, map, parameters).Result; /// <summary> /// Get the result of a multi-mapping query with 3 input types /// </summary> /// <param name="sql">Query</param> /// <param name="map">The function to map row types to the return type</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map) => GetAsync<TFirst, TSecond, TThird, TReturn>(sql, map).Result; /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, string splitOn, int? commandTimeout) { try { var isCustomTransaction = customTransaction != null; var connection = GetConnection(customTransaction); if (isCustomTransaction) return await connection.QueryAsync<TReturn>(sql, types, map, parameters, customTransaction.DbCommand.Transaction, splitOn: splitOn, commandTimeout: commandTimeout); else return await connection.QueryAsync<TReturn>(sql, types, map, parameters, splitOn: splitOn, commandTimeout: commandTimeout); } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } } /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) => await GetAsync<TReturn>(sql, types, map, parameters, customTransaction, "Id", null).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction) => await GetAsync<TReturn>(sql, types, map, parameters, customTransaction, null).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, string splitOn) => await GetAsync<TReturn>(sql, types, map, parameters, null, splitOn, null).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with parameters and an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters) => await GetAsync<TReturn>(sql, types, map, parameters, null, null).ConfigureAwait(false); /// <summary> /// Get the asynchronously result of a multi-mapping query with an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <returns>List of results</returns> public async Task<IEnumerable<TReturn>> GetAsync<TReturn>(string sql, Type[] types, Func<object[], TReturn> map) => await GetAsync<TReturn>(sql, types, map, null, null, null).ConfigureAwait(false); /// <summary> /// Get the result of a multi-mapping query with parameters and an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, string splitOn, int? commandTimeout) => GetAsync<TReturn>(sql, types, map, parameters, customTransaction, splitOn, commandTimeout).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) => GetAsync<TReturn>(sql, types, map, parameters, customTransaction, commandTimeout).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, CustomTransaction customTransaction) => GetAsync<TReturn>(sql, types, map, parameters, customTransaction).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id")</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters, string splitOn) => GetAsync<TReturn>(sql, types, map, parameters, splitOn).Result; /// <summary> /// Get the result of a multi-mapping query with parameters and an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <param name="parameters">Query parameters</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TReturn>(string sql, Type[] types, Func<object[], TReturn> map, Dictionary<string, object> parameters) => GetAsync<TReturn>(sql, types, map, parameters).Result; /// <summary> /// Get the result of a multi-mapping query with an arbitrary number of input types /// </summary> /// <param name="sql">Query</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type</param> /// <returns>List of results</returns> public IEnumerable<TReturn> Get<TReturn>(string sql, Type[] types, Func<object[], TReturn> map) => GetAsync<TReturn>(sql, types, map).Result; /// <summary> /// Get the item by id asynchronously /// </summary> /// <param name="id">Primary Key</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Item</returns> public async Task<T> GetByIdAsync(object id, CustomTransaction customTransaction, int? commandTimeout) { try { var isCustomTransaction = customTransaction != null; var primaryKey = MappingHelper.GetPrimaryKey(typeof(T)); if (!primaryKey.Any()) throw new CustomRepositoryException("Primary key is not defined"); if (primaryKey.Count > 1) throw new CustomRepositoryException("This method does not support a composite primary key"); var primaryKeyColumnName = primaryKey.FirstOrDefault(); var connection = GetConnection(customTransaction); if (isCustomTransaction) return await connection.QueryFirstOrDefaultAsync<T>($"Select * from {MappingHelper.GetTableName(typeof(T), _connection.Database)} where {primaryKeyColumnName} = @ID ", new { ID = id }, customTransaction.DbCommand.Transaction, commandTimeout); else return await connection.QueryFirstOrDefaultAsync<T>($"Select * from {MappingHelper.GetTableName(typeof(T), _connection.Database)} where {primaryKeyColumnName} = @ID ", new { ID = id }, commandTimeout: commandTimeout); } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } } /// <summary> /// Get the item by id /// </summary> /// <param name="id">Primary Key</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>Item</returns> public async Task<T> GetByIdAsync(object id, CustomTransaction customTransaction) => await GetByIdAsync(id, customTransaction, null).ConfigureAwait(false); /// <summary> /// Get the item by id /// </summary> /// <param name="id">Primary Key</param> /// <returns>Item</returns> public async Task<T> GetByIdAsync(object id) => await GetByIdAsync(id, null, null).ConfigureAwait(false); /// <summary> /// Get the item by id /// </summary> /// <param name="id">Primary Key</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Item</returns> public T GetById(object id, CustomTransaction customTransaction, int? commandTimeout) => GetByIdAsync(id, customTransaction, commandTimeout).Result; /// <summary> /// Get the item by id /// </summary> /// <param name="id">Primary Key</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>Item</returns> public T GetById(object id, CustomTransaction customTransaction) => GetByIdAsync(id, customTransaction).Result; /// <summary> /// Get the item by id /// </summary> /// <param name="id">Primary Key</param> /// <returns>Item</returns> public T GetById(object id) => GetByIdAsync(id).Result; /// <summary> /// Delete an item by id asynchronously /// </summary> /// <param name="id">Primary Key</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> public async Task DeleteAsync(object id, CustomTransaction customTransaction, int? commandTimeout) { try { var isCustomTransaction = customTransaction != null; var primaryKey = MappingHelper.GetPrimaryKey(typeof(T)); if (!primaryKey.Any()) throw new CustomRepositoryException("Primary key is not defined"); if (primaryKey.Count > 1) throw new CustomRepositoryException("This method does not support a composite primary key"); var primaryKeyColumnName = primaryKey.FirstOrDefault(); var connection = GetConnection(customTransaction); var sql = new StringBuilder(); var parameters = new Dictionary<string, object> { { "@ID", id } }; sql.AppendLine($"delete from {MappingHelper.GetTableName(typeof(T), _connection.Database)} where {primaryKeyColumnName} = @ID"); if (isCustomTransaction) await connection.ExecuteAsync(sql.ToString(), parameters, customTransaction.DbCommand.Transaction, commandTimeout); else await connection.ExecuteAsync(sql.ToString(), parameters, commandTimeout: commandTimeout); } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } } /// <summary> /// Delete an item by id /// </summary> /// <param name="id">Primary Key</param> /// <param name="customTransaction"> has a transaction object</param> public async Task DeleteAsync(object id, CustomTransaction customTransaction) => await DeleteAsync(id, customTransaction, null).ConfigureAwait(false); /// <summary> /// Delete an item by id /// </summary> /// <param name="id">Primary Key</param> public async Task DeleteAsync(object id) => await DeleteAsync(id, null, null).ConfigureAwait(false); /// <summary> /// Delete an item by id /// </summary> /// <param name="id">Primary Key</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> public void Delete(object id, CustomTransaction customTransaction, int? commandTimeout) => DeleteAsync(id, customTransaction, commandTimeout).Wait(); /// <summary> /// Delete an item by id /// </summary> /// <param name="id">Primary Key</param> /// <param name="customTransaction"> has a transaction object</param> public void Delete(object id, CustomTransaction customTransaction) => DeleteAsync(id, customTransaction).Wait(); /// <summary> /// Delete an item by id /// </summary> /// <param name="id">Primary Key</param> public void Delete(object id) => DeleteAsync(id).Wait(); #endregion #region ADO /// <summary> /// Get DataSet result with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>DataSet of results</returns> public DataSet GetDataSet(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) { var isCustomTransaction = customTransaction != null; try { DbCommand.Connection = GetConnection(customTransaction); if (commandTimeout.HasValue) DbCommand.CommandTimeout = commandTimeout.Value; DbCommand.CommandType = CommandType.Text; DbCommand.Parameters.Clear(); DbCommand.CommandText = sql; if (DBConnection.State == ConnectionState.Closed) DBConnection.Open(); foreach (var parameter in parameters) { DbCommand.Parameters.Add(_connection.GetParameter(parameter)); } using (var da = _connection.GetDataAdapter()) { da.SelectCommand = DbCommand; using (var ds = new DataSet()) { da.Fill(ds); return ds; } } } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } finally { DisposeDB(isCustomTransaction); } } /// <summary> /// Get DataSet result with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>DataSet of results</returns> public DataSet GetDataSet(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction) => GetDataSet(sql, parameters, customTransaction, null); /// <summary> /// Get DataSet result with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <returns>DataSet of results</returns> public DataSet GetDataSet(string sql, Dictionary<string, object> parameters) => GetDataSet(sql, parameters, null, null); /// <summary> /// Executes a query with parameters asynchronously /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Number of rows affected</returns> public async Task<int> ExecuteQueryAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) { var isCustomTransaction = customTransaction != null; try { if (isCustomTransaction) DbCommand = customTransaction.DbCommand; else DbCommand.Connection = DBConnection; if (commandTimeout.HasValue) DbCommand.CommandTimeout = commandTimeout.Value; DbCommand.CommandType = CommandType.Text; DbCommand.Parameters.Clear(); if (DBConnection.State == ConnectionState.Closed) DBConnection.Open(); if (parameters != null) { foreach (var parameter in parameters) DbCommand.Parameters.Add(_connection.GetParameter(parameter)); } DbCommand.CommandText = sql; return await DbCommand.ExecuteNonQueryAsync(); } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } finally { DisposeDB(isCustomTransaction); } } /// <summary> /// Executes a query with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>Number of rows affected</returns> public async Task<int> ExecuteQueryAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction) => await ExecuteQueryAsync(sql, parameters, customTransaction, null).ConfigureAwait(false); /// <summary> /// Executes a query with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <returns>Number of rows affected</returns> public async Task<int> ExecuteQueryAsync(string sql, Dictionary<string, object> parameters) => await ExecuteQueryAsync(sql, parameters, customTransaction: null, commandTimeout: null).ConfigureAwait(false); /// <summary> /// Executes a query without parameters /// </summary> /// <param name="sql">Query</param> /// <returns>Number of rows affected</returns> public async Task<int> ExecuteQueryAsync(string sql) => await ExecuteQueryAsync(sql, parameters: null, customTransaction: null, commandTimeout: null).ConfigureAwait(false); /// <summary> /// Executes a query with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Number of rows affected</returns> public int ExecuteQuery(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) => ExecuteQueryAsync(sql, parameters, customTransaction, commandTimeout).Result; /// <summary> /// Executes a query with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>Number of rows affected</returns> public int ExecuteQuery(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction) => ExecuteQueryAsync(sql, parameters, customTransaction).Result; /// <summary> /// Executes a query with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <returns>Number of rows affected</returns> public int ExecuteQuery(string sql, Dictionary<string, object> parameters) => ExecuteQueryAsync(sql, parameters).Result; /// <summary> /// Executes a query without parameters /// </summary> /// <param name="sql">Query</param> /// <returns>Number of rows affected</returns> public int ExecuteQuery(string sql) => ExecuteQueryAsync(sql).Result; /// <summary> /// Executes a insert with parameters asynchronously /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="identity">Primary Key or Oracle sequence</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Primary Key After Insert</returns> public async Task<string> ExecuteQueryAsync(string sql, Dictionary<string, object> parameters, string identity, CustomTransaction customTransaction, int? commandTimeout) { var isCustomTransaction = customTransaction != null; try { StringBuilder sbSql = new StringBuilder(); switch (_connection.Database) { case DataBaseType.SqlServer: sbSql.AppendLine(sql); sbSql.AppendLine("SELECT CAST(SCOPE_IDENTITY() as int);"); break; case DataBaseType.Oracle: sbSql.AppendLine($"BEGIN {sql} SELECT {identity}.currval FROM DUAL END; "); break; case DataBaseType.PostgreSQL: break; default: break; } if (isCustomTransaction) DbCommand = customTransaction.DbCommand; else DbCommand.Connection = DBConnection; if (commandTimeout.HasValue) DbCommand.CommandTimeout = commandTimeout.Value; DbCommand.CommandType = CommandType.Text; DbCommand.Parameters.Clear(); foreach (var parameter in parameters) { DbCommand.Parameters.Add(_connection.GetParameter(parameter)); } if (_connection.Database == DataBaseType.PostgreSQL) sbSql.AppendLine($" RETURNING {identity} ; "); DbCommand.CommandText = sbSql.ToString(); if (DBConnection.State == ConnectionState.Closed) DBConnection.Open(); var identityReturn = await DbCommand.ExecuteScalarAsync(); return identityReturn.ToString(); } catch (Exception exp) { throw new Exception(exp.Message); } finally { DisposeDB(isCustomTransaction); } } /// <summary> /// Executes a insert with parameters asynchronously /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="identity">Primary Key or Oracle sequence</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>Primary Key After Insert</returns> public async Task<string> ExecuteQueryAsync(string sql, Dictionary<string, object> parameters, string identity, CustomTransaction customTransaction) => await ExecuteQueryAsync(sql, parameters, identity, customTransaction, null).ConfigureAwait(false); /// <summary> /// Executes a Procedure with parameters asynchronously /// </summary> /// <param name="procedure">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Procedure return</returns> public async Task<int> ExecuteProcedureAsync(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) { var isCustomTransaction = customTransaction != null; try { if (isCustomTransaction) DbCommand = customTransaction.DbCommand; else DbCommand.Connection = DBConnection; if (commandTimeout.HasValue) DbCommand.CommandTimeout = commandTimeout.Value; DbCommand.CommandType = CommandType.StoredProcedure; DbCommand.CommandText = procedure; DbCommand.Parameters.Clear(); if (DBConnection.State == ConnectionState.Closed) DBConnection.Open(); if (parameters != null) { foreach (var parameter in parameters) DbCommand.Parameters.Add(_connection.GetParameter(parameter)); } return await DbCommand.ExecuteNonQueryAsync(); } catch (Exception exp) { throw new Exception(exp.Message); } finally { DisposeDB(isCustomTransaction); } } /// <summary> /// Executes a Procedure with parameters /// </summary> /// <param name="procedure">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>Procedure return</returns> public async Task<int> ExecuteProcedureAsync(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction) => await ExecuteProcedureAsync(procedure, parameters, customTransaction, null).ConfigureAwait(false); /// <summary> /// Executes a Procedure with parameters /// </summary> /// <param name="procedure">Query</param> /// <param name="parameters">Query parameters</param> /// <returns>Procedure return</returns> public async Task<int> ExecuteProcedureAsync(string procedure, Dictionary<string, object> parameters) => await ExecuteProcedureAsync(procedure, parameters, null, null).ConfigureAwait(false); /// <summary> /// Executes a Procedure without parameters /// </summary> /// <param name="procedure">Query</param> /// <returns>Procedure return</returns> public async Task<int> ExecuteProcedureAsync(string procedure) => await ExecuteProcedureAsync(procedure, null, null, null).ConfigureAwait(false); /// <summary> /// Executes a Procedure with parameters /// </summary> /// <param name="procedure">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Procedure return</returns> public int ExecuteProcedure(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) => ExecuteProcedureAsync(procedure, parameters, customTransaction, commandTimeout).Result; /// <summary> /// Executes a Procedure with parameters /// </summary> /// <param name="procedure">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>Procedure return</returns> public int ExecuteProcedure(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction) => ExecuteProcedureAsync(procedure, parameters, customTransaction).Result; /// <summary> /// Executes a Procedure with parameters /// </summary> /// <param name="procedure">Query</param> /// <param name="parameters">Query parameters</param> /// <returns>Procedure return</returns> public int ExecuteProcedure(string procedure, Dictionary<string, object> parameters) => ExecuteProcedureAsync(procedure, parameters).Result; /// <summary> /// Executes a Procedure without parameters /// </summary> /// <param name="procedure">Query</param> /// <returns>Procedure return</returns> public int ExecuteProcedure(string procedure) => ExecuteProcedureAsync(procedure).Result; /// <summary> /// Get Procedure DataSet with parameters /// </summary> /// <param name="procedure">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>DataSet</returns> public DataSet GetProcedureDataSet(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) { var isCustomTransaction = customTransaction != null; try { if (isCustomTransaction) DbCommand = customTransaction.DbCommand; else DbCommand.Connection = DBConnection; if (commandTimeout.HasValue) DbCommand.CommandTimeout = commandTimeout.Value; DbCommand.CommandType = CommandType.StoredProcedure; DbCommand.CommandText = procedure; DbCommand.Parameters.Clear(); if (DBConnection.State == ConnectionState.Closed) DBConnection.Open(); foreach (var parameter in parameters) { DbCommand.Parameters.Add(_connection.GetParameter(parameter)); } using (var da = _connection.GetDataAdapter()) { da.SelectCommand = DbCommand; using (var ds = new DataSet()) { da.Fill(ds); return ds; } } } catch (Exception exp) { throw new Exception(exp.Message); } finally { DisposeDB(isCustomTransaction); } } /// <summary> /// Get Procedure DataSet with parameters /// </summary> /// <param name="procedure">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>DataSet</returns> public DataSet GetProcedureDataSet(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction) => GetProcedureDataSet(procedure, parameters, customTransaction, null); /// <summary> /// Get Procedure DataSet with parameters /// </summary> /// <param name="procedure">Query</param> /// <param name="parameters">Query parameters</param> /// <returns>DataSet</returns> public DataSet GetProcedureDataSet(string procedure, Dictionary<string, object> parameters) => GetProcedureDataSet(procedure, parameters, null, null); /// <summary> /// Executes Scalar with parameters asynchronously /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Scalar result</returns> public async Task<object> ExecuteScalarAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) { var isCustomTransaction = customTransaction != null; try { if (isCustomTransaction) DbCommand = customTransaction.DbCommand; else DbCommand.Connection = DBConnection; if (commandTimeout.HasValue) DbCommand.CommandTimeout = commandTimeout.Value; DbCommand.CommandType = CommandType.Text; DbCommand.Parameters.Clear(); if (DBConnection.State == ConnectionState.Closed) DBConnection.Open(); foreach (var parameter in parameters) { DbCommand.Parameters.Add(_connection.GetParameter(parameter)); } DbCommand.CommandText = sql; return await DbCommand.ExecuteScalarAsync(); } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } finally { DisposeDB(isCustomTransaction); } } /// <summary> /// Executes Scalar with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>Scalar result</returns> public async Task<object> ExecuteScalarAsync(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction) => await ExecuteScalarAsync(sql, parameters, customTransaction, null).ConfigureAwait(false); /// <summary> /// Executes Scalar with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <returns>Scalar result</returns> public async Task<object> ExecuteScalarAsync(string sql, Dictionary<string, object> parameters) => await ExecuteScalarAsync(sql, parameters, null, null).ConfigureAwait(false); /// <summary> /// Executes Scalar with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Scalar result</returns> public object ExecuteScalar(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) => ExecuteScalarAsync(sql, parameters, customTransaction, commandTimeout).Result; /// <summary> /// Executes Scalar with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <param name="customTransaction"> has a transaction object</param> /// <returns>Scalar result</returns> public object ExecuteScalar(string sql, Dictionary<string, object> parameters, CustomTransaction customTransaction) => ExecuteScalarAsync(sql, parameters, customTransaction).Result; /// <summary> /// Executes Scalar with parameters /// </summary> /// <param name="sql">Query</param> /// <param name="parameters">Query parameters</param> /// <returns>Scalar result</returns> public object ExecuteScalar(string sql, Dictionary<string, object> parameters) => ExecuteScalarAsync(sql, parameters).Result; public string GetConnectionString() => this._connection.ConnectionString; #endregion public async Task<DataTable> GetProcedureDataTableAsync(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) { if (_connection.Database == DataBaseType.Oracle) throw new NotImplementedDatabaseException(); var isCustomTransaction = customTransaction != null; try { var connection = GetConnection(customTransaction); DbDataReader reader; if (isCustomTransaction) reader = await connection.ExecuteReaderAsync(procedure, parameters, customTransaction.DbCommand.Transaction, commandTimeout); else reader = await connection.ExecuteReaderAsync(procedure, parameters, commandTimeout: commandTimeout); DataTable dtReturn = new DataTable(); dtReturn.Load(reader); return dtReturn; } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } } public async Task<DataTable> GetProcedureDataTableAsync(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction) => await GetProcedureDataTableAsync(procedure, parameters, customTransaction, null).ConfigureAwait(false); public async Task<DataTable> GetProcedureDataTableAsync(string procedure, Dictionary<string, object> parameters) => await GetProcedureDataTableAsync(procedure, parameters, null, null).ConfigureAwait(false); public async Task<DataTable> GetProcedureDataTableAsync(string procedure, Dictionary<string, object> parameters, int? commandTimeout) => await GetProcedureDataTableAsync(procedure, parameters, null, commandTimeout).ConfigureAwait(false); public DataTable GetProcedureDataTable(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction, int? commandTimeout) { if (_connection.Database == DataBaseType.Oracle) throw new NotImplementedDatabaseException(); var isCustomTransaction = customTransaction != null; try { var connection = GetConnection(customTransaction); IDataReader reader; if (isCustomTransaction) reader = connection.ExecuteReader(procedure, parameters, customTransaction.DbCommand.Transaction, commandTimeout); else reader = connection.ExecuteReader(procedure, parameters, commandTimeout: commandTimeout); DataTable dtReturn = new DataTable(); dtReturn.Load(reader); return dtReturn; } catch (Exception ex) { throw new CustomRepositoryException(ex.Message); } } public DataTable GetProcedureDataTable(string procedure, Dictionary<string, object> parameters, CustomTransaction customTransaction) => GetProcedureDataTable(procedure, parameters, customTransaction, null); public DataTable GetProcedureDataTable(string procedure, Dictionary<string, object> parameters) => GetProcedureDataTable(procedure, parameters, null, null); public DataTable GetProcedureDataTable(string procedure, Dictionary<string, object> parameters, int? commandTimeout) => GetProcedureDataTable(procedure, parameters, null, commandTimeout); } } <|start_filename|>RepositoryHelpers/Utils/CustomAttributeDataExtensions.cs<|end_filename|> using System.Reflection; namespace RepositoryHelpers.Utils { internal static class CustomAttributeDataExtensions { public static string GetAttributeName(this CustomAttributeData customAttribute) => customAttribute.AttributeType.ToString().ToUpperInvariant(); } } <|start_filename|>RepositoryHelpers/DataBaseRepository/Base/ILiteDbRepository.cs<|end_filename|> using System; namespace RepositoryHelpers.DataBaseRepository.Base { public interface ILiteDbRepository { int Id { get; set; } DateTime Update { get; set; } } } <|start_filename|>RepositoryHelpers/Utils/Enum.cs<|end_filename|> namespace RepositoryHelpers.Utils { public enum DataBaseType { SqlServer = 0, Oracle = 1, PostgreSQL = 2 } } <|start_filename|>RepositoryHelpers/Utils/NotImplementedDatabaseException.cs<|end_filename|> using System; namespace RepositoryHelpers.Utils { public class NotImplementedDatabaseException : Exception { public NotImplementedDatabaseException() : base("Not implemented for selected database") { } public NotImplementedDatabaseException(string message, Exception inner) : base(message, inner) { } } } <|start_filename|>RepositoryHelpers/Utils/CustomRepositoryException.cs<|end_filename|> using System; namespace RepositoryHelpers.Utils { public class CustomRepositoryException : Exception { public CustomRepositoryException() { } public CustomRepositoryException(string message) : base(message) { } public CustomRepositoryException(string message, Exception inner) : base(message, inner) { } } } <|start_filename|>RepositoryHelpers/Mapping/Attributes/PrimaryKey.cs<|end_filename|> using System; namespace RepositoryHelpers { [AttributeUsage(AttributeTargets.Property)] public sealed class PrimaryKey : Attribute { } }
alexcanario/RepositoryHelpers
<|start_filename|>Nintroller/Controllers/ClassicControllerPro.cs<|end_filename|> using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace NintrollerLib { public struct ClassicControllerPro : INintrollerState, IWiimoteExtension { public Wiimote wiimote { get; set; } public Joystick LJoy, RJoy; public bool A, B, X, Y; public bool Up, Down, Left, Right; public bool L, R, ZL, ZR; public bool Plus, Minus, Home; public ClassicControllerPro(Wiimote wm) { this = new ClassicControllerPro(); wiimote = wm; } public bool Start { get { return Plus; } set { Plus = value; } } public bool Select { get { return Minus; } set { Minus = value; } } public void Update(byte[] data) { int offset = Utils.GetExtensionOffset((InputReport)data[0]); if (offset > 0) { // Buttons A = (data[offset + 5] & 0x10) == 0; B = (data[offset + 5] & 0x40) == 0; X = (data[offset + 5] & 0x08) == 0; Y = (data[offset + 5] & 0x20) == 0; L = (data[offset + 4] & 0x20) == 0; R = (data[offset + 4] & 0x02) == 0; ZL = (data[offset + 5] & 0x80) == 0; ZR = (data[offset + 5] & 0x04) == 0; Plus = (data[offset + 4] & 0x04) == 0; Minus = (data[offset + 4] & 0x10) == 0; Home = (data[offset + 4] & 0x08) == 0; // Dpad Up = (data[offset + 5] & 0x01) == 0; Down = (data[offset + 4] & 0x40) == 0; Left = (data[offset + 5] & 0x02) == 0; Right = (data[offset + 4] & 0x80) == 0; // Joysticks LJoy.rawX = (byte)(data[offset] & 0x3F); LJoy.rawY = (byte)(data[offset + 1] & 0x3F); RJoy.rawX = (byte)(data[offset + 2] >> 7 | (data[offset + 1] & 0xC0) >> 5 | (data[offset] & 0xC0) >> 3); RJoy.rawY = (byte)(data[offset + 2] & 0x1F); // Normalize LJoy.Normalize(); RJoy.Normalize(); } // Simply calling the Update(data) method doesn't seem to be working. // the button data will get updated correctly but when stepping over this // statement in debug mode the button data is all set to its default values. wiimote = new Wiimote(data, wiimote); } public float GetValue(string input) { switch (input) { case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.A: return A ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.B: return B ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.X: return X ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.Y: return Y ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.UP: return Up ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.DOWN: return Down ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LEFT: return Left ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RIGHT: return Right ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.L: return L ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.R: return R ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.ZL: return ZL ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.ZR: return ZR ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LX: return LJoy.X; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LY: return LJoy.Y; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RX: return RJoy.X; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RY: return RJoy.Y; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LUP: return LJoy.Y > 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LDOWN: return LJoy.Y < 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LLEFT: return LJoy.X < 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LRIGHT: return LJoy.X > 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RUP: return RJoy.Y > 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RDOWN: return RJoy.Y < 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RLEFT: return RJoy.X < 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RRIGHT: return RJoy.X > 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.SELECT: return Select ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.START: return Start ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER_PRO.HOME: return Home ? 1 : 0; } return wiimote.GetValue(input); } public void SetCalibration(Calibrations.CalibrationPreset preset) { wiimote.SetCalibration(preset); switch (preset) { case Calibrations.CalibrationPreset.Default: //LJoy.Calibrate(Calibrations.Defaults.ClassicControllerProDefault.LJoy); //RJoy.Calibrate(Calibrations.Defaults.ClassicControllerProDefault.RJoy); SetCalibration(Calibrations.Defaults.ClassicControllerProDefault); break; case Calibrations.CalibrationPreset.Modest: SetCalibration(Calibrations.Moderate.ClassicControllerProModest); break; case Calibrations.CalibrationPreset.Extra: SetCalibration(Calibrations.Extras.ClassicControllerProExtra); break; case Calibrations.CalibrationPreset.Minimum: SetCalibration(Calibrations.Minimum.ClassicControllerProMinimal); break; case Calibrations.CalibrationPreset.None: SetCalibration(Calibrations.None.ClassicControllerProRaw); break; } } public void SetCalibration(INintrollerState from) { if (from.CalibrationEmpty) { // don't apply empty calibrations return; } if (from.GetType() == typeof(ClassicControllerPro)) { LJoy.Calibrate(((ClassicControllerPro)from).LJoy); RJoy.Calibrate(((ClassicControllerPro)from).RJoy); } else if (from.GetType() == typeof(Wiimote)) { wiimote.SetCalibration(from); } } public void SetCalibration(string calibrationString) { if (calibrationString.Count(c => c == '0') > 5) { // don't set empty calibrations return; } string[] components = calibrationString.Split(new char[] { ':' }); foreach (string component in components) { if (component.StartsWith("joyL")) { string[] joyLConfig = component.Split(new char[] { '|' }); for (int jL = 1; jL < joyLConfig.Length; jL++) { int value = 0; if (int.TryParse(joyLConfig[jL], out value)) { switch (jL) { case 1: LJoy.centerX = value; break; case 2: LJoy.minX = value; break; case 3: LJoy.maxX = value; break; case 4: LJoy.deadX = value; break; case 5: LJoy.centerY = value; break; case 6: LJoy.minY = value; break; case 7: LJoy.maxY = value; break; case 8: LJoy.deadY = value; break; default: break; } } } } else if (component.StartsWith("joyR")) { string[] joyRConfig = component.Split(new char[] { '|' }); for (int jR = 1; jR < joyRConfig.Length; jR++) { int value = 0; if (int.TryParse(joyRConfig[jR], out value)) { switch (jR) { case 1: RJoy.centerX = value; break; case 2: RJoy.minX = value; break; case 3: RJoy.maxX = value; break; case 4: RJoy.deadX = value; break; case 5: RJoy.centerY = value; break; case 6: RJoy.minY = value; break; case 7: RJoy.maxY = value; break; case 8: RJoy.deadY = value; break; default: break; } } } } } } public string GetCalibrationString() { StringBuilder sb = new StringBuilder(); sb.Append("-ccp"); sb.Append(":joyL"); sb.Append("|"); sb.Append(LJoy.centerX); sb.Append("|"); sb.Append(LJoy.minX); sb.Append("|"); sb.Append(LJoy.maxX); sb.Append("|"); sb.Append(LJoy.deadX); sb.Append("|"); sb.Append(LJoy.centerY); sb.Append("|"); sb.Append(LJoy.minY); sb.Append("|"); sb.Append(LJoy.maxY); sb.Append("|"); sb.Append(LJoy.deadY); sb.Append(":joyR"); sb.Append("|"); sb.Append(RJoy.centerX); sb.Append("|"); sb.Append(RJoy.minX); sb.Append("|"); sb.Append(RJoy.maxX); sb.Append("|"); sb.Append(RJoy.deadX); sb.Append("|"); sb.Append(RJoy.centerY); sb.Append("|"); sb.Append(RJoy.minY); sb.Append("|"); sb.Append(RJoy.maxY); sb.Append("|"); sb.Append(RJoy.deadY); return sb.ToString(); } public bool CalibrationEmpty { get { if (LJoy.maxX == 0 && LJoy.maxY == 0 && RJoy.maxX == 0 && RJoy.maxY == 0) { return true; } else { return false; } } } public IEnumerator<KeyValuePair<string, float>> GetEnumerator() { foreach (var input in wiimote) { yield return input; } yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.A, A ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.B, B ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.X, X ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.Y, Y ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.L, L ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.R, R ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.ZL, ZL ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.ZR, ZR ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.UP, Up ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.DOWN, Down ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LEFT, Left ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RIGHT, Right ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.START, Start ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.SELECT, Select ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.HOME, Home ? 1.0f : 0.0f); LJoy.Normalize(); RJoy.Normalize(); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LX, LJoy.X); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LY, LJoy.Y); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RX, RJoy.X); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RY, RJoy.X); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LUP, LJoy.Y > 0f ? LJoy.Y : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LDOWN, LJoy.Y > 0f ? 0.0f : -LJoy.Y); // These are inverted yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LLEFT, LJoy.X > 0f ? 0.0f : -LJoy.X); // because they yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.LRIGHT, LJoy.X > 0f ? LJoy.X : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RUP, RJoy.Y > 0f ? RJoy.Y : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RDOWN, RJoy.Y > 0f ? 0.0f : -RJoy.Y); // represents how far the yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RLEFT, RJoy.X > 0f ? 0.0f : -RJoy.X); // input is left or down yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER_PRO.RRIGHT, RJoy.X > 0f ? RJoy.X : 0.0f); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <|start_filename|>Scp/ScpMonitor/ScpForm.Designer.cs<|end_filename|> namespace ScpMonitor { partial class ScpForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.lblHost = new System.Windows.Forms.Label(); this.lblPad_1 = new System.Windows.Forms.Label(); this.lblPad_2 = new System.Windows.Forms.Label(); this.lblPad_3 = new System.Windows.Forms.Label(); this.lblPad_4 = new System.Windows.Forms.Label(); this.tmrUpdate = new System.Windows.Forms.Timer(this.components); this.niTray = new System.Windows.Forms.NotifyIcon(this.components); this.cmTray = new System.Windows.Forms.ContextMenuStrip(this.components); this.tmConfig = new System.Windows.Forms.ToolStripMenuItem(); this.tmProfile = new System.Windows.Forms.ToolStripMenuItem(); this.tmReset = new System.Windows.Forms.ToolStripMenuItem(); this.tmExit = new System.Windows.Forms.ToolStripMenuItem(); this.btnUp_1 = new System.Windows.Forms.Button(); this.btnUp_2 = new System.Windows.Forms.Button(); this.btnUp_3 = new System.Windows.Forms.Button(); this.cmTray.SuspendLayout(); this.SuspendLayout(); // // lblHost // this.lblHost.AutoSize = true; this.lblHost.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblHost.Location = new System.Drawing.Point(10, 10); this.lblHost.Name = "lblHost"; this.lblHost.Size = new System.Drawing.Size(223, 13); this.lblHost.TabIndex = 1; this.lblHost.Text = "Host Address : Disconnected"; // // lblPad_1 // this.lblPad_1.AutoSize = true; this.lblPad_1.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblPad_1.Location = new System.Drawing.Point(320, 10); this.lblPad_1.Name = "lblPad_1"; this.lblPad_1.Size = new System.Drawing.Size(167, 13); this.lblPad_1.TabIndex = 2; this.lblPad_1.Text = "Pad 1 : Disconnected"; // // lblPad_2 // this.lblPad_2.AutoSize = true; this.lblPad_2.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblPad_2.Location = new System.Drawing.Point(320, 35); this.lblPad_2.Name = "lblPad_2"; this.lblPad_2.Size = new System.Drawing.Size(167, 13); this.lblPad_2.TabIndex = 3; this.lblPad_2.Text = "Pad 2 : Disconnected"; // // lblPad_3 // this.lblPad_3.AutoSize = true; this.lblPad_3.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblPad_3.Location = new System.Drawing.Point(320, 60); this.lblPad_3.Name = "lblPad_3"; this.lblPad_3.Size = new System.Drawing.Size(167, 13); this.lblPad_3.TabIndex = 4; this.lblPad_3.Text = "Pad 3 : Disconnected"; // // lblPad_4 // this.lblPad_4.AutoSize = true; this.lblPad_4.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblPad_4.Location = new System.Drawing.Point(320, 85); this.lblPad_4.Name = "lblPad_4"; this.lblPad_4.Size = new System.Drawing.Size(167, 13); this.lblPad_4.TabIndex = 5; this.lblPad_4.Text = "Pad 4 : Disconnected"; // // tmrUpdate // this.tmrUpdate.Tick += new System.EventHandler(this.tmrUpdate_Tick); // // niTray // this.niTray.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info; this.niTray.BalloonTipTitle = "SCP Monitor"; this.niTray.ContextMenuStrip = this.cmTray; this.niTray.Text = "SCP Monitor"; this.niTray.Visible = true; this.niTray.MouseClick += new System.Windows.Forms.MouseEventHandler(this.niTray_Click); // // cmTray // this.cmTray.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tmConfig, this.tmProfile, this.tmReset, this.tmExit}); this.cmTray.Name = "cmTray"; this.cmTray.Size = new System.Drawing.Size(159, 92); // // tmConfig // this.tmConfig.Enabled = false; this.tmConfig.Name = "tmConfig"; this.tmConfig.Size = new System.Drawing.Size(158, 22); this.tmConfig.Text = "&Configuration"; this.tmConfig.Click += new System.EventHandler(this.tmConfig_Click); // // tmProfile // this.tmProfile.Enabled = false; this.tmProfile.Name = "tmProfile"; this.tmProfile.Size = new System.Drawing.Size(158, 22); this.tmProfile.Text = "&Profile Manager"; this.tmProfile.Click += new System.EventHandler(this.tmProfile_Click); // // tmReset // this.tmReset.Name = "tmReset"; this.tmReset.Size = new System.Drawing.Size(158, 22); this.tmReset.Text = "&Reset Position"; this.tmReset.Click += new System.EventHandler(this.tmReset_Click); // // tmExit // this.tmExit.Name = "tmExit"; this.tmExit.Size = new System.Drawing.Size(158, 22); this.tmExit.Text = "E&xit"; this.tmExit.Click += new System.EventHandler(this.tmExit_Click); // // btnUp_1 // this.btnUp_1.Enabled = false; this.btnUp_1.Location = new System.Drawing.Point(294, 29); this.btnUp_1.Name = "btnUp_1"; this.btnUp_1.Size = new System.Drawing.Size(20, 23); this.btnUp_1.TabIndex = 6; this.btnUp_1.Tag = "1"; this.btnUp_1.Text = "^"; this.btnUp_1.UseVisualStyleBackColor = true; this.btnUp_1.Click += new System.EventHandler(this.btnUp_Click); this.btnUp_1.Enter += new System.EventHandler(this.Button_Enter); // // btnUp_2 // this.btnUp_2.Enabled = false; this.btnUp_2.Location = new System.Drawing.Point(294, 54); this.btnUp_2.Name = "btnUp_2"; this.btnUp_2.Size = new System.Drawing.Size(20, 23); this.btnUp_2.TabIndex = 7; this.btnUp_2.Tag = "2"; this.btnUp_2.Text = "^"; this.btnUp_2.UseVisualStyleBackColor = true; this.btnUp_2.Click += new System.EventHandler(this.btnUp_Click); this.btnUp_2.Enter += new System.EventHandler(this.Button_Enter); // // btnUp_3 // this.btnUp_3.Enabled = false; this.btnUp_3.Location = new System.Drawing.Point(294, 79); this.btnUp_3.Name = "btnUp_3"; this.btnUp_3.Size = new System.Drawing.Size(20, 23); this.btnUp_3.TabIndex = 8; this.btnUp_3.Tag = "3"; this.btnUp_3.Text = "^"; this.btnUp_3.UseVisualStyleBackColor = true; this.btnUp_3.Click += new System.EventHandler(this.btnUp_Click); this.btnUp_3.Enter += new System.EventHandler(this.Button_Enter); // // ScpForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(734, 111); this.Controls.Add(this.btnUp_3); this.Controls.Add(this.btnUp_2); this.Controls.Add(this.btnUp_1); this.Controls.Add(this.lblPad_4); this.Controls.Add(this.lblPad_3); this.Controls.Add(this.lblPad_2); this.Controls.Add(this.lblPad_1); this.Controls.Add(this.lblHost); this.DoubleBuffered = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ScpForm"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "SCP Monitor"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form_Closing); this.Load += new System.EventHandler(this.Form_Load); this.cmTray.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lblHost; private System.Windows.Forms.Label lblPad_1; private System.Windows.Forms.Label lblPad_2; private System.Windows.Forms.Label lblPad_3; private System.Windows.Forms.Label lblPad_4; private System.Windows.Forms.Timer tmrUpdate; private System.Windows.Forms.NotifyIcon niTray; private System.Windows.Forms.ContextMenuStrip cmTray; private System.Windows.Forms.ToolStripMenuItem tmExit; private System.Windows.Forms.ToolStripMenuItem tmConfig; private System.Windows.Forms.Button btnUp_1; private System.Windows.Forms.Button btnUp_2; private System.Windows.Forms.Button btnUp_3; private System.Windows.Forms.ToolStripMenuItem tmReset; private System.Windows.Forms.ToolStripMenuItem tmProfile; } } <|start_filename|>WiinUPro/Assignments/MouseAbsoluteAssignment.cs<|end_filename|> namespace WiinUPro { public class MouseAbsoluteAssignment : IAssignment { static float xPosition = 0.5f; static float yPosition = 0.5f; public MousePosition Input { get; set; } public MouseAbsoluteAssignment() { } public MouseAbsoluteAssignment(MousePosition inputType) { Input = inputType; } public void Apply(float value) { switch (Input) { case MousePosition.X: xPosition = value; break; case MousePosition.Y: yPosition = value; break; case MousePosition.Center: xPosition = 0.5f; yPosition = 0.5f; break; } MouseDirector.Access.MouseMoveTo(xPosition, yPosition); } public bool SameAs(IAssignment assignment) { var other = assignment as MouseAbsoluteAssignment; if (other == null) { return false; } else { return Input == other.Input; } } public override bool Equals(object obj) { var other = obj as MouseAbsoluteAssignment; if (other == null) { return false; } else { return Input == other.Input; } } public override int GetHashCode() { int hash = (int)Input + 1; return hash; } public override string ToString() { return "Mouse " + Input.ToString() + " Position"; } public string GetDisplayName() { return $"M.Abs_{Input}"; } } public enum MousePosition { X, Y, Center } } <|start_filename|>WiinUPro/Assignments/MouseAssignment.cs<|end_filename|> using System; namespace WiinUPro { public class MouseAssignment : IAssignment { public const int PIXEL_RATE = 8; public MouseInput Input { get; set; } public float Rate { get; set; } //public bool Absolute { get; set; } public MouseAssignment() { } public MouseAssignment(MouseInput inputType) : this(inputType, 1.0f) { } public MouseAssignment(MouseInput inputType, float rate) { Input = inputType; Rate = rate; } public void Apply(float value) { int pixels = (int)Math.Round(PIXEL_RATE * Rate * value); switch (Input) { case MouseInput.MoveUp: MouseDirector.Access.MouseMoveY(pixels * -1); break; case MouseInput.MoveDown: MouseDirector.Access.MouseMoveY(pixels); break; case MouseInput.MoveLeft: MouseDirector.Access.MouseMoveX(pixels * -1); break; case MouseInput.MoveRight: MouseDirector.Access.MouseMoveX(pixels); break; } } public bool SameAs(IAssignment assignment) { var other = assignment as MouseAssignment; if (other == null) { return false; } else { bool result = true; result &= Input == other.Input; result &= Rate == other.Rate; return result; } } public override bool Equals(object obj) { var other = obj as MouseAssignment; if (other == null) { return false; } else { return Input == other.Input; } } public override int GetHashCode() { int hash = (int)Input + 1; hash += (int)Math.Round(10 * Rate); return hash; } public override string ToString() { return Input.ToString(); } public string GetDisplayName() { return ToString().Replace("ove", "."); } } public enum MouseInput { /// <summary>Positive movement along the Y-axis</summary> MoveUp, /// <summary>Negative movement along the Y-axis</summary> MoveDown, /// <summary>Negative movement along the X-axis</summary> MoveLeft, /// <summary>Positive movement along the X-axis</summary> MoveRight } } <|start_filename|>Scp/ScpControl/UsbDs4.cs<|end_filename|> using System; using System.ComponentModel; namespace ScpControl { public partial class UsbDs4 : UsbDevice { public static String USB_CLASS_GUID = "{2ED90CE1-376F-4982-8F7F-E056CBC3CA71}"; protected Boolean m_DisableLightBar = false; protected Byte m_Brightness = Global.Brightness; protected const Int32 R = 6, G = 7, B = 8; // Led Offsets protected Byte[] m_Report = { 0x05, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; protected virtual Byte MapBattery(Byte Value) { Byte Mapped = (Byte) DsBattery.None; switch (Value) { case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: Mapped = (Byte) DsBattery.Charging; break; case 0x1B: Mapped = (Byte) DsBattery.Charged; break; } return Mapped; } public override DsPadId PadId { get { return (DsPadId) m_ControllerId; } set { m_ControllerId = (Byte) value; m_ReportArgs.Pad = PadId; switch (value) { case DsPadId.One: // Blue m_Report[R] = 0x00; m_Report[G] = 0x00; m_Report[B] = m_Brightness; break; case DsPadId.Two: // Green m_Report[R] = 0x00; m_Report[G] = m_Brightness; m_Report[B] = 0x00; break; case DsPadId.Three: // Yellow m_Report[R] = m_Brightness; m_Report[G] = m_Brightness; m_Report[B] = 0x00; break; case DsPadId.Four: // Cyan m_Report[R] = 0x00; m_Report[G] = m_Brightness; m_Report[B] = m_Brightness; break; case DsPadId.None: // Red m_Report[R] = m_Brightness; m_Report[G] = 0x00; m_Report[B] = 0x00; break; } if (Global.DisableLightBar) { m_Report[R] = m_Report[G] = m_Report[B] = m_Report[12] = m_Report[13] = 0x00; } } } public UsbDs4() : base(USB_CLASS_GUID) { InitializeComponent(); } public UsbDs4(IContainer container) : base(USB_CLASS_GUID) { container.Add(this); InitializeComponent(); } public override Boolean Open(String DevicePath) { if (base.Open(DevicePath)) { m_State = DsState.Reserved; GetDeviceInstance(ref m_Instance); Int32 Transfered = 0; if (SendTransfer(0xA1, 0x01, 0x0312, m_Buffer, ref Transfered)) { m_Master = new Byte[] { m_Buffer[15], m_Buffer[14], m_Buffer[13], m_Buffer[12], m_Buffer[11], m_Buffer[10] }; m_Local = new Byte[] { m_Buffer[ 6], m_Buffer[ 5], m_Buffer[ 4], m_Buffer[ 3], m_Buffer[ 2], m_Buffer[ 1] }; } m_Mac = String.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}", m_Local[0], m_Local[1], m_Local[2], m_Local[3], m_Local[4], m_Local[5]); } return State == DsState.Reserved; } public override Boolean Start() { m_Model = (Byte) DsModel.DS4; if (Global.Repair) { Int32 Transfered = 0; Byte[] Buffer = { 0x13, m_Master[5], m_Master[4], m_Master[3], m_Master[2], m_Master[1], m_Master[0], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; Array.Copy(Global.BD_Link, 0, Buffer, 7, Global.BD_Link.Length); if (SendTransfer(0x21, 0x09, 0x0313, Buffer, ref Transfered)) { LogDebug(String.Format("++ Repaired DS4 [{0}] Link Key For BTH Dongle [{1}]", Local, Remote)); } else { LogDebug(String.Format("++ Repair DS4 [{0}] Link Key For BTH Dongle [{1}] Failed!", Local, Remote)); } } return base.Start(); } public override Boolean Rumble(Byte Large, Byte Small) { lock (this) { Int32 Transfered = 0; m_Report[4] = (Byte)(Small); m_Report[5] = (Byte)(Large); return WriteIntPipe(m_Report, m_Report.Length, ref Transfered); } } public override Boolean Pair(Byte[] Master) { Int32 Transfered = 0; Byte[] Buffer = { 0x13, Master[5], Master[4], Master[3], Master[2], Master[1], Master[0], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; Array.Copy(Global.BD_Link, 0, Buffer, 7, Global.BD_Link.Length); if (SendTransfer(0x21, 0x09, 0x0313, Buffer, ref Transfered)) { for (Int32 Index = 0; Index < m_Master.Length; Index++) { m_Master[Index] = Master[Index]; } LogDebug(String.Format("++ Paired DS4 [{0}] To BTH Dongle [{1}]", Local, Remote)); return true; } LogDebug(String.Format("++ Pair Failed [{0}]", Local)); return false; } protected override void Parse(Byte[] Report) { if (Report[0] != 0x01) return; m_Packet++; m_ReportArgs.Report[2] = m_BatteryStatus = MapBattery(Report[30]); m_ReportArgs.Report[4] = (Byte)(m_Packet >> 0 & 0xFF); m_ReportArgs.Report[5] = (Byte)(m_Packet >> 8 & 0xFF); m_ReportArgs.Report[6] = (Byte)(m_Packet >> 16 & 0xFF); m_ReportArgs.Report[7] = (Byte)(m_Packet >> 24 & 0xFF); Ds4Button Buttons = (Ds4Button)((Report[5] << 0) | (Report[6] << 8) | (Report[7] << 16)); //++ Convert HAT to DPAD Report[5] &= 0xF0; switch ((UInt32) Buttons & 0xF) { case 0: Report[5] |= (Byte)(Ds4Button.Up); break; case 1: Report[5] |= (Byte)(Ds4Button.Up | Ds4Button.Right); break; case 2: Report[5] |= (Byte)(Ds4Button.Right); break; case 3: Report[5] |= (Byte)(Ds4Button.Right | Ds4Button.Down); break; case 4: Report[5] |= (Byte)(Ds4Button.Down); break; case 5: Report[5] |= (Byte)(Ds4Button.Down | Ds4Button.Left); break; case 6: Report[5] |= (Byte)(Ds4Button.Left); break; case 7: Report[5] |= (Byte)(Ds4Button.Left | Ds4Button.Up); break; } //-- for (int Index = 8; Index < 72; Index++) { m_ReportArgs.Report[Index] = Report[Index - 8]; } Publish(); } protected override void Process(DateTime Now) { lock (this) { if ((Now - m_Last).TotalMilliseconds >= 500) { Int32 Transfered = 0; m_Last = Now; if (!Global.DisableLightBar) { if (Battery != DsBattery.Charged) { m_Report[9] = m_Report[10] = 0x80; } else { m_Report[9] = m_Report[10] = 0x00; } } if (Global.Brightness != m_Brightness) { m_Brightness = Global.Brightness; PadId = PadId; } if (Global.DisableLightBar != m_DisableLightBar) { m_DisableLightBar = Global.DisableLightBar; PadId = PadId; } WriteIntPipe(m_Report, m_Report.Length, ref Transfered); } } } } } <|start_filename|>WiinUPro/Directors/VJoyDirector.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using vJoyInterfaceWrap; namespace WiinUPro { public class VJoyDirector { public static VJoyDirector Access { get; protected set; } static VJoyDirector() { Access = new VJoyDirector(); } public bool Available { // TODO: Check if DLL exists /* [DllImport("kernel32", SetLastError=true)] static extern IntPtr LoadLibrary(string lpFileName); static bool CheckLibrary(string fileName) { return LoadLibrary(fileName) == IntPtr.Zero; } */ get { uint verDll = 0; uint verDriver = 0; return _interface.vJoyEnabled() && _interface.DriverMatch(ref verDll, ref verDriver); } } public int ControllerCount { get { return _devices.Count; } } public List<JoyDevice> Devices { get { return _devices; } } protected static vJoy _interface; protected List<JoyDevice> _devices; protected Dictionary<uint, vJoy.JoystickState> _states; protected Dictionary<uint, Dictionary<POVDirection, bool>> _activeDirections; public VJoyDirector() { _interface = new vJoy(); _devices = new List<JoyDevice>(); _states = new Dictionary<uint, vJoy.JoystickState>(); _activeDirections = new Dictionary<uint, Dictionary<POVDirection, bool>>(); if (Available) { for (uint i = 1; i <= 16; i++) { if (_interface.isVJDExists(i)) { var status = _interface.GetVJDStatus(i); if (status == VjdStat.VJD_STAT_FREE || status == VjdStat.VJD_STAT_OWN) { _devices.Add(new JoyDevice(i)); } } } } } public bool AquireDevice(uint id) { if (_interface.GetVJDStatus(id) == VjdStat.VJD_STAT_OWN) { return true; } var result = _interface.AcquireVJD(id); if (result) { // Set to neutral state var neutral = new vJoy.JoystickState() { bDevice = (byte)id }; for (HID_USAGES axis = HID_USAGES.HID_USAGE_X; axis <= HID_USAGES.HID_USAGE_WHL; axis++) { if (_interface.GetVJDAxisExist(id, axis)) { long min = 0; long max = 0; _interface.GetVJDAxisMax(id, axis, ref max); _interface.GetVJDAxisMin(id, axis, ref min); long mid = (max - min) / 2; switch (axis) { case HID_USAGES.HID_USAGE_X: neutral.AxisX = (int)mid; break; case HID_USAGES.HID_USAGE_Y: neutral.AxisY = (int)mid; break; case HID_USAGES.HID_USAGE_Z: neutral.AxisZ = (int)mid; break; case HID_USAGES.HID_USAGE_RX: neutral.AxisXRot = (int)mid; break; case HID_USAGES.HID_USAGE_RY: neutral.AxisYRot = (int)mid; break; case HID_USAGES.HID_USAGE_RZ: neutral.AxisZRot = (int)mid; break; case HID_USAGES.HID_USAGE_SL0: neutral.Slider = (int)mid; break; case HID_USAGES.HID_USAGE_SL1: neutral.Dial = (int)mid; break; case HID_USAGES.HID_USAGE_WHL: neutral.Wheel = (int)mid; break; } } } neutral.bHats = 0xFFFFFFFF; neutral.bHatsEx1 = 0xFFFFFFFF; neutral.bHatsEx2 = 0xFFFFFFFF; neutral.bHatsEx3 = 0xFFFFFFFF; _interface.UpdateVJD(id, ref neutral); _states.Add(id, neutral); _activeDirections.Add(id, new Dictionary<POVDirection, bool> { { POVDirection._1Up, false }, { POVDirection._1Down, false }, { POVDirection._1Left, false }, { POVDirection._1Right, false }, { POVDirection._2Up, false }, { POVDirection._2Down, false }, { POVDirection._2Left, false }, { POVDirection._2Right, false }, { POVDirection._3Up, false }, { POVDirection._3Down, false }, { POVDirection._3Left, false }, { POVDirection._3Right, false }, { POVDirection._4Up, false }, { POVDirection._4Down, false }, { POVDirection._4Left, false }, { POVDirection._4Right, false } }); } return result; } public void ReleaseDevice(uint id) { _states.Remove(id); _activeDirections.Remove(id); _interface.RelinquishVJD(id); } public void SetButton(int button, bool state, uint id) { if (_states.ContainsKey(id)) { var current = _states[id]; current.Buttons &= ~(1u << (button - 1)); if (state) { current.Buttons |= 1u << (button - 1); } _states[id] = current; } } public void SetAxis(HID_USAGES axis, float value, bool positive, uint id) { if (_states.ContainsKey(id) && _interface.GetVJDAxisExist(id, axis)) { // Y axis is inverted if (axis == HID_USAGES.HID_USAGE_Y) positive = !positive; var current = _states[id]; long max = 0; long min = 0; long mid = 0; if (!positive) value *= -1; _interface.GetVJDAxisMax(id, axis, ref max); _interface.GetVJDAxisMin(id, axis, ref min); mid = (max - min) / 2; float norm = value + 1f; norm /= 2f; int output = (int)Math.Round(Math.Min(Math.Max(max * norm - min, min), max)); if (Math.Abs(output - mid) < 4) output = (int)mid; // Set on the correct axis, only if current value matches switch (axis) { case HID_USAGES.HID_USAGE_X: if (SameDirection(mid, current.AxisX, positive)) { current.AxisX = output; } break; case HID_USAGES.HID_USAGE_Y: if (SameDirection(mid, current.AxisY, positive)) current.AxisY = output; break; case HID_USAGES.HID_USAGE_Z: if (SameDirection(mid, current.AxisZ, positive)) current.AxisZ = output; break; case HID_USAGES.HID_USAGE_RX: if (SameDirection(mid, current.AxisXRot, positive)) current.AxisXRot = output; break; case HID_USAGES.HID_USAGE_RY: if (SameDirection(mid, current.AxisYRot, positive)) current.AxisYRot = output; break; case HID_USAGES.HID_USAGE_RZ: if (SameDirection(mid, current.AxisZRot, positive)) current.AxisZRot = output; break; case HID_USAGES.HID_USAGE_SL0: if (SameDirection(mid, current.Slider, positive)) current.Slider = output; break; case HID_USAGES.HID_USAGE_SL1: if (SameDirection(mid, current.Dial, positive)) current.Dial = output; break; } _states[id] = current; } } protected bool SameDirection(long mid, int current, bool positive) { if (current == mid) return true; if (positive) { return current >= mid; } else { return current <= mid; } } public void SetPOV(int pov, POVDirection direction, bool state, uint id) { if (_states.ContainsKey(id) && _activeDirections.ContainsKey(id)) { _activeDirections[id][direction] = state; var current = _states[id]; var device = Devices.Find((d) => d.ID == id); uint value = 0xFF; if (device != null) { // If using a 4 direction POV Hat if (device.POV4Ds > 0) { string dir = direction.ToString().Substring(2); // If this direction is being released, look for another active direciton if (!state) { POVDirection d = POVDirection._1Up; if (Enum.TryParse("_" + pov + "Up", true, out d) && _activeDirections[id][d]) { dir = "Up"; } else if (Enum.TryParse("_" + pov + "Right", true, out d) && _activeDirections[id][d]) { dir = "Right"; } else if (Enum.TryParse("_" + pov + "Down", true, out d) && _activeDirections[id][d]) { dir = "Down"; } else if (Enum.TryParse("_" + pov + "Left", true, out d) && _activeDirections[id][d]) { dir = "Left"; } else { dir = "Neutral"; } } // Set the value based ont he direction to be applied switch (dir) { case "Up": value = 0x00; break; case "Right": value = 0x01; break; case "Down": value = 0x02; break; case "Left": value = 0x03; break; default: value = 0xFF; break; } // Set new Hat value var shift = ((pov - 1) * 4); current.bHats &= (0xFFFFFFFF & (uint)(0x00 << shift)); current.bHats |= (value << shift); } else { value = 0xFFFFFFFF; POVDirection d = POVDirection._1Up; bool up = false; bool left = false; bool down = false; bool right = false; if (Enum.TryParse("_" + pov + "Up", true, out d)) { up = _activeDirections[id][d]; } if (Enum.TryParse("_" + pov + "Right", true, out d)) { right = _activeDirections[id][d]; } if (Enum.TryParse("_" + pov + "Down", true, out d)) { down = _activeDirections[id][d]; } if (Enum.TryParse("_" + pov + "Left", true, out d)) { left = _activeDirections[id][d]; } if (state) { // New state takes priority string dir = direction.ToString().Substring(2); switch (dir) { case "Up": if (left) value = 31500; else if (right) value = 4500; else value = 0; break; case "Right": if (up) value = 4500; else if (down) value = 13500; else value = 9000; break; case "Down": if (right) value = 13500; else if (left) value = 22500; else value = 18000; break; case "Left": if (up) value = 31500; else if (down) value = 22500; else value = 27000; break; default: value = 0xFFFFFFFF; break; } } else { if (up) { if (left) value = 31500; else if (right) value = 4500; else value = 0; } else if (right) { // up & right already handled if (down) value = 13500; else value = 9000; } else if (down) { // down & right already handled if (left) value = 22500; else value = 18000; } else if (left) { // up & left, down & left already handled value = 27000; } else { value = 0xFFFFFFFF; } } // Set the new Hat value switch (pov) { case 1: current.bHats = value; break; case 2: current.bHatsEx1 = value; break; case 3: current.bHatsEx2 = value; break; case 4: current.bHatsEx3 = value; break; default: break; } } _states[id] = current; } } } public void ApplyAll() { foreach (var state in _states.ToArray()) { vJoy.JoystickState s = state.Value; _interface.UpdateVJD(state.Key, ref s); } } public void Apply(uint deviceId) { if (_states.ContainsKey(deviceId)) { vJoy.JoystickState s = _states[deviceId]; _interface.UpdateVJD(deviceId, ref s); } } public class JoyDevice { public uint ID { get; protected set; } public int Buttons { get; protected set; } public int POVs { get; protected set; } public int POV4Ds { get; protected set; } public bool hasX { get; protected set; } public bool hasY { get; protected set; } public bool hasZ { get; protected set; } public bool hasRx { get; protected set; } public bool hasRy { get; protected set; } public bool hasRz { get; protected set; } public bool hasSlider { get; protected set; } public bool hasSlider2 { get; protected set; } public bool ForceFeedback { get; protected set; } public List<string> Axes { get; protected set; } public JoyDevice(uint id) { ID = id; Buttons = _interface.GetVJDButtonNumber(id); POVs = _interface.GetVJDContPovNumber(id); POV4Ds = _interface.GetVJDDiscPovNumber(id); hasX = _interface.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_X); hasY = _interface.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Y); hasZ = _interface.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Z); hasRx = _interface.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RX); hasRy = _interface.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RY); hasRz = _interface.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RZ); hasSlider = _interface.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_SL0); hasSlider2 = _interface.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_SL1); ForceFeedback = _interface.IsDeviceFfb(id); Axes = new List<string>(); if (hasX) Axes.Add("X Axis"); if (hasY) Axes.Add("Y Axis"); if (hasZ) Axes.Add("Z Axis"); if (hasRx) Axes.Add("Rx Axis"); if (hasRy) Axes.Add("Ry Axis"); if (hasRz) Axes.Add("Rz Axis"); if (hasSlider) Axes.Add("Slider 1"); if (hasSlider2) Axes.Add("Slider 2"); } } public enum POVDirection { _1Up = 0, _1Down, _1Left, _1Right, _2Up, _2Down, _2Left, _2Right, _3Up, _3Down, _3Left, _3Right, _4Up, _4Down, _4Left, _4Right, } public enum AxisDirection { X_Pos = 0, X_Neg, Y_Pos, Y_Neg, Z_Pos, Z_Neg, RX_Pos, RX_Neg, RY_Pos, RY_Neg, RZ_Pos, RZ_Neg, SL0_Pos, SL0_Neg, SL1_Pos, SL1_Neg } } } <|start_filename|>Scp/XInput_Scp/pnp.cpp<|end_filename|> #include "StdAfx.h" BOOLEAN FindKnownHidDevices(OUT PHID_DEVICE* HidDevices, OUT PULONG NumberDevices) { HDEVINFO hardwareDeviceInfo; SP_DEVICE_INTERFACE_DATA deviceInfoData; ULONG i = 0; BOOLEAN done; PHID_DEVICE hidDeviceInst; GUID hidGuid; PSP_DEVICE_INTERFACE_DETAIL_DATA functionClassDeviceData = NULL; ULONG predictedLength = 0; ULONG requiredLength = 0; PHID_DEVICE newHidDevices; HidD_GetHidGuid(&hidGuid); *HidDevices = NULL; *NumberDevices = 0; // // Open a handle to the plug and play dev node. // hardwareDeviceInfo = SetupDiGetClassDevs(&hidGuid, NULL, // Define no enumerator (global) NULL, // Define no (DIGCF_PRESENT | // Only Devices present DIGCF_DEVICEINTERFACE)); // Function class devices. if (hardwareDeviceInfo == INVALID_HANDLE_VALUE) { return FALSE; } // // Take a wild guess to start // *NumberDevices = 4; done = FALSE; deviceInfoData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); while (!done) { *NumberDevices *= 2; if (*HidDevices) { newHidDevices = (PHID_DEVICE) realloc(*HidDevices, (*NumberDevices * sizeof(HID_DEVICE))); if (newHidDevices == NULL) { free(*HidDevices); } *HidDevices = newHidDevices; } else { *HidDevices = (PHID_DEVICE) calloc(*NumberDevices, sizeof(HID_DEVICE)); } if (*HidDevices == NULL) { SetupDiDestroyDeviceInfoList(hardwareDeviceInfo); return FALSE; } hidDeviceInst = *HidDevices + i; for (; i < *NumberDevices; i++, hidDeviceInst++) { if (SetupDiEnumDeviceInterfaces(hardwareDeviceInfo, 0, // No care about specific PDOs &hidGuid, i, &deviceInfoData)) { // // allocate a function class device data structure to receive the // goods about this particular device. // SetupDiGetDeviceInterfaceDetail( hardwareDeviceInfo, &deviceInfoData, NULL, // probing so no output buffer yet 0, // probing so output buffer length of zero &requiredLength, NULL); // not interested in the specific dev-node predictedLength = requiredLength; functionClassDeviceData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc(predictedLength); if (functionClassDeviceData) { functionClassDeviceData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); ZeroMemory(functionClassDeviceData->DevicePath, sizeof(functionClassDeviceData->DevicePath)); } else { SetupDiDestroyDeviceInfoList(hardwareDeviceInfo); return FALSE; } // // Retrieve the information from Plug and Play. // if (! SetupDiGetDeviceInterfaceDetail( hardwareDeviceInfo, &deviceInfoData, functionClassDeviceData, predictedLength, &requiredLength, NULL)) { SetupDiDestroyDeviceInfoList(hardwareDeviceInfo); free(functionClassDeviceData); return FALSE; } // // Open device with just generic query abilities to begin with // if (! OpenHidDevice(functionClassDeviceData->DevicePath, FALSE, // ReadAccess - none FALSE, // WriteAccess - none FALSE, // Overlapped - no FALSE, // Exclusive - no hidDeviceInst)) { SetupDiDestroyDeviceInfoList(hardwareDeviceInfo); free(functionClassDeviceData); return FALSE; } } else { if (GetLastError() == ERROR_NO_MORE_ITEMS) { done = TRUE; break; } } } } *NumberDevices = i; SetupDiDestroyDeviceInfoList(hardwareDeviceInfo); free(functionClassDeviceData); return TRUE; } BOOLEAN OpenHidDevice(IN LPTSTR DevicePath, IN BOOL HasReadAccess, IN BOOL HasWriteAccess, IN BOOL IsOverlapped, IN BOOL IsExclusive, __inout PHID_DEVICE HidDevice) { DWORD accessFlags = 0; DWORD sharingFlags = 0; INT iDevicePathSize; if (DevicePath == NULL) { return FALSE; } iDevicePathSize = (INT) (_tcslen(DevicePath) + 1) * sizeof(TCHAR); HidDevice->DevicePath = (PTCHAR) malloc(iDevicePathSize); if (HidDevice->DevicePath == NULL) { return FALSE; } StringCbCopy(HidDevice->DevicePath, iDevicePathSize, DevicePath); if (HasReadAccess ) accessFlags |= GENERIC_READ; if (HasWriteAccess) accessFlags |= GENERIC_WRITE; if (!IsExclusive ) sharingFlags = FILE_SHARE_READ | FILE_SHARE_WRITE; HidDevice->HidDevice = CreateFile(DevicePath, accessFlags, sharingFlags, NULL, OPEN_EXISTING, 0, NULL); if (HidDevice->HidDevice == INVALID_HANDLE_VALUE) { free(HidDevice->DevicePath); HidDevice->DevicePath = NULL; return FALSE; } HidDevice->OpenedForRead = HasReadAccess; HidDevice->OpenedForWrite = HasWriteAccess; HidDevice->OpenedOverlapped = IsOverlapped; HidDevice->OpenedExclusive = IsExclusive; if (!HidD_GetPreparsedData(HidDevice->HidDevice, &HidDevice->Ppd)) { free(HidDevice->DevicePath); HidDevice->DevicePath = NULL; CloseHandle(HidDevice->HidDevice); HidDevice->HidDevice = INVALID_HANDLE_VALUE; return FALSE; } if (!HidD_GetAttributes(HidDevice->HidDevice, &HidDevice->Attributes)) { free(HidDevice->DevicePath); HidDevice->DevicePath = NULL; CloseHandle(HidDevice->HidDevice); HidDevice->HidDevice = INVALID_HANDLE_VALUE; HidD_FreePreparsedData(HidDevice->Ppd); HidDevice->Ppd = NULL; return FALSE; } if (!HidP_GetCaps(HidDevice->Ppd, &HidDevice->Caps)) { free(HidDevice->DevicePath); HidDevice->DevicePath = NULL; CloseHandle(HidDevice->HidDevice); HidDevice->HidDevice = INVALID_HANDLE_VALUE; HidD_FreePreparsedData(HidDevice->Ppd); HidDevice->Ppd = NULL; return FALSE; } if (!FillDeviceInfo(HidDevice)) { CloseHidDevice(HidDevice); return FALSE; } if (IsOverlapped) { CloseHandle(HidDevice->HidDevice); HidDevice->HidDevice = CreateFile(DevicePath, accessFlags, sharingFlags, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (HidDevice->HidDevice == INVALID_HANDLE_VALUE) { CloseHidDevice(HidDevice); return FALSE; } } return TRUE; } BOOLEAN FillDeviceInfo(IN PHID_DEVICE HidDevice) { ULONG numValues; USHORT numCaps; PHIDP_BUTTON_CAPS buttonCaps; PHIDP_VALUE_CAPS valueCaps; PHID_DATA data; ULONG i; USAGE usage; UINT dataIdx; ULONG newFeatureDataLength; ULONG tmpSum; HidDevice->InputReportBuffer = (PCHAR) calloc(HidDevice->Caps.InputReportByteLength, sizeof(CHAR)); HidDevice->InputButtonCaps = buttonCaps = (PHIDP_BUTTON_CAPS) calloc(HidDevice->Caps.NumberInputButtonCaps, sizeof(HIDP_BUTTON_CAPS)); if (buttonCaps == NULL) { return FALSE; } HidDevice->InputValueCaps = valueCaps = (PHIDP_VALUE_CAPS) calloc(HidDevice->Caps.NumberInputValueCaps, sizeof(HIDP_VALUE_CAPS)); if (valueCaps == NULL) { return FALSE; } numCaps = HidDevice->Caps.NumberInputButtonCaps; if(numCaps > 0) { if(HidP_GetButtonCaps(HidP_Input, buttonCaps, &numCaps, HidDevice->Ppd) != HIDP_STATUS_SUCCESS) { return FALSE; } } numCaps = HidDevice->Caps.NumberInputValueCaps; if(numCaps > 0) { if(HidP_GetValueCaps(HidP_Input, valueCaps, &numCaps, HidDevice->Ppd) != HIDP_STATUS_SUCCESS) { return FALSE; } } numValues = 0; for (i = 0; i < HidDevice->Caps.NumberInputValueCaps; i++, valueCaps++) { if (valueCaps->IsRange) { numValues += valueCaps->Range.UsageMax - valueCaps->Range.UsageMin + 1; if(valueCaps->Range.UsageMin >= valueCaps->Range.UsageMax + (HidDevice->Caps).NumberInputButtonCaps) { return FALSE; } } else { numValues++; } } valueCaps = HidDevice->InputValueCaps; HidDevice->InputDataLength = HidDevice->Caps.NumberInputButtonCaps + numValues; HidDevice->InputData = data = (PHID_DATA) calloc(HidDevice->InputDataLength, sizeof(HID_DATA)); if (data == NULL) { return FALSE; } dataIdx = 0; for (i = 0; i < HidDevice->Caps.NumberInputButtonCaps; i++, data++, buttonCaps++, dataIdx++) { data->IsButtonData = TRUE; data->Status = HIDP_STATUS_SUCCESS; data->UsagePage = buttonCaps->UsagePage; if (buttonCaps->IsRange) { data->ButtonData.UsageMin = buttonCaps->Range.UsageMin; data->ButtonData.UsageMax = buttonCaps->Range.UsageMax; } else { data->ButtonData.UsageMin = data->ButtonData.UsageMax = buttonCaps->NotRange.Usage; } data->ButtonData.MaxUsageLength = HidP_MaxUsageListLength(HidP_Input, buttonCaps->UsagePage, HidDevice->Ppd); data->ButtonData.Usages = (PUSAGE) calloc(data->ButtonData.MaxUsageLength, sizeof(USAGE)); data->ReportID = buttonCaps->ReportID; } for (i = 0; i < HidDevice->Caps.NumberInputValueCaps ; i++, valueCaps++) { if (valueCaps->IsRange) { for (usage = valueCaps->Range.UsageMin; usage <= valueCaps->Range.UsageMax; usage++) { if(dataIdx >= HidDevice->InputDataLength) { return FALSE; } data->IsButtonData = FALSE; data->Status = HIDP_STATUS_SUCCESS; data->UsagePage = valueCaps->UsagePage; data->ValueData.Usage = usage; data->ReportID = valueCaps->ReportID; data++; dataIdx++; } } else { if(dataIdx >= HidDevice->InputDataLength) { return FALSE; } data->IsButtonData = FALSE; data->Status = HIDP_STATUS_SUCCESS; data->UsagePage = valueCaps->UsagePage; data->ValueData.Usage = valueCaps->NotRange.Usage; data->ReportID = valueCaps->ReportID; data++; dataIdx++; } } HidDevice->OutputReportBuffer = (PCHAR) calloc(HidDevice->Caps.OutputReportByteLength, sizeof(CHAR)); HidDevice->OutputButtonCaps = buttonCaps = (PHIDP_BUTTON_CAPS) calloc(HidDevice->Caps.NumberOutputButtonCaps, sizeof(HIDP_BUTTON_CAPS)); if (buttonCaps == NULL) { return FALSE; } HidDevice->OutputValueCaps = valueCaps = (PHIDP_VALUE_CAPS) calloc(HidDevice->Caps.NumberOutputValueCaps, sizeof(HIDP_VALUE_CAPS)); if (valueCaps == NULL) { return FALSE; } numCaps = HidDevice->Caps.NumberOutputButtonCaps; if(numCaps > 0) { if(HidP_GetButtonCaps(HidP_Output, buttonCaps, &numCaps, HidDevice->Ppd) != HIDP_STATUS_SUCCESS) { return FALSE; } } numCaps = HidDevice->Caps.NumberOutputValueCaps; if(numCaps > 0) { if(HidP_GetValueCaps(HidP_Output, valueCaps, &numCaps, HidDevice->Ppd) != HIDP_STATUS_SUCCESS) { return FALSE; } } numValues = 0; for (i = 0; i < HidDevice->Caps.NumberOutputValueCaps; i++, valueCaps++) { if (valueCaps->IsRange) { numValues += valueCaps->Range.UsageMax - valueCaps->Range.UsageMin + 1; } else { numValues++; } } valueCaps = HidDevice->OutputValueCaps; HidDevice->OutputDataLength = HidDevice->Caps.NumberOutputButtonCaps + numValues; HidDevice->OutputData = data = (PHID_DATA) calloc(HidDevice->OutputDataLength, sizeof(HID_DATA)); if (data == NULL) { return FALSE; } for (i = 0; i < HidDevice->Caps.NumberOutputButtonCaps; i++, data++, buttonCaps++) { if (i >= HidDevice->OutputDataLength) { return FALSE; } if(FAILED(ULongAdd(HidDevice->Caps.NumberOutputButtonCaps, valueCaps->Range.UsageMax, &tmpSum))) { return FALSE; } if(valueCaps->Range.UsageMin == tmpSum) { return FALSE; } data->IsButtonData = TRUE; data->Status = HIDP_STATUS_SUCCESS; data->UsagePage = buttonCaps->UsagePage; if (buttonCaps->IsRange) { data->ButtonData.UsageMin = buttonCaps->Range.UsageMin; data->ButtonData.UsageMax = buttonCaps->Range.UsageMax; } else { data->ButtonData.UsageMin = data->ButtonData.UsageMax = buttonCaps->NotRange.Usage; } data->ButtonData.MaxUsageLength = HidP_MaxUsageListLength(HidP_Output, buttonCaps->UsagePage, HidDevice->Ppd); data->ButtonData.Usages = (PUSAGE) calloc(data->ButtonData.MaxUsageLength, sizeof(USAGE)); data->ReportID = buttonCaps->ReportID; } for (i = 0; i < HidDevice->Caps.NumberOutputValueCaps ; i++, valueCaps++) { if (valueCaps->IsRange) { for (usage = valueCaps->Range.UsageMin; usage <= valueCaps->Range.UsageMax; usage++) { data->IsButtonData = FALSE; data->Status = HIDP_STATUS_SUCCESS; data->UsagePage = valueCaps->UsagePage; data->ValueData.Usage = usage; data->ReportID = valueCaps->ReportID; data++; } } else { data->IsButtonData = FALSE; data->Status = HIDP_STATUS_SUCCESS; data->UsagePage = valueCaps->UsagePage; data->ValueData.Usage = valueCaps->NotRange.Usage; data->ReportID = valueCaps->ReportID; data++; } } HidDevice->FeatureReportBuffer = (PCHAR) calloc(HidDevice->Caps.FeatureReportByteLength, sizeof(CHAR)); HidDevice->FeatureButtonCaps = buttonCaps = (PHIDP_BUTTON_CAPS) calloc(HidDevice->Caps.NumberFeatureButtonCaps, sizeof(HIDP_BUTTON_CAPS)); if (buttonCaps == NULL) { return FALSE; } HidDevice->FeatureValueCaps = valueCaps = (PHIDP_VALUE_CAPS) calloc(HidDevice->Caps.NumberFeatureValueCaps, sizeof(HIDP_VALUE_CAPS)); if (valueCaps == NULL) { return FALSE; } numCaps = HidDevice->Caps.NumberFeatureButtonCaps; if(numCaps > 0) { if(HidP_GetButtonCaps(HidP_Feature, buttonCaps, &numCaps, HidDevice->Ppd) != HIDP_STATUS_SUCCESS) { return FALSE; } } numCaps = HidDevice->Caps.NumberFeatureValueCaps; if(numCaps > 0) { if(HidP_GetValueCaps(HidP_Feature, valueCaps, &numCaps, HidDevice->Ppd) != HIDP_STATUS_SUCCESS) { return FALSE; } } numValues = 0; for (i = 0; i < HidDevice->Caps.NumberFeatureValueCaps; i++, valueCaps++) { if (valueCaps->IsRange) { numValues += valueCaps->Range.UsageMax - valueCaps->Range.UsageMin + 1; } else { numValues++; } } valueCaps = HidDevice->FeatureValueCaps; if(FAILED(ULongAdd(HidDevice->Caps.NumberFeatureButtonCaps, numValues, &newFeatureDataLength))) { return FALSE; } HidDevice->FeatureDataLength = newFeatureDataLength; HidDevice->FeatureData = data = (PHID_DATA) calloc(HidDevice->FeatureDataLength, sizeof(HID_DATA)); if (data == NULL) { return FALSE; } dataIdx = 0; for (i = 0; i < HidDevice->Caps.NumberFeatureButtonCaps; i++, data++, buttonCaps++, dataIdx++) { data->IsButtonData = TRUE; data->Status = HIDP_STATUS_SUCCESS; data->UsagePage = buttonCaps->UsagePage; if (buttonCaps->IsRange) { data->ButtonData.UsageMin = buttonCaps->Range.UsageMin; data->ButtonData.UsageMax = buttonCaps->Range.UsageMax; } else { data->ButtonData.UsageMin = data->ButtonData.UsageMax = buttonCaps->NotRange.Usage; } data->ButtonData.MaxUsageLength = HidP_MaxUsageListLength(HidP_Feature, buttonCaps->UsagePage, HidDevice->Ppd); data->ButtonData.Usages = (PUSAGE) calloc(data->ButtonData.MaxUsageLength, sizeof(USAGE)); data->ReportID = buttonCaps->ReportID; } for (i = 0; i < HidDevice->Caps.NumberFeatureValueCaps ; i++, valueCaps++) { if (valueCaps->IsRange) { for (usage = valueCaps->Range.UsageMin; usage <= valueCaps->Range.UsageMax; usage++) { if(dataIdx >= HidDevice->FeatureDataLength) { return FALSE; } data->IsButtonData = FALSE; data->Status = HIDP_STATUS_SUCCESS; data->UsagePage = valueCaps->UsagePage; data->ValueData.Usage = usage; data->ReportID = valueCaps->ReportID; data++; dataIdx++; } } else { if(dataIdx >= HidDevice->FeatureDataLength) { return FALSE; } data->IsButtonData = FALSE; data->Status = HIDP_STATUS_SUCCESS; data->UsagePage = valueCaps->UsagePage; data->ValueData.Usage = valueCaps->NotRange.Usage; data->ReportID = valueCaps->ReportID; data++; dataIdx++; } } return TRUE; } VOID CloseHidDevices(IN PHID_DEVICE HidDevices, IN ULONG NumberDevices) { for (ULONG Index = 0; Index < NumberDevices; Index++) { CloseHidDevice(&HidDevices[Index]); } } VOID CloseHidDevice(IN PHID_DEVICE HidDevice) { if (HidDevice->DevicePath != NULL) { free(HidDevice->DevicePath); HidDevice->DevicePath = NULL; } if (HidDevice->HidDevice != INVALID_HANDLE_VALUE) { CloseHandle(HidDevice->HidDevice); HidDevice->HidDevice = INVALID_HANDLE_VALUE; } if (HidDevice->Ppd != NULL) { HidD_FreePreparsedData(HidDevice->Ppd); HidDevice->Ppd = NULL; } if (HidDevice->InputReportBuffer != NULL) { free(HidDevice->InputReportBuffer); HidDevice->InputReportBuffer = NULL; } if (HidDevice->InputData != NULL) { free(HidDevice->InputData); HidDevice->InputData = NULL; } if (HidDevice->InputButtonCaps != NULL) { free(HidDevice->InputButtonCaps); HidDevice->InputButtonCaps = NULL; } if (HidDevice->InputValueCaps != NULL) { free(HidDevice->InputValueCaps); HidDevice->InputValueCaps = NULL; } if (HidDevice->OutputReportBuffer != NULL) { free(HidDevice->OutputReportBuffer); HidDevice->OutputReportBuffer = NULL; } if (HidDevice->OutputData != NULL) { free(HidDevice->OutputData); HidDevice->OutputData = NULL; } if (HidDevice->OutputButtonCaps != NULL) { free(HidDevice->OutputButtonCaps); HidDevice->OutputButtonCaps = NULL; } if (HidDevice->OutputValueCaps != NULL) { free(HidDevice->OutputValueCaps); HidDevice->OutputValueCaps = NULL; } if (HidDevice->FeatureReportBuffer != NULL) { free(HidDevice->FeatureReportBuffer); HidDevice->FeatureReportBuffer = NULL; } if (HidDevice->FeatureData != NULL) { free(HidDevice->FeatureData); HidDevice->FeatureData = NULL; } if (HidDevice->FeatureButtonCaps != NULL) { free(HidDevice->FeatureButtonCaps); HidDevice->FeatureButtonCaps = NULL; } if (HidDevice->FeatureValueCaps != NULL) { free(HidDevice->FeatureValueCaps); HidDevice->FeatureValueCaps = NULL; } return; } <|start_filename|>WiinUPro/Controls/GameCubeControl.xaml.cs<|end_filename|> using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using NintrollerLib; using Shared; namespace WiinUPro { /// <summary> /// Interaction logic for GameCubeControl.xaml /// </summary> public partial class GameCubeControl : BaseControl, INintyControl { public event Delegates.BoolArrDel OnChangeLEDs; public event Delegates.JoystickDel OnJoyCalibrated; public event Delegates.TriggerDel OnTriggerCalibrated; public event Action<int> OnSelectedPortChanged; protected Windows.JoyCalibrationWindow _openJoyWindow = null; protected Windows.TriggerCalibrationWindow _openTrigWindow = null; protected string _calibrationTarget = ""; protected GameCubeAdapter _lastState; protected GameCubePort _activePort = GameCubePort.PORT1; private string _connectedStatus; private string _disconnectedStatus; protected enum GameCubePort { PORT1 = 1, PORT2 = 2, PORT3 = 3, PORT4 = 4 } public GameCubeControl() { _inputPrefix = "1_"; _connectedStatus = Globalization.Translate("Controller_Connected"); _disconnectedStatus = Globalization.Translate("Controller_Disconnect"); InitializeComponent(); for (int i = 0; i < 4; ++i) (portSelection.Items[i] as MenuItem).Header = Globalization.TranslateFormat("GCN_Port", i); } public GameCubeControl(string deviceId) : this() { DeviceID = deviceId; } public void ApplyInput(INintrollerState state) { // Maybe one day I will remember what this was for or just remove it } public void UpdateVisual(INintrollerState state) { if (state is GameCubeAdapter gcn) { _lastState = gcn; GameCubeController activePort; bool connecited = GetActivePort(out activePort); A.Opacity = activePort.A ? 1 : 0; B.Opacity = activePort.B ? 1 : 0; X.Opacity = activePort.X ? 1 : 0; Y.Opacity = activePort.Y ? 1 : 0; Z.Opacity = activePort.Z ? 1 : 0; START.Opacity = activePort.Start ? 1 : 0; dpadUp.Opacity = activePort.Up ? 1 : 0; dpadDown.Opacity = activePort.Down ? 1 : 0; dpadLeft.Opacity = activePort.Left ? 1 : 0; dpadRight.Opacity = activePort.Right ? 1 : 0; L.Opacity = activePort.L.value > 0 ? 1 : 0; R.Opacity = activePort.R.value > 0 ? 1 : 0; var lOpacityMask = L.OpacityMask as LinearGradientBrush; if (lOpacityMask != null && lOpacityMask.GradientStops.Count == 2) { double offset = 1 - System.Math.Min(1, activePort.L.value); lOpacityMask.GradientStops[0].Offset = offset; lOpacityMask.GradientStops[1].Offset = offset; } var rOpacityMask = R.OpacityMask as LinearGradientBrush; if (rOpacityMask != null && rOpacityMask.GradientStops.Count == 2) { double offset = 1 - System.Math.Min(1, activePort.R.value); rOpacityMask.GradientStops[0].Offset = offset; rOpacityMask.GradientStops[1].Offset = offset; } joystick.Margin = new Thickness(190 + 100 * activePort.joystick.X, 272 - 100 * activePort.joystick.Y, 0, 0); cStick.Margin = new Thickness(887 + 100 * activePort.cStick.X, 618 - 100 * activePort.cStick.Y, 0, 0); connectionStatus.Content = connecited ? _connectedStatus : _disconnectedStatus; if (_openJoyWindow != null) { if (_calibrationTarget == "joy") _openJoyWindow.Update(activePort.joystick); else if (_calibrationTarget == "cStk") _openJoyWindow.Update(activePort.cStick); } else if (_openTrigWindow != null) { if (_calibrationTarget == "L") _openTrigWindow.Update(activePort.L); else if (_calibrationTarget == "R") _openTrigWindow.Update(activePort.R); } } } public void SetInputTooltip(string inputName, string tooltip) { if (!inputName.StartsWith(_inputPrefix)) return; switch (inputName.Substring(_inputPrefix.Length)) { case INPUT_NAMES.GCN_CONTROLLER.A: A.ToolTip = tooltip; break; case INPUT_NAMES.GCN_CONTROLLER.B: B.ToolTip = tooltip; break; case INPUT_NAMES.GCN_CONTROLLER.X: X.ToolTip = tooltip; break; case INPUT_NAMES.GCN_CONTROLLER.Y: Y.ToolTip = tooltip; break; case INPUT_NAMES.GCN_CONTROLLER.Z: Z.ToolTip = tooltip; break; case INPUT_NAMES.GCN_CONTROLLER.START: START.ToolTip = tooltip; break; case INPUT_NAMES.GCN_CONTROLLER.LT: UpdateTooltipLine(L, tooltip, 0); break; case INPUT_NAMES.GCN_CONTROLLER.LFULL: UpdateTooltipLine(L, tooltip, 1); break; case INPUT_NAMES.GCN_CONTROLLER.RT: UpdateTooltipLine(R, tooltip, 0); break; case INPUT_NAMES.GCN_CONTROLLER.RFULL: UpdateTooltipLine(R, tooltip, 1); break; case INPUT_NAMES.GCN_CONTROLLER.JOY_UP: UpdateTooltipLine(joystick, tooltip, 0); break; case INPUT_NAMES.GCN_CONTROLLER.JOY_LEFT: UpdateTooltipLine(joystick, tooltip, 1); break; case INPUT_NAMES.GCN_CONTROLLER.JOY_RIGHT: UpdateTooltipLine(joystick, tooltip, 2); break; case INPUT_NAMES.GCN_CONTROLLER.JOY_DOWN: UpdateTooltipLine(joystick, tooltip, 3); break; case INPUT_NAMES.GCN_CONTROLLER.C_UP: UpdateTooltipLine(cStick, tooltip, 0); break; case INPUT_NAMES.GCN_CONTROLLER.C_LEFT: UpdateTooltipLine(cStick, tooltip, 1); break; case INPUT_NAMES.GCN_CONTROLLER.C_RIGHT: UpdateTooltipLine(cStick, tooltip, 2); break; case INPUT_NAMES.GCN_CONTROLLER.C_DOWN: UpdateTooltipLine(cStick, tooltip, 3); break; case INPUT_NAMES.GCN_CONTROLLER.UP: dpadUp.ToolTip = tooltip; UpdateTooltipLine(dpadCenter, tooltip, 0); break; case INPUT_NAMES.GCN_CONTROLLER.LEFT: dpadLeft.ToolTip = tooltip; UpdateTooltipLine(dpadCenter, tooltip, 1); break; case INPUT_NAMES.GCN_CONTROLLER.RIGHT: dpadRight.ToolTip = tooltip; UpdateTooltipLine(dpadCenter, tooltip, 2); break; case INPUT_NAMES.GCN_CONTROLLER.DOWN: dpadDown.ToolTip = tooltip; UpdateTooltipLine(dpadCenter, tooltip, 3); break; } } public void ClearTooltips() { string unsetText = Globalization.Translate("Input_Unset"); A.ToolTip = unsetText; B.ToolTip = unsetText; X.ToolTip = unsetText; Y.ToolTip = unsetText; Z.ToolTip = unsetText; START.ToolTip = unsetText; dpadUp.ToolTip = unsetText; dpadLeft.ToolTip = unsetText; dpadRight.ToolTip = unsetText; dpadDown.ToolTip = unsetText; UpdateTooltipLine(L, unsetText, 0); UpdateTooltipLine(L, unsetText, 1); UpdateTooltipLine(R, unsetText, 0); UpdateTooltipLine(R, unsetText, 1); UpdateTooltipLine(joystick, unsetText, 0); UpdateTooltipLine(joystick, unsetText, 1); UpdateTooltipLine(joystick, unsetText, 2); UpdateTooltipLine(joystick, unsetText, 3); UpdateTooltipLine(cStick, unsetText, 0); UpdateTooltipLine(cStick, unsetText, 1); UpdateTooltipLine(cStick, unsetText, 2); UpdateTooltipLine(cStick, unsetText, 3); UpdateTooltipLine(dpadCenter, unsetText, 0); UpdateTooltipLine(dpadCenter, unsetText, 1); UpdateTooltipLine(dpadCenter, unsetText, 2); UpdateTooltipLine(dpadCenter, unsetText, 3); } public void ChangeLEDs(bool one, bool two, bool three, bool four) { // Doesn't use LEDs } private bool GetActivePort(out GameCubeController controller) { switch (_activePort) { default: case GameCubePort.PORT1: controller = _lastState.port1; return _lastState.port1Connected; case GameCubePort.PORT2: controller = _lastState.port2; return _lastState.port2Connected; case GameCubePort.PORT3: controller = _lastState.port3; return _lastState.port3Connected; case GameCubePort.PORT4: controller = _lastState.port4; return _lastState.port4Connected; } } protected override void CalibrateInput(string inputName) { if (inputName == _inputPrefix + R.Tag.ToString()) CalibrateTrigger(true); else if (inputName == _inputPrefix + L.Tag.ToString()) CalibrateTrigger(false); else if (inputName == _inputPrefix + joystick.Tag.ToString()) CalibrateJoystick(false); else if (inputName == _inputPrefix + cStick.Tag.ToString()) CalibrateJoystick(true); } private void CalibrateJoystick(bool cStick) { GameCubeController controller; GetActivePort(out controller); var nonCalibrated = new NintrollerLib.Joystick(); var curCalibrated = new NintrollerLib.Joystick(); if (cStick) { _calibrationTarget = "cStk"; nonCalibrated = Calibrations.None.GameCubeControllerRaw.cStick; curCalibrated = controller.cStick; } else { _calibrationTarget = "joy"; nonCalibrated = Calibrations.None.GameCubeControllerRaw.joystick; curCalibrated = controller.joystick; } Windows.JoyCalibrationWindow joyCal = new Windows.JoyCalibrationWindow(nonCalibrated, curCalibrated); _openJoyWindow = joyCal; #if DEBUG // Don't use show dialog so dummy values can be modified if (DeviceID?.StartsWith("Dummy") ?? false) { joyCal.Closed += (obj, args) => { if (joyCal.Apply) { OnJoyCalibrated?.Invoke(joyCal.Calibration, _calibrationTarget, joyCal.FileName); } _openJoyWindow = null; }; joyCal.Show(); return; } #endif joyCal.ShowDialog(); if (joyCal.Apply) { OnJoyCalibrated?.Invoke(joyCal.Calibration, _calibrationTarget, joyCal.FileName); } _openJoyWindow = null; joyCal = null; } private void CalibrateTrigger(bool rightTrigger) { GameCubeController controller; GetActivePort(out controller); var nonCalibrated = new NintrollerLib.Trigger(); var curCalibrated = new NintrollerLib.Trigger(); if (rightTrigger) { _calibrationTarget = "R"; nonCalibrated = Calibrations.None.GameCubeControllerRaw.R; curCalibrated = controller.R; } else { _calibrationTarget = "L"; nonCalibrated = Calibrations.None.GameCubeControllerRaw.L; curCalibrated = controller.L; } Windows.TriggerCalibrationWindow trigCal = new Windows.TriggerCalibrationWindow(nonCalibrated, curCalibrated); _openTrigWindow = trigCal; #if DEBUG // Don't use show dialog so dummy values can be modified if (DeviceID?.StartsWith("Dummy") ?? false) { trigCal.Closed += (obj, args) => { if (trigCal.Apply) { OnTriggerCalibrated?.Invoke(trigCal.Calibration, _calibrationTarget, trigCal.FileName); } _openTrigWindow = null; }; trigCal.Show(); return; } #endif trigCal.ShowDialog(); if (trigCal.Apply) { OnTriggerCalibrated?.Invoke(trigCal.Calibration, _calibrationTarget, trigCal.FileName); } _openTrigWindow = null; trigCal = null; } private void portSelection_SelectionChanged(object sender, SelectionChangedEventArgs e) { switch (portSelection.SelectedIndex) { default: case 0: _activePort = GameCubePort.PORT1; break; case 1: _activePort = GameCubePort.PORT2; break; case 2: _activePort = GameCubePort.PORT3; break; case 3: _activePort = GameCubePort.PORT4; break; } _inputPrefix = ((int)_activePort).ToString() + "_"; OnSelectedPortChanged?.Invoke((int)_activePort); } } } <|start_filename|>Scp/XInput_Scp/stdafx.h<|end_filename|> #pragma once #include "targetver.h" #define STRICT #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <basetyps.h> #include <tchar.h> #include <stdlib.h> #include <wtypes.h> #include <strsafe.h> #include <intsafe.h> #include <process.h> #include <CGuid.h> #include <windef.h> #include <XInput.h> #include <WinSock2.h> #pragma warning(push) #pragma warning(disable : 4995) #include <string> #pragma warning(pop) typedef std::basic_string<TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR>> _tstring; #define XINPUT_GAMEPAD_GUIDE 0x400 #include "XInput_SCP.h" #include "XInput_Wrap.h" #include "LibUsbApi.h" extern "C" { #include "hid.h" } #include "SCPController.h" #include "BTConnection.h" #include "DS2Controller.h" #include "DS3Controller.h" #include "SL3Controller.h" #include "X360Controller.h" <|start_filename|>WiinUSoft/Windows/CalDefaultWindow.xaml.cs<|end_filename|> using System.Windows; namespace WiinUSoft.Windows { /// <summary> /// Interaction logic for CalDefaultWindow.xaml /// </summary> public partial class CalDefaultWindow : Window { public CalDefaultWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { if (UserPrefs.Instance.defaultProperty != null) { switch (UserPrefs.Instance.defaultProperty.calPref) { case Property.CalibrationPreference.Minimal: radioMin.IsChecked = true; break; case Property.CalibrationPreference.Default: radioDefault.IsChecked = true; break; case Property.CalibrationPreference.More: radioMod.IsChecked = true; break; case Property.CalibrationPreference.Extra: radioExt.IsChecked = true; break; } } foreach (var pref in UserPrefs.Instance.devicePrefs) { if (pref.hid != "all") copyCombo.Items.Add(pref.name); } if (copyCombo.Items.Count > 0) { radioCopy.IsEnabled = true; copyCombo.IsEnabled = true; copyCombo.SelectedIndex = 0; } } private void saveBtn_Click(object sender, RoutedEventArgs e) { Property prop = new Property(); prop.hid = "all"; prop.name = "Default"; if (radioDefault.IsChecked ?? false) { prop.calPref = Property.CalibrationPreference.Default; } else if (radioMin.IsChecked ?? false) { prop.calPref = Property.CalibrationPreference.Minimal; } else if (radioMod.IsChecked ?? false) { prop.calPref = Property.CalibrationPreference.More; } else if (radioExt.IsChecked ?? false) { prop.calPref = Property.CalibrationPreference.Extra; } else if (radioCopy.IsChecked ?? false) { prop.calPref = Property.CalibrationPreference.Custom; var copy = UserPrefs.Instance.devicePrefs[copyCombo.SelectedIndex]; prop.autoConnect = copy.autoConnect; prop.autoNum = copy.autoNum; prop.calString = copy.calString; prop.rumbleIntensity = copy.rumbleIntensity; prop.useRumble = copy.useRumble; } UserPrefs.Instance.defaultProperty = prop; UserPrefs.SavePrefs(); Close(); } private void clearBtn_Click(object sender, RoutedEventArgs e) { UserPrefs.Instance.devicePrefs.Remove(UserPrefs.Instance.defaultProperty); UserPrefs.Instance.defaultProfile = null; UserPrefs.SavePrefs(); Close(); } } } <|start_filename|>WiinUSoft/Inputs/Xbox360.cs<|end_filename|> namespace WiinUSoft.Inputs { public static class Xbox360 { public const string A = "xA"; public const string B = "xB"; public const string X = "xX"; public const string Y = "xY"; public const string UP = "xUP"; public const string DOWN = "xDOWN"; public const string LEFT = "xLEFT"; public const string RIGHT = "xRIGHT"; public const string LB = "xLB"; public const string RB = "xRB"; public const string LT = "xLT"; public const string RT = "xRT"; //public const string LX = "LX"; //public const string LY = "LY"; //public const string RX = "RX"; //public const string RY = "RY"; public const string LUP = "xLUP"; public const string LDOWN = "xLDOWN"; public const string LLEFT = "xLLEFT"; public const string LRIGHT = "xLRIGHT"; public const string RUP = "xRUP"; public const string RDOWN = "xRDOWN"; public const string RLEFT = "xRLEFT"; public const string RRIGHT = "xRRIGHT"; public const string LS = "xLS"; public const string RS = "xRS"; public const string BACK = "xBACK"; public const string START = "xSTART"; public const string GUIDE = "xGUIDE"; } } <|start_filename|>Scp/ScpMonitor/Properties/AssemblyInfo.cs<|end_filename|> using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ScpMonitor")] [assembly: AssemblyProduct("ScpMonitor")] [assembly: Guid("85966027-b1d8-4a14-bc29-36f9091db86b")] <|start_filename|>WiinUPro/Windows/RumbleWindow.xaml.cs<|end_filename|> using Shared; using System.Windows; namespace WiinUPro.Windows { /// <summary> /// Interaction logic for RumbleWindow.xaml /// </summary> public partial class RumbleWindow : Window { public bool[] Result { get; protected set; } public RumbleWindow() { InitializeComponent(); Result = new bool[4]; } public RumbleWindow(bool[] subscriptions) : this() { if (subscriptions.Length >= 4) { xDeviceA.IsChecked = subscriptions[0]; xDeviceB.IsChecked = subscriptions[1]; xDeviceC.IsChecked = subscriptions[2]; xDeviceD.IsChecked = subscriptions[3]; Result = subscriptions; } } private void acceptBtn_Click(object sender, RoutedEventArgs e) { Result[0] = xDeviceA.IsChecked ?? false; Result[1] = xDeviceB.IsChecked ?? false; Result[2] = xDeviceC.IsChecked ?? false; Result[3] = xDeviceD.IsChecked ?? false; Close(); } private void Window_Loaded(object sender, RoutedEventArgs e) { Globalization.ApplyTranslations(this); } } } <|start_filename|>Shared/Delegates.cs<|end_filename|> namespace Shared { public static class Delegates { public delegate void BoolArrDel(bool[] arr); public delegate void StringDel(string str); public delegate void StringArrDel(string[] str); public delegate void JoystickDel(NintrollerLib.Joystick joy, string target, string file = ""); public delegate void TriggerDel(NintrollerLib.Trigger trig, string target, string file = ""); public delegate DeviceInfo ObtainDeviceInfo(); } } <|start_filename|>Shared/CommonStream.cs<|end_filename|> using System.IO; namespace Shared { public abstract class CommonStream : Stream { public abstract bool OpenConnection(); } } <|start_filename|>Scp/XInput_Scp/DS2Controller.h<|end_filename|> #pragma once // Play.com USB Adapter only (vid_0b43&pid_0003) class CDS2Controller : public CSCPController { public: static const DWORD CollectionSize = 2; public: CDS2Controller(DWORD dwIndex); virtual DWORD GetExtended(DWORD dwUserIndex, SCP_EXTN *Pressure); protected: virtual void FormatReport(void); virtual void XInputMapState(void); }; <|start_filename|>Nintroller/Utils.cs<|end_filename|> namespace NintrollerLib { internal static class Utils { internal static bool ReportContainsCoreButtons(InputReport reportType) { switch (reportType) { case InputReport.ReadMem: case InputReport.Acknowledge: case InputReport.BtnsOnly: case InputReport.BtnsAcc: case InputReport.BtnsExt: case InputReport.BtnsAccIR: case InputReport.BtnsExtB: case InputReport.BtnsAccExt: case InputReport.BtnsIRExt: case InputReport.BtnsAccIRExt: // 0x3E & 0x3F Also return button data but we don't use those return true; default: return false; } } internal static bool ReportContainsAccelerometer(InputReport reportType) { switch (reportType) { case InputReport.BtnsAcc: case InputReport.BtnsAccExt: case InputReport.BtnsAccIR: case InputReport.BtnsAccIRExt: return true; default: return false; } } internal static int GetExtensionOffset(InputReport reportType) { switch (reportType) { case InputReport.BtnsExt: case InputReport.BtnsExtB: return 3; case InputReport.BtnsAccExt: return 6; case InputReport.BtnsIRExt: return 13; case InputReport.BtnsAccIRExt: return 16; case InputReport.ExtOnly: return 1; // No other reports send extension bytes default: return -1; } } } } <|start_filename|>Scp/ScpBus/bus/busenum.h<|end_filename|> #include <ntddk.h> #include <wmilib.h> #include <initguid.h> #include <ntintsafe.h> #include <wdmsec.h> #include <wdmguid.h> #include <usbdrivr.h> #include "ScpVBus.h" #define NTSTRSAFE_LIB #include <ntstrsafe.h> #include <dontuse.h> //{6D2B0C28-F583-4B58-99F6-4B3FEF105EDB} DEFINE_GUID (GUID_SD_BUSENUM_PDO, 0x6d2b0c28, 0xf583, 0x4b58, 0x99, 0xf6, 0x4b, 0x3f, 0xef, 0x10, 0x5e, 0xdb); //{D61CA365-5AF4-4486-998B-9DB4734C6CA3} DEFINE_GUID (GUID_DEVCLASS_X360WIRED, 0xD61CA365, 0x5AF4, 0x4486, 0x99, 0x8B, 0x9D, 0xB4, 0x73, 0x4C, 0x6C, 0xA3); #ifndef BUSENUM_H #define BUSENUM_H #define BUSENUM_POOL_TAG (ULONG) 'VpcS' #define DEVICE_HARDWARE_ID L"USB\\VID_045E&PID_028E\0" #define DEVICE_HARDWARE_ID_LENGTH sizeof(DEVICE_HARDWARE_ID) #define BUS_HARDWARE_IDS L"USB\\VID_045E&PID_028E&REV_0114\0USB\\VID_045E&PID_028E\0" #define BUS_HARDWARE_IDS_LENGTH sizeof(BUS_HARDWARE_IDS) #define BUSENUM_COMPATIBLE_IDS L"USB\\MS_COMP_XUSB10\0USB\\Class_FF&SubClass_5D&Prot_01\0USB\\Class_FF&SubClass_5D\0USB\\Class_FF\0" #define BUSENUM_COMPATIBLE_IDS_LENGTH sizeof(BUSENUM_COMPATIBLE_IDS) #define FILE_DEVICE_BUSENUM FILE_DEVICE_BUS_EXTENDER #define PRODUCT L"Xbox 360 Controller for Windows" #define VENDORNAME L"SCP " #define MODEL L"Virtual X360 Bus : #" #define DESCRIPTOR_SIZE 0x0099 #if defined(_X86_) #define CONFIGURATION_SIZE 0x00E4 #else #define CONFIGURATION_SIZE 0x0130 #endif #define RUMBLE_SIZE 8 #define LEDSET_SIZE 3 #if DBG #define DRIVERNAME "ScpVBus.sys: " #define Bus_KdPrint(_x_) \ DbgPrint (DRIVERNAME); \ DbgPrint _x_; #else #define Bus_KdPrint(_x_) #endif typedef enum _DEVICE_PNP_STATE { NotStarted = 0, // Not started yet Started, // Device has received the START_DEVICE IRP StopPending, // Device has received the QUERY_STOP IRP Stopped, // Device has received the STOP_DEVICE IRP RemovePending, // Device has received the QUERY_REMOVE IRP SurpriseRemovePending, // Device has received the SURPRISE_REMOVE IRP Deleted, // Device has received the REMOVE_DEVICE IRP UnKnown // Unknown state } DEVICE_PNP_STATE; typedef struct _GLOBALS { UNICODE_STRING RegistryPath; } GLOBALS; extern GLOBALS Globals; typedef struct _PENDING_IRP { LIST_ENTRY Link; PIRP Irp; } PENDING_IRP, *PPENDING_IRP; typedef struct _COMMON_DEVICE_DATA { PDEVICE_OBJECT Self; BOOLEAN IsFDO; DEVICE_PNP_STATE DevicePnPState; DEVICE_PNP_STATE PreviousPnPState; SYSTEM_POWER_STATE SystemPowerState; DEVICE_POWER_STATE DevicePowerState; } COMMON_DEVICE_DATA, *PCOMMON_DEVICE_DATA; typedef struct _PDO_DEVICE_DATA { #pragma warning(suppress:4201) COMMON_DEVICE_DATA; PDEVICE_OBJECT ParentFdo; __drv_aliasesMem PWCHAR HardwareIDs; ULONG SerialNo; LIST_ENTRY Link; BOOLEAN Present; BOOLEAN ReportedMissing; UCHAR Reserved[2]; // for 4 byte alignment ULONG InterfaceRefCount; LIST_ENTRY HoldingQueue; LIST_ENTRY PendingQueue; KSPIN_LOCK PendingQueueLock; UCHAR Rumble[8]; UCHAR Report[20]; UNICODE_STRING InterfaceName; } PDO_DEVICE_DATA, *PPDO_DEVICE_DATA; typedef struct _FDO_DEVICE_DATA { #pragma warning(suppress:4201) COMMON_DEVICE_DATA; PDEVICE_OBJECT UnderlyingPDO; PDEVICE_OBJECT NextLowerDriver; LIST_ENTRY ListOfPDOs; ULONG NumPDOs; FAST_MUTEX Mutex; ULONG OutstandingIO; KEVENT RemoveEvent; KEVENT StopEvent; UNICODE_STRING InterfaceName; } FDO_DEVICE_DATA, *PFDO_DEVICE_DATA; #define FDO_FROM_PDO(pdoData) \ ((PFDO_DEVICE_DATA) (pdoData)->ParentFdo->DeviceExtension) #define INITIALIZE_PNP_STATE(_Data_) \ (_Data_)->DevicePnPState = NotStarted;\ (_Data_)->PreviousPnPState = NotStarted; #define SET_NEW_PNP_STATE(_Data_, _state_) \ (_Data_)->PreviousPnPState = (_Data_)->DevicePnPState;\ (_Data_)->DevicePnPState = (_state_); #define RESTORE_PREVIOUS_PNP_STATE(_Data_) \ (_Data_)->DevicePnPState = (_Data_)->PreviousPnPState;\ // // Defined in busenum.c // DRIVER_INITIALIZE DriverEntry; DRIVER_UNLOAD Bus_DriverUnload; __drv_dispatchType(IRP_MJ_CREATE) __drv_dispatchType(IRP_MJ_CLOSE) DRIVER_DISPATCH Bus_CreateClose; __drv_dispatchType(IRP_MJ_DEVICE_CONTROL) DRIVER_DISPATCH Bus_IoCtl; __drv_dispatchType(IRP_MJ_INTERNAL_DEVICE_CONTROL) DRIVER_DISPATCH Bus_Internal_IoCtl; DRIVER_CANCEL Bus_CancelIrp; VOID Bus_IncIoCount(__in PFDO_DEVICE_DATA Data); VOID Bus_DecIoCount(__in PFDO_DEVICE_DATA Data); NTSTATUS Bus_ReportDevice(PBUSENUM_REPORT_HARDWARE Report, PFDO_DEVICE_DATA fdoData, PUCHAR pBuffer); // // Defined in pnp.c // DRIVER_ADD_DEVICE Bus_AddDevice; __drv_dispatchType(IRP_MJ_PNP) DRIVER_DISPATCH Bus_PnP; NTSTATUS Bus_FDO_PnP(__in PDEVICE_OBJECT DeviceObject, __in PIRP Irp, __in PIO_STACK_LOCATION IrpStack, __in PFDO_DEVICE_DATA DeviceData); NTSTATUS Bus_StartFdo(__in PFDO_DEVICE_DATA FdoData, __in PIRP Irp); VOID Bus_RemoveFdo(__in PFDO_DEVICE_DATA FdoData); DRIVER_DISPATCH Bus_SendIrpSynchronously; IO_COMPLETION_ROUTINE Bus_CompletionRoutine; NTSTATUS Bus_DestroyPdo(PDEVICE_OBJECT Device, PPDO_DEVICE_DATA PdoData); VOID Bus_InitializePdo(__drv_in(__drv_aliasesMem) PDEVICE_OBJECT Pdo, PFDO_DEVICE_DATA FdoData); NTSTATUS Bus_PlugInDevice(PBUSENUM_PLUGIN_HARDWARE PlugIn, ULONG PlugInLength, PFDO_DEVICE_DATA DeviceData); NTSTATUS Bus_UnPlugDevice(PBUSENUM_UNPLUG_HARDWARE UnPlug, PFDO_DEVICE_DATA DeviceData); NTSTATUS Bus_EjectDevice(PBUSENUM_EJECT_HARDWARE Eject, PFDO_DEVICE_DATA FdoData); PCHAR DbgDeviceIDString(BUS_QUERY_ID_TYPE Type); PCHAR DbgDeviceRelationString(__in DEVICE_RELATION_TYPE Type); PCHAR PnPMinorFunctionString(UCHAR MinorFunction); // // Defined in power.c // __drv_dispatchType(IRP_MJ_POWER) DRIVER_DISPATCH Bus_Power; NTSTATUS Bus_FDO_Power(PFDO_DEVICE_DATA FdoData, PIRP Irp); NTSTATUS Bus_PDO_Power(PPDO_DEVICE_DATA PdoData, PIRP Irp); PCHAR PowerMinorFunctionString(UCHAR MinorFunction); PCHAR DbgSystemPowerString(__in SYSTEM_POWER_STATE Type); PCHAR DbgDevicePowerString(__in DEVICE_POWER_STATE Type); // // Defined in buspdo.c // NTSTATUS Bus_PDO_PnP(__in PDEVICE_OBJECT DeviceObject, __in PIRP Irp, __in PIO_STACK_LOCATION IrpStack, __in PPDO_DEVICE_DATA DeviceData); NTSTATUS Bus_PDO_QueryDeviceCaps(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp); NTSTATUS Bus_PDO_QueryDeviceId(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp); NTSTATUS Bus_PDO_QueryDeviceText(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp); NTSTATUS Bus_PDO_QueryResources(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp); NTSTATUS Bus_PDO_QueryResourceRequirements(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp); NTSTATUS Bus_PDO_QueryDeviceRelations(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp); NTSTATUS Bus_PDO_QueryBusInformation(__in PPDO_DEVICE_DATA DeviceData,__in PIRP Irp); NTSTATUS Bus_GetDeviceCapabilities(__in PDEVICE_OBJECT DeviceObject, __out PDEVICE_CAPABILITIES DeviceCapabilities); VOID Bus_InterfaceReference(__in PVOID Context); VOID Bus_InterfaceDereference(__in PVOID Context); BOOLEAN USB_BUSIFFN Bus_IsDeviceHighSpeed(IN PVOID BusContext); NTSTATUS USB_BUSIFFN Bus_QueryBusInformation(IN PVOID BusContext, IN ULONG Level, IN OUT PVOID BusInformationBuffer, IN OUT PULONG BusInformationBufferLength, OUT PULONG BusInformationActualLength); NTSTATUS USB_BUSIFFN Bus_SubmitIsoOutUrb(IN PVOID BusContext, IN PURB Urb); NTSTATUS USB_BUSIFFN Bus_QueryBusTime(IN PVOID BusContext, IN OUT PULONG CurrentUsbFrame); VOID USB_BUSIFFN Bus_GetUSBDIVersion(IN PVOID BusContext, IN OUT PUSBD_VERSION_INFORMATION VersionInformation, IN OUT PULONG HcdCapabilities); NTSTATUS Bus_PDO_QueryInterface(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp); #endif <|start_filename|>Scp/Lilypad/DualShock3.cpp<|end_filename|> #include "Global.h" #include "InputManager.h" #include <xinput.h> typedef struct { float SCP_UP; float SCP_RIGHT; float SCP_DOWN; float SCP_LEFT; float SCP_LX; float SCP_LY; float SCP_L1; float SCP_L2; float SCP_L3; float SCP_RX; float SCP_RY; float SCP_R1; float SCP_R2; float SCP_R3; float SCP_T; float SCP_C; float SCP_X; float SCP_S; float SCP_SELECT; float SCP_START; float SCP_PS; } SCP_EXTN; typedef void (CALLBACK *_XInputEnable)(BOOL enable); typedef DWORD(CALLBACK *_XInputGetState)(DWORD dwUserIndex, XINPUT_STATE* pState); typedef DWORD(CALLBACK *_XInputSetState)(DWORD dwUserIndex, XINPUT_VIBRATION* pVibration); typedef DWORD(CALLBACK *_XInputGetExtended)(DWORD dwUserIndex, SCP_EXTN* pPressure); static _XInputEnable pXInputEnable = 0; static _XInputGetState pXInputGetState = 0; static _XInputSetState pXInputSetState = 0; static _XInputGetExtended pXInputGetExtended = 0; static int xInputActiveCount = 0; __forceinline int FloatToValue(float f) { return (int)(f * ((float)(FULLY_DOWN))); } class DualShock3Device : public Device { protected: // Cached last vibration values by pad and motor. // Need this, as only one value is changed at a time. int ps2Vibration[2][4][2]; // Minor optimization - cache last set vibration values // When there's no change, no need to do anything. XINPUT_VIBRATION xInputVibration; public: int index; DualShock3Device(int index, wchar_t *name) : Device(DS3, OTHER, name) { memset(ps2Vibration, 0, sizeof(ps2Vibration)); memset(&xInputVibration, 0, sizeof(xInputVibration)); this->index = index; for (int i = 0; i < 12; i++) { AddPhysicalControl(PRESSURE_BTN, i, 0); } for (int i = 12; i < 16; i++) { AddPhysicalControl(PSHBTN, i, 0); } for (int i = 16; i < 20; i++) { AddPhysicalControl(ABSAXIS, i, 0); } AddPhysicalControl(PSHBTN, 20, 0); AddFFAxis(L"Slow Motor", 0); AddFFAxis(L"Fast Motor", 1); AddFFEffectType(L"Constant Effect", L"Constant", EFFECT_CONSTANT); } wchar_t *GetPhysicalControlName(PhysicalControl *control) { const static wchar_t *names[] = { L"Up", L"Right", L"Down", L"Left", L"Triangle", L"Circle", L"Cross", L"Square", L"L1", L"L2", L"R1", L"R2", L"L3", L"R3", L"Select", L"Start", L"L-Stick X", L"L-Stick Y", L"R-Stick X", L"R-Stick Y", L"PS", }; unsigned int i = (unsigned int)(control - physicalControls); if (i < 21) return (wchar_t*)names[i]; return Device::GetPhysicalControlName(control); } int Activate(InitInfo *initInfo) { if (active) Deactivate(); if (!xInputActiveCount) pXInputEnable(1); xInputActiveCount++; active = 1; AllocState(); return 1; } int Update() { if (!active) return 0; SCP_EXTN extn; if (pXInputGetExtended(index, &extn) != ERROR_SUCCESS) { Deactivate(); return 0; } physicalControlState[0] = FloatToValue(extn.SCP_UP); physicalControlState[1] = FloatToValue(extn.SCP_RIGHT); physicalControlState[2] = FloatToValue(extn.SCP_DOWN); physicalControlState[3] = FloatToValue(extn.SCP_LEFT); physicalControlState[4] = FloatToValue(extn.SCP_T); physicalControlState[5] = FloatToValue(extn.SCP_C); physicalControlState[6] = FloatToValue(extn.SCP_X); physicalControlState[7] = FloatToValue(extn.SCP_S); physicalControlState[8] = FloatToValue(extn.SCP_L1); physicalControlState[9] = FloatToValue(extn.SCP_L2); physicalControlState[10] = FloatToValue(extn.SCP_R1); physicalControlState[11] = FloatToValue(extn.SCP_R2); physicalControlState[12] = FloatToValue(extn.SCP_L3); physicalControlState[13] = FloatToValue(extn.SCP_R3); physicalControlState[14] = FloatToValue(extn.SCP_SELECT); physicalControlState[15] = FloatToValue(extn.SCP_START); physicalControlState[16] = FloatToValue(extn.SCP_LX); physicalControlState[17] = FloatToValue(extn.SCP_LY); physicalControlState[18] = FloatToValue(extn.SCP_RX); physicalControlState[19] = FloatToValue(extn.SCP_RY); physicalControlState[20] = FloatToValue(extn.SCP_PS); return 1; } void SetEffects(unsigned char port, unsigned int slot, unsigned char motor, unsigned char force) { int newVibration[2] = { 0, 0 }; ps2Vibration[port][slot][motor] = force; for (int p = 0; p < 2; p++) { for (int s = 0; s < 4; s++) { for (int i = 0; i < pads[p][s].numFFBindings; i++) { ForceFeedbackBinding *ffb = &pads[p][s].ffBindings[i]; newVibration[0] += (int)((ffb->axes[0].force * (__int64)ps2Vibration[p][s][ffb->motor]) / 255); newVibration[1] += (int)((ffb->axes[1].force * (__int64)ps2Vibration[p][s][ffb->motor]) / 255); } } } newVibration[0] = abs(newVibration[0]); if (newVibration[0] > 65535) newVibration[0] = 65535; newVibration[1] = abs(newVibration[1]); if (newVibration[1] > 65535) newVibration[1] = 65535; if (newVibration[0] != xInputVibration.wLeftMotorSpeed || newVibration[1] != xInputVibration.wRightMotorSpeed) { XINPUT_VIBRATION newv = { newVibration[0], newVibration[1] }; if (pXInputSetState(index, &newv) == ERROR_SUCCESS) { xInputVibration = newv; } } } void SetEffect(ForceFeedbackBinding *binding, unsigned char force) { PadBindings pBackup = pads[0][0]; pads[0][0].ffBindings = binding; pads[0][0].numFFBindings = 1; SetEffects(0, 0, binding->motor, force); pads[0][0] = pBackup; } void Deactivate() { memset(&xInputVibration, 0, sizeof(xInputVibration)); memset(ps2Vibration, 0, sizeof(ps2Vibration)); pXInputSetState(index, &xInputVibration); FreeState(); if (active) { if (!--xInputActiveCount) { pXInputEnable(0); } active = 0; } } ~DualShock3Device() { } }; void EnumDualShock3s() { wchar_t name[30]; XINPUT_STATE state; SCP_EXTN extn; if (!pXInputSetState) { if (pXInputGetExtended) return; HMODULE hMod = 0; if (hMod = LoadLibraryW(L"XInput1_3.dll")) { if ((pXInputEnable = (_XInputEnable)GetProcAddress(hMod, "XInputEnable")) && (pXInputGetState = (_XInputGetState)GetProcAddress(hMod, "XInputGetState")) && (pXInputSetState = (_XInputSetState)GetProcAddress(hMod, "XInputSetState"))) { pXInputGetExtended = (_XInputGetExtended)GetProcAddress(hMod, "XInputGetExtended"); } } if (!pXInputGetExtended) { pXInputGetExtended = (_XInputGetExtended)-1; return; } } pXInputEnable(1); for (int index = 0; index < 4; index++) { if (pXInputGetState(index, &state) == ERROR_SUCCESS && pXInputGetExtended(index, &extn) == ERROR_SUCCESS) { wsprintfW(name, L"DualShock 3 #%i", index + 1); dm->AddDevice(new DualShock3Device(index, name)); } } pXInputEnable(0); } int DualShock3Possible() { int retVal = 0; HMODULE hMod = 0; if (hMod = LoadLibraryW(L"XInput1_3.dll")) { _XInputGetExtended pXInputGetExtended = 0; if (pXInputGetExtended = (_XInputGetExtended)GetProcAddress(hMod, "XInputGetExtended")) { SCP_EXTN extn; for (int index = 0; index < 4; index++) { if (pXInputGetExtended(index, &extn) == ERROR_SUCCESS) { retVal = 1; break; } } } FreeLibrary(hMod); } return retVal; } void UninitLibUsb() { return; } <|start_filename|>Scp/XInput_Scp/LibUsbApi.cpp<|end_filename|> #include "StdAfx.h" #include "lusb0_usb.h" static HMODULE l_hLibUsbDll = NULL; static FARPROC l_hLibUsbFunc[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL }; static unsigned short idVendor = 0x054c; static unsigned short idProduct = 0x0268; #define DS3_REQUEST_CODE 0x09 #define DS3_REQUEST_VALUE 0x03F4 #define DS3_REQUEST_SIZE 0x04 static CHAR l_hwStartData[DS3_REQUEST_SIZE] = { 0x42, 0x0C, 0x00, 0x00 }; static volatile bool bInited = false; typedef void (__cdecl *usb_initFunction)(void); typedef int (__cdecl *usb_find_bussesFunction)(void); typedef int (__cdecl *usb_find_devicesFunction)(void); typedef struct usb_bus *(__cdecl *usb_get_bussesFunction)(void); typedef usb_dev_handle *(__cdecl *usb_openFunction)(struct usb_device *dev); typedef int (__cdecl *usb_control_msgFunction)(usb_dev_handle *dev, int requesttype, int request, int value, int index, char *bytes, int size, int timeout); typedef int (__cdecl *usb_closeFunction)(usb_dev_handle *dev); void load_lib_usb() { if (!bInited) { if ((l_hLibUsbDll = LoadLibrary(_T("C:\\Windows\\System32\\libusb0.dll"))) != NULL) { if ((l_hLibUsbFunc[0] = GetProcAddress(l_hLibUsbDll, "usb_init")) && (l_hLibUsbFunc[1] = GetProcAddress(l_hLibUsbDll, "usb_find_busses")) && (l_hLibUsbFunc[2] = GetProcAddress(l_hLibUsbDll, "usb_find_devices")) && (l_hLibUsbFunc[3] = GetProcAddress(l_hLibUsbDll, "usb_get_busses")) && (l_hLibUsbFunc[4] = GetProcAddress(l_hLibUsbDll, "usb_open")) && (l_hLibUsbFunc[5] = GetProcAddress(l_hLibUsbDll, "usb_control_msg")) && (l_hLibUsbFunc[6] = GetProcAddress(l_hLibUsbDll, "usb_close"))) { ((usb_initFunction) l_hLibUsbFunc[0])(); bInited = true; } } } } void init_lib_usb() { bool bFound = false; if (bInited) { struct usb_bus* bus; struct usb_device* dev; struct usb_dev_handle* udev; ((usb_find_bussesFunction) l_hLibUsbFunc[1])(); ((usb_find_devicesFunction) l_hLibUsbFunc[2]()); for (bus = ((usb_get_bussesFunction) l_hLibUsbFunc[3])(); bus; bus = bus->next) { for (dev = bus->devices; dev; dev = dev->next) { if (dev->descriptor.idVendor == idVendor && dev->descriptor.idProduct == idProduct) { if ((udev = ((usb_openFunction) l_hLibUsbFunc[4])(dev))) { ((usb_control_msgFunction) l_hLibUsbFunc[5])(udev, USB_ENDPOINT_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE, DS3_REQUEST_CODE, DS3_REQUEST_VALUE, dev->config->interface->altsetting->bInterfaceNumber, l_hwStartData, DS3_REQUEST_SIZE, 500); ((usb_closeFunction) l_hLibUsbFunc[6])(udev); bFound = true; } } } } } if (bFound) Sleep(100); } <|start_filename|>Scp/ScpBus/bus/power.c<|end_filename|> #include "busenum.h" NTSTATUS Bus_Power(PDEVICE_OBJECT DeviceObject, PIRP Irp) { PIO_STACK_LOCATION irpStack; NTSTATUS status; PCOMMON_DEVICE_DATA commonData; status = STATUS_SUCCESS; irpStack = IoGetCurrentIrpStackLocation(Irp); ASSERT(irpStack->MajorFunction == IRP_MJ_POWER); commonData = (PCOMMON_DEVICE_DATA) DeviceObject->DeviceExtension; if (commonData->DevicePnPState == Deleted) { PoStartNextPowerIrp(Irp); Irp->IoStatus.Status = status = STATUS_NO_SUCH_DEVICE ; IoCompleteRequest(Irp, IO_NO_INCREMENT); return status; } if (commonData->IsFDO) { Bus_KdPrint(("FDO %s IRP:0x%p %s %s\n", PowerMinorFunctionString(irpStack->MinorFunction), Irp, DbgSystemPowerString(commonData->SystemPowerState), DbgDevicePowerString(commonData->DevicePowerState))); status = Bus_FDO_Power((PFDO_DEVICE_DATA) DeviceObject->DeviceExtension, Irp); } else { Bus_KdPrint(("PDO %s IRP:0x%p %s %s\n", PowerMinorFunctionString(irpStack->MinorFunction), Irp, DbgSystemPowerString(commonData->SystemPowerState), DbgDevicePowerString(commonData->DevicePowerState))); status = Bus_PDO_Power((PPDO_DEVICE_DATA) DeviceObject->DeviceExtension, Irp); } return status; } NTSTATUS Bus_FDO_Power(PFDO_DEVICE_DATA Data, PIRP Irp) { NTSTATUS status; POWER_STATE powerState; POWER_STATE_TYPE powerType; PIO_STACK_LOCATION stack; stack = IoGetCurrentIrpStackLocation(Irp); powerType = stack->Parameters.Power.Type; powerState = stack->Parameters.Power.State; Bus_IncIoCount(Data); if (Data->DevicePnPState == NotStarted) { PoStartNextPowerIrp(Irp); IoSkipCurrentIrpStackLocation(Irp); status = PoCallDriver(Data->NextLowerDriver, Irp); Bus_DecIoCount(Data); return status; } if (stack->MinorFunction == IRP_MN_SET_POWER) { Bus_KdPrint(("\tRequest to set %s state to %s\n", ((powerType == SystemPowerState) ? "System" : "Device"), ((powerType == SystemPowerState) ? DbgSystemPowerString(powerState.SystemState) : DbgDevicePowerString(powerState.DeviceState)))); } PoStartNextPowerIrp(Irp); IoSkipCurrentIrpStackLocation(Irp); status = PoCallDriver(Data->NextLowerDriver, Irp); Bus_DecIoCount(Data); return status; } NTSTATUS Bus_PDO_Power(PPDO_DEVICE_DATA PdoData, PIRP Irp) { NTSTATUS status; PIO_STACK_LOCATION stack; POWER_STATE powerState; POWER_STATE_TYPE powerType; stack = IoGetCurrentIrpStackLocation(Irp); powerType = stack->Parameters.Power.Type; powerState = stack->Parameters.Power.State; switch (stack->MinorFunction) { case IRP_MN_SET_POWER: Bus_KdPrint(("\tSetting %s power state to %s\n", ((powerType == SystemPowerState) ? "System" : "Device"), ((powerType == SystemPowerState) ? DbgSystemPowerString(powerState.SystemState) : DbgDevicePowerString(powerState.DeviceState)))); switch (powerType) { case DevicePowerState: PoSetPowerState(PdoData->Self, powerType, powerState); PdoData->DevicePowerState = powerState.DeviceState; status = STATUS_SUCCESS; break; case SystemPowerState: PdoData->SystemPowerState = powerState.SystemState; status = STATUS_SUCCESS; break; default: status = STATUS_NOT_SUPPORTED; break; } break; case IRP_MN_QUERY_POWER: status = STATUS_SUCCESS; break; case IRP_MN_WAIT_WAKE: case IRP_MN_POWER_SEQUENCE: default: status = STATUS_NOT_SUPPORTED; break; } if (status != STATUS_NOT_SUPPORTED) { Irp->IoStatus.Status = status; } PoStartNextPowerIrp(Irp); status = Irp->IoStatus.Status; IoCompleteRequest(Irp, IO_NO_INCREMENT); return status; } #if DBG PCHAR PowerMinorFunctionString(UCHAR MinorFunction) { switch (MinorFunction) { case IRP_MN_SET_POWER: return "IRP_MN_SET_POWER"; case IRP_MN_QUERY_POWER: return "IRP_MN_QUERY_POWER"; case IRP_MN_POWER_SEQUENCE: return "IRP_MN_POWER_SEQUENCE"; case IRP_MN_WAIT_WAKE: return "IRP_MN_WAIT_WAKE"; default: return "unknown_power_irp"; } } PCHAR DbgSystemPowerString(__in SYSTEM_POWER_STATE Type) { switch (Type) { case PowerSystemUnspecified: return "PowerSystemUnspecified"; case PowerSystemWorking: return "PowerSystemWorking"; case PowerSystemSleeping1: return "PowerSystemSleeping1"; case PowerSystemSleeping2: return "PowerSystemSleeping2"; case PowerSystemSleeping3: return "PowerSystemSleeping3"; case PowerSystemHibernate: return "PowerSystemHibernate"; case PowerSystemShutdown: return "PowerSystemShutdown"; case PowerSystemMaximum: return "PowerSystemMaximum"; default: return "UnKnown System Power State"; } } PCHAR DbgDevicePowerString(__in DEVICE_POWER_STATE Type) { switch (Type) { case PowerDeviceUnspecified: return "PowerDeviceUnspecified"; case PowerDeviceD0: return "PowerDeviceD0"; case PowerDeviceD1: return "PowerDeviceD1"; case PowerDeviceD2: return "PowerDeviceD2"; case PowerDeviceD3: return "PowerDeviceD3"; case PowerDeviceMaximum: return "PowerDeviceMaximum"; default: return "UnKnown Device Power State"; } } #endif <|start_filename|>WiinUPro/Assignments/VJoyAxisAssignment.cs<|end_filename|> namespace WiinUPro { public class VJoyAxisAssignment : IAssignment { public uint DeviceId { get; set; } public HID_USAGES Axis { get; set; } public bool Positive { get; set; } public VJoyAxisAssignment() { } public VJoyAxisAssignment(HID_USAGES axis, bool positive = true, uint device = 1) { Axis = axis; Positive = positive; DeviceId = device; } public void Apply(float value) { VJoyDirector.Access.SetAxis(Axis, value, Positive, DeviceId); } public bool SameAs(IAssignment assignment) { var other = assignment as VJoyAxisAssignment; if (other == null) { return false; } bool result = true; result &= Axis == other.Axis; result &= DeviceId == other.DeviceId; result &= Positive == other.Positive; return result; } public override bool Equals(object obj) { var other = obj as VJoyAxisAssignment; if (other == null) { return false; } else { return Axis == other.Axis && DeviceId == other.DeviceId; } } public override int GetHashCode() { int hash = (int)Axis + (int)DeviceId; return hash; } public override string ToString() { return Axis.ToString(); } public string GetDisplayName() { return ToString().Replace("HID_USAGE_", "Joy."); } } } <|start_filename|>Scp/ScpInstaller/ScpForm.cs<|end_filename|> using System; using System.IO; using System.ComponentModel; using System.Text; using System.Windows.Forms; using System.Threading; using System.Reflection; using System.Xml; using System.Resources; using System.Management; using System.Text.RegularExpressions; using System.ServiceProcess; using System.Configuration.Install; using System.Collections; using System.Collections.Specialized; namespace ScpDriver { public enum OSType { INVALID, XP, VISTA, WIN7, WIN8, WIN81, DEFAULT }; public partial class ScpForm : Form { protected String DS3_BUS_CLASS_GUID = "{F679F562-3164-42CE-A4DB-E7DDBE723909}"; protected Cursor Saved; protected Difx Installer; protected Boolean Bus_Device_Configured = false; protected Boolean Bus_Driver_Configured = false; protected Boolean DS3_Driver_Configured = false; protected Boolean BTH_Driver_Configured = false; protected Boolean Scp_Service_Configured = false; protected Boolean Reboot = false; protected OSType Valid = OSType.INVALID; protected String InfPath = @".\System\"; protected String ScpService = "SCP DS3 Service"; protected String[] Desc = new String[] { "SUCCESS", "INFO ", "WARNING", "ERROR " }; protected void Logger(DifxLog Event, Int32 Error, String Description) { if (tbOutput.InvokeRequired) { Difx.LogEventHandler d = new Difx.LogEventHandler(Logger); Invoke(d, new object[] { Event, Error, Description }); } else { StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0} - {1}", Desc[(Int32) Event], Description); sb.AppendLine(); tbOutput.AppendText(sb.ToString()); } } protected String OSInfo() { String Info = String.Empty; try { using (ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem")) { foreach (ManagementObject mo in mos.Get()) { try { Info = Regex.Replace(mo.GetPropertyValue("Caption").ToString(), "[^A-Za-z0-9 ]", "").Trim(); try { Object spv = mo.GetPropertyValue("ServicePackMajorVersion"); if (spv != null && spv.ToString() != "0") { Info += " Service Pack " + spv.ToString(); } } catch { } Info = String.Format("{0} ({1} {2})", Info, System.Environment.OSVersion.Version.ToString(), System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")); } catch { } mo.Dispose(); } } } catch { } return Info; } protected OSType OSParse(String Info) { OSType Valid = OSType.INVALID; try { String Architecture = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE").ToUpper().Trim(); if (Environment.Is64BitOperatingSystem == Environment.Is64BitProcess && (Architecture == "X86" || Architecture == "AMD64")) { Valid = OSType.DEFAULT; if (!String.IsNullOrEmpty(Info)) { String[] Token = Info.Split(new char[] { ' ' }); if (Token[0].ToUpper().Trim() == "MICROSOFT" && Token[1].ToUpper().Trim() == "WINDOWS") { switch (Token[2].ToUpper().Trim()) { case "XP": if (!System.Environment.Is64BitOperatingSystem) Valid = OSType.XP; break; case "VISTA": Valid = OSType.VISTA; break; case "7": Valid = OSType.WIN7; break; case "8": Valid = OSType.WIN8; break; case "81": Valid = OSType.WIN81; break; case "SERVER": switch (Token[3].ToUpper().Trim()) { case "2008": if (Token[4].ToUpper().Trim() == "R2") { Valid = OSType.WIN7; } else { Valid = OSType.VISTA; } break; case "2012": Valid = OSType.WIN8; break; } break; } } } } } catch { } return Valid; } protected Boolean Start(String Service) { try { ServiceController sc = new ServiceController("SCP DS3 Service"); if (sc.Status == ServiceControllerStatus.Stopped) { sc.Start(); Thread.Sleep(1000); return true; } } catch { } return false; } protected Boolean Stop(String Service) { try { ServiceController sc = new ServiceController("SCP DS3 Service"); if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); Thread.Sleep(1000); return true; } } catch { } return false; } protected Boolean Configuration() { Boolean Loaded = true, Enabled = true; try { String m_File = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + Assembly.GetExecutingAssembly().GetName().Name + ".xml"; XmlDocument m_Xdoc = new XmlDocument(); XmlNode Item; m_Xdoc.Load(m_File); try { Item = m_Xdoc.SelectSingleNode("/ScpDriver/Service"); Boolean.TryParse(Item.InnerText, out Enabled); cbService.Checked = cbService.Visible = Enabled; } catch { } try { Item = m_Xdoc.SelectSingleNode("/ScpDriver/Bluetooth"); Boolean.TryParse(Item.InnerText, out Enabled); cbBluetooth.Checked = cbBluetooth.Visible = Enabled; } catch { } try { Item = m_Xdoc.SelectSingleNode("/ScpDriver/DualShock3"); Boolean.TryParse(Item.InnerText, out Enabled); cbDS3.Checked = cbDS3.Visible = Enabled; } catch { } try { Item = m_Xdoc.SelectSingleNode("/ScpDriver/VirtualBus"); Boolean.TryParse(Item.InnerText, out Enabled); cbBus.Checked = cbBus.Visible = Enabled; // Don't install Service if Bus not Enabled if (!Enabled) cbService.Checked = cbService.Visible = Enabled; } catch { } } catch { Loaded = false; } return Loaded; } public ScpForm() { InitializeComponent(); Configuration(); StringBuilder sb = new StringBuilder(); sb.AppendFormat("SCP Driver Installer {0} [{1}]", Application.ProductVersion, DateTime.Now); sb.AppendLine(); sb.AppendLine(); Installer = Difx.Factory(); Installer.onLogEvent += Logger; String Info = OSInfo(); Valid = OSParse(Info); sb.Append("Detected - "); sb.Append(Info); sb.AppendLine(); tbOutput.AppendText(sb.ToString()); sb.Clear(); if (Valid == OSType.INVALID) { btnInstall.Enabled = false; btnUninstall.Enabled = false; sb.AppendLine("Could not find a valid configuration."); } else { btnInstall.Enabled = true; btnUninstall.Enabled = true; sb.AppendFormat("Selected {0} configuration.", Valid); } sb.AppendLine(); sb.AppendLine(); tbOutput.AppendText(sb.ToString()); } protected void ScpForm_Load(object sender, EventArgs e) { Icon = Properties.Resources.Scp_All; } protected void ScpForm_Close(object sender, FormClosingEventArgs e) { try { File.AppendAllLines("ScpDriver.log", tbOutput.Lines); } catch { } } protected void btnInstall_Click(object sender, EventArgs e) { Saved = Cursor; Cursor = Cursors.WaitCursor; btnInstall.Enabled = false; btnUninstall.Enabled = false; btnExit.Enabled = false; Bus_Device_Configured = false; Bus_Driver_Configured = false; DS3_Driver_Configured = false; BTH_Driver_Configured = false; Scp_Service_Configured = false; pbRunning.Style = ProgressBarStyle.Marquee; InstallWorker.RunWorkerAsync(InfPath); } protected void btnUninstall_Click(object sender, EventArgs e) { Saved = Cursor; Cursor = Cursors.WaitCursor; btnInstall.Enabled = false; btnUninstall.Enabled = false; btnExit.Enabled = false; Bus_Device_Configured = false; Bus_Driver_Configured = false; DS3_Driver_Configured = false; BTH_Driver_Configured = false; Scp_Service_Configured = false; pbRunning.Style = ProgressBarStyle.Marquee; UninstallWorker.RunWorkerAsync(InfPath); } protected void btnExit_Click(object sender, EventArgs e) { Close(); } protected void InstallWorker_DoWork(object sender, DoWorkEventArgs e) { String InfPath = (String) e.Argument; String DevPath = String.Empty, InstanceId = String.Empty; try { UInt32 Result = 0; Boolean RebootRequired = false; DifxFlags Flags = DifxFlags.DRIVER_PACKAGE_ONLY_IF_DEVICE_PRESENT; if (cbForce.Checked) Flags |= DifxFlags.DRIVER_PACKAGE_FORCE; if (cbBus.Checked) { if (!Devcon.Find(new Guid(DS3_BUS_CLASS_GUID), ref DevPath, ref InstanceId)) { if (Devcon.Create("System", new Guid("{4D36E97D-E325-11CE-BFC1-08002BE10318}"), "root\\ScpVBus\0\0")) { Logger(DifxLog.DIFXAPI_SUCCESS, 0, "Virtual Bus Created"); Bus_Device_Configured = true; } } Result = Installer.Install(InfPath + @"ScpVBus.inf", Flags, out RebootRequired); Reboot |= RebootRequired; if (Result == 0) Bus_Driver_Configured = true; } if (cbBluetooth.Checked) { Result = Installer.Install(InfPath + @"BthWinUsb.inf", Flags, out RebootRequired); Reboot |= RebootRequired; if (Result == 0) BTH_Driver_Configured = true; } if (cbDS3.Checked) { Result = Installer.Install(InfPath + @"Ds3WinUsb.inf", Flags, out RebootRequired); Reboot |= RebootRequired; if (Result == 0) DS3_Driver_Configured = true; } if (cbService.Checked) { IDictionary State = new Hashtable(); AssemblyInstaller Service = new AssemblyInstaller(Directory.GetCurrentDirectory() + @"\ScpService.exe", null); State.Clear(); Service.UseNewContext = true; Service.Install(State); Service.Commit (State); if (Start(ScpService)) Logger(DifxLog.DIFXAPI_INFO, 0, ScpService + " Started."); else Reboot = true; Scp_Service_Configured = true; } } catch { } } protected void InstallWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { pbRunning.Style = ProgressBarStyle.Continuous; btnInstall.Enabled = true; btnUninstall.Enabled = true; btnExit.Enabled = true; Cursor = Saved; StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.AppendFormat("Install Succeeded."); if (Reboot) sb.Append(" [Reboot Required]"); sb.AppendLine(); sb.AppendLine(); sb.AppendLine("-- Install Summary --"); if (Scp_Service_Configured) sb.AppendLine("SCP DS3 Service"); if (Bus_Device_Configured) sb.AppendLine("Bus Device"); if (Bus_Driver_Configured) sb.AppendLine("Bus Driver"); if (DS3_Driver_Configured) sb.AppendLine("DS3 USB Driver"); if (BTH_Driver_Configured) sb.AppendLine("Bluetooth Driver"); sb.AppendLine(); sb.AppendLine(); tbOutput.AppendText(sb.ToString()); } protected void UninstallWorker_DoWork(object sender, DoWorkEventArgs e) { String InfPath = (String) e.Argument; String DevPath = String.Empty, InstanceId = String.Empty; try { UInt32 Result = 0; Boolean RebootRequired = false; if (cbService.Checked) { IDictionary State = new Hashtable(); AssemblyInstaller Service = new AssemblyInstaller(Directory.GetCurrentDirectory() + @"\ScpService.exe", null); State.Clear(); Service.UseNewContext = true; if (Stop(ScpService)) { Logger(DifxLog.DIFXAPI_INFO, 0, ScpService + " Stopped."); } try { Service.Uninstall(State); Scp_Service_Configured = true; } catch { } } if (cbBluetooth.Checked) { Result = Installer.Uninstall(InfPath + @"BthWinUsb.inf", DifxFlags.DRIVER_PACKAGE_DELETE_FILES, out RebootRequired); Reboot |= RebootRequired; if (Result == 0) BTH_Driver_Configured = true; } if (cbDS3.Checked) { Result = Installer.Uninstall(InfPath + @"Ds3WinUsb.inf", DifxFlags.DRIVER_PACKAGE_DELETE_FILES, out RebootRequired); Reboot |= RebootRequired; if (Result == 0) DS3_Driver_Configured = true; } if (cbBus.Checked && Devcon.Find(new Guid(DS3_BUS_CLASS_GUID), ref DevPath, ref InstanceId)) { if (Devcon.Remove(new Guid(DS3_BUS_CLASS_GUID), DevPath, InstanceId)) { Logger(DifxLog.DIFXAPI_SUCCESS, 0, "Virtual Bus Removed"); Bus_Device_Configured = true; Installer.Uninstall(InfPath + @"ScpVBus.inf", DifxFlags.DRIVER_PACKAGE_DELETE_FILES, out RebootRequired); Reboot |= RebootRequired; } else { Logger(DifxLog.DIFXAPI_ERROR, 0, "Virtual Bus Removal Failure"); } } } catch { } } protected void UninstallWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { pbRunning.Style = ProgressBarStyle.Continuous; btnInstall.Enabled = true; btnUninstall.Enabled = true; btnExit.Enabled = true; Cursor = Saved; StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.AppendFormat("Uninstall Succeeded."); if (Reboot) sb.Append(" [Reboot Required]"); sb.AppendLine(); sb.AppendLine(); sb.AppendLine("-- Uninstall Summary --"); if (Scp_Service_Configured) sb.AppendLine("SCP DS3 Service"); if (Bus_Device_Configured) sb.AppendLine("Bus Device"); if (Bus_Driver_Configured) sb.AppendLine("Bus Driver"); if (DS3_Driver_Configured) sb.AppendLine("DS3 USB Driver"); if (BTH_Driver_Configured) sb.AppendLine("Bluetooth Driver"); sb.AppendLine(); tbOutput.AppendText(sb.ToString()); } } } <|start_filename|>Nintroller/Controllers/WiimotePlus.cs<|end_filename|> using System; using System.Collections; using System.Collections.Generic; namespace NintrollerLib { public struct WiimotePlus : INintrollerState, IWiimoteExtension { public Wiimote wiimote { get; set; } //gyro public void Update(byte[] data) { throw new NotImplementedException(); } public float GetValue(string input) { throw new NotImplementedException(); } // TODO: Calibration - Balance Board Calibration public void SetCalibration(Calibrations.CalibrationPreset preset) { switch (preset) { case Calibrations.CalibrationPreset.Default: break; case Calibrations.CalibrationPreset.Modest: break; case Calibrations.CalibrationPreset.Extra: break; case Calibrations.CalibrationPreset.Minimum: break; case Calibrations.CalibrationPreset.None: break; } } public void SetCalibration(INintrollerState from) { if (from.GetType() == typeof(WiimotePlus)) { } } public void SetCalibration(string calibrationString) { } public string GetCalibrationString() { return ""; } public bool CalibrationEmpty { get { return false; } } public IEnumerator<KeyValuePair<string, float>> GetEnumerator() { foreach (var input in wiimote) { yield return input; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <|start_filename|>WiinUPro/Directors/MouseDirector.cs<|end_filename|> using System; using System.Collections.Generic; using InputManager; using System.Windows.Forms; using System.Drawing; namespace WiinUPro { class MouseDirector { #region Access public static MouseDirector Access { get; protected set; } static MouseDirector() { Access = new MouseDirector(); } #endregion private List<Mouse.MouseKeys> _pressedButtons; private Rectangle _screenResolution; public MouseDirector() { _pressedButtons = new List<Mouse.MouseKeys>(); // Listen for Screen size changes _screenResolution = Screen.PrimaryScreen.Bounds; Microsoft.Win32.SystemEvents.DisplaySettingsChanged += OnDisplaySettingsChanged; } private void OnDisplaySettingsChanged(object sender, EventArgs e) { _screenResolution = Screen.PrimaryScreen.Bounds; } public void MouseButtonDown(Mouse.MouseKeys code) { if (!_pressedButtons.Contains(code)) { Mouse.ButtonDown(code); _pressedButtons.Add(code); } } public void MouseButtonUp(Mouse.MouseKeys code) { if (_pressedButtons.Contains(code)) { Mouse.ButtonUp(code); _pressedButtons.Remove(code); } } public void MouseButtonPress(Mouse.MouseKeys code) { Mouse.PressButton(code); } public void MouseMoveX(int amount) { Mouse.MoveRelative(amount, 0); } public void MouseMoveY(int amount) { Mouse.MoveRelative(0, amount); } public void MouseMoveTo(float x, float y) { if (x > 1f) x = 1f; else if (x < 0) x = 0; if (y > 1f) y = 1f; else if (y < 0) y = 0; Mouse.Move((int)Math.Floor(x * _screenResolution.Width), (int)Math.Floor(_screenResolution.Height - y * _screenResolution.Height)); } // Will need to change and test how the scrolling works public void MouseScroll(Mouse.ScrollDirection scrollDirection) { Mouse.Scroll(scrollDirection); } public void Release() { foreach (var btn in _pressedButtons.ToArray()) { Mouse.ButtonUp(btn); } } } } <|start_filename|>Shared/DummyDevice.cs<|end_filename|> using System; using System.Collections.Generic; using System.IO; using NintrollerLib; namespace Shared { public class DummyDevice : Stream { #region Properties public ControllerType DeviceType { get; private set; } public INintrollerState State { get; set; } public InputReport NextReport { get; set; } = InputReport.BtnsOnly; public byte RumbleByte { get; set; } public byte BatteryLevel { get; set; } = 0xFF; public bool BatteryLow { get; set; } public bool LED_1 { get; set; } public bool LED_2 { get; set; } public bool LED_3 { get; set; } public bool LED_4 { get; set; } #endregion protected byte[] _lastReport; protected InputReport DataReportMode = InputReport.BtnsOnly; protected Queue<InputReport> _nextQueue; protected Queue<byte[]> _reportQueue; public DummyDevice(INintrollerState state) { _nextQueue = new Queue<InputReport>(); _reportQueue = new Queue<byte[]>(); if (state is ProController) { DeviceType = ControllerType.ProController; ConfigureProController((ProController)state); } else if (state is Wiimote) { DeviceType = ControllerType.Wiimote; ConfigureWiimote((Wiimote)state); } else if (state is GameCubeAdapter) { DeviceType = ControllerType.Other; ConfigureGameCubeAdapter((GameCubeAdapter)state); } else { State = state; } } public void ChangeExtension(ControllerType type) { if (DeviceType == type) return; switch (type) { case ControllerType.Wiimote: if (State is IWiimoteExtension) { ConfigureWiimote(((IWiimoteExtension)State).wiimote); } else { ConfigureWiimote(new Wiimote()); } break; case ControllerType.Nunchuk: case ControllerType.NunchukB: var nState = new Nunchuk(); nState.SetCalibration(Calibrations.CalibrationPreset.Default); ConfigureNunchuk(nState); ConfigureWiimote(nState.wiimote); break; case ControllerType.ClassicController: var cState = new ClassicController(); cState.SetCalibration(Calibrations.CalibrationPreset.Default); ConfigureClassicController(cState); ConfigureWiimote(cState.wiimote); break; case ControllerType.ClassicControllerPro: var ccpState = new ClassicControllerPro(); ccpState.SetCalibration(Calibrations.CalibrationPreset.Default); ConfigureClassicControllerPro(ccpState); ConfigureWiimote(ccpState.wiimote); break; case ControllerType.Guitar: var guitar = new Guitar(); guitar.SetCalibration(Calibrations.CalibrationPreset.Default); ConfigureGuitar(guitar); ConfigureWiimote(guitar.wiimote); break; case ControllerType.TaikoDrum: var takio = new TaikoDrum(); takio.SetCalibration(Calibrations.CalibrationPreset.Default); // for wiimote ConfigureWiimote(takio.wiimote); break; default: // Invalid return; } DeviceType = type; _nextQueue.Enqueue(InputReport.Status); } #region State Configs public void ConfigureProController(ProController pState) { pState.LJoy.rawX = (short)pState.LJoy.centerX; pState.LJoy.rawY = (short)pState.LJoy.centerY; pState.RJoy.rawX = (short)pState.RJoy.centerX; pState.RJoy.rawY = (short)pState.RJoy.centerY; State = pState; } public void ConfigureWiimote(Wiimote wState) { wState.accelerometer.rawX = (short)wState.accelerometer.centerX; wState.accelerometer.rawY = (short)wState.accelerometer.centerY; wState.accelerometer.rawZ = (short)wState.accelerometer.centerZ; State = wState; } public void ConfigureNunchuk(Nunchuk nState) { nState.joystick.rawX = (short)nState.joystick.centerX; nState.joystick.rawY = (short)nState.joystick.centerY; nState.accelerometer.rawX = (short)nState.accelerometer.centerX; nState.accelerometer.rawY = (short)nState.accelerometer.centerY; nState.accelerometer.rawZ = (short)nState.accelerometer.centerZ; State = nState; } public void ConfigureClassicController(ClassicController cState) { cState.LJoy.rawX = (short)cState.LJoy.centerX; cState.LJoy.rawY = (short)cState.LJoy.centerY; cState.RJoy.rawX = (short)cState.RJoy.centerX; cState.RJoy.rawY = (short)cState.RJoy.centerY; State = cState; } public void ConfigureClassicControllerPro(ClassicControllerPro ccpState) { ccpState.LJoy.rawX = (short)ccpState.LJoy.centerX; ccpState.LJoy.rawY = (short)ccpState.LJoy.centerY; ccpState.RJoy.rawX = (short)ccpState.RJoy.centerX; ccpState.RJoy.rawY = (short)ccpState.RJoy.centerY; State = ccpState; } public void ConfigureGuitar(Guitar guitar) { guitar.joystick.rawX = (short)guitar.joystick.centerX; guitar.joystick.rawY = (short)guitar.joystick.centerY; State = guitar; } public void ConfigureGameCubeAdapter(GameCubeAdapter gState) { gState.port1.joystick.rawX = gState.port1.joystick.centerX; gState.port1.joystick.rawY = gState.port1.joystick.centerY; gState.port1.cStick.rawX = gState.port1.cStick.centerX; gState.port1.cStick.rawY = gState.port1.cStick.centerY; gState.port2.joystick.rawX = gState.port2.joystick.centerX; gState.port2.joystick.rawY = gState.port2.joystick.centerY; gState.port2.cStick.rawX = gState.port2.cStick.centerX; gState.port2.cStick.rawY = gState.port2.cStick.centerY; gState.port3.joystick.rawX = gState.port3.joystick.centerX; gState.port3.joystick.rawY = gState.port3.joystick.centerY; gState.port3.cStick.rawX = gState.port3.cStick.centerX; gState.port3.cStick.rawY = gState.port3.cStick.centerY; gState.port4.joystick.rawX = gState.port4.joystick.centerX; gState.port4.joystick.rawY = gState.port4.joystick.centerY; gState.port4.cStick.rawX = gState.port4.cStick.centerX; gState.port4.cStick.rawY = gState.port4.cStick.centerY; State = gState; } #endregion #region System.IO.Stream Implimentation public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotImplementedException(); } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { if (DeviceType == ControllerType.Other) { GameCubeAdapter gcn = (GameCubeAdapter)State; Array.Copy(GetGCNController(gcn.port1), 0, buffer, 1, 9); Array.Copy(GetGCNController(gcn.port2), 0, buffer, 10, 9); Array.Copy(GetGCNController(gcn.port3), 0, buffer, 19, 9); Array.Copy(GetGCNController(gcn.port4), 0, buffer, 28, 9); buffer[1] |= (byte)(gcn.port1Connected ? 0x10 : 0x00); buffer[10] |= (byte)(gcn.port2Connected ? 0x10 : 0x00); buffer[19] |= (byte)(gcn.port3Connected ? 0x10 : 0x00); buffer[28] |= (byte)(gcn.port4Connected ? 0x10 : 0x00); return buffer.Length; } int value = -1; // This won't block since Read is call asynchronously while (_reportQueue.Count == 0 && (_nextQueue.Count != 0 && (byte)_nextQueue.Peek() < 0x30)) ; // Set Error buffer[4] = 0x00; // Assuming we are sending these bytes (# read) value = buffer.Length; byte[] coreBtns = GetCoreButtons(); if (_nextQueue.Count > 0) NextReport = _nextQueue.Dequeue(); else NextReport = DataReportMode; if (_reportQueue.Count > 0) _lastReport = _reportQueue.Dequeue(); else _lastReport = null; switch (NextReport) { case InputReport.Status: // 20 BB BB LF 00 00 VV // 20 - Status type buffer[0] = (byte)InputReport.Status; // BB BB - Core Buttons buffer[1] = coreBtns[0]; buffer[2] = coreBtns[1]; // F - Flags: Battery Low, Extension, Speaker Enabled, IR Sensor Enabled buffer[3] = (byte)(BatteryLow ? 0x01 : 0x00); buffer[3] += (byte)(DeviceType != ControllerType.Wiimote ? 0x02 : 0x00); //buffer[3] += (byte)(Speaker ? 0x04 : 0x00); //buffer[3] += (byte)(IRSensor ? 0x08 : 0x00); // L - LEDs buffer[3] += (byte)(LED_1 ? 0x10 : 0x00); buffer[3] += (byte)(LED_2 ? 0x20 : 0x00); buffer[3] += (byte)(LED_3 ? 0x40 : 0x00); buffer[3] += (byte)(LED_4 ? 0x80 : 0x00); // VV - Battery Level buffer[6] = BatteryLevel; break; case InputReport.ReadMem: // 21 BB BB SE AA AA DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD // 21 - Read Memory buffer[0] = 0x21; // BB BB - Core Buttons buffer[1] = coreBtns[0]; buffer[2] = coreBtns[1]; // E - Error Code buffer[3] = 0x00; // S - Data Size buffer[3] += 0xF0; // AA AA - Last 4 bytes of the requested address //buffer[4] = _lastReport[3]; //buffer[5] = _lastReport[4]; // DD - Data bytes padded to 16 var typeBytes = BitConverter.GetBytes((long)DeviceType); buffer[6] = typeBytes[5]; buffer[7] = typeBytes[4]; buffer[8] = typeBytes[3]; buffer[9] = typeBytes[2]; buffer[10] = typeBytes[1]; buffer[11] = typeBytes[0]; if (_lastReport.Length >= 4 && _lastReport[4] == 250) { //NextReport = DataReportMode; _nextQueue.Enqueue(DataReportMode); } break; case InputReport.Acknowledge: // 22 BB BB RR EE // 22 - Acknowledge Report buffer[0] = 0x22; // BB BB - Core Buttons buffer[1] = coreBtns[0]; buffer[2] = coreBtns[1]; // RR - Output Report that is being acknowledged // EE - Error Code buffer[4] = 0x00; break; case InputReport.BtnsOnly: // 30 BB BB buffer[0] = 0x30; buffer[1] = coreBtns[0]; buffer[2] = coreBtns[1]; break; case InputReport.BtnsAcc: // 31 BB BB AA AA AA buffer[0] = 0x31; buffer[1] = coreBtns[0]; buffer[2] = coreBtns[1]; break; case InputReport.BtnsExt: // 32 BB BB EE EE EE EE EE EE EE EE buffer[0] = 0x32; buffer[1] = coreBtns[0]; buffer[2] = coreBtns[1]; Array.Copy(GetExtension(), 0, buffer, 3, 8); break; case InputReport.BtnsAccIR: // 33 BB BB AA AA AA II II II II II II II II II II II II buffer[0] = 0x33; buffer[1] = coreBtns[0]; buffer[2] = coreBtns[1]; break; case InputReport.BtnsExtB: // 34 BB BB EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE buffer[0] = 0x34; buffer[1] = coreBtns[0]; buffer[2] = coreBtns[1]; Array.Copy(GetExtension(), 0, buffer, 3, 19); break; case InputReport.BtnsAccExt: // 35 BB BB AA AA AA EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE buffer[0] = 0x35; buffer[1] = coreBtns[0]; buffer[2] = coreBtns[1]; Array.Copy(GetExtension(), 0, buffer, 6, 16); break; case InputReport.BtnsIRExt: // 36 BB BB II II II II II II II II II II EE EE EE EE EE EE EE EE EE buffer[0] = 0x36; buffer[1] = coreBtns[0]; buffer[2] = coreBtns[1]; Array.Copy(GetExtension(), 0, buffer, 13, 9); break; case InputReport.BtnsAccIRExt: // 37 BB BB AA AA AA II II II II II II II II II II EE EE EE EE EE EE buffer[0] = 0x37; buffer[1] = coreBtns[0]; buffer[2] = coreBtns[1]; Array.Copy(GetExtension(), 0, buffer, 16, 6); break; case InputReport.ExtOnly: // 3d EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE buffer[0] = 0x3D; Array.Copy(GetExtension(), 0, buffer, 1, 21); break; } _lastReport = null; return value; } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { //_lastReport = buffer; _reportQueue.Enqueue(buffer); OutputReport output = (OutputReport)buffer[0]; switch (output) { case OutputReport.StatusRequest: //NextReport = InputReport.Status; _nextQueue.Enqueue(InputReport.Status); RumbleByte = buffer[1]; break; case OutputReport.ReadMemory: // 21 BB BB SE AA AA DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD //if (NextReport != InputReport.ReadMem) if (!_nextQueue.Contains(InputReport.ReadMem)) { // Extension Step A //NextReport = InputReport.ReadMem; _nextQueue.Enqueue(InputReport.ReadMem); } else { // Extension Step B } break; case OutputReport.LEDs: // 11 LL //NextReport = InputReport.Acknowledge; _nextQueue.Enqueue(InputReport.Acknowledge); LED_1 = (buffer[1] & 0x10) != 0x00; LED_2 = (buffer[1] & 0x20) != 0x00; LED_3 = (buffer[1] & 0x30) != 0x00; LED_4 = (buffer[1] & 0x40) != 0x00; break; case OutputReport.DataReportMode: // 12 TT MM DataReportMode = (InputReport)buffer[2]; //if ((byte)NextReport >= 0x30) //{ // NextReport = DataReportMode; //} if (_nextQueue.Count == 0 || (byte)_nextQueue.Peek() >= 0x30) { _nextQueue.Enqueue(DataReportMode); } break; } } #endregion #region Get Input Bytes protected byte[] GetCoreButtons() { byte[] buf = new byte[2]; var buttons = new CoreButtons(); switch (DeviceType) { case ControllerType.ProController: var p = (ProController)State; buttons.A = p.A; buttons.B = p.B; buttons.Plus = p.Plus; buttons.Minus = p.Minus; buttons.Home = p.Home; buttons.Up = p.Up; buttons.Down = p.Down; buttons.Left = p.Left; buttons.Right = p.Right; break; case ControllerType.Wiimote: buttons = ((Wiimote)State).buttons; break; case ControllerType.Nunchuk: case ControllerType.NunchukB: case ControllerType.ClassicController: case ControllerType.ClassicControllerPro: case ControllerType.MotionPlus: case ControllerType.MotionPlusCC: case ControllerType.MotionPlusNunchuk: case ControllerType.Guitar: case ControllerType.TaikoDrum: //case ControllerType.Drums: //case ControllerType.TurnTable: //case ControllerType.DrawTablet: buttons = ((IWiimoteExtension)State).wiimote.buttons; break; } buf[0] |= (byte)(buttons.Left ? 0x01 : 0x00); buf[0] |= (byte)(buttons.Right ? 0x02 : 0x00); buf[0] |= (byte)(buttons.Down ? 0x04 : 0x00); buf[0] |= (byte)(buttons.Up ? 0x08 : 0x00); buf[0] |= (byte)(buttons.Plus ? 0x10 : 0x00); buf[1] |= (byte)(buttons.Two ? 0x01 : 0x00); buf[1] |= (byte)(buttons.One ? 0x02 : 0x00); buf[1] |= (byte)(buttons.B ? 0x04 : 0x00); buf[1] |= (byte)(buttons.A ? 0x08 : 0x00); buf[1] |= (byte)(buttons.Minus ? 0x10 : 0x00); buf[1] |= (byte)(buttons.Home ? 0x80 : 0x00); return buf; } protected byte[] GetAccelerometer() { byte[] buf = new byte[3]; return buf; } protected byte[] Get9ByteIR() { byte[] buf = new byte[9]; return buf; } protected byte[] Get10ByteIR() { byte[] buf = new byte[10]; return buf; } protected byte[] GetExtension() { byte[] buf = new byte[21]; if (DeviceType == ControllerType.ProController) { var pro = (ProController)State; var lx = BitConverter.GetBytes(pro.LJoy.rawX); var ly = BitConverter.GetBytes(pro.LJoy.rawY); var rx = BitConverter.GetBytes(pro.RJoy.rawX); var ry = BitConverter.GetBytes(pro.RJoy.rawY); buf[0] = lx[0]; buf[1] = lx[1]; buf[2] = rx[0]; buf[3] = rx[1]; buf[4] = ly[0]; buf[5] = ly[1]; buf[6] = ry[0]; buf[7] = ry[1]; buf[8] = 0x00; buf[8] += (byte)(!pro.R ? 0x02 : 0x00); buf[8] += (byte)(!pro.Plus ? 0x04 : 0x00); buf[8] += (byte)(!pro.Home ? 0x08 : 0x00); buf[8] += (byte)(!pro.Minus ? 0x10 : 0x00); buf[8] += (byte)(!pro.L ? 0x20 : 0x00); buf[8] += (byte)(!pro.Down ? 0x40 : 0x00); buf[8] += (byte)(!pro.Right ? 0x80 : 0x00); buf[9] = 0x00; buf[9] += (byte)(!pro.Up ? 0x01 : 0x00); buf[9] += (byte)(!pro.Left ? 0x02 : 0x00); buf[9] += (byte)(!pro.ZR ? 0x04 : 0x00); buf[9] += (byte)(!pro.X ? 0x08 : 0x00); buf[9] += (byte)(!pro.A ? 0x10 : 0x00); buf[9] += (byte)(!pro.Y ? 0x20 : 0x00); buf[9] += (byte)(!pro.B ? 0x40 : 0x00); buf[9] += (byte)(!pro.ZL ? 0x80 : 0x00); buf[10] = 0x00; buf[10] += (byte)(!pro.RStick ? 0x01 : 0x00); buf[10] += (byte)(!pro.LStick ? 0x02 : 0x00); buf[10] += (byte)(!pro.charging ? 0x04 : 0x00); buf[10] += (byte)(!pro.usbConnected ? 0x08 : 0x00); } else if (DeviceType == ControllerType.Nunchuk || DeviceType == ControllerType.NunchukB) { var nun = (Nunchuk)State; var x = BitConverter.GetBytes(nun.joystick.rawX); var y = BitConverter.GetBytes(nun.joystick.rawY); buf[0] = x[0]; buf[1] = y[0]; // Generate Accelerometer bytes buf[5] = 0x00; buf[5] += (byte)(!nun.Z ? 0x01 : 0x00); buf[5] += (byte)(!nun.C ? 0x02 : 0x00); } else if (DeviceType == ControllerType.ClassicController) { var cc = (ClassicController)State; var lx = BitConverter.GetBytes(cc.LJoy.rawX); var ly = BitConverter.GetBytes(cc.LJoy.rawY); var rx = BitConverter.GetBytes(cc.RJoy.rawX); var ry = BitConverter.GetBytes(cc.RJoy.rawY); var l = BitConverter.GetBytes(cc.L.rawValue); var r = BitConverter.GetBytes(cc.R.rawValue); buf[0] = (byte)(lx[0] + (rx[0] << 3 & 0xC0)); buf[1] = (byte)(ly[0] + (rx[0] << 5 & 0xC0)); buf[2] = (byte)(ry[0] + (rx[0] << 7 & 0x80) + (l[0] << 2 & 0x60)); buf[3] = (byte)(r[0] + (l[0] << 5 & 0xE0)); buf[4] = 0x01; buf[4] += (byte)(!cc.RFull ? 0x02 : 0x00); buf[4] += (byte)(!cc.Plus ? 0x04 : 0x00); buf[4] += (byte)(!cc.Home ? 0x08 : 0x00); buf[4] += (byte)(!cc.Minus ? 0x10 : 0x00); buf[4] += (byte)(!cc.LFull ? 0x20 : 0x00); buf[4] += (byte)(!cc.Down ? 0x40 : 0x00); buf[4] += (byte)(!cc.Right ? 0x80 : 0x00); buf[5] = 0x00; buf[5] += (byte)(!cc.Up ? 0x01 : 0x00); buf[5] += (byte)(!cc.Left ? 0x02 : 0x00); buf[5] += (byte)(!cc.ZR ? 0x04 : 0x00); buf[5] += (byte)(!cc.X ? 0x08 : 0x00); buf[5] += (byte)(!cc.A ? 0x10 : 0x00); buf[5] += (byte)(!cc.Y ? 0x20 : 0x00); buf[5] += (byte)(!cc.B ? 0x40 : 0x00); buf[5] += (byte)(!cc.ZL ? 0x80 : 0x00); } else if (DeviceType == ControllerType.ClassicControllerPro) { var ccp = (ClassicControllerPro)State; var lx = BitConverter.GetBytes(ccp.LJoy.rawX); var ly = BitConverter.GetBytes(ccp.LJoy.rawY); var rx = BitConverter.GetBytes(ccp.RJoy.rawX); var ry = BitConverter.GetBytes(ccp.RJoy.rawY); buf[0] = (byte)(lx[0] + (rx[0] << 3 & 0xC0)); buf[1] = (byte)(ly[0] + (rx[0] << 5 & 0xC0)); buf[2] = (byte)(ry[0] + (rx[0] << 7 & 0x80)); buf[4] = 0x01; buf[4] += (byte)(!ccp.R ? 0x02 : 0x00); buf[4] += (byte)(!ccp.Plus ? 0x04 : 0x00); buf[4] += (byte)(!ccp.Home ? 0x08 : 0x00); buf[4] += (byte)(!ccp.Minus ? 0x10 : 0x00); buf[4] += (byte)(!ccp.L ? 0x20 : 0x00); buf[4] += (byte)(!ccp.Down ? 0x40 : 0x00); buf[4] += (byte)(!ccp.Right ? 0x80 : 0x00); buf[5] = 0x00; buf[5] += (byte)(!ccp.Up ? 0x01 : 0x00); buf[5] += (byte)(!ccp.Left ? 0x02 : 0x00); buf[5] += (byte)(!ccp.ZR ? 0x04 : 0x00); buf[5] += (byte)(!ccp.X ? 0x08 : 0x00); buf[5] += (byte)(!ccp.A ? 0x10 : 0x00); buf[5] += (byte)(!ccp.Y ? 0x20 : 0x00); buf[5] += (byte)(!ccp.B ? 0x40 : 0x00); buf[5] += (byte)(!ccp.ZL ? 0x80 : 0x00); } else if (DeviceType == ControllerType.Guitar) { var g = (Guitar)State; var x = BitConverter.GetBytes(g.joystick.rawX); var y = BitConverter.GetBytes(g.joystick.rawY); buf[0] = (byte)(x[0] + 0xC0); buf[1] = (byte)(y[0] + 0xC0); // Toucbar buf[2] = 0x00; if (g.T5) { if (g.T4) buf[2] = 0x1A; else buf[2] = 0x1F; } else if (g.T4) { if (g.T3) buf[2] = 0x14; else buf[2] = 0x17; } else if (g.T3) { if (g.T2) buf[2] = 0x0C; else buf[2] = 0x12; } else if (g.T2) { if (g.T1) buf[2] = 0x07; else buf[2] = 0x0A; } else if (g.T1) { buf[2] = 0x04; } // Whammy bar buf[3] = BitConverter.GetBytes(g.whammyBar.rawValue)[0]; buf[4] = 0xAB; buf[4] += (byte)(!g.Plus ? 0x04 : 0x00); buf[4] += (byte)(!g.Minus ? 0x10 : 0x00); buf[4] += (byte)(!g.StrumDown ? 0x40 : 0x00); buf[5] = 0x06; buf[5] += (byte)(!g.StrumUp ? 0x01 : 0x00); buf[5] += (byte)(!g.Yellow ? 0x08 : 0x00); buf[5] += (byte)(!g.Green ? 0x10 : 0x00); buf[5] += (byte)(!g.Blue ? 0x20 : 0x00); buf[5] += (byte)(!g.Red ? 0x40 : 0x00); buf[5] += (byte)(!g.Orange ? 0x80 : 0x00); } else if (DeviceType == ControllerType.TaikoDrum) { var tak = (TaikoDrum)State; buf[0] = 0x87; buf[0] += (byte)(!tak.rimRight ? 0x08 : 0x00); buf[0] += (byte)(!tak.centerRight ? 0x10 : 0x00); buf[0] += (byte)(!tak.rimLeft ? 0x20 : 0x00); buf[0] += (byte)(!tak.centerLeft ? 0x40 : 0x00); } return buf; } protected byte[] GetGCNController(GameCubeController controller) { byte[] buf = new byte[9]; buf[1] |= (byte)(controller.A ? 0x01 : 0x00); buf[1] |= (byte)(controller.B ? 0x02 : 0x00); buf[1] |= (byte)(controller.X ? 0x04 : 0x00); buf[1] |= (byte)(controller.Y ? 0x08 : 0x00); buf[1] |= (byte)(controller.Left ? 0x10 : 0x00); buf[1] |= (byte)(controller.Right ? 0x20 : 0x00); buf[1] |= (byte)(controller.Down ? 0x40 : 0x00); buf[1] |= (byte)(controller.Up ? 0x80 : 0x00); buf[2] |= (byte)(controller.Start ? 0x01 : 0x00); buf[2] |= (byte)(controller.Z ? 0x02 : 0x00); buf[2] |= (byte)(controller.R.full ? 0x04 : 0x00); buf[2] |= (byte)(controller.L.full ? 0x08 : 0x00); buf[3] = (byte)controller.joystick.rawX; buf[4] = (byte)controller.joystick.rawY; buf[5] = (byte)controller.cStick.rawX; buf[6] = (byte)controller.cStick.rawY; buf[7] = (byte)controller.L.rawValue; buf[8] = (byte)controller.R.rawValue; return buf; } #endregion } } <|start_filename|>Shared/ICommonStream.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Shared { interface ICommonStream { bool OpenConnection(); void Close(); } } <|start_filename|>Scp/XInput_Scp/DS3Controller.h<|end_filename|> #pragma once class CDS3Controller : public CSCPController { public: static const DWORD CollectionSize = 1; public: CDS3Controller(DWORD dwIndex); protected: virtual void FormatReport(void); virtual void XInputMapState(void); }; <|start_filename|>Scp/ScpBus/inc/ScpVBus.h<|end_filename|> //{F679F562-3164-42CE-A4DB-E7DDBE723909} DEFINE_GUID (GUID_DEVINTERFACE_SCPVBUS, 0xf679f562, 0x3164, 0x42ce, 0xa4, 0xdb, 0xe7, 0xdd, 0xbe, 0x72, 0x39, 0x9); #ifndef __SCPVBUS_H #define __SCPVBUS_H #define BUSENUM_IOCTL(_index_) CTL_CODE(FILE_DEVICE_BUSENUM, _index_, METHOD_BUFFERED, FILE_READ_DATA) #define IOCTL_BUSENUM_PLUGIN_HARDWARE BUSENUM_IOCTL(0x0) #define IOCTL_BUSENUM_UNPLUG_HARDWARE BUSENUM_IOCTL(0x1) #define IOCTL_BUSENUM_EJECT_HARDWARE BUSENUM_IOCTL(0x2) #define IOCTL_BUSENUM_REPORT_HARDWARE BUSENUM_IOCTL(0x3) #define REPORT_SIZE 20 // // Data structures used in User IoCtls // typedef struct _BUSENUM_PLUGIN_HARDWARE { __in ULONG Size; __in ULONG SerialNo; ULONG Reserved[2]; } BUSENUM_PLUGIN_HARDWARE, *PBUSENUM_PLUGIN_HARDWARE; typedef struct _BUSENUM_UNPLUG_HARDWARE { __in ULONG Size; __in ULONG SerialNo; ULONG Reserved[2]; } BUSENUM_UNPLUG_HARDWARE, *PBUSENUM_UNPLUG_HARDWARE; typedef struct _BUSENUM_EJECT_HARDWARE { __in ULONG Size; __in ULONG SerialNo; ULONG Reserved[2]; } BUSENUM_EJECT_HARDWARE, *PBUSENUM_EJECT_HARDWARE; typedef struct _BUSENUM_REPORT_HARDWARE { __in ULONG Size; __in ULONG SerialNo; UCHAR Data[REPORT_SIZE]; } BUSENUM_REPORT_HARDWARE, *PBUSENUM_REPORT_HARDWARE; #endif <|start_filename|>Scp/ScpControl/RootHub.Designer.cs<|end_filename|> namespace ScpControl { partial class RootHub { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.UDP_Worker = new System.ComponentModel.BackgroundWorker(); this.scpMap = new ScpControl.ScpMapper(this.components); // // UDP_Worker // this.UDP_Worker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.UDP_Worker_Thread); // // scpMapper // this.scpMap.Active = ""; this.scpMap.Xml = "System.Xml.XmlDocument"; } #endregion private System.ComponentModel.BackgroundWorker UDP_Worker; private ScpMapper scpMap; } } <|start_filename|>Scp/ScpMonitor/SettingsForm.cs<|end_filename|> using System; using System.Windows.Forms; using System.Text; using System.Net; using System.Net.Sockets; namespace ScpMonitor { public partial class SettingsForm : Form { protected Char[] m_Delim = new Char[] { '^' }; protected IPEndPoint m_ServerEp = new IPEndPoint(IPAddress.Loopback, 26760); protected UdpClient m_Server = new UdpClient(); protected Byte[] m_Buffer = new Byte[17]; public SettingsForm() { InitializeComponent(); m_Server.Client.ReceiveTimeout = 250; ttSSP.SetToolTip(cbSSP, @"Requires Service Restart"); } public void Reset() { CenterToScreen(); } public void Request() { try { m_Buffer[1] = 0x03; if (m_Server.Send(m_Buffer, m_Buffer.Length, m_ServerEp) == m_Buffer.Length) { IPEndPoint ReferenceEp = new IPEndPoint(IPAddress.Loopback, 0); Byte[] Buffer = m_Server.Receive(ref ReferenceEp); tbIdle.Value = Buffer[ 2]; cbLX.Checked = Buffer[ 3] == 1; cbLY.Checked = Buffer[ 4] == 1; cbRX.Checked = Buffer[ 5] == 1; cbRY.Checked = Buffer[ 6] == 1; cbLED.Checked = Buffer[ 7] == 1; cbRumble.Checked = Buffer[ 8] == 1; cbTriggers.Checked = Buffer[ 9] == 1; tbLatency.Value = Buffer[10]; tbLeft.Value = Buffer[11]; tbRight.Value = Buffer[12]; cbNative.Checked = Buffer[13] == 1; cbSSP.Checked = Buffer[14] == 1; tbBrightness.Value = Buffer[15]; cbForce.Checked = Buffer[16] == 1; } } catch { } } protected void Form_Load(object sender, EventArgs e) { Icon = Properties.Resources.Scp_All; } protected void Form_Closing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; Hide(); } } protected void btnOK_Click(object sender, EventArgs e) { m_Buffer[ 1] = 0x04; m_Buffer[ 2] = (Byte) tbIdle.Value; m_Buffer[ 3] = (Byte)(cbLX.Checked ? 0x01 : 0x00); m_Buffer[ 4] = (Byte)(cbLY.Checked ? 0x01 : 0x00); m_Buffer[ 5] = (Byte)(cbRX.Checked ? 0x01 : 0x00); m_Buffer[ 6] = (Byte)(cbRY.Checked ? 0x01 : 0x00); m_Buffer[ 7] = (Byte)(cbLED.Checked ? 0x01 : 0x00); m_Buffer[ 8] = (Byte)(cbRumble.Checked ? 0x01 : 0x00); m_Buffer[ 9] = (Byte)(cbTriggers.Checked ? 0x01 : 0x00); m_Buffer[10] = (Byte) tbLatency.Value; m_Buffer[11] = (Byte) tbLeft.Value; m_Buffer[12] = (Byte) tbRight.Value; m_Buffer[13] = (Byte)(cbNative.Checked ? 0x01 : 0x00); m_Buffer[14] = (Byte)(cbSSP.Checked ? 0x01 : 0x00); m_Buffer[15] = (Byte) tbBrightness.Value; m_Buffer[16] = (Byte)(cbForce.Checked ? 0x01 : 0x00); m_Server.Send(m_Buffer, m_Buffer.Length, m_ServerEp); Hide(); } protected void btnCancel_Click(object sender, EventArgs e) { Hide(); } protected void tbIdle_ValueChanged(object sender, EventArgs e) { Int32 Value = tbIdle.Value; if (Value == 0) { lblIdle.Text = "Idle Timeout : Disabled"; } else if (Value == 1) { lblIdle.Text = "Idle Timeout : 1 minute"; } else { lblIdle.Text = String.Format("Idle Timeout : {0} minutes", Value); } } protected void tbLatency_ValueChanged(object sender, EventArgs e) { Int32 Value = tbLatency.Value << 4; lblLatency.Text = String.Format("DS3 Rumble Latency : {0} ms", Value); } protected void tbBrightness_ValueChanged(object sender, EventArgs e) { Int32 Value = tbBrightness.Value; if (Value == 0) { lblBrightness.Text = String.Format("DS4 Light Bar Brighness : Disabled", Value); } else { lblBrightness.Text = String.Format("DS4 Light Bar Brighness : {0}", Value); } } } } <|start_filename|>WiinUSoft/App.xaml.cs<|end_filename|> using Microsoft.Shell; using System; using System.Collections.Generic; using System.Windows; namespace WiinUSoft { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application, ISingleInstanceApp { internal const string PROFILE_FILTER = "WiinUSoft Profile|*.wsp"; private const string Unique = "wiinupro-or-wiinusoft-instance"; private const string NATIVE_OVERLAPPED = "NaitiveOverlapped"; [STAThread] public static void Main() { if (SingleInstance<App>.InitializeAsFirstInstance(Unique)) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; var application = new App(); application.InitializeComponent(); application.Run(); // Allow single instance code to perform cleanup operations SingleInstance<App>.Cleanup(); } } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args) { Exception e = (Exception)args.ExceptionObject; // Ignore this native code exception. // Can't handle it, and it doesn't seem to have any negative effects. if (e.StackTrace.Contains(NATIVE_OVERLAPPED)) return; SingleInstance<App>.Cleanup(); Current.Dispatcher.Invoke(new Action(() => { var box = new ErrorWindow(e); box.ShowDialog(); })); } public bool SignalExternalCommandLineArgs(IList<string> args) { MessageBox.Show("WiinUSoft is already Running!"); // show the original instance if (this.MainWindow.WindowState == WindowState.Minimized) { ((MainWindow)this.MainWindow).ShowWindow(); } this.MainWindow.Activate(); return true; } } } <|start_filename|>WiinUPro/Assignments/AssignmentProfile.cs<|end_filename|> using System.Collections.Generic; namespace WiinUPro { public class AssignmentProfile { public List<AssignmentPair> MainAssignments; public List<AssignmentPair> RedAssignments; public List<AssignmentPair> BlueAssignments; public List<AssignmentPair> GreenAssignments; public AssignmentProfile SubProfile; public string SubName; public bool[] RumbleDevices = new bool[4]; public AssignmentProfile() { MainAssignments = new List<AssignmentPair>(); RedAssignments = new List<AssignmentPair>(); BlueAssignments = new List<AssignmentPair>(); GreenAssignments = new List<AssignmentPair>(); } public AssignmentProfile(Dictionary<string, AssignmentCollection>[] assignments) : this() { FromAssignmentArray(assignments); } public Dictionary<string, AssignmentCollection>[] ToAssignmentArray(IDeviceControl device = null) { Dictionary<string, AssignmentCollection>[] result = new[] { new Dictionary<string, AssignmentCollection>(), new Dictionary<string, AssignmentCollection>(), new Dictionary<string, AssignmentCollection>(), new Dictionary<string, AssignmentCollection>() }; AddAssignments(result[0], MainAssignments, device); AddAssignments(result[1], RedAssignments, device); AddAssignments(result[2], BlueAssignments, device); AddAssignments(result[3], GreenAssignments, device); return result; } public void FromAssignmentArray(Dictionary<string, AssignmentCollection>[] assignments) { if (assignments.Length > 0) { foreach (var a in assignments[0]) MainAssignments.Add(new AssignmentPair(a.Key, a.Value)); } if (assignments.Length > 1) { foreach (var a in assignments[1]) RedAssignments.Add(new AssignmentPair(a.Key, a.Value)); } if (assignments.Length > 2) { foreach (var a in assignments[2]) BlueAssignments.Add(new AssignmentPair(a.Key, a.Value)); } if (assignments.Length > 3) { foreach (var a in assignments[3]) GreenAssignments.Add(new AssignmentPair(a.Key, a.Value)); } } private void AddAssignments(Dictionary<string, AssignmentCollection> mapping, List<AssignmentPair> assignmentPairs, IDeviceControl device = null) { foreach (var pair in assignmentPairs) { var collection = pair.GetCollection(); foreach (var assignment in collection) { if (assignment is ShiftAssignment) { (assignment as ShiftAssignment).SetControl(device); } } mapping.Add(pair.input, pair.GetCollection()); } } } public class AssignmentPair { public string input; public List<AssignmentInfo> collection; public AssignmentPair() { input = ""; collection = new List<AssignmentInfo>(); } public AssignmentPair(string inputName, AssignmentCollection assignments) : this() { input = inputName; foreach (var a in assignments) { AssignmentInfo info = new AssignmentInfo(); if (a is KeyboardAssignment) { info.type = AssignmentType.Keyboard; info.keyboardAssignment = (KeyboardAssignment)a; } else if (a is MouseAssignment) { info.type = AssignmentType.Mouse; info.mouseAssignment = (MouseAssignment)a; } else if (a is MouseButtonAssignment) { info.type = AssignmentType.MouseButton; info.mouseButtonAssignment = (MouseButtonAssignment)a; } else if (a is MouseScrollAssignment) { info.type = AssignmentType.MouseScroll; info.mouseScrollAssignment = (MouseScrollAssignment)a; } else if (a is ShiftAssignment) { info.type = AssignmentType.Shift; info.shiftAssignment = (ShiftAssignment)a; } else if (a is XInputAxisAssignment) { info.type = AssignmentType.XboxAxis; info.xinputAxisAssignment = (XInputAxisAssignment)a; } else if (a is XInputButtonAssignment) { info.type = AssignmentType.XboxButton; info.xinputButtonAssignment = (XInputButtonAssignment)a; } else if (a is VJoyButtonAssignment) { info.type = AssignmentType.VJoyButton; info.vjoyButtonAssignment = (VJoyButtonAssignment)a; } else if (a is VJoyAxisAssignment) { info.type = AssignmentType.VJoyAxis; info.vjoyAxisAssignment = (VJoyAxisAssignment)a; } else if (a is VJoyPOVAssignment) { info.type = AssignmentType.VJoyPOV; info.vjoyPOVAssignment = (VJoyPOVAssignment)a; } collection.Add(info); } } public AssignmentCollection GetCollection() { AssignmentCollection result = new AssignmentCollection(); foreach (var c in collection) { switch (c.type) { case AssignmentType.Keyboard: result.Add(c.keyboardAssignment); break; case AssignmentType.Mouse: result.Add(c.mouseAssignment); break; case AssignmentType.MouseButton: result.Add(c.mouseButtonAssignment); break; case AssignmentType.MouseScroll: result.Add(c.mouseScrollAssignment); break; case AssignmentType.Shift: result.Add(c.shiftAssignment); break; case AssignmentType.XboxAxis: result.Add(c.xinputAxisAssignment); break; case AssignmentType.XboxButton: result.Add(c.xinputButtonAssignment); break; case AssignmentType.VJoyButton: result.Add(c.vjoyButtonAssignment); break; case AssignmentType.VJoyAxis: result.Add(c.vjoyAxisAssignment); break; case AssignmentType.VJoyPOV: result.Add(c.vjoyPOVAssignment); break; } } return result; } } public class AssignmentInfo { public AssignmentType type; public KeyboardAssignment keyboardAssignment; public MouseAssignment mouseAssignment; public MouseButtonAssignment mouseButtonAssignment; public MouseScrollAssignment mouseScrollAssignment; public ShiftAssignment shiftAssignment; public XInputAxisAssignment xinputAxisAssignment; public XInputButtonAssignment xinputButtonAssignment; public VJoyButtonAssignment vjoyButtonAssignment; public VJoyAxisAssignment vjoyAxisAssignment; public VJoyPOVAssignment vjoyPOVAssignment; } public enum AssignmentType { Keyboard, Mouse, MouseButton, MouseScroll, Shift, XboxAxis, XboxButton, VJoyButton, VJoyAxis, VJoyPOV } } <|start_filename|>Nintroller/Constants.cs<|end_filename|> namespace NintrollerLib { // TODO: Place any magic numbers in this class internal static class Constants { // Vendor ID (Nintendo) & Product IDs public const int VID = 0x057e; public const int PID1 = 0x0306; // Legacy Wiimotes public const int PID2 = 0x0330; // Newer Wiimotes (And Pro Controllers) public const int PID3 = 0x0337; // GCN Adapter // Report Size, There are several reports to choose from public const int REPORT_LENGTH = 22; // Buttons, Accelerometer, IR, and Extension public const int REPORT_LENGTH_GCN = 37; // Wiimote Registers public const int REGISTER_IR = 0x04b00030; public const int REGISTER_IR_SENSITIVITY_1 = 0x04b00000; public const int REGISTER_IR_SENSITIVITY_2 = 0x04b0001a; public const int REGISTER_IR_MODE = 0x04b00033; public const int REGISTER_EXTENSION_INIT_1 = 0x04a400f0; public const int REGISTER_EXTENSION_INIT_2 = 0x04a400fb; public const int REGISTER_EXTENSION_TYPE = 0x04a400fa; public const int REGISTER_EXTENSION_TYPE_2 = 0x04a400fe; public const int REGISTER_EXTENSION_CALIBRATION = 0x04a40020; // Write 0x04 to this register to init motion plus public const int REGISTER_MOTIONPLUS_INIT = 0x04a600fe; // Read 2 bytes from here to identify if motion plus connected public const int REGISTER_MOTIONPLUS = 0x04A600FE; // Write 0x55 to initialze motion plus's extiontion public const int REGISTER_MOTIONPLUS_EXT = 0x04A600F0; // Length and Width between Balance Board Sensors public const int BB_LENGTH = 43; public const int BB_WIDTH = 24; // Pound - KG Conversion public const float KG_TO_LBS = 2.20462262f; } } <|start_filename|>WiinUPro/Directors/ScpDirector.cs<|end_filename|> using System.Collections.Generic; using ScpControl; namespace WiinUPro { public class ScpDirector { public const int MAX_XINPUT_INSTNACES = 4; #region Access public static ScpDirector Access { get; protected set; } static ScpDirector() { // TODO Director: Initialize SCPControl Access = new ScpDirector(); Access.Available = true; } #endregion protected List<XInputBus> _xInstances; protected bool[] _deviceStatus; /// <summary> /// Gets the desired XInputBus (0 to 3). /// </summary> /// <param name="index">Any out of range index will return the first device.</param> /// <returns>The XInputBus</returns> //protected XInputBus this[int index] //{ // get // { // if (index < 0 || index >= MAX_XINPUT_INSTNACES) // { // index = 0; // } // // while (index >= _xInstances.Count) // { // _xInstances.Add(new XInputBus(index)); // } // // return _xInstances[index]; // } //} public bool Available { get; protected set; } public int Instances { get { return _xInstances.Count; } } // Left motor is the larger one public delegate void RumbleChangeDelegate(byte leftMotor, byte rightMotor); public ScpDirector() { _xInstances = new List<XInputBus> { new XInputBus((int)XInput_Device.Device_A), new XInputBus((int)XInput_Device.Device_B), new XInputBus((int)XInput_Device.Device_C), new XInputBus((int)XInput_Device.Device_D) }; _deviceStatus = new bool[] { false, false, false, false }; } public void SetButton(X360Button button, bool pressed) { SetButton(button, pressed, XInput_Device.Device_A); } public void SetButton(X360Button button, bool pressed, XInput_Device device) { //this[(int)device].SetInput(button, pressed); _xInstances[(int)device - 1].SetInput(button, pressed); } public void SetAxis(X360Axis axis, float value) { SetAxis(axis, value, XInput_Device.Device_A); } public void SetAxis(X360Axis axis, float value, XInput_Device device) { //this[(int)device].SetInput(axis, value); _xInstances[(int)device - 1].SetInput(axis, value); } /// <summary> /// Connects up to the given device. /// Ex: If C is used then A, B, & C will be connected. /// </summary> /// <param name="device">The highest device to be connected.</param> /// <returns>If all connections are successful.</returns> public bool ConnectDevice(XInput_Device device) { bool result = _deviceStatus[(int)device - 1]; if (!result) { result = _xInstances[(int)device - 1].Connect(); } return result; } /// <summary> /// Disconnects down to the given device. /// Ex: If A is used then all of the devices will be disconnected. /// </summary> /// <param name="device">The lowest device to be disconnected.</param> /// <returns>If all devices were disconnected</returns> public bool DisconnectDevice(XInput_Device device) { if (_deviceStatus[(int)device - 1]) { return true; } else { return _xInstances[(int)device - 1].Disconnect(); } } public bool IsConnected(XInput_Device device) { return _xInstances[(int)device - 1].PluggedIn; } public void Apply(XInput_Device device) { //this[(int)device].Update(); _xInstances[(int)device - 1].Update(); } public void ApplyAll() { foreach (var bus in _xInstances.ToArray()) { if (bus.PluggedIn) bus.Update(); } } public void SetModifier(int value) { XInputBus.Modifier = value; } public void SubscribeToRumble(XInput_Device device, RumbleChangeDelegate callback) { _xInstances[(int)device - 1].RumbleEvent += callback; } public void UnSubscribeToRumble(XInput_Device device, RumbleChangeDelegate callback) { _xInstances[(int)device - 1].RumbleEvent -= callback; } public enum XInput_Device : int { Device_A = 1, Device_B = 2, Device_C = 3, Device_D = 4 } public struct XInputState { public bool A, B, X, Y; public bool Up, Down, Left, Right; public bool LB, RB, LS, RS; public bool Start, Back, Guide; public float LX, LY, LT; public float RX, RY, RT; public bool this[X360Button btn] { set { switch (btn) { case X360Button.A: A = value; break; case X360Button.B: B = value; break; case X360Button.X: X = value; break; case X360Button.Y: Y = value; break; case X360Button.LB: LB = value; break; case X360Button.RB: RB = value; break; case X360Button.LS: LS = value; break; case X360Button.RS: RS = value; break; case X360Button.Up: Up = value; break; case X360Button.Down: Down = value; break; case X360Button.Left: Left = value; break; case X360Button.Right: Right = value; break; case X360Button.Start: Start = value; break; case X360Button.Back: Back = value; break; case X360Button.Guide: Guide = value; break; default: break; } } get { switch (btn) { case X360Button.A: return A; case X360Button.B: return B; case X360Button.X: return X; case X360Button.Y: return Y; case X360Button.LB: return LB; case X360Button.RB: return RB; case X360Button.LS: return LS; case X360Button.RS: return RS; case X360Button.Up: return Up; case X360Button.Down: return Down; case X360Button.Left: return Left; case X360Button.Right: return Right; case X360Button.Start: return Start; case X360Button.Back: return Back; case X360Button.Guide: return Back; default: return false; } } } public float this[X360Axis axis] { set { switch (axis) { case X360Axis.LX_Hi: LX = value; break; case X360Axis.LX_Lo: LX = -value; break; case X360Axis.LY_Hi: LY = value; break; case X360Axis.LY_Lo: LY = -value; break; case X360Axis.LT: LT = value; break; case X360Axis.RX_Hi: RX = value; break; case X360Axis.RX_Lo: RX = -value; break; case X360Axis.RY_Hi: RY = value; break; case X360Axis.RY_Lo: RY = -value; break; case X360Axis.RT: RT = value; break; default: break; } } get { switch (axis) { case X360Axis.LX_Hi: case X360Axis.LX_Lo: return LX; case X360Axis.LY_Hi: case X360Axis.LY_Lo: return LY; case X360Axis.LT: return LT; case X360Axis.RX_Hi: case X360Axis.RX_Lo: return RX; case X360Axis.RY_Hi: case X360Axis.RY_Lo: return RY; case X360Axis.RT: return RT; default: return 0; } } } public void Reset() { A = B = X = Y = false; Up = Down = Left = Right = false; LB = RB = LS = RS = false; Start = Back = Guide = false; LX = LY = LT = 0; RX = RY = RT = 0; } } protected class BusAccess : BusDevice { public static BusAccess Instance { get { if (_instance == null) { _instance = new BusAccess(); _instance.Open(); _instance.Start(); } return _instance; } } public static BusAccess _instance; protected BusAccess() { App.Current.Exit += App_Exit; } private void App_Exit(object sender, System.Windows.ExitEventArgs e) { if (_instance != null) { _instance.Stop(); _instance.Close(); } } } protected class XInputBus { public static int Modifier; public XInputState inputs; public event RumbleChangeDelegate RumbleEvent; public int ID { get { return _id + Modifier; } protected set { _id = value; } } public bool PluggedIn { get; protected set; } protected BusAccess busRef; private int _id; private float tempLX = -10; private float tempLY = -10; private float tempRX = -10; private float tempRY = -10; public XInputBus(int id) { inputs = new XInputState(); ID = id; busRef = BusAccess.Instance; } public bool Connect() { if (!PluggedIn) { busRef.Unplug(ID); PluggedIn = busRef.Plugin(ID); } return PluggedIn; } public bool Disconnect() { if (PluggedIn) { PluggedIn = !busRef.Unplug(ID); RumbleEvent?.Invoke(0, 0); } return PluggedIn == false; } public void SetInput(X360Button button, bool state) { inputs[button] = state;// || inputs[button]; } public void SetInput(X360Axis axis, float value) { switch (axis) { case X360Axis.LX_Hi: case X360Axis.LX_Lo: if (value > tempLX) { tempLX = value; inputs[axis] = value; } break; case X360Axis.LY_Hi: case X360Axis.LY_Lo: if (value > tempLY) { tempLY = value; inputs[axis] = value; } break; case X360Axis.RX_Hi: case X360Axis.RX_Lo: if (value > tempRX) { tempRX = value; inputs[axis] = value; } break; case X360Axis.RY_Hi: case X360Axis.RY_Lo: if (value > tempRY) { tempRY = value; inputs[axis] = value; } break; default: inputs[axis] = value;// == 0 ? inputs[axis] : value; break; } } public void Update() { //if (!Started) return; // reset temps tempLX = -10; tempLY = -10; tempRX = -10; tempRY = -10; byte[] rumble = new byte[8]; byte[] output = new byte[28]; // Fill the output to be sent output[0] = 0x1C; output[4] = (byte)ID; output[9] = 0x14; // buttons int buttonFlags = 0x00; output[10] |= (byte)(inputs.Up ? 1 << 0 : 0); output[10] |= (byte)(inputs.Down ? 1 << 1 : 0); output[10] |= (byte)(inputs.Left ? 1 << 2 : 0); output[10] |= (byte)(inputs.Right ? 1 << 3 : 0); output[10] |= (byte)(inputs.Start ? 1 << 4 : 0); output[10] |= (byte)(inputs.Back ? 1 << 5 : 0); output[10] |= (byte)(inputs.LS ? 1 << 6 : 0); output[10] |= (byte)(inputs.RS ? 1 << 7 : 0); output[11] |= (byte)(inputs.LB ? 1 << 0 : 0); output[11] |= (byte)(inputs.RB ? 1 << 1 : 0); output[11] |= (byte)(inputs.Guide ? 1 << 2 : 0); output[11] |= (byte)(inputs.A ? 1 << 4 : 0); output[11] |= (byte)(inputs.B ? 1 << 5 : 0); output[11] |= (byte)(inputs.X ? 1 << 6 : 0); output[11] |= (byte)(inputs.Y ? 1 << 7 : 0); // triggers output[(uint)X360Axis.LT] = GetRawTrigger(inputs.LT); output[(uint)X360Axis.RT] = GetRawTrigger(inputs.RT); // Left Joystick int rawLX = GetRawAxis(inputs.LX); int rawLY = GetRawAxis(inputs.LY); output[(uint)X360Axis.LX_Lo] = (byte)((rawLX >> 0) & 0xFF); output[(uint)X360Axis.LX_Hi] = (byte)((rawLX >> 8) & 0xFF); output[(uint)X360Axis.LY_Lo] = (byte)((rawLY >> 0) & 0xFF); output[(uint)X360Axis.LY_Hi] = (byte)((rawLY >> 8) & 0xFF); // Right Joystick int rawRX = GetRawAxis(inputs.RX); int rawRY = GetRawAxis(inputs.RY); output[(uint)X360Axis.RX_Lo] = (byte)((rawRX >> 0) & 0xFF); output[(uint)X360Axis.RX_Hi] = (byte)((rawRX >> 8) & 0xFF); output[(uint)X360Axis.RY_Lo] = (byte)((rawRY >> 0) & 0xFF); output[(uint)X360Axis.RY_Hi] = (byte)((rawRY >> 8) & 0xFF); if (busRef.Report(output, rumble)) { // True on rumble state change if (rumble[1] == 0x08) { RumbleEvent?.Invoke(rumble[3], rumble[4]); } } //inputs.Reset(); } public int GetRawAxis(float axis) { if (axis > 1.0f) { return 32767; } if (axis < -1.0f) { return -32767; } return (int)(axis * 32767); } public byte GetRawTrigger(float trigger) { if (trigger > 1.0f) { return 0xFF; } if (trigger < 0.0f) { return 0; } return (byte)(trigger * 0xFF); } } } } <|start_filename|>Scp/ScpControl/ScpTimer.cs<|end_filename|> using System; using System.ComponentModel; using System.Runtime.InteropServices; namespace ScpControl { public partial class ScpTimer : Component { [Flags] protected enum EventFlags : uint { TIME_ONESHOT = 0, TIME_PERIODIC = 1, } protected delegate void TimerCallback(UInt32 uTimerId, UInt32 uMsg, UIntPtr dwUser, UIntPtr dw1, UIntPtr dw2); [DllImport("Winmm", CharSet = CharSet.Auto)] private static extern UInt32 timeSetEvent(UInt32 uDelay, UInt32 uResolution, TimerCallback lpTimeProc, UIntPtr dwUser, EventFlags Flags); [DllImport("Winmm", CharSet = CharSet.Auto)] private static extern UInt32 timeKillEvent(UInt32 uTimerId); protected UInt32 m_Id = 0, m_Interval = 100; protected EventArgs m_Args = new EventArgs(); protected TimerCallback m_Callback; public event EventHandler Tick; public object Tag { get; set; } public Boolean Enabled { get { return m_Id != 0; } set { lock (this) { if (Enabled != value) { if (value) { Start(); } else { Stop(); } } } } } public UInt32 Interval { get { return m_Interval; } set { m_Interval = value; } } public ScpTimer() { InitializeComponent(); m_Callback = new TimerCallback(OnTick); } public ScpTimer(IContainer container) { container.Add(this); InitializeComponent(); m_Callback = new TimerCallback(OnTick); } public void Start() { lock (this) { if (!Enabled) { m_Id = timeSetEvent(Interval, 0, m_Callback, UIntPtr.Zero, EventFlags.TIME_PERIODIC); } } } public void Stop() { lock (this) { if (Enabled) { timeKillEvent(m_Id); m_Id = 0; } } } protected void OnTick(UInt32 uTimerID, UInt32 uMsg, UIntPtr dwUser, UIntPtr dw1, UIntPtr dw2) { if (Tick != null) { Tick(this, m_Args); } } } } <|start_filename|>Scp/ScpControl/UsbHub.cs<|end_filename|> using System; using System.ComponentModel; namespace ScpControl { public partial class UsbHub : ScpHub { protected UsbDevice[] Device = new UsbDevice[4]; public UsbHub() { InitializeComponent(); } public UsbHub(IContainer container) { container.Add(this); InitializeComponent(); } public override Boolean Open() { for (Byte Pad = 0; Pad < Device.Length; Pad++) { Device[Pad] = new UsbDevice(); Device[Pad].PadId = (DsPadId) Pad; } return base.Open(); } public override Boolean Start() { m_Started = true; Byte Index = 0; for (Byte Instance = 0; Instance < Device.Length && Index < Device.Length; Instance++) { try { UsbDevice Current = new UsbDs4(); Current.PadId = (DsPadId)Index; if (Current.Open(Instance)) { if (LogArrival(Current)) { Current.Debug += new EventHandler<DebugEventArgs> (On_Debug); Current.Report += new EventHandler<ReportEventArgs>(On_Report); Device[Index++] = Current; } else Current.Close(); } else Current.Close(); } catch { break; } } for (Byte Instance = 0; Instance < Device.Length && Index < Device.Length; Instance++) { try { UsbDevice Current = new UsbDs3(); Current.PadId = (DsPadId)Index; if (Current.Open(Instance)) { if (LogArrival(Current)) { Current.Debug += new EventHandler<DebugEventArgs> (On_Debug); Current.Report += new EventHandler<ReportEventArgs>(On_Report); Device[Index++] = Current; } else Current.Close(); } else Current.Close(); } catch { break; } } try { for (Index = 0; Index < Device.Length; Index++) { if (Device[Index].State == DsState.Reserved) { Device[Index].Start(); } } } catch { } return base.Start(); } public override Boolean Stop() { m_Started = false; try { for (Int32 Index = 0; Index < Device.Length; Index++) { if (Device[Index].State == DsState.Connected) { Device[Index].Stop(); } } } catch { } return base.Stop(); } public override Boolean Close() { m_Started = false; try { for (Int32 Index = 0; Index < Device.Length; Index++) { if (Device[Index].State == DsState.Connected) { Device[Index].Close(); } } } catch { } return base.Close(); } public override Boolean Suspend() { Stop(); Close(); return base.Suspend(); } public override Boolean Resume() { Open(); Start(); return base.Resume(); } public override DsPadId Notify(ScpDevice.Notified Notification, String Class, String Path) { LogDebug(String.Format("++ Notify [{0}] [{1}] [{2}]", Notification, Class, Path)); switch (Notification) { case ScpDevice.Notified.Arrival: { UsbDevice Arrived = new UsbDevice(); if (Class.ToUpper() == UsbDs3.USB_CLASS_GUID.ToUpper()) { Arrived = new UsbDs3(); LogDebug("-- DS3 Arrival Event"); } if (Class.ToUpper() == UsbDs4.USB_CLASS_GUID.ToUpper()) { Arrived = new UsbDs4(); LogDebug("-- DS4 Arrival Event"); } if (Arrived.Open(Path)) { LogDebug(String.Format("-- Device Arrival [{0}]", Arrived.Local)); if (LogArrival(Arrived)) { if (Device[(Byte) Arrived.PadId].IsShutdown) { Device[(Byte) Arrived.PadId].IsShutdown = false; Device[(Byte) Arrived.PadId].Close(); Device[(Byte) Arrived.PadId] = Arrived; return Arrived.PadId; } else { Arrived.Debug += new EventHandler<DebugEventArgs> (On_Debug ); Arrived.Report += new EventHandler<ReportEventArgs>(On_Report); Device[(Byte) Arrived.PadId].Close(); Device[(Byte) Arrived.PadId] = Arrived; if (m_Started) Arrived.Start(); return Arrived.PadId; } } } Arrived.Close(); } break; case ScpDevice.Notified.Removal: { for (Int32 Index = 0; Index < Device.Length; Index++) { if (Device[Index].State == DsState.Connected && Path == Device[Index].Path) { LogDebug(String.Format("-- Device Removal [{0}]", Device[Index].Local)); Device[Index].Stop(); } } } break; } return DsPadId.None; } } } <|start_filename|>WiinUSoft/Windows/SyncWindow.xaml.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Windows; using Shared.Windows; namespace WiinUSoft.Windows { /// <summary> /// Interaction logic for SyncWindow.xaml /// </summary> public partial class SyncWindow : Window { private const string deviceNameMatch = "Nintendo"; public bool Cancelled { get; protected set; } public int Count { get; protected set; } bool _notCompatable = false; public SyncWindow() { InitializeComponent(); } public void Sync() { var radioParams = new NativeImports.BLUETOOTH_FIND_RADIO_PARAMS(); Guid HidServiceClass = Guid.Parse(NativeImports.HID_GUID); List<IntPtr> btRadios = new List<IntPtr>(); IntPtr foundRadio; IntPtr handle; radioParams.Initialize(); // Get first BT Radio handle = NativeImports.BluetoothFindFirstRadio(ref radioParams, out foundRadio); bool more = handle != IntPtr.Zero; if (!more) { uint findBtError = NativeImports.GetLastError(); Prompt("Error Code " + findBtError.ToString()); } do { if (foundRadio != IntPtr.Zero) { btRadios.Add(foundRadio); } // Find more more = NativeImports.BluetoothFindNextRadio(ref handle, out foundRadio); } while (more); if (btRadios.Count > 0) { Prompt("Searching for controllers..."); // Search until cancelled or at least one device is paired while (Count == 0 && !Cancelled) { foreach (var radio in btRadios) { IntPtr found; var radioInfo = new NativeImports.BLUETOOTH_RADIO_INFO(); var deviceInfo = new NativeImports.BLUETOOTH_DEVICE_INFO(); var searchParams = new NativeImports.BLUETOOTH_DEVICE_SEARCH_PARAMS(); radioInfo.Initialize(); deviceInfo.Initialize(); searchParams.Initialize(); // Access radio information uint getInfoError = NativeImports.BluetoothGetRadioInfo(radio, ref radioInfo); // Success if (getInfoError == 0) { // Set search parameters searchParams.hRadio = radio; searchParams.fIssueInquiry = true; searchParams.fReturnUnknown = true; searchParams.fReturnConnected = false; searchParams.fReturnRemembered = false; searchParams.fReturnAuthenticated = false; searchParams.cTimeoutMultiplier = 2; // Search for a device found = NativeImports.BluetoothFindFirstDevice(ref searchParams, ref deviceInfo); // Success if (found != IntPtr.Zero) { do { // Note: Switch Pro Controller is simply called "Pro Controller" // Note: The Wiimote MotionPlus reveals its name only after BT authentication var probeUnnamed = String.IsNullOrEmpty(deviceInfo.szName); if (probeUnnamed || deviceInfo.szName.StartsWith(SyncWindow.deviceNameMatch)) { if (!probeUnnamed) { Prompt("Found " + deviceInfo.szName); } StringBuilder password = new StringBuilder(); uint pcService = 16; Guid[] guids = new Guid[16]; bool success = true; // Create Password out of BT radio MAC address var bytes = BitConverter.GetBytes(radioInfo.address); for (int i = 0; i < 6; i++) { password.Append((char)bytes[i]); } // Authenticate if (success) { var errAuth = NativeImports.BluetoothAuthenticateDevice(IntPtr.Zero, radio, ref deviceInfo, password.ToString(), 6); success = errAuth == 0; if(probeUnnamed) { if(String.IsNullOrEmpty(deviceInfo.szName) || !deviceInfo.szName.StartsWith(SyncWindow.deviceNameMatch)) { continue; } else if(success) { probeUnnamed = false; Prompt("Found " + deviceInfo.szName); } } } // Install PC Service if (success) { var errService = NativeImports.BluetoothEnumerateInstalledServices(radio, ref deviceInfo, ref pcService, guids); success = errService == 0; } // Set to HID service if (success) { var errActivate = NativeImports.BluetoothSetServiceState(radio, ref deviceInfo, ref HidServiceClass, 0x01); success = errActivate == 0; } if (success) { Prompt("Successfully Paired!"); Count += 1; } else if (!probeUnnamed) { Prompt("Failed to Pair."); } } } while (NativeImports.BluetoothFindNextDevice(found, ref deviceInfo)); } } else { // Failed to get BT Radio info } } } // Close each Radio foreach (var openRadio in btRadios) { NativeImports.CloseHandle(openRadio); } } else { // No (compatable) Bluetooth SetPrompt( "No compatable Bluetooth Radios found." + Environment.NewLine + "This only works for the Microsoft Bluetooth Stack."); _notCompatable = true; return; } // Close this window Dispatcher.BeginInvoke((Action)(() => Close())); } private void Prompt(string text) { Dispatcher.BeginInvoke(new Action(() => { prompt.Text += text + Environment.NewLine; })); } private void SetPrompt(string text) { Dispatcher.BeginInvoke(new Action(() => { prompt.Text = text; })); } private void cancelBtn_Click(object sender, RoutedEventArgs e) { if (_notCompatable) { Close(); } Prompt("Cancelling"); Cancelled = true; } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (!Cancelled && Count == 0 && !_notCompatable) { Cancelled = true; Prompt("Cancelling"); e.Cancel = true; } } private void Window_Loaded(object sender, RoutedEventArgs e) { Task t = new Task(() => Sync()); t.Start(); } } } <|start_filename|>WiinUSoft/Windows/ConfigWindow.xaml.cs<|end_filename|> using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; using System.Xml.Serialization; using NintrollerLib; namespace WiinUSoft { /// <summary> /// Interaction logic for ConfigWindow.xaml /// </summary> public partial class ConfigWindow : Window { public bool result = false; public Dictionary<string, string> map; private Dictionary<string, Shape> mapShapes; private Dictionary<Shape, string> mapValues; private Dictionary<Shape, string> deviceShapes; private ControllerType deviceType = ControllerType.Wiimote; private Shape currentSelection; private ConfigWindow() { InitializeComponent(); } public ConfigWindow(Dictionary<string, string> mappings, ControllerType type) //public ConfigWindow(Dictionary<string, string> mappings, ControllerType type) { InitializeComponent(); // Copy the mappings over map = mappings.ToDictionary(entry => entry.Key, entry => entry.Value); deviceType = type; GetShapes(); RotateTransform rt = new RotateTransform(-90); // other views should already be hidden except the pro controller switch (deviceType) { case ControllerType.ProController: ProGrid.Visibility = Visibility.Visible; break; case ControllerType.ClassicController: ProGrid.Visibility = Visibility.Hidden; CCGrid.Visibility = Visibility.Visible; WmGrid.Visibility = Visibility.Visible; // Reposition Wiimote Grid Canvas.SetLeft(WmGrid, 70); Canvas.SetTop(WmGrid, -50); WmGrid.RenderTransform = rt; break; case ControllerType.ClassicControllerPro: ProGrid.Visibility = Visibility.Hidden; CCPGrid.Visibility = Visibility.Visible; WmGrid.Visibility = Visibility.Visible; // Reposition Wiimote Grid Canvas.SetLeft(WmGrid, 70); Canvas.SetTop(WmGrid, -50); WmGrid.RenderTransform = rt; break; case ControllerType.Nunchuk: case ControllerType.NunchukB: ProGrid.Visibility = Visibility.Hidden; NkGrid.Visibility = Visibility.Visible; WmGrid.Visibility = Visibility.Visible; break; case ControllerType.Wiimote: ProGrid.Visibility = Visibility.Hidden; WmGrid.Visibility = Visibility.Visible; break; } } private void GetShapes() { #region Xbox Clickables mapShapes = new Dictionary<string,Shape>(); mapShapes.Add(Inputs.Xbox360.A , x_aClick); mapShapes.Add(Inputs.Xbox360.B , x_bClick); mapShapes.Add(Inputs.Xbox360.X , x_xClick); mapShapes.Add(Inputs.Xbox360.Y , x_yClick); mapShapes.Add(Inputs.Xbox360.LB , x_lbClick); mapShapes.Add(Inputs.Xbox360.LT , x_ltClick); mapShapes.Add(Inputs.Xbox360.LS , x_lsClick); mapShapes.Add(Inputs.Xbox360.RB , x_rbClick); mapShapes.Add(Inputs.Xbox360.RT , x_rtClick); mapShapes.Add(Inputs.Xbox360.RS , x_rsClick); mapShapes.Add(Inputs.Xbox360.UP , x_upClick); mapShapes.Add(Inputs.Xbox360.DOWN , x_downClick); mapShapes.Add(Inputs.Xbox360.LEFT , x_leftClick); mapShapes.Add(Inputs.Xbox360.RIGHT , x_rightClick); mapShapes.Add(Inputs.Xbox360.LUP , x_lupClick); mapShapes.Add(Inputs.Xbox360.LDOWN , x_ldownClick); mapShapes.Add(Inputs.Xbox360.LLEFT , x_lleftClick); mapShapes.Add(Inputs.Xbox360.LRIGHT, x_lrightClick); mapShapes.Add(Inputs.Xbox360.RUP , x_rupClick); mapShapes.Add(Inputs.Xbox360.RDOWN , x_rdownClick); mapShapes.Add(Inputs.Xbox360.RLEFT , x_rleftClick); mapShapes.Add(Inputs.Xbox360.RRIGHT, x_rrightClick); mapShapes.Add(Inputs.Xbox360.START , x_startClick); mapShapes.Add(Inputs.Xbox360.BACK , x_backClick); mapShapes.Add(Inputs.Xbox360.GUIDE , x_guideClick); mapShapes.Add("", x_noneClick); #endregion #region Xbox Mappings mapValues = new Dictionary<Shape, string>(); mapValues.Add(x_aClick ,Inputs.Xbox360.A); mapValues.Add(x_bClick ,Inputs.Xbox360.B); mapValues.Add(x_xClick ,Inputs.Xbox360.X); mapValues.Add(x_yClick ,Inputs.Xbox360.Y); mapValues.Add(x_lbClick ,Inputs.Xbox360.LB); mapValues.Add(x_ltClick ,Inputs.Xbox360.LT); mapValues.Add(x_lsClick ,Inputs.Xbox360.LS); mapValues.Add(x_rbClick ,Inputs.Xbox360.RB); mapValues.Add(x_rtClick ,Inputs.Xbox360.RT); mapValues.Add(x_rsClick ,Inputs.Xbox360.RS); mapValues.Add(x_upClick ,Inputs.Xbox360.UP); mapValues.Add(x_downClick ,Inputs.Xbox360.DOWN); mapValues.Add(x_leftClick ,Inputs.Xbox360.LEFT); mapValues.Add(x_rightClick ,Inputs.Xbox360.RIGHT); mapValues.Add(x_lupClick ,Inputs.Xbox360.LUP); mapValues.Add(x_ldownClick ,Inputs.Xbox360.LDOWN); mapValues.Add(x_lleftClick ,Inputs.Xbox360.LLEFT); mapValues.Add(x_lrightClick ,Inputs.Xbox360.LRIGHT); mapValues.Add(x_rupClick ,Inputs.Xbox360.RUP); mapValues.Add(x_rdownClick ,Inputs.Xbox360.RDOWN); mapValues.Add(x_rleftClick ,Inputs.Xbox360.RLEFT); mapValues.Add(x_rrightClick ,Inputs.Xbox360.RRIGHT); mapValues.Add(x_startClick ,Inputs.Xbox360.START); mapValues.Add(x_backClick ,Inputs.Xbox360.BACK); mapValues.Add(x_guideClick ,Inputs.Xbox360.GUIDE); mapValues.Add(x_noneClick, ""); #endregion #if MouseMode // Mouse Mode mapShapes.Add("MouseMode", mouseClick); mapValues.Add(mouseClick, "MouseMode"); #endif deviceShapes = new Dictionary<Shape, string>(); if (deviceType == ControllerType.ProController) { #region Pro Clickables deviceShapes.Add(pro_aClick , Inputs.ProController.A); deviceShapes.Add(pro_bClick , Inputs.ProController.B); deviceShapes.Add(pro_xClick , Inputs.ProController.X); deviceShapes.Add(pro_yClick , Inputs.ProController.Y); deviceShapes.Add(pro_lClick , Inputs.ProController.L); deviceShapes.Add(pro_zlClick , Inputs.ProController.ZL); deviceShapes.Add(pro_lsClick , Inputs.ProController.LS); deviceShapes.Add(pro_rClick , Inputs.ProController.R); deviceShapes.Add(pro_zrClick , Inputs.ProController.ZR); deviceShapes.Add(pro_rsClick , Inputs.ProController.RS); deviceShapes.Add(pro_upClick , Inputs.ProController.UP); deviceShapes.Add(pro_downClick , Inputs.ProController.DOWN); deviceShapes.Add(pro_leftClick , Inputs.ProController.LEFT); deviceShapes.Add(pro_rightClick , Inputs.ProController.RIGHT); deviceShapes.Add(pro_lupClick , Inputs.ProController.LUP); deviceShapes.Add(pro_ldownClick , Inputs.ProController.LDOWN); deviceShapes.Add(pro_lleftClick , Inputs.ProController.LLEFT); deviceShapes.Add(pro_lrightClick, Inputs.ProController.LRIGHT); deviceShapes.Add(pro_rupClick , Inputs.ProController.RUP); deviceShapes.Add(pro_rdownClick , Inputs.ProController.RDOWN); deviceShapes.Add(pro_rleftClick , Inputs.ProController.RLEFT); deviceShapes.Add(pro_rrightClick, Inputs.ProController.RRIGHT); deviceShapes.Add(pro_startClick , Inputs.ProController.START); deviceShapes.Add(pro_selectClick, Inputs.ProController.SELECT); deviceShapes.Add(pro_homeClick , Inputs.ProController.HOME); #endregion } else { #region Wiimote Clickalbes deviceShapes.Add(wm_aClick, Inputs.Wiimote.A); deviceShapes.Add(wm_bClick, Inputs.Wiimote.B); deviceShapes.Add(wm_upClick, Inputs.Wiimote.UP); deviceShapes.Add(wm_downClick, Inputs.Wiimote.DOWN); deviceShapes.Add(wm_leftClick, Inputs.Wiimote.LEFT); deviceShapes.Add(wm_rightClick, Inputs.Wiimote.RIGHT); deviceShapes.Add(wm_oneClick, Inputs.Wiimote.ONE); deviceShapes.Add(wm_twoClick, Inputs.Wiimote.TWO); deviceShapes.Add(wm_homeClick, Inputs.Wiimote.HOME); deviceShapes.Add(wm_selectClick, Inputs.Wiimote.MINUS); deviceShapes.Add(wm_startClick, Inputs.Wiimote.PLUS); deviceShapes.Add(wm_accXClick, Inputs.Wiimote.ACC_SHAKE_X); deviceShapes.Add(wm_accYClick, Inputs.Wiimote.ACC_SHAKE_Y); deviceShapes.Add(wm_accZClick, Inputs.Wiimote.ACC_SHAKE_Z); deviceShapes.Add(wm_aRollClick, Inputs.Wiimote.TILT_RIGHT); deviceShapes.Add(wm_aRollNegClick, Inputs.Wiimote.TILT_LEFT); deviceShapes.Add(wm_aPitchClick, Inputs.Wiimote.TILT_UP); deviceShapes.Add(wm_aPitchNegClick, Inputs.Wiimote.TILT_DOWN); deviceShapes.Add(wm_irRightClick, Inputs.Wiimote.IR_RIGHT); deviceShapes.Add(wm_irLeftClick, Inputs.Wiimote.IR_LEFT); deviceShapes.Add(wm_irUpClick, Inputs.Wiimote.IR_UP); deviceShapes.Add(wm_irDownClick, Inputs.Wiimote.IR_DOWN); #endregion if (deviceType == ControllerType.ClassicController) { #region Classic Clickables deviceShapes.Add(cc_aClick , Inputs.ClassicController.A); deviceShapes.Add(cc_bClick , Inputs.ClassicController.B); deviceShapes.Add(cc_xClick , Inputs.ClassicController.X); deviceShapes.Add(cc_yClick , Inputs.ClassicController.Y); deviceShapes.Add(cc_lClick , Inputs.ClassicController.LT); deviceShapes.Add(cc_zlClick , Inputs.ClassicController.ZL); deviceShapes.Add(cc_rClick , Inputs.ClassicController.RT); deviceShapes.Add(cc_zrClick , Inputs.ClassicController.ZR); deviceShapes.Add(cc_upClick , Inputs.ClassicController.UP); deviceShapes.Add(cc_downClick , Inputs.ClassicController.DOWN); deviceShapes.Add(cc_leftClick , Inputs.ClassicController.LEFT); deviceShapes.Add(cc_rightClick , Inputs.ClassicController.RIGHT); deviceShapes.Add(cc_lupClick , Inputs.ClassicController.LUP); deviceShapes.Add(cc_ldownClick , Inputs.ClassicController.LDOWN); deviceShapes.Add(cc_lleftClick , Inputs.ClassicController.LLEFT); deviceShapes.Add(cc_lrightClick, Inputs.ClassicController.LRIGHT); deviceShapes.Add(cc_rupClick , Inputs.ClassicController.RUP); deviceShapes.Add(cc_rdownClick , Inputs.ClassicController.RDOWN); deviceShapes.Add(cc_rleftClick , Inputs.ClassicController.RLEFT); deviceShapes.Add(cc_rrightClick, Inputs.ClassicController.RRIGHT); deviceShapes.Add(cc_startClick , Inputs.ClassicController.START); deviceShapes.Add(cc_selectClick, Inputs.ClassicController.SELECT); deviceShapes.Add(cc_homeClick , Inputs.ClassicController.HOME); #endregion } else if (deviceType == ControllerType.ClassicControllerPro) { #region Classic Pro Clickables deviceShapes.Add(ccp_aClick , Inputs.ClassicControllerPro.A); deviceShapes.Add(ccp_bClick , Inputs.ClassicControllerPro.B); deviceShapes.Add(ccp_xClick , Inputs.ClassicControllerPro.X); deviceShapes.Add(ccp_yClick , Inputs.ClassicControllerPro.Y); deviceShapes.Add(ccp_lClick , Inputs.ClassicControllerPro.L); deviceShapes.Add(ccp_zlClick , Inputs.ClassicControllerPro.ZL); deviceShapes.Add(ccp_rClick , Inputs.ClassicControllerPro.R); deviceShapes.Add(ccp_zrClick , Inputs.ClassicControllerPro.ZR); deviceShapes.Add(ccp_upClick , Inputs.ClassicControllerPro.UP); deviceShapes.Add(ccp_downClick , Inputs.ClassicControllerPro.DOWN); deviceShapes.Add(ccp_leftClick , Inputs.ClassicControllerPro.LEFT); deviceShapes.Add(ccp_rightClick , Inputs.ClassicControllerPro.RIGHT); deviceShapes.Add(ccp_lupClick , Inputs.ClassicControllerPro.LUP); deviceShapes.Add(ccp_ldownClick , Inputs.ClassicControllerPro.LDOWN); deviceShapes.Add(ccp_lleftClick , Inputs.ClassicControllerPro.LLEFT); deviceShapes.Add(ccp_lrightClick, Inputs.ClassicControllerPro.LRIGHT); deviceShapes.Add(ccp_rupClick , Inputs.ClassicControllerPro.RUP); deviceShapes.Add(ccp_rdownClick , Inputs.ClassicControllerPro.RDOWN); deviceShapes.Add(ccp_rleftClick , Inputs.ClassicControllerPro.RLEFT); deviceShapes.Add(ccp_rrightClick, Inputs.ClassicControllerPro.RRIGHT); deviceShapes.Add(ccp_startClick , Inputs.ClassicControllerPro.START); deviceShapes.Add(ccp_selectClick, Inputs.ClassicControllerPro.SELECT); deviceShapes.Add(ccp_homeClick , Inputs.ClassicControllerPro.HOME); #endregion } else if (deviceType == ControllerType.Nunchuk || deviceType == ControllerType.NunchukB) { #region Nunchuk Clickables deviceShapes.Add(nk_cClick, Inputs.Nunchuk.C); deviceShapes.Add(nk_zClick, Inputs.Nunchuk.Z); deviceShapes.Add(nk_upClick, Inputs.Nunchuk.UP); deviceShapes.Add(nk_downClick, Inputs.Nunchuk.DOWN); deviceShapes.Add(nk_leftClick, Inputs.Nunchuk.LEFT); deviceShapes.Add(nk_rightClick, Inputs.Nunchuk.RIGHT); // TODO: other Nunchuk Clickables (Acc) (not for 1st release) deviceShapes.Add(nk_aRightClick, Inputs.Nunchuk.ACC_SHAKE_X); deviceShapes.Add(nk_aUpClick, Inputs.Nunchuk.ACC_SHAKE_Y); deviceShapes.Add(nk_aForwardClick, Inputs.Nunchuk.ACC_SHAKE_Z); deviceShapes.Add(nk_aRollClick, Inputs.Nunchuk.TILT_LEFT); deviceShapes.Add(nk_aRollNegClick, Inputs.Nunchuk.TILT_RIGHT); deviceShapes.Add(nk_aPitchClick, Inputs.Nunchuk.TILT_UP); deviceShapes.Add(nk_aPitchNegClick, Inputs.Nunchuk.TILT_DOWN); #endregion } } // TODO: add other controller maps (Balance Board, Musicals) (not for 1st release) if (deviceType == ControllerType.ProController) { currentSelection = pro_homeClick; } else if (deviceType == ControllerType.ClassicController) { currentSelection = cc_homeClick; } else if (deviceType == ControllerType.ClassicControllerPro) { currentSelection = ccp_homeClick; } else { currentSelection = wm_homeClick; } device_MouseDown(currentSelection, new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Left)); } private void MoveSelector(Shape s, Ellipse selector, Line guide) { double top = 0; double left = 0; if (s.Name.StartsWith("wm") && deviceType != ControllerType.Wiimote && deviceType != ControllerType.Nunchuk && deviceType != ControllerType.NunchukB) { top = 0;// Canvas.GetLeft((UIElement)s.Parent) - 50; top += WmGrid.Width - s.Margin.Left; top += selector.Width / 2; top -= s.Width / 2; top -= 22; left = Canvas.GetTop((UIElement)s.Parent); left += s.Margin.Top; left += selector.Height / 2; left += s.Height / 2; left += 20; } else { top = Canvas.GetTop(((UIElement)s.Parent)); top += s.Margin.Top; top -= selector.Height / 2; top += s.Height / 2; left = Canvas.GetLeft((UIElement)(s.Parent)); left += s.Margin.Left; left -= selector.Width / 2; left += s.Width / 2; } Canvas.SetTop(selector, top); Canvas.SetLeft(selector, left); Canvas.SetLeft(guide, Canvas.GetLeft(selector) + selector.Width / 2); guide.Y2 = Canvas.GetTop(selector) - selector.Height / 2 - selector.StrokeThickness; if (guide == guideMap) { guideMeet.X2 = Canvas.GetLeft(guide); } else { guideMeet.X1 = Canvas.GetLeft(guide); } } private void OnMouseEnter(object sender, MouseEventArgs e) { Shape clickArea = (Shape)sender; clickArea.StrokeThickness = 1; } private void OnMouseLeave(object sender, MouseEventArgs e) { Shape clickArea = (Shape)sender; clickArea.StrokeThickness = 0; } private void device_MouseDown(object sender, MouseButtonEventArgs e) { Shape s = (Shape)sender; deviceLabel.Content = s.ToolTip; MoveSelector((Shape)sender, selectionDevice, guideDevice); currentSelection = s; if (deviceShapes.ContainsKey(s) && map.ContainsKey(deviceShapes[s])) { MoveSelector(mapShapes[map[deviceShapes[s]]], selectionMap, guideMap); mapLabel.Content = mapShapes[map[deviceShapes[s]]].ToolTip; } } private void map_MouseDown(object sender, MouseButtonEventArgs e) { Shape s = (Shape)sender; mapLabel.Content = s.ToolTip; MoveSelector((Shape)sender, selectionMap, guideMap); if (deviceShapes.ContainsKey(currentSelection) && mapValues.ContainsKey(s) && map.ContainsKey(deviceShapes[currentSelection])) { map[deviceShapes[currentSelection]] = mapValues[s]; } } private void btnApply_Click(object sender, RoutedEventArgs e) { result = true; Close(); } private void btnCancel_Click(object sender, RoutedEventArgs e) { result = false; Close(); } private void btnDefault_Click(object sender, RoutedEventArgs e) { map = Holders.XInputHolder.GetDefaultMapping(deviceType).ToDictionary(entry => entry.Key, entry => entry.Value); result = true; Close(); } private void btnSave_Click(object sender, RoutedEventArgs e) { Profile newProfile = new Profile(deviceType); foreach (KeyValuePair<string, string> item in map) { newProfile.controllerMapKeys.Add(item.Key); newProfile.controllerMapValues.Add(item.Value); } Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog(); dialog.FileName = deviceType.ToString() + "_profile"; dialog.DefaultExt = ".wsp"; dialog.Filter = App.PROFILE_FILTER; bool? doSave = dialog.ShowDialog(); if (doSave == true) { XmlSerializer serializer = new XmlSerializer(typeof(Profile)); using (FileStream stream = File.Create(dialog.FileName)) using (StreamWriter writer = new StreamWriter(stream)) { serializer.Serialize(writer, newProfile); writer.Close(); stream.Close(); } } } private void btnLoad_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog(); dialog.FileName = deviceType.ToString() + "_profile"; dialog.DefaultExt = ".wsp"; dialog.Filter = App.PROFILE_FILTER; bool? doLoad = dialog.ShowDialog(); Profile loadedProfile = null; if (doLoad == true && dialog.CheckFileExists) { try { XmlSerializer serializer = new XmlSerializer(typeof(Profile)); using (FileStream stream = File.OpenRead(dialog.FileName)) using (StreamReader reader = new StreamReader(stream)) { loadedProfile = serializer.Deserialize(reader) as Profile; reader.Close(); stream.Close(); } } catch (Exception err) { var c = MessageBox.Show("Could not open the file \"" + err.Message + "\".", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } if (loadedProfile != null) { if (loadedProfile.profileType != deviceType) { MessageBoxResult m = MessageBox.Show("Profile is not for this controller type. Load anyway?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (m != MessageBoxResult.Yes) { doLoad = false; } } if (doLoad == true) { for (int i = 0; i < Math.Min(loadedProfile.controllerMapKeys.Count, loadedProfile.controllerMapValues.Count); i++) { if (map.ContainsKey(loadedProfile.controllerMapKeys[i])) { map[loadedProfile.controllerMapKeys[i]] = loadedProfile.controllerMapValues[i]; } else { map.Add(loadedProfile.controllerMapKeys[i], loadedProfile.controllerMapValues[i]); } } result = true; Close(); } } } else if (doLoad == true && !dialog.CheckFileExists) { var a = MessageBox.Show("Could not find the file \"" + dialog.FileName + "\".", "File Not Found", MessageBoxButton.OK, MessageBoxImage.Error); } } } } <|start_filename|>WiinUPro/Directors/KeyboardDirector.cs<|end_filename|> using System.Collections.Generic; using InputManager; namespace WiinUPro { class KeyboardDirector { #region Access public static KeyboardDirector Access { get; protected set; } static KeyboardDirector() { Access = new KeyboardDirector(); } #endregion private List<VirtualKeyCode> _pressedKeys; public KeyboardDirector() { _pressedKeys = new List<VirtualKeyCode>(); } public void KeyDown(VirtualKeyCode code) { if (!_pressedKeys.Contains(code)) { Keyboard.KeyDown((uint)code); _pressedKeys.Add(code); } } public void KeyUp(VirtualKeyCode code) { if (_pressedKeys.Contains(code)) { Keyboard.KeyUp((uint)code); _pressedKeys.Remove(code); } } public void KeyPress(VirtualKeyCode code) { Keyboard.KeyPress(code); } public void DetectKey() { // TODO Director: start key detection } public void Release() { foreach (var key in _pressedKeys.ToArray()) { Keyboard.KeyUp((uint)key); } _pressedKeys.Clear(); } } } <|start_filename|>Nintroller/INPUT_NAMES.cs<|end_filename|> namespace NintrollerLib { public static class INPUT_NAMES { public static class WIIMOTE { public const string A = "wA"; public const string B = "wB"; public const string ONE = "wONE"; public const string TWO = "wTWO"; // dpad when wiimote is vertical public const string UP = "wUP"; public const string DOWN = "wDOWN"; public const string LEFT = "wLEFT"; public const string RIGHT = "wRIGHT"; public const string MINUS = "wMINUS"; public const string PLUS = "wPLUS"; public const string HOME = "wHOME"; // Accelerometer public const string ACC_X = "wAccX"; public const string ACC_Y = "wAccY"; public const string ACC_Z = "wAccZ"; // tilting the controler with the wrist public const string TILT_RIGHT = "wTILTRIGHT"; public const string TILT_LEFT = "wTILTLEFT"; public const string TILT_UP = "wTILTUP"; public const string TILT_DOWN = "wTILTDOWN"; public const string FACE_UP = "wTILTFACEUP"; public const string FACE_DOWN = "wTILTFACEDOWN"; // Pointer from IR camera public const string IR_X = "wIRX"; public const string IR_Y = "wIRY"; public const string IR_UP = "wIRUP"; public const string IR_DOWN = "wIRDOWN"; public const string IR_LEFT = "wIRLEFT"; public const string IR_RIGHT = "wIRRIGHT"; } public static class NUNCHUK { public const string C = "nC"; public const string Z = "nZ"; public const string JOY_X = "nJoyX"; public const string JOY_Y = "nJoyY"; public const string UP = "nUP"; public const string DOWN = "nDOWN"; public const string LEFT = "nLEFT"; public const string RIGHT = "nRIGHT"; public const string ACC_X = "nAccX"; public const string ACC_Y = "nAccY"; public const string ACC_Z = "nAccZ"; // tilting the controler with the wrist public const string TILT_RIGHT = "nTILTRIGHT"; public const string TILT_LEFT = "nTILTLEFT"; public const string TILT_UP = "nTILTUP"; public const string TILT_DOWN = "nTILTDOWN"; public const string FACE_UP = "nTILTFACEUP"; public const string FACE_DOWN = "nTILTFACEDOWN"; } public static class CLASSIC_CONTROLLER { public const string A = "ccA"; public const string B = "ccB"; public const string X = "ccX"; public const string Y = "ccY"; public const string UP = "ccUP"; public const string DOWN = "ccDOWN"; public const string LEFT = "ccLEFT"; public const string RIGHT = "ccRIGHT"; public const string L = "ccL"; public const string R = "ccR"; public const string ZL = "ccZL"; public const string ZR = "ccZR"; public const string LX = "ccLX"; public const string LY = "ccLY"; public const string RX = "ccRX"; public const string RY = "ccRY"; public const string LUP = "ccLUP"; public const string LDOWN = "ccLDOWN"; public const string LLEFT = "ccLLEFT"; public const string LRIGHT = "ccLRIGHT"; public const string RUP = "ccRUP"; public const string RDOWN = "ccRDOWN"; public const string RLEFT = "ccRLEFT"; public const string RRIGHT = "ccRRIGHT"; public const string LT = "ccLT"; public const string RT = "ccRT"; public const string LFULL = "ccLFULL"; public const string RFULL = "ccRFULL"; public const string SELECT = "ccSELECT"; public const string START = "ccSTART"; public const string HOME = "ccHOME"; } public static class CLASSIC_CONTROLLER_PRO { public const string A = "ccpA"; public const string B = "ccpB"; public const string X = "ccpX"; public const string Y = "ccpY"; public const string UP = "ccpUP"; public const string DOWN = "ccpDOWN"; public const string LEFT = "ccpLEFT"; public const string RIGHT = "ccpRIGHT"; public const string L = "ccpL"; public const string R = "ccpR"; public const string ZL = "ccpZL"; public const string ZR = "ccpZR"; public const string LX = "ccpLX"; public const string LY = "ccpLY"; public const string RX = "ccpRX"; public const string RY = "ccpRY"; public const string LUP = "ccpLUP"; public const string LDOWN = "ccpLDOWN"; public const string LLEFT = "ccpLLEFT"; public const string LRIGHT = "ccpLRIGHT"; public const string RUP = "ccpRUP"; public const string RDOWN = "ccpRDOWN"; public const string RLEFT = "ccpRLEFT"; public const string RRIGHT = "ccpRRIGHT"; public const string SELECT = "ccpSELECT"; public const string START = "ccpSTART"; public const string HOME = "ccpHOME"; } public static class PRO_CONTROLLER { public const string A = "proA"; public const string B = "proB"; public const string X = "proX"; public const string Y = "proY"; public const string UP = "proUP"; public const string DOWN = "proDOWN"; public const string LEFT = "proLEFT"; public const string RIGHT = "proRIGHT"; public const string L = "proL"; public const string R = "proR"; public const string ZL = "proZL"; public const string ZR = "proZR"; public const string LX = "proLX"; public const string LY = "proLY"; public const string RX = "proRX"; public const string RY = "proRY"; public const string LUP = "proLUP"; public const string LDOWN = "proLDOWN"; public const string LLEFT = "proLLEFT"; public const string LRIGHT = "proLRIGHT"; public const string RUP = "proRUP"; public const string RDOWN = "proRDOWN"; public const string RLEFT = "proRLEFT"; public const string RRIGHT = "proRRIGHT"; public const string LS = "proLS"; public const string RS = "proRS"; public const string SELECT = "proSELECT"; public const string START = "proSTART"; public const string HOME = "proHOME"; } public static class GUITAR { public const string GREEN = "gutG"; public const string RED = "gutR"; public const string YELLOW = "gutY"; public const string BLUE = "gutB"; public const string ORANGE = "gutO"; public const string STRUM_UP = "gutSUp"; public const string STRUM_DOWN = "gutSDown"; public const string PLUS = "gutPLUS"; public const string MINUS = "gutMINUS"; public const string WHAMMY = "gutW"; public const string WHAMMY_BAR = "gutWT"; public const string WHAMMY_FULL = "gutWFULL"; public const string JOY_X = "gutJoyX"; public const string JOY_Y = "gutJoyY"; public const string UP = "gutUP"; public const string DOWN = "gutDOWN"; public const string LEFT = "gutLEFT"; public const string RIGHT = "gutRIGHT"; public const string TOUCH_1 = "gutT1"; public const string TOUCH_2 = "gutT2"; public const string TOUCH_3 = "gutT3"; public const string TOUCH_4 = "gutT4"; public const string TOUCH_5 = "gutT5"; } public static class TAIKO_DRUM { public const string CENTER_LEFT = "takL"; public const string CENTER_RIGHT = "takR"; public const string RIM_LEFT = "takRimL"; public const string RIM_RIGHT = "takRimR"; } public static class MOTION_PLUS { public const string GYROUP = "mpGYROUP"; public const string GYRODOWN = "mpGYRODOWN"; public const string GYROLEFT = "mpGYROLEFT"; public const string GYRORIGHT = "mpGYRORIGHT"; public const string GYROFORWARD = "mpGYROFORWARD"; public const string GYROBACKWARD = "mpGYROBACKWARD"; } public static class GCN_ADAPTER { public const string PORT_1_CONNECTED = "1_gcnENABLED"; public const string PORT_2_CONNECTED = "2_gcnENABLED"; public const string PORT_3_CONNECTED = "3_gcnENABLED"; public const string PORT_4_CONNECTED = "4_gcnENABLED"; public const string PORT_1_PREFIX = "1_"; public const string PORT_2_PREFIX = "2_"; public const string PORT_3_PREFIX = "3_"; public const string PORT_4_PREFIX = "4_"; } public static class GCN_CONTROLLER { public const string A = "gcnA"; public const string B = "gcnB"; public const string X = "gcnX"; public const string Y = "gcnY"; public const string UP = "gcnUP"; public const string DOWN = "gcnDOWN"; public const string LEFT = "gcnLEFT"; public const string RIGHT = "gcnRIGHT"; public const string L = "gcnL"; public const string R = "gcnR"; public const string Z = "gcnZ"; public const string START = "gcnSTART"; public const string LT = "gcnLT"; public const string RT = "gcnRT"; public const string LFULL = "gcnLFULL"; public const string RFULL = "gcnRFULL"; public const string JOY_X = "gcnJoyX"; public const string JOY_Y = "gcnJoyY"; public const string C_X = "gcnCX"; public const string C_Y = "gcnCY"; public const string JOY_UP = "gcnJOY_UP"; public const string JOY_DOWN = "gcnJOY_DOWN"; public const string JOY_LEFT = "gcnJOY_LEFT"; public const string JOY_RIGHT = "gcnJOY_RIGHT"; public const string C_UP = "gcnC_UP"; public const string C_DOWN = "gcnC_DOWN"; public const string C_LEFT = "gcnC_LEFT"; public const string C_RIGHT = "gcnC_RIGHT"; } } } <|start_filename|>Scp/ScpPair/ScpForm.cs<|end_filename|> using System; using System.Drawing; using System.Windows.Forms; using ScpControl; using System.Runtime.InteropServices; namespace ScpPair { public partial class ScpForm : Form { protected IntPtr m_UsbNotify = IntPtr.Zero; protected Byte[] Master = new Byte[6]; public ScpForm() { InitializeComponent(); } private void tmEnable_Tick(object sender, EventArgs e) { if (usbDevice.State == DsState.Connected) { String[] Split = tbMaster.Text.Split(new String[] { ":" }, StringSplitOptions.RemoveEmptyEntries); if (Split.Length == 6) { Boolean Ok = true; for (Int32 Index = 0; Index < 6 && Ok; Index++) { if (Split[Index].Length != 2 || !Byte.TryParse(Split[Index], System.Globalization.NumberStyles.HexNumber, null, out Master[Index])) { Ok = false; } } btnSet.Enabled = Ok; } lblMac.Text = usbDevice.Local; lblMaster.Text = usbDevice.Remote; } else { lblMac.Text = String.Empty; lblMaster.Text = String.Empty; } } private void btnSet_Click(object sender, EventArgs e) { usbDevice.Pair(Master); } private void Form_Load(object sender, EventArgs e) { Icon = Properties.Resources.Scp_All; if (usbDevice.Open()) usbDevice.Start(); ScpDevice.RegisterNotify(Handle, new Guid(UsbDs3.USB_CLASS_GUID), ref m_UsbNotify); } private void Form_Close(object sender, FormClosingEventArgs e) { if (m_UsbNotify != IntPtr.Zero) ScpDevice.UnregisterNotify(m_UsbNotify); if (usbDevice.State == DsState.Connected) usbDevice.Close(); } protected override void WndProc(ref Message m) { try { if (m.Msg == ScpDevice.WM_DEVICECHANGE) { String Path; ScpDevice.DEV_BROADCAST_HDR hdr; Int32 Type = m.WParam.ToInt32(); hdr = (ScpDevice.DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(ScpDevice.DEV_BROADCAST_HDR)); if (hdr.dbch_devicetype == ScpDevice.DBT_DEVTYP_DEVICEINTERFACE) { ScpDevice.DEV_BROADCAST_DEVICEINTERFACE_M deviceInterface; deviceInterface = (ScpDevice.DEV_BROADCAST_DEVICEINTERFACE_M)Marshal.PtrToStructure(m.LParam, typeof(ScpDevice.DEV_BROADCAST_DEVICEINTERFACE_M)); Path = new String(deviceInterface.dbcc_name); Path = Path.Substring(0, Path.IndexOf('\0')).ToUpper(); switch (Type) { case ScpDevice.DBT_DEVICEARRIVAL: if (usbDevice.State != DsState.Connected) { usbDevice.Close(); usbDevice = new UsbDs3(); if (usbDevice.Open(Path)) usbDevice.Start(); } break; case ScpDevice.DBT_DEVICEREMOVECOMPLETE: if (Path == usbDevice.Path && usbDevice.State == DsState.Connected) { usbDevice.Close(); } break; } } } } catch { } base.WndProc(ref m); } protected void Button_Enter(object sender, EventArgs e) { ThemeUtil.UpdateFocus(((Button) sender).Handle); } } } <|start_filename|>Scp/ScpInstaller/Devcon.cs<|end_filename|> using System; using System.Text; using System.Runtime.InteropServices; namespace ScpDriver { public class Devcon { public static Boolean Find(Guid Target, ref String Path, ref String InstanceId, Int32 Instance = 0) { IntPtr detailDataBuffer = IntPtr.Zero; IntPtr deviceInfoSet = IntPtr.Zero; try { SP_DEVINFO_DATA deviceInterfaceData = new SP_DEVINFO_DATA(), da = new SP_DEVINFO_DATA(); Int32 bufferSize = 0, memberIndex = 0; deviceInfoSet = SetupDiGetClassDevs(ref Target, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); deviceInterfaceData.cbSize = da.cbSize = Marshal.SizeOf(deviceInterfaceData); while (SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref Target, memberIndex, ref deviceInterfaceData)) { SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, ref da); { detailDataBuffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); if (SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, ref da)) { IntPtr pDevicePathName = detailDataBuffer + 4; Path = Marshal.PtrToStringAuto(pDevicePathName).ToUpper(); if (memberIndex == Instance) { Int32 nBytes = 256; IntPtr ptrInstanceBuf = Marshal.AllocHGlobal(nBytes); CM_Get_Device_ID(da.Flags, ptrInstanceBuf, nBytes, 0); InstanceId = Marshal.PtrToStringAuto(ptrInstanceBuf).ToUpper(); Marshal.FreeHGlobal(ptrInstanceBuf); return true; } } else Marshal.FreeHGlobal(detailDataBuffer); } memberIndex++; } } catch (Exception ex) { Console.WriteLine("{0} {1}", ex.HelpLink, ex.Message); throw; } finally { if (deviceInfoSet != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceInfoSet); } } return false; } public static Boolean Create(String ClassName, Guid ClassGuid, String Node) { IntPtr DeviceInfoSet = (IntPtr)(-1); SP_DEVINFO_DATA DeviceInfoData = new SP_DEVINFO_DATA(); try { DeviceInfoSet = SetupDiCreateDeviceInfoList(ref ClassGuid, IntPtr.Zero); if (DeviceInfoSet == (IntPtr)(-1)) { return false; } DeviceInfoData.cbSize = Marshal.SizeOf(DeviceInfoData); if (!SetupDiCreateDeviceInfo(DeviceInfoSet, ClassName, ref ClassGuid, null, IntPtr.Zero, DICD_GENERATE_ID, ref DeviceInfoData)) { return false; } if (!SetupDiSetDeviceRegistryProperty(DeviceInfoSet, ref DeviceInfoData, SPDRP_HARDWAREID, Node, Node.Length * 2)) { return false; } if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, DeviceInfoSet, ref DeviceInfoData)) { return false; } } catch { } finally { if (DeviceInfoSet != (IntPtr)(-1)) { SetupDiDestroyDeviceInfoList(DeviceInfoSet); } } return true; } public static Boolean Remove(Guid ClassGuid, String Path, String InstanceId) { IntPtr deviceInfoSet = IntPtr.Zero; try { SP_DEVINFO_DATA deviceInterfaceData = new SP_DEVINFO_DATA(); deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData); deviceInfoSet = SetupDiGetClassDevs(ref ClassGuid, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (SetupDiOpenDeviceInfo(deviceInfoSet, InstanceId, IntPtr.Zero, 0, ref deviceInterfaceData)) { SP_REMOVEDEVICE_PARAMS props = new SP_REMOVEDEVICE_PARAMS(); props.ClassInstallHeader = new SP_CLASSINSTALL_HEADER(); props.ClassInstallHeader.cbSize = Marshal.SizeOf(props.ClassInstallHeader); props.ClassInstallHeader.InstallFunction = DIF_REMOVE; props.Scope = DI_REMOVEDEVICE_GLOBAL; props.HwProfile = 0x00; if (SetupDiSetClassInstallParams(deviceInfoSet, ref deviceInterfaceData, ref props, Marshal.SizeOf(props))) { return SetupDiCallClassInstaller(DIF_REMOVE, deviceInfoSet, ref deviceInterfaceData); } } } catch (Exception ex) { Console.WriteLine("{0} {1}", ex.HelpLink, ex.Message); throw; } finally { if (deviceInfoSet != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceInfoSet); } } return false; } #region Constant and Structure Definitions protected const Int32 DIGCF_PRESENT = 0x0002; protected const Int32 DIGCF_DEVICEINTERFACE = 0x0010; protected const Int32 DICD_GENERATE_ID = 0x0001; protected const Int32 SPDRP_HARDWAREID = 0x0001; protected const Int32 DIF_REMOVE = 0x0005; protected const Int32 DIF_REGISTERDEVICE = 0x0019; protected const Int32 DI_REMOVEDEVICE_GLOBAL = 0x0001; [StructLayout(LayoutKind.Sequential)] protected struct SP_DEVINFO_DATA { internal Int32 cbSize; internal Guid ClassGuid; internal Int32 Flags; internal IntPtr Reserved; } [StructLayout(LayoutKind.Sequential)] protected struct SP_CLASSINSTALL_HEADER { internal Int32 cbSize; internal Int32 InstallFunction; } [StructLayout(LayoutKind.Sequential)] protected struct SP_REMOVEDEVICE_PARAMS { internal SP_CLASSINSTALL_HEADER ClassInstallHeader; internal Int32 Scope; internal Int32 HwProfile; } #endregion #region Interop Definitions [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern IntPtr SetupDiCreateDeviceInfoList(ref Guid ClassGuid, IntPtr hwndParent); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiCreateDeviceInfo(IntPtr DeviceInfoSet, String DeviceName, ref Guid ClassGuid, String DeviceDescription, IntPtr hwndParent, Int32 CreationFlags, ref SP_DEVINFO_DATA DeviceInfoData); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiSetDeviceRegistryProperty(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, Int32 Property, [MarshalAs(UnmanagedType.LPWStr)] String PropertyBuffer, Int32 PropertyBufferSize); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiCallClassInstaller(Int32 InstallFunction, IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid, IntPtr Enumerator, IntPtr hwndParent, Int32 Flags); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref System.Guid InterfaceClassGuid, Int32 MemberIndex, ref SP_DEVINFO_DATA DeviceInterfaceData); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, Int32 DeviceInterfaceDetailDataSize, ref Int32 RequiredSize, ref SP_DEVINFO_DATA DeviceInfoData); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Int32 CM_Get_Device_ID(Int32 DevInst, IntPtr Buffer, Int32 BufferLen, Int32 Flags); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiOpenDeviceInfo(IntPtr DeviceInfoSet, String DeviceInstanceId, IntPtr hwndParent, Int32 Flags, ref SP_DEVINFO_DATA DeviceInfoData); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiSetClassInstallParams(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInterfaceData, ref SP_REMOVEDEVICE_PARAMS ClassInstallParams, Int32 ClassInstallParamsSize); #endregion } } <|start_filename|>WiinUPro/Controls/BaseControl.cs<|end_filename|> using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Shared; namespace WiinUPro { public abstract class BaseControl : UserControl, IBaseControl { public string DeviceID { get; protected set; } public event Delegates.StringDel OnInputRightClick; public event Delegates.StringDel OnInputSelected; public event AssignmentCollection.AssignDelegate OnQuickAssign; public event Delegates.StringArrDel OnRemoveInputs; protected string _inputPrefix = ""; protected string _menuOwnerTag = ""; protected ContextMenu _analogMenu; protected string _analogMenuInput = ""; protected BaseControl() { _analogMenu = new ContextMenu(); // Create menu items for assigning input directions. _analogMenu.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Up"), Tag="UP" }); _analogMenu.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Left"), Tag="LEFT" }); _analogMenu.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Right"), Tag="RIGHT" }); _analogMenu.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Down"), Tag="DOWN" }); _analogMenu.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Joy_Button"), Tag="S" }); // Create menu items for analog triggers _analogMenu.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Press"), Tag="T" }); _analogMenu.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Press_Full"), Tag="FULL" }); foreach (var menuItem in _analogMenu.Items) (menuItem as MenuItem).Click += OpenSelectedInput; _analogMenu.Items.Add(new Separator()); // Create menu items for quick assignment var quickAssign = new MenuItem { Header = Globalization.Translate("Context_Quick") }; var quickMouse = new MenuItem { Header = Globalization.Translate("Context_Quick_Mouse") }; { quickMouse.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Quick_Mouse_50"), Tag = "50" }); quickMouse.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Quick_Mouse_100"), Tag = "100" }); quickMouse.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Quick_Mouse_150"), Tag = "150" }); quickMouse.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Quick_Mouse_200"), Tag = "200" }); quickMouse.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Quick_Mouse_250"), Tag = "250" }); quickMouse.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Quick_Mouse_300"), Tag = "300" }); } foreach (var menuItem in quickMouse.Items) (menuItem as MenuItem).Click += QuickAssignMouse_Click; quickAssign.Items.Add(quickMouse); quickAssign.Items.Add(new MenuItem { Header = "WASD" }); quickAssign.Items.Add(new MenuItem { Header = Globalization.Translate("Context_Quick_Arrows") }); (quickAssign.Items[1] as MenuItem).Click += QuickAssign_Click; (quickAssign.Items[2] as MenuItem).Click += QuickAssign_Click; _analogMenu.Items.Add(quickAssign); _analogMenu.Items.Add(new Separator()); // Create menu items for IR camera var irMode = new MenuItem { Header = Globalization.Translate("Context_IR_Mode") }; { irMode.Items.Add(new MenuItem { Header = Globalization.Translate("Context_IR_Basic") }); irMode.Items.Add(new MenuItem { Header = Globalization.Translate("Context_IR_Wide") }); irMode.Items.Add(new MenuItem { Header = Globalization.Translate("Context_IR_Full") }); irMode.Items.Add(new MenuItem { Header = Globalization.Translate("Context_IR_Off") }); } foreach (var irModeItem in irMode.Items) (irModeItem as MenuItem).Click += SetIRCamMode_Click; var irLevel = new MenuItem { Header = Globalization.Translate("Context_IR_Level") }; { irLevel.Items.Add(new MenuItem { Header = Globalization.Translate("Context_IR_Level_1") }); irLevel.Items.Add(new MenuItem { Header = Globalization.Translate("Context_IR_Level_2") }); irLevel.Items.Add(new MenuItem { Header = Globalization.Translate("Context_IR_Level_3") }); irLevel.Items.Add(new MenuItem { Header = Globalization.Translate("Context_IR_Level_4") }); irLevel.Items.Add(new MenuItem { Header = Globalization.Translate("Context_IR_Level_5") }); } foreach (var irLevelItem in irLevel.Items) (irLevelItem as MenuItem).Click += SetIRCamSensitivity_Click; _analogMenu.Items.Add(irMode); _analogMenu.Items.Add(irLevel); // Add Calibration menu item var calibrationItem = new MenuItem { Header = Globalization.Translate("Context_Calibrate") }; calibrationItem.Click += CalibrateInput_Click; _analogMenu.Items.Add(calibrationItem); ContextMenu = _analogMenu; ContextMenuService.SetIsEnabled(this, false); } protected void SetupAnalogMenuForJoystick(bool withStickClick) { int i = 0; for (; i < 4; ++i) { (_analogMenu.Items[i] as MenuItem).Visibility = Visibility.Visible; } (_analogMenu.Items[i++] as MenuItem).Visibility = withStickClick ? Visibility.Visible : Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as Separator).Visibility = Visibility.Visible; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Visible; (_analogMenu.Items[i++] as Separator).Visibility = Visibility.Visible; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Visible; } protected void SetupAnalogMenuForDpad() { int i = 0; for (; i < 4; ++i) { (_analogMenu.Items[i] as MenuItem).Visibility = Visibility.Visible; } (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as Separator).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Visible; (_analogMenu.Items[i++] as Separator).Visibility = Visibility.Visible; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; } protected void SetupAnalogMenuForTrigger() { int i = 0; for (; i < 5; ++i) { (_analogMenu.Items[i] as MenuItem).Visibility = Visibility.Collapsed; } (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Visible; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Visible; (_analogMenu.Items[i++] as Separator).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as Separator).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Collapsed; (_analogMenu.Items[i++] as MenuItem).Visibility = Visibility.Visible; } protected void SetupAnalogMenuForIRCam() { int i = 0; for (; i < 4; ++i) { (_analogMenu.Items[i] as MenuItem).Visibility = Visibility.Visible; } for (; i < 7; ++i) { (_analogMenu.Items[i] as MenuItem).Visibility = Visibility.Collapsed; } for (; i < 13; ++i) { ((Control)_analogMenu.Items[i]).Visibility = Visibility.Visible; } } protected void UpdateTooltipLine(FrameworkElement element, string update, int line) { if (!(element.ToolTip is string)) return; string[] parts = ((string)element.ToolTip).Split('\n'); if (parts.Length > line) parts[line] = update; string result = parts[0]; for (int i = 1; i < parts.Length; ++i) result += "\n" + parts[i]; element.ToolTip = result; } #region Event passthroughs protected virtual void CallEvent_OnInputRightClick(string value) { OnInputRightClick?.Invoke(value); } protected virtual void CallEvent_OnInputSelected(string value) { OnInputSelected?.Invoke(value); } protected virtual void CallEvent_OnQuickAssign(Dictionary<string, AssignmentCollection> collection) { OnQuickAssign?.Invoke(collection); } protected virtual void CallEvent_OnRemoveInputs(string[] inputs) { OnRemoveInputs?.Invoke(inputs); } #endregion protected virtual void OpenInput(object sender, RoutedEventArgs e = null) { var element = sender as FrameworkElement; var tag = element == null ? "" : _inputPrefix + element.Tag as string; // TODO: Solve issue where this is being triggered twice for the guitar // Open input assignment window if (OnInputSelected != null && tag != null) { OnInputSelected(tag); } } protected virtual void Axis_Click(object sender, RoutedEventArgs e) { OpenInput(sender); } protected virtual void Btn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (e.ClickCount == 2) { OpenInput(sender); } } protected virtual void Btn_MouseRightButtonUp(object sender, MouseButtonEventArgs e) { var element = sender as FrameworkElement; var tag = element == null ? "" : element.Tag as string; // Open Context menu if (OnInputRightClick != null && tag != null) { OnInputRightClick(tag); } } #region Context Menu Actions protected virtual void OpenContextMenu(object sender, MouseButtonEventArgs e) { var element = sender as FrameworkElement; if (element != null && element.ContextMenu != null) { element.ContextMenu.IsOpen = true; } } protected virtual void OpenJoystickMenu(object sender, MouseButtonEventArgs e) { var item = sender as FrameworkElement; if (item != null) { _menuOwnerTag = item.Tag as string; SetupAnalogMenuForJoystick(false); _analogMenuInput = _inputPrefix + (item.Tag as string); _analogMenu.IsOpen = true; } } protected virtual void OpenJoystickClickMenu(object sender, MouseButtonEventArgs e) { var item = sender as FrameworkElement; if (item != null) { _menuOwnerTag = item.Tag as string; SetupAnalogMenuForJoystick(true); _analogMenuInput = _inputPrefix + (item.Tag as string); _analogMenu.IsOpen = true; } } protected virtual void OpenDpadMenu(object sender, MouseButtonEventArgs e) { var item = sender as FrameworkElement; if (item != null) { _menuOwnerTag = item.Tag as string; SetupAnalogMenuForDpad(); _analogMenuInput = _inputPrefix + (item.Tag as string); _analogMenu.IsOpen = true; } } protected virtual void OpenTriggerMenu(object sender, MouseButtonEventArgs e) { var item = sender as FrameworkElement; if (item != null) { _menuOwnerTag = item.Tag as string; SetupAnalogMenuForTrigger(); _analogMenuInput = _inputPrefix + (item.Tag as string); _analogMenu.IsOpen = true; } } protected virtual void OpenIRCamMenu(object sender, MouseButtonEventArgs e) { var item = sender as FrameworkElement; if (item != null) { _menuOwnerTag = item.Tag as string; SetupAnalogMenuForIRCam(); _analogMenuInput = _inputPrefix + (item.Tag as string); _analogMenu.IsOpen = true; } } protected virtual void OpenSelectedInput(object sender, RoutedEventArgs e) { OnInputSelected?.Invoke(_analogMenuInput + (sender as FrameworkElement)?.Tag?.ToString()); } protected virtual void QuickAssign(string prefix, string type) { Dictionary<string, AssignmentCollection> args = new Dictionary<string, AssignmentCollection>(); if (type == "Mouse") { args.Add(prefix + "UP", new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveUp) })); args.Add(prefix + "DOWN", new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveDown) })); args.Add(prefix + "LEFT", new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveLeft) })); args.Add(prefix + "RIGHT", new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveRight) })); } else if (type == "WASD") { args.Add(prefix + "UP", new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.K_W) })); args.Add(prefix + "DOWN", new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.K_S) })); args.Add(prefix + "LEFT", new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.K_A) })); args.Add(prefix + "RIGHT", new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.K_D) })); } else if (type == "Arrows") { args.Add(prefix + "UP", new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.VK_UP) })); args.Add(prefix + "DOWN", new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.VK_DOWN) })); args.Add(prefix + "LEFT", new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.VK_LEFT) })); args.Add(prefix + "RIGHT", new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.VK_RIGHT) })); } CallEvent_OnQuickAssign(args); } protected virtual void QuickAssign_Click(object sender, RoutedEventArgs e) { var item = sender as MenuItem; if (item != null) { var header = item.Header as string; var tag = _inputPrefix + _menuOwnerTag ?? "" + item.Tag as string; if (header != null && tag != null) { QuickAssign(tag, header); } } } protected virtual void QuickAssignMouse_Click(object sender, RoutedEventArgs e) { var item = sender as MenuItem; if (item != null) { var mouseSpeed = item.Tag as string; if (mouseSpeed != null) { float speed; switch (mouseSpeed) { case "50": speed = 0.5f; break; case "150": speed = 1.5f; break; case "200": speed = 2.0f; break; case "250": speed = 2.5f; break; case "300": speed = 3.0f; break; case "100": default: speed = 1f; break; } string prefix = (_inputPrefix ?? "") + (_menuOwnerTag ?? ""); Dictionary<string, AssignmentCollection> args = new Dictionary<string, AssignmentCollection>(); args.Add(prefix + "UP", new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveUp, speed) })); args.Add(prefix + "DOWN", new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveDown, speed) })); args.Add(prefix + "LEFT", new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveLeft, speed) })); args.Add(prefix + "RIGHT", new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveRight, speed) })); CallEvent_OnQuickAssign(args); } } } protected virtual void SetIRCamMode_Click(object sender, RoutedEventArgs e) { // To be overriden in WiiControl. } protected virtual void SetIRCamSensitivity_Click(object sender, RoutedEventArgs e) { // To be overriden in WiiControl. } protected virtual void CalibrateInput_Click(object sender, RoutedEventArgs e) { CalibrateInput((_inputPrefix ?? "") + (_menuOwnerTag ?? "")); } #endregion protected abstract void CalibrateInput(string inputName); #region Input Highlighting public static readonly DependencyProperty HighlightProperty = App.IsDesignMode ? null : DependencyProperty.Register("HighlightInput", typeof(bool), typeof(UIElement)); public static readonly DependencyProperty DisplayProperty = App.IsDesignMode ? null : DependencyProperty.Register("DisplayInput", typeof(bool), typeof(UIElement)); /// For mousing over an input protected void HighlightElement(UIElement element, bool doHighlight) { if (doHighlight != (bool)element.GetValue(HighlightProperty)) { element.SetValue(HighlightProperty, doHighlight); element.Opacity += doHighlight ? 0.2d : -0.2d; } } /// For displaying when input is activated protected void Display(UIElement element, bool doDisplay) { if (doDisplay != (bool)element.GetValue(DisplayProperty)) { element.SetValue(DisplayProperty, doDisplay); element.Opacity += doDisplay ? 0.8d : -0.8d; } } protected void Highlight(object sender, MouseEventArgs e) { HighlightElement((UIElement)sender, true); } protected void Unhighlight(object sender, MouseEventArgs e) { HighlightElement((UIElement)sender, false); } #endregion } public interface IBaseControl { string DeviceID { get; } event Delegates.StringDel OnInputRightClick; event Delegates.StringDel OnInputSelected; event AssignmentCollection.AssignDelegate OnQuickAssign; event Delegates.StringArrDel OnRemoveInputs; } } <|start_filename|>Scp/ScpInstaller/Program.cs<|end_filename|> using System; using System.Windows.Forms; using System.Security.Principal; namespace ScpDriver { static class Program { [STAThread] static void Main(String[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ScpForm()); } } } <|start_filename|>Nintroller/Controllers/TaikoDrum.cs<|end_filename|> using System.Collections; using System.Collections.Generic; namespace NintrollerLib { public struct TaikoDrum : INintrollerState, IWiimoteExtension { public Wiimote wiimote { get; set; } public bool centerLeft, centerRight, rimLeft, rimRight; public void Update(byte[] data) { int offset = Utils.GetExtensionOffset((InputReport)data[0]); if (offset > 0) { rimRight = (data[offset] & 0x08) == 0; centerRight = (data[offset] & 0x10) == 0; rimLeft = (data[offset] & 0x20) == 0; centerLeft = (data[offset] & 0x40) == 0; } wiimote = new Wiimote(data, wiimote); } public float GetValue(string input) { switch (input) { case INPUT_NAMES.TAIKO_DRUM.CENTER_LEFT: return centerLeft ? 1 : 0; case INPUT_NAMES.TAIKO_DRUM.CENTER_RIGHT: return centerRight ? 1 : 0; case INPUT_NAMES.TAIKO_DRUM.RIM_LEFT: return rimLeft ? 1 : 0; case INPUT_NAMES.TAIKO_DRUM.RIM_RIGHT: return rimRight ? 1 : 0; } return wiimote.GetValue(input); } public void SetCalibration(Calibrations.CalibrationPreset preset) { wiimote.SetCalibration(preset); } public void SetCalibration(INintrollerState from) { // no calibration needed } public void SetCalibration(string calibrationString) { // no calibration needed } public string GetCalibrationString() { // none needed return string.Empty; } public bool CalibrationEmpty { get { return wiimote.CalibrationEmpty; } } public IEnumerator<KeyValuePair<string, float>> GetEnumerator() { foreach (var input in wiimote) { yield return input; } yield return new KeyValuePair<string, float>(INPUT_NAMES.TAIKO_DRUM.CENTER_LEFT, centerLeft ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.TAIKO_DRUM.CENTER_RIGHT, centerRight ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.TAIKO_DRUM.RIM_LEFT, rimLeft ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.TAIKO_DRUM.RIM_RIGHT, rimRight ? 1.0f : 0.0f); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <|start_filename|>Nintroller/TestApp/MainWindow.xaml.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using NintrollerLib; using System.Collections.ObjectModel; using System.Diagnostics; namespace TestApp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public List<string> DeviceList { get; set; } private Nintroller _nintroller; public MainWindow() { InitializeComponent(); } private void _btnFind_Click(object sender, RoutedEventArgs e) { /* This code is all obsolete * The Nintroller library is no longer responsible for finding controllers //var controllers = Nintroller.FindControllers(); var controllers = Nintroller.GetControllerPaths(); DeviceList = new List<string>(); foreach (string id in controllers) { DeviceList.Add(id); } _comboBoxDeviceList.ItemsSource = DeviceList; */ } private void _btnConnect_Click(object sender, RoutedEventArgs e) { /* This Code is obsolete if (_nintroller != null) { _nintroller.ExtensionChange -= ExtensionChange; //_nintroller.StateChange -= StateChange; _nintroller.StateUpdate -= StateUpdate; _nintroller.Disconnect(); _nintroller = null; _stackDigitalInputs.Children.Clear(); _stackAnalogInputs.Children.Clear(); _btnConnect.Content = "Connect"; } else if (_comboBoxDeviceList.SelectedItem != null) { _nintroller = new Nintroller((string)_comboBoxDeviceList.SelectedItem); bool success = _nintroller.Connect(); if (!success) { Debug.WriteLine("Failed to connect"); _nintroller = null; } else { _btnConnect.Content = "Disconnect"; _nintroller.ExtensionChange += ExtensionChange; _nintroller.StateUpdate += StateUpdate; _nintroller.BeginReading(); _nintroller.GetStatus(); _nintroller.SetPlayerLED(1); } } */ } private void ExtensionChange(object sender, NintrollerExtensionEventArgs e) { Dispatcher.Invoke(() => { _stackDigitalInputs.Children.Clear(); switch(e.controllerType) { case ControllerType.ProController: #region Pro Controller Inputs // Add Digital Inputs _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "A" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "B" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "X" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Y" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Up" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Down" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Left" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Right" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "L" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "R" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "ZL" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "ZR" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Plus" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Minus" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Home" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "LS" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "RS" }); // Add Analog Inputs for (int i = 0; i < 6; i++) { _stackAnalogInputs.Children.Add(new Label()); } #endregion break; case ControllerType.Wiimote: #region Wiimote Inputs AddWiimoteInputs(); #endregion break; case ControllerType.Nunchuk: case ControllerType.NunchukB: #region Nunchuk Inputs AddWiimoteInputs(); // Add Digital Inputs _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "C" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Z" }); // Add Analog Inputs for (int i = 0; i < 7; i++) { _stackAnalogInputs.Children.Add(new Label()); } #endregion break; case ControllerType.ClassicController: #region Classic Controller Inputs AddWiimoteInputs(); // Add Digital Inputs _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "A" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "B" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "X" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Y" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Up" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Down" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Left" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Right" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "L" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "R" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "L-Full" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "R-Full" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "ZL" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "ZR" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Plus" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Minus" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Home" }); // Add Analog Inputs for (int i = 0; i < 8; i++) { _stackAnalogInputs.Children.Add(new Label()); } #endregion break; case ControllerType.ClassicControllerPro: #region Classic Controller Pro Inputs AddWiimoteInputs(); // Add Digital Inputs _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "A" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "B" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "X" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Y" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Up" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Down" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Left" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Right" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "L" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "R" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "ZL" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "ZR" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Plus" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Minus" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Home" }); // Add Analog Inputs for (int i = 0; i < 6; i++) { _stackAnalogInputs.Children.Add(new Label()); } #endregion break; case ControllerType.BalanceBoard: #region Balance Board Inputs // Add Analog Inputs for (int i = 0; i < 4; i++) { _stackAnalogInputs.Children.Add(new Label()); } #endregion break; } Console.WriteLine(_stackDigitalInputs.Children.Count); }); } private void AddWiimoteInputs() { // Digital _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "A" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "B" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "1" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "2" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Up" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Down" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Left" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Right" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Plus" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Minus" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "Home" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "IR1 in view" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "IR2 in view" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "IR3 in view" }); _stackDigitalInputs.Children.Add(new CheckBox() { IsHitTestVisible = false, Content = "IR4 in view" }); // Analog (Acc & IR) for (int i = 0; i < 8; i++) { _stackAnalogInputs.Children.Add(new Label()); } } private void StateUpdate(object sender, NintrollerStateEventArgs e) { Dispatcher.Invoke(() => { try { switch (e.controllerType) { case ControllerType.ProController: #region Pro Controller Display ProController pro = new ProController(); pro = (ProController)e.state; if (_stackDigitalInputs.Children.Count < 17) return; ((CheckBox)_stackDigitalInputs.Children[0]).IsChecked = pro.A; ((CheckBox)_stackDigitalInputs.Children[1]).IsChecked = pro.B; ((CheckBox)_stackDigitalInputs.Children[2]).IsChecked = pro.X; ((CheckBox)_stackDigitalInputs.Children[3]).IsChecked = pro.Y; ((CheckBox)_stackDigitalInputs.Children[4]).IsChecked = pro.Up; ((CheckBox)_stackDigitalInputs.Children[5]).IsChecked = pro.Down; ((CheckBox)_stackDigitalInputs.Children[6]).IsChecked = pro.Left; ((CheckBox)_stackDigitalInputs.Children[7]).IsChecked = pro.Right; ((CheckBox)_stackDigitalInputs.Children[8]).IsChecked = pro.L; ((CheckBox)_stackDigitalInputs.Children[9]).IsChecked = pro.R; ((CheckBox)_stackDigitalInputs.Children[10]).IsChecked = pro.ZL; ((CheckBox)_stackDigitalInputs.Children[11]).IsChecked = pro.ZR; ((CheckBox)_stackDigitalInputs.Children[12]).IsChecked = pro.Plus; ((CheckBox)_stackDigitalInputs.Children[13]).IsChecked = pro.Minus; ((CheckBox)_stackDigitalInputs.Children[14]).IsChecked = pro.Home; ((CheckBox)_stackDigitalInputs.Children[15]).IsChecked = pro.LStick; ((CheckBox)_stackDigitalInputs.Children[16]).IsChecked = pro.RStick; if (_stackAnalogInputs.Children.Count < 4) return; ((Label)_stackAnalogInputs.Children[0]).Content = pro.LJoy.rawX.ToString(); ((Label)_stackAnalogInputs.Children[1]).Content = pro.LJoy.rawY.ToString(); ((Label)_stackAnalogInputs.Children[2]).Content = pro.LJoy.ToString(); ((Label)_stackAnalogInputs.Children[3]).Content = pro.RJoy.rawX.ToString(); ((Label)_stackAnalogInputs.Children[4]).Content = pro.RJoy.rawY.ToString(); ((Label)_stackAnalogInputs.Children[5]).Content = pro.RJoy.ToString(); #endregion break; case ControllerType.Wiimote: #region Wiimote Display //Wiimote wm = new Wiimote(); //wm = (Wiimote)e.state; // try/catch if we must UpdateWiimoteInputs((Wiimote)e.state); #endregion break; case ControllerType.Nunchuk: case ControllerType.NunchukB: #region Nunchuk Display var nun = ((Nunchuk)e.state); UpdateWiimoteInputs(nun.wiimote); // Update Digital Inputs if (_stackDigitalInputs.Children.Count < 17) return; ((CheckBox)_stackDigitalInputs.Children[15]).IsChecked = nun.C; ((CheckBox)_stackDigitalInputs.Children[16]).IsChecked = nun.Z; if (_stackAnalogInputs.Children.Count < 15) return; ((Label)_stackAnalogInputs.Children[8]).Content = "Left Joy: " + nun.joystick.ToString(); ((Label)_stackAnalogInputs.Children[9]).Content = "LJoy X: " + nun.joystick.rawX.ToString(); ((Label)_stackAnalogInputs.Children[10]).Content = "LJoy Y: " + nun.joystick.rawY.ToString(); ((Label)_stackAnalogInputs.Children[11]).Content = "Acc: " + nun.accelerometer.ToString(); ((Label)_stackAnalogInputs.Children[12]).Content = "Acc X: " + nun.accelerometer.rawX.ToString(); ((Label)_stackAnalogInputs.Children[13]).Content = "Acc Y: " + nun.accelerometer.rawY.ToString(); ((Label)_stackAnalogInputs.Children[14]).Content = "Acc Z: " + nun.accelerometer.rawZ.ToString(); #endregion break; case ControllerType.ClassicController: #region Classic Controller Display var cc = ((ClassicController)e.state); UpdateWiimoteInputs(cc.wiimote); // Update Digital Inputs if (_stackDigitalInputs.Children.Count < 32) return; ((CheckBox)_stackDigitalInputs.Children[15]).IsChecked = cc.A; ((CheckBox)_stackDigitalInputs.Children[16]).IsChecked = cc.B; ((CheckBox)_stackDigitalInputs.Children[17]).IsChecked = cc.X; ((CheckBox)_stackDigitalInputs.Children[18]).IsChecked = cc.Y; ((CheckBox)_stackDigitalInputs.Children[19]).IsChecked = cc.Up; ((CheckBox)_stackDigitalInputs.Children[20]).IsChecked = cc.Down; ((CheckBox)_stackDigitalInputs.Children[21]).IsChecked = cc.Left; ((CheckBox)_stackDigitalInputs.Children[22]).IsChecked = cc.Right; ((CheckBox)_stackDigitalInputs.Children[23]).IsChecked = cc.L.value > 0; ((CheckBox)_stackDigitalInputs.Children[24]).IsChecked = cc.R.value > 0; ((CheckBox)_stackDigitalInputs.Children[25]).IsChecked = cc.LFull;// cc.L.full; ((CheckBox)_stackDigitalInputs.Children[26]).IsChecked = cc.RFull;// cc.R.full; ((CheckBox)_stackDigitalInputs.Children[27]).IsChecked = cc.ZL; ((CheckBox)_stackDigitalInputs.Children[28]).IsChecked = cc.ZR; ((CheckBox)_stackDigitalInputs.Children[29]).IsChecked = cc.Plus; ((CheckBox)_stackDigitalInputs.Children[30]).IsChecked = cc.Minus; ((CheckBox)_stackDigitalInputs.Children[31]).IsChecked = cc.Home; if (_stackAnalogInputs.Children.Count < 16) return; ((Label)_stackAnalogInputs.Children[8]).Content = "Left Joy: " + cc.LJoy.ToString(); ((Label)_stackAnalogInputs.Children[9]).Content = "LJoy X: " + cc.LJoy.rawX.ToString(); ((Label)_stackAnalogInputs.Children[10]).Content = "LJoy Y: " + cc.LJoy.rawY.ToString(); ((Label)_stackAnalogInputs.Children[11]).Content = "Right Joy: " + cc.RJoy.ToString(); ((Label)_stackAnalogInputs.Children[12]).Content = "RJoy X: " + cc.RJoy.rawX.ToString(); ((Label)_stackAnalogInputs.Children[13]).Content = "RJoy Y: " + cc.RJoy.rawY.ToString(); ((Label)_stackAnalogInputs.Children[14]).Content = "LTrigger: " + cc.L.rawValue.ToString(); ((Label)_stackAnalogInputs.Children[15]).Content = "RTrigger: " + cc.R.rawValue.ToString(); #endregion break; case ControllerType.ClassicControllerPro: #region Classic Controller Pro Display var ccp = ((ClassicControllerPro)e.state); UpdateWiimoteInputs(ccp.wiimote); // Update Digital Inputs if (_stackDigitalInputs.Children.Count < 30) return; ((CheckBox)_stackDigitalInputs.Children[15]).IsChecked = ccp.A; ((CheckBox)_stackDigitalInputs.Children[16]).IsChecked = ccp.B; ((CheckBox)_stackDigitalInputs.Children[17]).IsChecked = ccp.X; ((CheckBox)_stackDigitalInputs.Children[18]).IsChecked = ccp.Y; ((CheckBox)_stackDigitalInputs.Children[19]).IsChecked = ccp.Up; ((CheckBox)_stackDigitalInputs.Children[20]).IsChecked = ccp.Down; ((CheckBox)_stackDigitalInputs.Children[21]).IsChecked = ccp.Left; ((CheckBox)_stackDigitalInputs.Children[22]).IsChecked = ccp.Right; ((CheckBox)_stackDigitalInputs.Children[23]).IsChecked = ccp.L; ((CheckBox)_stackDigitalInputs.Children[24]).IsChecked = ccp.R; ((CheckBox)_stackDigitalInputs.Children[25]).IsChecked = ccp.ZL; ((CheckBox)_stackDigitalInputs.Children[26]).IsChecked = ccp.ZR; ((CheckBox)_stackDigitalInputs.Children[27]).IsChecked = ccp.Plus; ((CheckBox)_stackDigitalInputs.Children[28]).IsChecked = ccp.Minus; ((CheckBox)_stackDigitalInputs.Children[29]).IsChecked = ccp.Home; if (_stackAnalogInputs.Children.Count < 14) return; ((Label)_stackAnalogInputs.Children[8]).Content = "Left Joy: " + ccp.LJoy.ToString(); ((Label)_stackAnalogInputs.Children[9]).Content = "LJoy X: " + ccp.LJoy.rawX.ToString(); ((Label)_stackAnalogInputs.Children[10]).Content = "LJoy Y: " + ccp.LJoy.rawY.ToString(); ((Label)_stackAnalogInputs.Children[11]).Content = "Right Joy: " + ccp.RJoy.ToString(); ((Label)_stackAnalogInputs.Children[12]).Content = "RJoy X: " + ccp.RJoy.rawX.ToString(); ((Label)_stackAnalogInputs.Children[13]).Content = "RJoy Y: " + ccp.RJoy.rawY.ToString(); #endregion break; case ControllerType.BalanceBoard: #region Balance Board Display #endregion break; } } catch(Exception ex) { } }); } private void UpdateWiimoteInputs(Wiimote wm) { // Update Digital Inputs if (_stackDigitalInputs.Children.Count < 15) return; ((CheckBox)_stackDigitalInputs.Children[0]).IsChecked = wm.buttons.A; ((CheckBox)_stackDigitalInputs.Children[1]).IsChecked = wm.buttons.B; ((CheckBox)_stackDigitalInputs.Children[2]).IsChecked = wm.buttons.One; ((CheckBox)_stackDigitalInputs.Children[3]).IsChecked = wm.buttons.Two; ((CheckBox)_stackDigitalInputs.Children[4]).IsChecked = wm.buttons.Up; ((CheckBox)_stackDigitalInputs.Children[5]).IsChecked = wm.buttons.Down; ((CheckBox)_stackDigitalInputs.Children[6]).IsChecked = wm.buttons.Left; ((CheckBox)_stackDigitalInputs.Children[7]).IsChecked = wm.buttons.Right; ((CheckBox)_stackDigitalInputs.Children[8]).IsChecked = wm.buttons.Plus; ((CheckBox)_stackDigitalInputs.Children[9]).IsChecked = wm.buttons.Minus; ((CheckBox)_stackDigitalInputs.Children[10]).IsChecked = wm.buttons.Home; ((CheckBox)_stackDigitalInputs.Children[11]).IsChecked = wm.irSensor.point1.visible; ((CheckBox)_stackDigitalInputs.Children[12]).IsChecked = wm.irSensor.point2.visible; ((CheckBox)_stackDigitalInputs.Children[13]).IsChecked = wm.irSensor.point3.visible; ((CheckBox)_stackDigitalInputs.Children[14]).IsChecked = wm.irSensor.point4.visible; // Update Analog Inputs if (_stackAnalogInputs.Children.Count < 8) return; ((Label)_stackAnalogInputs.Children[0]).Content = "Acc: " + wm.accelerometer.ToString(); ((Label)_stackAnalogInputs.Children[1]).Content = "Acc X: " + wm.accelerometer.rawX.ToString(); ((Label)_stackAnalogInputs.Children[2]).Content = "Acc Y: " + wm.accelerometer.rawY.ToString(); ((Label)_stackAnalogInputs.Children[3]).Content = "Acc Z: " + wm.accelerometer.rawZ.ToString(); ((Label)_stackAnalogInputs.Children[4]).Content = "IR: " + wm.irSensor.ToString(); ((Label)_stackAnalogInputs.Children[4]).Content = string.Format("IR 1: x:{0} y:{1} size:{2}", wm.irSensor.point1.rawX, wm.irSensor.point1.rawY, wm.irSensor.point1.size); ((Label)_stackAnalogInputs.Children[5]).Content = string.Format("IR 2: x:{0} y:{1} size:{2}", wm.irSensor.point2.rawX, wm.irSensor.point2.rawY, wm.irSensor.point2.size); ((Label)_stackAnalogInputs.Children[6]).Content = string.Format("IR 3: x:{0} y:{1} size:{2}", wm.irSensor.point3.rawX, wm.irSensor.point3.rawY, wm.irSensor.point3.size); ((Label)_stackAnalogInputs.Children[7]).Content = string.Format("IR 4: x:{0} y:{1} size:{2}", wm.irSensor.point4.rawX, wm.irSensor.point4.rawY, wm.irSensor.point4.size); } private void _btnEnableIR_Click(object sender, RoutedEventArgs e) { //_nintroller.InitIRCamera(); //_nintroller.EnableIR(); _nintroller.IRMode = IRCamMode.Wide; } private void typeBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (_nintroller == null) return; switch (typeBox.SelectedIndex) { case 0: _nintroller.ForceControllerType(ControllerType.Unknown); break; case 1: _nintroller.ForceControllerType(ControllerType.ProController); break; case 2: _nintroller.ForceControllerType(ControllerType.Wiimote); break; case 3: _nintroller.ForceControllerType(ControllerType.Nunchuk); break; case 4: _nintroller.ForceControllerType(ControllerType.ClassicController); break; case 5: _nintroller.ForceControllerType(ControllerType.ClassicControllerPro); break; default: break; } } } } <|start_filename|>WiinUPro/Assignments/ShiftAssignment.cs<|end_filename|> using System.Collections.Generic; namespace WiinUPro { public class ShiftAssignment : IAssignment { public const int SHIFT_STATE_COUNT = 4; /// <summary> /// The state to enter when used. /// </summary> public ShiftState TargetState { get; set; } /// <summary> /// True if this shift assignment toggles between states. /// </summary> public bool Toggles { get; set; } /// <summary> /// The shift states to be toggle between /// </summary> public List<ShiftState> ToggleStates { get; set; } /// <summary> /// What the applied value must be greater than to apply /// </summary> public float Threshold { get { return _threashold; } set { _threashold = value; } } private IDeviceControl _control; private ShiftState _previousState; private float _threashold = 0.1f; private bool _isEnabled = false; public ShiftAssignment() { } public ShiftAssignment(IDeviceControl control) { _control = control; ToggleStates = new List<ShiftState>(); } public void Apply(float value) { bool isDown = value > Threshold; if (_isEnabled != isDown) { _isEnabled = isDown; if (Toggles) { if (isDown) { if (ToggleStates.Contains(_control.CurrentShiftState)) { int index = ToggleStates.IndexOf(_control.CurrentShiftState); if (ToggleStates.Count > index + 1) { _control.ChangeState(ToggleStates[index + 1]); } else { _control.ChangeState(ToggleStates[0]); } } else { _control.ChangeState(ToggleStates[0]); } } } else if (isDown) { if (TargetState != _control.CurrentShiftState) _previousState = _control.CurrentShiftState; _control.ChangeState(TargetState); } else { _control.ChangeState(_previousState); } } } public bool SameAs(IAssignment assignment) { var obj = assignment as ShiftAssignment; if (assignment == null) { return false; } bool result = true; result &= Toggles == obj.Toggles; if (Toggles) { result &= ToggleStates == obj.ToggleStates; } else { result &= TargetState == obj.TargetState; } return result; } public void SetControl(IDeviceControl control) { _control = control; } public override bool Equals(object obj) { var other = obj as ShiftAssignment; if (other == null) { return false; } if (Toggles != other.Toggles) { return false; } if (Toggles) { return TargetState == other.TargetState; } else { return ToggleStates == other.ToggleStates; } } public override int GetHashCode() { int hash = (int)TargetState + 1; if (Toggles && ToggleStates != null) { hash = (hash * 17) + ToggleStates.Count; foreach (var state in ToggleStates) { hash = (hash * 17) + (int)state; } } return hash; } public override string ToString() { string result = ""; if (Toggles) { foreach (var state in ToggleStates) { result += state; } } else { result = TargetState.ToString(); } return result; } public string GetDisplayName() { if (Toggles) { string s = "Toggle"; foreach (var shift in ToggleStates) s += $".{shift}"; return s; } else { return $"Shift.{TargetState}"; } } } public enum ShiftState { None = 0, Red = 1, Blue = 2, Green = 3 } } <|start_filename|>Scp/ScpControl/ScpPadState.cs<|end_filename|> using System; using System.Windows.Forms; using System.ComponentModel; namespace ScpControl { public partial class ScpPadState : Component { protected ScpProxy m_Proxy = null; protected const Int32 Centre = 127; protected const Int32 Accelerate = 75; protected const Int32 Repeat_Delay = 40; protected const Int32 Repeat_Rate = 5; protected DsPadId m_Pad = DsPadId.One; // Mouse protected Int32 m_Threshold = 0; protected Int32 m_vx = 0, m_vy = 0; protected Int32 m_dx = 0, m_dy = 0; public ScpProxy Proxy { get { return m_Proxy; } set { m_Proxy = value; Proxy.Packet += Sample; } } public DsPadId Pad { get { return m_Pad; } set { lock (this) { m_Pad = value; } } } public Boolean Enabled { get { return tmUpdate.Enabled; } set { if (tmUpdate.Enabled != value) { lock (this) { tmUpdate.Enabled = value; if (!value) { try { Reset(); } catch { } } } } } } public Int32 Threshold { get { return m_Threshold; } set { lock (this) { m_Threshold = value; } } } public Int32 ScaleX { get { return m_vx; } set { lock (this) { m_vx = value; } } } public Int32 ScaleY { get { return m_vy; } set { lock (this) { m_vy = value; } } } public ScpPadState() { InitializeComponent(); } public ScpPadState(IContainer container) { container.Add(this); InitializeComponent(); } public virtual void Sample(object sender, DsPacket Packet) { lock (this) { if (Packet.Detail.Pad == Pad) { if (Packet.Detail.State == DsState.Connected) { switch (Packet.Detail.Model) { case DsModel.DS3: try { SampleDs3(Packet); } catch { }; break; case DsModel.DS4: try { SampleDs4(Packet); } catch { } break; } } else { try { Reset(); } catch { } } } } } protected virtual void SampleDs3(DsPacket Packet) { m_dx = Mouse(Packet.Axis(Ds3Axis.RX), m_vx); m_dy = Mouse(Packet.Axis(Ds3Axis.RY), m_vy); } protected virtual void SampleDs4(DsPacket Packet) { m_dx = Mouse(Packet.Axis(Ds4Axis.RX), m_vx); m_dy = Mouse(Packet.Axis(Ds4Axis.RY), m_vy); } protected virtual void Rumble(Byte Large, Byte Small) { if (Proxy != null) { Proxy.Rumble(Pad, Large, Small); } } protected virtual void Reset() { m_dx = m_dy = 0; } protected virtual void Timer() { if (m_dx != 0 || m_dy != 0) KbmPost.Move(m_dx, m_dy); } protected virtual Int32 Mouse (Int32 Old, Int32 Scale) { Int32 New = 0; if (Old < (Centre - m_Threshold)) { New = -Scale; if (Old < (Centre - Accelerate)) New <<= 1; } if (Old > (Centre + m_Threshold)) { New = +Scale; if (Old > (Centre + Accelerate)) New <<= 1; } return New; } protected virtual Boolean Mouse (Boolean Old, Boolean New, KbmPost.MouseButtons Button) { if (Old != New) KbmPost.Button(Button, New); return New; } protected virtual Boolean Button(Boolean Old, Boolean New, Keys Key, Boolean Extended) { if (Old != New) KbmPost.Key(Key, Extended, New); return New; } protected virtual Int32 Repeat(Boolean Old, Int32 Count, Keys Key, Boolean Extended) { if (Old) { if ((++Count >= Repeat_Delay) && ((Count % Repeat_Rate) == 0)) { KbmPost.Key(Key, Extended, false); KbmPost.Key(Key, Extended, true); } } else { Count = 0; } return Count; } protected virtual Boolean Macro (Boolean Old, Boolean New, Keys[] Keys) { if (!Old && New) { foreach(Keys Key in Keys) { KbmPost.Key(Key, false, true ); KbmPost.Key(Key, false, false); } } return New; } protected virtual Boolean Wheel (Boolean Old, Boolean New, Boolean Vertical, Boolean Direction) { if (!Old && New) KbmPost.Wheel(Vertical, Direction ? 1 : -1); return New; } protected virtual Boolean Toggle(Boolean Old, Boolean New, ref Boolean Target) { if (!Old && New) Target = !Target; return New; } internal virtual void tmUpdate_Tick(object sender, EventArgs e) { lock (this) { try { Timer(); } catch { } } } } } <|start_filename|>WiinUPro/Assignments/MouseButtonAssignment.cs<|end_filename|> using System; using InputManager; namespace WiinUPro { public class MouseButtonAssignment : IAssignment { /// <summary> /// The Mouse Button to be simulated /// </summary> public Mouse.MouseKeys MouseButton { get; set; } /// <summary> /// Set to use Turbo feature /// </summary> public bool TurboEnabled { get; set; } /// <summary> /// Turbo rate in milliseconds (0ms to 1000ms) /// </summary> public int TurboRate { get { return _turboRate; } set { _turboRate = Math.Min(Math.Max(0, value), 1000); } } /// <summary> /// What the applied value must be greater than to apply /// </summary> public float Threshold { get { return _threashold; } set { _threashold = value; } } /// <summary> /// Set to apply key simulation when input is not being applied /// </summary> public bool InverseInput { get; set; } private int _turboRate = 200; private float _threashold = 0.1f; private bool _lastState = false; private int _lastApplied = 0; public MouseButtonAssignment() { } public MouseButtonAssignment(Mouse.MouseKeys btn) { MouseButton = btn; } public void Apply(float value) { bool isDown = value >= Threshold; if (InverseInput) { isDown = !isDown; } if (TurboEnabled) { if (!isDown) { return; } int now = DateTime.Now.Millisecond; if (_lastApplied > now) { _lastApplied = _lastApplied + TurboRate - 1000; } if (now > _lastApplied + TurboRate) { MouseDirector.Access.MouseButtonPress(MouseButton); _lastApplied = now; } } else if (isDown != _lastState) { if (isDown) { MouseDirector.Access.MouseButtonDown(MouseButton); } else { MouseDirector.Access.MouseButtonUp(MouseButton); } _lastState = isDown; } } public bool SameAs(IAssignment assignment) { var other = assignment as MouseButtonAssignment; if (other == null) { return false; } bool result = true; result &= MouseButton == other.MouseButton; result &= InverseInput == other.InverseInput; result &= Threshold == other.Threshold; result &= TurboEnabled == other.TurboEnabled; result &= TurboRate == other.TurboRate; return result; } public override bool Equals(object obj) { var other = obj as MouseButtonAssignment; if (other == null) { return false; } else { return MouseButton == other.MouseButton; } } public override int GetHashCode() { int hash = (int) MouseButton + 5; return hash; } public override string ToString() { return MouseButton.ToString(); } public string GetDisplayName() { return $"M.{ToString()}"; } } } <|start_filename|>WiinUPro/Controls/SwitchProControl.xaml.cs<|end_filename|> using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using Shared; using SharpDX.DirectInput; namespace WiinUPro { /// <summary> /// Interaction logic for SwitchProControl.xaml /// </summary> public partial class SwitchProControl : BaseControl, IJoyControl { public Guid AssociatedInstanceID { get; set; } public event Delegates.JoystickDel OnJoystickCalibrated; public AxisCalibration leftXCalibration; public AxisCalibration leftYCalibration; public AxisCalibration rightXCalibration; public AxisCalibration rightYCalibration; protected bool _leftCalibration; protected Windows.JoyCalibrationWindow _openJoyWindow; protected NintrollerLib.Joystick _calLeftJoystick; protected NintrollerLib.Joystick _calRightJoystick; public SwitchProControl() { InitializeComponent(); _calLeftJoystick = new NintrollerLib.Joystick(); _calRightJoystick = new NintrollerLib.Joystick(); leftXCalibration = new AxisCalibration(0, 65535, 32767, 2048); leftYCalibration = new AxisCalibration(0, 65535, 32767, 2048); rightXCalibration = new AxisCalibration(0, 65535, 32767, 2048); rightYCalibration = new AxisCalibration(0, 65535, 32767, 2048); } public SwitchProControl(AxisCalibration _leftXCal, AxisCalibration _leftYCal, AxisCalibration _rightXCal, AxisCalibration _rightYCal) : this() { leftXCalibration = _leftXCal; leftYCalibration = _leftYCal; rightXCalibration = _rightXCal; rightYCalibration = _rightYCal; } public void UpdateVisual(JoystickUpdate[] updates) { foreach (var update in updates) { switch (update.Offset) { case JoystickOffset.Buttons0: bBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons1: aBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons2: yBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons3: xBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons4: lBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons5: rBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons6: zlBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons7: zrBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons8: minusBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons9: plusBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons10: leftStickButton.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons11: rightStickButton.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons12: homeBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons13: shareBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.PointOfViewControllers0: leftBtn.Opacity = 0; rightBtn.Opacity = 0; upBtn.Opacity = 0; downBtn.Opacity = 0; center.Opacity = 0; if (update.Value == -1) { break; } else if (update.Value == 0) { upBtn.Opacity = 1; center.Opacity = 1; } else if (update.Value > 0 && update.Value < 9000) { upBtn.Opacity = 1; rightBtn.Opacity = 1; center.Opacity = 1; } else if (update.Value == 9000) { rightBtn.Opacity = 1; center.Opacity = 1; } else if (update.Value > 9000 && update.Value < 18000) { rightBtn.Opacity = 1; downBtn.Opacity = 1; center.Opacity = 1; } else if (update.Value == 18000) { downBtn.Opacity = 1; center.Opacity = 1; } else if (update.Value > 18000 && update.Value < 27000) { downBtn.Opacity = 1; leftBtn.Opacity = 1; center.Opacity = 1; } else if (update.Value == 27000) { leftBtn.Opacity = 1; center.Opacity = 1; } else if (update.Value > 27000) { leftBtn.Opacity = 1; upBtn.Opacity = 1; center.Opacity = 1; } break; case JoystickOffset.X: _calLeftJoystick.rawX = update.Value; break; case JoystickOffset.Y: _calLeftJoystick.rawY = 65535 - update.Value; break; case JoystickOffset.RotationX: _calRightJoystick.rawX = update.Value; break; case JoystickOffset.RotationY: _calRightJoystick.rawY = 65535 - update.Value; break; } } var joyL = JoyControl.ConvertToNintyJoy(leftXCalibration, leftYCalibration); var joyR = JoyControl.ConvertToNintyJoy(rightXCalibration, rightYCalibration); joyL.rawX = _calLeftJoystick.rawX; joyL.rawY = _calLeftJoystick.rawY; joyR.rawX = _calRightJoystick.rawX; joyR.rawY = _calRightJoystick.rawY; joyL.Normalize(); joyR.Normalize(); leftStick.Margin = new Thickness(146 + 30 * joyL.X, 291 - 30 * joyL.Y, 0, 0); rightStick.Margin = new Thickness(507 + 30 * joyR.X, 412 - 30 * joyR.Y, 0, 0); leftStickButton.Margin = leftStick.Margin; rightStickButton.Margin = rightStick.Margin; if (_openJoyWindow != null) { _openJoyWindow.Update(_leftCalibration ? _calLeftJoystick : _calRightJoystick); } } public void SetInputTooltip(string inputName, string tooltip) { if (Enum.TryParse(inputName, out JoystickOffset input)) { switch (input) { case JoystickOffset.Buttons0: bBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons1: aBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons2: yBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons3: xBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons4: lBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons5: rBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons6: zlBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons7: zrBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons8: minusBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons9: plusBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons10: UpdateTooltipLine(leftStickButton, tooltip, 4); break; case JoystickOffset.Buttons11: UpdateTooltipLine(rightStickButton, tooltip, 4); break; case JoystickOffset.Buttons12: homeBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons13: shareBtn.ToolTip = tooltip; break; } } else { switch (inputName) { case "Y+": UpdateTooltipLine(leftStickButton, tooltip, 0); break; case "X-": UpdateTooltipLine(leftStickButton, tooltip, 1); break; case "X+": UpdateTooltipLine(leftStickButton, tooltip, 2); break; case "Y-": UpdateTooltipLine(leftStickButton, tooltip, 3); break; case "RotationY+": UpdateTooltipLine(rightStickButton, tooltip, 0); break; case "RotationX-": UpdateTooltipLine(rightStickButton, tooltip, 1); break; case "RotationX+": UpdateTooltipLine(rightStickButton, tooltip, 2); break; case "RotationY-": UpdateTooltipLine(rightStickButton, tooltip, 3); break; case "pov0N": upBtn.ToolTip = tooltip; UpdateTooltipLine(center, tooltip, 0); break; case "pov0L": leftBtn.ToolTip = tooltip; UpdateTooltipLine(center, tooltip, 1); break; case "pov0R": rightBtn.ToolTip = tooltip; UpdateTooltipLine(center, tooltip, 2); break; case "pov0S": downBtn.ToolTip = tooltip; UpdateTooltipLine(center, tooltip, 3); break; } } } public void ClearTooltips() { string unsetText = Globalization.Translate("Input_Unset"); bBtn.ToolTip = unsetText; aBtn.ToolTip = unsetText; yBtn.ToolTip = unsetText; xBtn.ToolTip = unsetText; lBtn.ToolTip = unsetText; rBtn.ToolTip = unsetText; zlBtn.ToolTip = unsetText; zrBtn.ToolTip = unsetText; minusBtn.ToolTip = unsetText; plusBtn.ToolTip = unsetText; homeBtn.ToolTip = unsetText; shareBtn.ToolTip = unsetText; upBtn.ToolTip = unsetText; leftBtn.ToolTip = unsetText; rightBtn.ToolTip = unsetText; downBtn.ToolTip = unsetText; UpdateTooltipLine(leftStickButton, unsetText, 0); UpdateTooltipLine(leftStickButton, unsetText, 1); UpdateTooltipLine(leftStickButton, unsetText, 2); UpdateTooltipLine(leftStickButton, unsetText, 3); UpdateTooltipLine(leftStickButton, unsetText, 4); UpdateTooltipLine(leftStickButton, unsetText, 0); UpdateTooltipLine(leftStickButton, unsetText, 1); UpdateTooltipLine(leftStickButton, unsetText, 2); UpdateTooltipLine(leftStickButton, unsetText, 3); UpdateTooltipLine(leftStickButton, unsetText, 4); UpdateTooltipLine(center, unsetText, 0); UpdateTooltipLine(center, unsetText, 1); UpdateTooltipLine(center, unsetText, 2); UpdateTooltipLine(center, unsetText, 3); } protected override void OpenSelectedInput(object sender, RoutedEventArgs e) { string input = (sender as FrameworkElement)?.Tag?.ToString(); // Convert analog input names switch(input) { case "UP": if (_menuOwnerTag == "swpR") input = "RotationY+"; else input = "Y+"; break; case "LEFT": if (_menuOwnerTag == "swpR") input = "RotationX-"; else input = "X-"; break; case "RIGHT": if (_menuOwnerTag == "swpR") input = "RotationX+"; else input = "X+"; break; case "DOWN": if (_menuOwnerTag == "swpR") input = "RotationY-"; else input = "Y-"; break; case "S": if (_menuOwnerTag == "swpR") input = "Buttons11"; else input = "Buttons10"; break; } CallEvent_OnInputSelected(input); } private string[] GetQuickInputSet() { string[] dir = new string[4]; if (_menuOwnerTag == "pov") { dir[0] = "pov0N"; dir[1] = "pov0L"; dir[2] = "pov0R"; dir[3] = "pov0S"; } else if (_menuOwnerTag == "swpR") { dir[0] = "RotationY+"; dir[1] = "RotationY-"; dir[2] = "RotationX-"; dir[3] = "RotationX+"; } else { dir[0] = "Y+"; dir[1] = "Y-"; dir[2] = "X-"; dir[3] = "X+"; } return dir; } protected override void QuickAssign(string prefix, string type) { string[] dir = GetQuickInputSet(); Dictionary<string, AssignmentCollection> args = new Dictionary<string, AssignmentCollection>(); if (type == "Mouse") { args.Add(dir[0], new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveUp) })); args.Add(dir[1], new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveDown) })); args.Add(dir[2], new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveLeft) })); args.Add(dir[3], new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveRight) })); } else if (type == "WASD") { args.Add(dir[0], new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.K_W) })); args.Add(dir[1], new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.K_S) })); args.Add(dir[2], new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.K_A) })); args.Add(dir[3], new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.K_D) })); } else if (type == "Arrows") { args.Add(dir[0], new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.VK_UP) })); args.Add(dir[1], new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.VK_DOWN) })); args.Add(dir[2], new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.VK_LEFT) })); args.Add(dir[3], new AssignmentCollection(new List<IAssignment> { new KeyboardAssignment(InputManager.VirtualKeyCode.VK_RIGHT) })); } CallEvent_OnQuickAssign(args); } protected override void QuickAssignMouse_Click(object sender, RoutedEventArgs e) { var item = sender as MenuItem; if (item != null) { var mouseSpeed = item.Tag as string; if (mouseSpeed != null) { float speed; switch (mouseSpeed) { case "50": speed = 0.5f; break; case "150": speed = 1.5f; break; case "200": speed = 2.0f; break; case "250": speed = 2.5f; break; case "300": speed = 3.0f; break; case "100": default: speed = 1f; break; } string[] dir = GetQuickInputSet(); Dictionary<string, AssignmentCollection> args = new Dictionary<string, AssignmentCollection>(); args.Add(dir[0], new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveUp, speed) })); args.Add(dir[1], new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveDown, speed) })); args.Add(dir[2], new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveLeft, speed) })); args.Add(dir[3], new AssignmentCollection(new List<IAssignment> { new MouseAssignment(MouseInput.MoveRight, speed) })); CallEvent_OnQuickAssign(args); } } } protected override void CalibrateInput(string inputName) { _leftCalibration = inputName == "swpL"; string targetCalibration = _leftCalibration ? App.CAL_SWP_LJOYSTICK : App.CAL_SWP_RJOYSTICK; NintrollerLib.Joystick nonCalibrated = new NintrollerLib.Joystick { minX = 0, minY = 0, maxX = 65535, maxY = 65535, centerX = 32767, centerY = 32767 }; NintrollerLib.Joystick curCalibration = new NintrollerLib.Joystick { minX = _leftCalibration ? leftXCalibration.min : rightXCalibration.min, minY = _leftCalibration ? leftYCalibration.min : rightYCalibration.min, maxX = _leftCalibration ? leftXCalibration.max : rightXCalibration.max, maxY = _leftCalibration ? leftYCalibration.max : rightYCalibration.max, centerX = _leftCalibration ? leftXCalibration.center : rightXCalibration.center, centerY = _leftCalibration ? leftYCalibration.center : rightYCalibration.center, deadXn = _leftCalibration ? leftXCalibration.deadNeg : rightXCalibration.deadNeg, deadXp = _leftCalibration ? leftXCalibration.deadPos : rightXCalibration.deadPos, deadYn = _leftCalibration ? leftYCalibration.deadNeg : rightYCalibration.deadNeg, deadYp = _leftCalibration ? leftYCalibration.deadPos : rightYCalibration.deadPos }; Windows.JoyCalibrationWindow joyCal = new Windows.JoyCalibrationWindow(nonCalibrated, curCalibration); _openJoyWindow = joyCal; joyCal.ShowDialog(); if (joyCal.Apply) { OnJoystickCalibrated?.Invoke(joyCal.Calibration, targetCalibration, joyCal.FileName); } _openJoyWindow = null; } } } <|start_filename|>WiinUPro/Controls/ProControl.xaml.cs<|end_filename|> using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Shared; using NintrollerLib; namespace WiinUPro { /// <summary> /// Interaction logic for ProControl.xaml /// </summary> public partial class ProControl : BaseControl, INintyControl { public event Delegates.BoolArrDel OnChangeLEDs; public event Delegates.JoystickDel OnJoyCalibrated; protected Windows.JoyCalibrationWindow _openJoyWindow = null; protected bool _rightJoyOpen = false; protected ProController _lastState; private ProControl() { InitializeComponent(); } public ProControl(string deviceID) : this() { DeviceID = deviceID; } public void ApplyInput(INintrollerState state) { ProController? pro = state as ProController?; if (pro != null && pro.HasValue) { //pro.Value.GetValue } } public void UpdateVisual(INintrollerState state) { if (state is ProController) { var pro = (ProController)state; _lastState = pro; Display(aBtn, pro.A); Display(bBtn, pro.B); Display(xBtn, pro.X); Display(yBtn, pro.Y); Display(lBtn, pro.L); Display(rBtn, pro.R); Display(zlBtn, pro.ZL); Display(zrBtn, pro.ZR); Display(dpadUp, pro.Up); Display(dpadDown, pro.Down); Display(dpadLeft, pro.Left); Display(dpadRight, pro.Right); Display(dpadCenter, (pro.Up || pro.Down || pro.Left || pro.Right)); Display(homeBtn, pro.Home); Display(plusBtn, pro.Plus); Display(minusBtn, pro.Minus); Display(leftStickBtn, pro.LStick); Display(rightStickBtn, pro.RStick); leftStick.Margin = new Thickness(196 + 50 * pro.LJoy.X, 232 - 50 * pro.LJoy.Y, 0, 0); leftStickBtn.Margin = new Thickness(196 + 50 * pro.LJoy.X, 230 - 50 * pro.LJoy.Y, 0, 0); rightStick.Margin = new Thickness(980 + 50 * pro.RJoy.X, 232 - 50 * pro.RJoy.Y, 0, 0); rightStickBtn.Margin = new Thickness(980 + 50 * pro.RJoy.X, 230 - 50 * pro.RJoy.Y, 0, 0); if (_openJoyWindow != null) { _openJoyWindow.Update(_rightJoyOpen ? pro.RJoy : pro.LJoy); } } } public void SetInputTooltip(string inputName, string tooltip) { switch (inputName) { case INPUT_NAMES.PRO_CONTROLLER.A: aBtn.ToolTip = tooltip; break; case INPUT_NAMES.PRO_CONTROLLER.B: bBtn.ToolTip = tooltip; break; case INPUT_NAMES.PRO_CONTROLLER.X: xBtn.ToolTip = tooltip; break; case INPUT_NAMES.PRO_CONTROLLER.Y: yBtn.ToolTip = tooltip; break; case INPUT_NAMES.PRO_CONTROLLER.L: lBtn.ToolTip = tooltip; break; case INPUT_NAMES.PRO_CONTROLLER.R: rBtn.ToolTip = tooltip; break; case INPUT_NAMES.PRO_CONTROLLER.ZL: zlBtn.ToolTip = tooltip; break; case INPUT_NAMES.PRO_CONTROLLER.ZR: zrBtn.ToolTip = tooltip; break; case INPUT_NAMES.PRO_CONTROLLER.HOME: homeBtn.ToolTip = tooltip; break; case INPUT_NAMES.PRO_CONTROLLER.START: plusBtn.ToolTip = tooltip; break; case INPUT_NAMES.PRO_CONTROLLER.SELECT: minusBtn.ToolTip = tooltip; break; case INPUT_NAMES.PRO_CONTROLLER.LUP: UpdateTooltipLine(leftStickBtn, tooltip, 0); break; case INPUT_NAMES.PRO_CONTROLLER.LLEFT: UpdateTooltipLine(leftStickBtn, tooltip, 1); break; case INPUT_NAMES.PRO_CONTROLLER.LRIGHT: UpdateTooltipLine(leftStickBtn, tooltip, 2); break; case INPUT_NAMES.PRO_CONTROLLER.LDOWN: UpdateTooltipLine(leftStickBtn, tooltip, 3); break; case INPUT_NAMES.PRO_CONTROLLER.LS: UpdateTooltipLine(leftStickBtn, tooltip, 4); break; case INPUT_NAMES.PRO_CONTROLLER.RUP: UpdateTooltipLine(rightStickBtn, tooltip, 0); break; case INPUT_NAMES.PRO_CONTROLLER.RLEFT: UpdateTooltipLine(rightStickBtn, tooltip, 1); break; case INPUT_NAMES.PRO_CONTROLLER.RRIGHT: UpdateTooltipLine(rightStickBtn, tooltip, 2); break; case INPUT_NAMES.PRO_CONTROLLER.RDOWN: UpdateTooltipLine(rightStickBtn, tooltip, 3); break; case INPUT_NAMES.PRO_CONTROLLER.RS: UpdateTooltipLine(rightStickBtn, tooltip, 4); break; case INPUT_NAMES.PRO_CONTROLLER.UP: dpadUp.ToolTip = tooltip; UpdateTooltipLine(dpadCenter, tooltip, 0); break; case INPUT_NAMES.PRO_CONTROLLER.LEFT: dpadLeft.ToolTip = tooltip; UpdateTooltipLine(dpadCenter, tooltip, 1); break; case INPUT_NAMES.PRO_CONTROLLER.RIGHT: dpadRight.ToolTip = tooltip; UpdateTooltipLine(dpadCenter, tooltip, 2); break; case INPUT_NAMES.PRO_CONTROLLER.DOWN: dpadDown.ToolTip = tooltip; UpdateTooltipLine(dpadCenter, tooltip, 3); break; } } public void ClearTooltips() { string unsetText = Globalization.Translate("Input_Unset"); aBtn.ToolTip = unsetText; bBtn.ToolTip = unsetText; xBtn.ToolTip = unsetText; yBtn.ToolTip = unsetText; lBtn.ToolTip = unsetText; rBtn.ToolTip = unsetText; zlBtn.ToolTip = unsetText; zrBtn.ToolTip = unsetText; homeBtn.ToolTip = unsetText; plusBtn.ToolTip = unsetText; minusBtn.ToolTip = unsetText; dpadUp.ToolTip = unsetText; dpadLeft.ToolTip = unsetText; dpadRight.ToolTip = unsetText; dpadDown.ToolTip = unsetText; UpdateTooltipLine(leftStickBtn, unsetText, 0); UpdateTooltipLine(leftStickBtn, unsetText, 1); UpdateTooltipLine(leftStickBtn, unsetText, 2); UpdateTooltipLine(leftStickBtn, unsetText, 3); UpdateTooltipLine(leftStickBtn, unsetText, 4); UpdateTooltipLine(rightStickBtn, unsetText, 0); UpdateTooltipLine(rightStickBtn, unsetText, 1); UpdateTooltipLine(rightStickBtn, unsetText, 2); UpdateTooltipLine(rightStickBtn, unsetText, 3); UpdateTooltipLine(rightStickBtn, unsetText, 4); UpdateTooltipLine(dpadCenter, unsetText, 0); UpdateTooltipLine(dpadCenter, unsetText, 1); UpdateTooltipLine(dpadCenter, unsetText, 2); UpdateTooltipLine(dpadCenter, unsetText, 3); } public void ChangeLEDs(bool one, bool two, bool three, bool four) { led1.Opacity = one ? 1 : 0; led2.Opacity = two ? 1 : 0; led3.Opacity = three ? 1 : 0; led4.Opacity = four ? 1 : 0; } public void XboxAssign() { Dictionary<string, AssignmentCollection> defaults = new Dictionary<string, AssignmentCollection>(); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.LUP, new AssignmentCollection(new List<IAssignment> { new XInputAxisAssignment(ScpControl.X360Axis.LY_Hi) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.LDOWN, new AssignmentCollection(new List<IAssignment> { new XInputAxisAssignment(ScpControl.X360Axis.LY_Lo) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.LRIGHT, new AssignmentCollection(new List<IAssignment> { new XInputAxisAssignment(ScpControl.X360Axis.LX_Hi) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.LLEFT, new AssignmentCollection(new List<IAssignment> { new XInputAxisAssignment(ScpControl.X360Axis.LX_Lo) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.RUP, new AssignmentCollection(new List<IAssignment> { new XInputAxisAssignment(ScpControl.X360Axis.RY_Hi) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.RDOWN, new AssignmentCollection(new List<IAssignment> { new XInputAxisAssignment(ScpControl.X360Axis.RY_Lo) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.RRIGHT, new AssignmentCollection(new List<IAssignment> { new XInputAxisAssignment(ScpControl.X360Axis.RX_Hi) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.RLEFT, new AssignmentCollection(new List<IAssignment> { new XInputAxisAssignment(ScpControl.X360Axis.RX_Lo) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.ZL, new AssignmentCollection(new List<IAssignment> { new XInputAxisAssignment(ScpControl.X360Axis.LT) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.ZR, new AssignmentCollection(new List<IAssignment> { new XInputAxisAssignment(ScpControl.X360Axis.RT) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.UP, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.Up) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.DOWN, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.Down) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.LEFT, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.Left) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.RIGHT, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.Right) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.A, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.A) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.B, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.B) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.X, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.X) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.Y, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.Y) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.L, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.LB) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.R, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.RB) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.LS, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.LS) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.RS, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.RS) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.START, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.Start) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.SELECT, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.Back) })); defaults.Add(INPUT_NAMES.PRO_CONTROLLER.HOME, new AssignmentCollection(new List<IAssignment> { new XInputButtonAssignment(ScpControl.X360Button.Guide) })); CallEvent_OnQuickAssign(defaults); } private void led_MouseUp(object sender, MouseButtonEventArgs e) { var light = sender as Image; if (light != null) { light.Opacity = light.Opacity > 0.1 ? 0 : 1; } if (OnChangeLEDs != null) { bool[] leds = new bool[4]; leds[0] = led1.Opacity > 0.1; leds[1] = led2.Opacity > 0.1; leds[2] = led3.Opacity > 0.1; leds[3] = led4.Opacity > 0.1; OnChangeLEDs(leds); } } private void quickXboxbtn_Click(object sender, RoutedEventArgs e) { XboxAssign(); } protected override void CalibrateInput(string inputName) { _rightJoyOpen = inputName == "proR"; string joyTarget = _rightJoyOpen ? App.CAL_PRO_RJOYSTICK : App.CAL_PRO_LJOYSTICK; var prefs = AppPrefs.Instance.GetDevicePreferences(DeviceID); string filename = ""; prefs?.calibrationFiles.TryGetValue(joyTarget, out filename); Windows.JoyCalibrationWindow joyCal = new Windows.JoyCalibrationWindow( _rightJoyOpen ? Calibrations.None.ProControllerRaw.RJoy : Calibrations.None.ProControllerRaw.LJoy, _rightJoyOpen ? _lastState.RJoy : _lastState.LJoy, filename ?? ""); _openJoyWindow = joyCal; #if DEBUG // This will allow for the dummy device window to retain focus if (DeviceID.StartsWith("Dummy")) { joyCal.Closed += (obj, args) => { if (joyCal.Apply) { OnJoyCalibrated?.Invoke(joyCal.Calibration, joyTarget, joyCal.FileName); } _openJoyWindow = null; }; joyCal.Show(); return; } #endif joyCal.ShowDialog(); if (joyCal.Apply) { OnJoyCalibrated?.Invoke(joyCal.Calibration, joyTarget, joyCal.FileName); } _openJoyWindow = null; joyCal = null; } } } <|start_filename|>WiinUPro/Assignments/MouseScrollAssignment.cs<|end_filename|> using System; using InputManager; namespace WiinUPro { public class MouseScrollAssignment : IAssignment { /// <summary> /// The Scroll direction to be simulated /// </summary> public Mouse.ScrollDirection ScrollDirection { get; set; } /// <summary> /// Set to constantly scroll while Applying /// </summary> public bool Continuous { get; set; } public int ScrollRate { get { return _scrollRate; } set { _scrollRate = Math.Min(Math.Max(0, value), 1000); } } /// <summary> /// What the applied value must be greater than to apply /// </summary> public float Threshold { get { return _threashold; } set { _threashold = value; } } private int _scrollRate = 200; private float _threashold = 0.1f; private bool _lastState = false; private int _lastApplied = 0; public MouseScrollAssignment() { } public MouseScrollAssignment(Mouse.ScrollDirection dir) { ScrollDirection = dir; } public void Apply(float value) { bool isDown = value >= _threashold; if (Continuous) { if (!isDown) { return; } int now = DateTime.Now.Millisecond; if (_lastApplied > now) { _lastApplied = _lastApplied + ScrollRate - 1000; } if (now > _lastApplied + ScrollRate) { MouseDirector.Access.MouseScroll(ScrollDirection); _lastApplied = now; } } else if (isDown != _lastState) { if (isDown) { MouseDirector.Access.MouseScroll(ScrollDirection); } _lastState = isDown; } } public bool SameAs(IAssignment assignment) { var other = assignment as MouseScrollAssignment; if (other == null) { return false; } bool result = true; result &= ScrollDirection == other.ScrollDirection; result &= Continuous == other.Continuous; result &= ScrollRate == other.ScrollRate; result &= Threshold == other.Threshold; return result; } public override bool Equals(object obj) { var other = obj as MouseScrollAssignment; if (other == null) { return false; } else { return ScrollDirection == other.ScrollDirection; } } public override int GetHashCode() { int hash = (int)ScrollDirection + 51; return hash; } public override string ToString() { return ScrollDirection.ToString(); } public string GetDisplayName() { return $"Scroll.{ToString()}"; } } } <|start_filename|>Scp/ScpUser/ScpExtended.cpp<|end_filename|> #include "StdAfx.h" #include "SCPExtensions.h" #include "SCPExtended.h" <|start_filename|>Scp/XInput_Scp/XInput_Wrap.cpp<|end_filename|> #include "StdAfx.h" #define XINPUT_FUNCTIONS 11 static BOOL l_bInited = false; static HMODULE l_hXInputDll = NULL; static FARPROC l_hXInputFunc[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; typedef DWORD (WINAPI *XInputGetStateFunction)(__in DWORD dwUserIndex, __out XINPUT_STATE* pState); typedef DWORD (WINAPI *XInputSetStateFunction)(__in DWORD dwUserIndex, __in XINPUT_VIBRATION* pVibration); typedef DWORD (WINAPI *XInputGetCapabilitiesFunction)(__in DWORD dwUserIndex, __in DWORD dwFlags, __out XINPUT_CAPABILITIES* pCapabilities); typedef void (WINAPI *XInputEnableFunction)(__in BOOL enable); typedef DWORD (WINAPI *XInputGetDSoundAudioDeviceGuidsFunction)(__in DWORD dwUserIndex, __out GUID* pDSoundRenderGuid, __out GUID* pDSoundCaptureGuid); typedef DWORD (WINAPI *XInputGetBatteryInformationFunction)(__in DWORD dwUserIndex, __in BYTE devType, __out XINPUT_BATTERY_INFORMATION* pBatteryInformation); typedef DWORD (WINAPI *XInputGetKeystrokeFunction)(__in DWORD dwUserIndex, __reserved DWORD dwReserved, __out PXINPUT_KEYSTROKE pKeystroke); // UNDOCUMENTED typedef DWORD (WINAPI *XInputGetStateExFunction)(__in DWORD dwUserIndex, __out XINPUT_STATE* pState); typedef DWORD (WINAPI *InputWaitForGuideButtonFunction)(__in DWORD dwUserIndex, __in DWORD dwFlag, __out LPVOID pVoid); typedef DWORD (WINAPI *XInputCancelGuideButtonWaitFunction)(__in DWORD dwUserIndex); typedef DWORD (WINAPI *XInputPowerOffControllerFunction)(__in DWORD dwUserIndex); BOOL WINAPI WRAP_LoadXInput ( __in BOOL enable ) { if (enable && !l_bInited) { TCHAR libdir[MAX_PATH]; GetSystemDirectory(libdir, MAX_PATH); _stprintf_s(libdir, _T("%s\\XInput1_3.dll"), libdir); if ((l_hXInputDll = LoadLibrary(libdir)) != NULL) { l_hXInputFunc[ 0] = GetProcAddress(l_hXInputDll, "XInputGetState"); l_hXInputFunc[ 1] = GetProcAddress(l_hXInputDll, "XInputSetState"); l_hXInputFunc[ 2] = GetProcAddress(l_hXInputDll, "XInputGetCapabilities"); l_hXInputFunc[ 3] = GetProcAddress(l_hXInputDll, "XInputEnable"); l_hXInputFunc[ 4] = GetProcAddress(l_hXInputDll, "XInputGetDSoundAudioDeviceGuids"); l_hXInputFunc[ 5] = GetProcAddress(l_hXInputDll, "XInputGetBatteryInformation"); l_hXInputFunc[ 6] = GetProcAddress(l_hXInputDll, "XInputGetKeystroke"); l_hXInputFunc[ 7] = GetProcAddress(l_hXInputDll, (LPCSTR) 100); // XInputGetStateEx l_hXInputFunc[ 8] = GetProcAddress(l_hXInputDll, (LPCSTR) 101); // XInputWaitForGuideButton l_hXInputFunc[ 9] = GetProcAddress(l_hXInputDll, (LPCSTR) 102); // XInputCancelGuideButtonWait l_hXInputFunc[10] = GetProcAddress(l_hXInputDll, (LPCSTR) 103); // XInputPowerOffController l_bInited = true; } } else if (!enable && l_bInited) { for (int i = 0; i < XINPUT_FUNCTIONS; i++) l_hXInputFunc[i] = NULL; if (l_hXInputDll) { FreeLibrary(l_hXInputDll); l_hXInputDll = NULL; } l_bInited = false; } return true; } DWORD WINAPI WRAP_XInputGetState ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __out XINPUT_STATE* pState // Receives the current state ) { if (!l_bInited || !l_hXInputFunc[0]) return ERROR_DEVICE_NOT_CONNECTED; return ((XInputGetStateFunction)(l_hXInputFunc[0]))(dwUserIndex, pState); } DWORD WINAPI WRAP_XInputSetState ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __in XINPUT_VIBRATION* pVibration // The vibration information to send to the controller ) { if (!l_bInited || !l_hXInputFunc[1]) return ERROR_DEVICE_NOT_CONNECTED; return ((XInputSetStateFunction)(l_hXInputFunc[1]))(dwUserIndex, pVibration); } DWORD WINAPI WRAP_XInputGetCapabilities ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __in DWORD dwFlags, // Input flags that identify the device type __out XINPUT_CAPABILITIES* pCapabilities // Receives the capabilities ) { if (!l_bInited || !l_hXInputFunc[2]) return ERROR_DEVICE_NOT_CONNECTED; return ((XInputGetCapabilitiesFunction)(l_hXInputFunc[2]))(dwUserIndex, dwFlags, pCapabilities); } void WINAPI WRAP_XInputEnable ( __in BOOL enable // [in] Indicates whether xinput is enabled or disabled. ) { if (!l_bInited || !l_hXInputFunc[3]) return; return ((XInputEnableFunction)(l_hXInputFunc[3]))(enable); } DWORD WINAPI WRAP_XInputGetDSoundAudioDeviceGuids ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __out GUID* pDSoundRenderGuid, // DSound device ID for render __out GUID* pDSoundCaptureGuid // DSound device ID for capture ) { if (!l_bInited || !l_hXInputFunc[4]) return ERROR_DEVICE_NOT_CONNECTED; return ((XInputGetDSoundAudioDeviceGuidsFunction)(l_hXInputFunc[4]))(dwUserIndex, pDSoundRenderGuid, pDSoundCaptureGuid); } DWORD WINAPI WRAP_XInputGetBatteryInformation ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __in BYTE devType, // Which device on this user index __out XINPUT_BATTERY_INFORMATION* pBatteryInformation // Contains the level and types of batteries ) { if (!l_bInited || !l_hXInputFunc[5]) return ERROR_DEVICE_NOT_CONNECTED; return ((XInputGetBatteryInformationFunction)(l_hXInputFunc[5]))(dwUserIndex, devType, pBatteryInformation); } DWORD WINAPI WRAP_XInputGetKeystroke ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __reserved DWORD dwReserved, // Reserved for future use __out PXINPUT_KEYSTROKE pKeystroke // Pointer to an XINPUT_KEYSTROKE structure that receives an input event. ) { if (!l_bInited || !l_hXInputFunc[6]) return ERROR_DEVICE_NOT_CONNECTED; return ((XInputGetKeystrokeFunction)(l_hXInputFunc[6]))(dwUserIndex, dwReserved, pKeystroke); } // UNDOCUMENTED DWORD WINAPI WRAP_XInputGetStateEx ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __out XINPUT_STATE* pState // Receives the current state + the Guide/Home button ) { if (!l_bInited || !l_hXInputFunc[7]) return ERROR_DEVICE_NOT_CONNECTED; return ((XInputGetStateExFunction)(l_hXInputFunc[7]))(dwUserIndex, pState); } DWORD WINAPI WRAP_XInputWaitForGuideButton ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __in DWORD dwFlag, // ??? __out LPVOID pVoid // ??? ) { if (!l_bInited || !l_hXInputFunc[8]) return ERROR_DEVICE_NOT_CONNECTED; return ((InputWaitForGuideButtonFunction)(l_hXInputFunc[8]))(dwUserIndex, dwFlag, pVoid); } DWORD WINAPI WRAP_XInputCancelGuideButtonWait ( __in DWORD dwUserIndex // Index of the gamer associated with the device ) { if (!l_bInited || !l_hXInputFunc[9]) return ERROR_DEVICE_NOT_CONNECTED; return ((XInputCancelGuideButtonWaitFunction)(l_hXInputFunc[9]))(dwUserIndex); } DWORD WINAPI WRAP_XInputPowerOffController ( __in DWORD dwUserIndex // Index of the gamer associated with the device ) { if (!l_bInited || !l_hXInputFunc[10]) return ERROR_DEVICE_NOT_CONNECTED; return ((XInputPowerOffControllerFunction)(l_hXInputFunc[10]))(dwUserIndex); } <|start_filename|>Nintroller/Controllers/GameCubeAdapter.cs<|end_filename|> using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace NintrollerLib { public struct GameCubeAdapter : INintrollerState { public bool port1Connected; public bool port2Connected; public bool port3Connected; public bool port4Connected; public GameCubeController port1; public GameCubeController port2; public GameCubeController port3; public GameCubeController port4; public GameCubeAdapter(bool doPrefix) { this = new GameCubeAdapter(); if (doPrefix) { port1 = new GameCubeController(INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX); port2 = new GameCubeController(INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX); port3 = new GameCubeController(INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX); port4 = new GameCubeController(INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX); } } public bool CalibrationEmpty { get { return port1.CalibrationEmpty && port2.CalibrationEmpty && port3.CalibrationEmpty && port4.CalibrationEmpty; } } public void Update(byte[] data) { // 0x10 is a wired controller // 0x22 is a wave bird port1Connected = data[ 1] >= 0x10; port2Connected = data[10] >= 0x10; port3Connected = data[19] >= 0x10; port4Connected = data[28] >= 0x10; if (port1Connected) { byte[] p1 = new byte[9]; Array.Copy(data, 1, p1, 0, 9); port1.Update(p1); } if (port2Connected) { byte[] p2 = new byte[9]; Array.Copy(data, 10, p2, 0, 9); port2.Update(p2); } if (port3Connected) { byte[] p3 = new byte[9]; Array.Copy(data, 19, p3, 0, 9); port3.Update(p3); } if (port4Connected) { byte[] p4 = new byte[9]; Array.Copy(data, 28, p4, 0, 9); port4.Update(p4); } } public float GetValue(string input) { switch (input) { case INPUT_NAMES.GCN_ADAPTER.PORT_1_CONNECTED: return port1Connected ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_CONNECTED: return port2Connected ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_CONNECTED: return port3Connected ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_CONNECTED: return port4Connected ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.A: return port1.A ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.B: return port1.B ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.X: return port1.X ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.Y: return port1.Y ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.UP: return port1.Up ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.DOWN: return port1.Down ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LEFT: return port1.Left ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RIGHT: return port1.Right ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.L: return port1.L.value > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.R: return port1.R.value > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LT: return port1.L.value; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RT: return port1.R.value; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LFULL: return port1.L.full ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RFULL: return port1.R.full ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_X: return port1.joystick.X; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_Y: return port1.joystick.Y; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_X: return port1.cStick.X; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_Y: return port1.cStick.Y; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_UP: return port1.joystick.Y > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_DOWN: return port1.joystick.Y < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_LEFT: return port1.joystick.X < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_RIGHT: return port1.joystick.X > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_UP: return port1.cStick.Y > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_DOWN: return port1.cStick.Y < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_LEFT: return port1.cStick.X < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_RIGHT: return port1.cStick.X > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_1_PREFIX + INPUT_NAMES.GCN_CONTROLLER.START: return port1.Start ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.A: return port2.A ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.B: return port2.B ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.X: return port2.X ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.Y: return port2.Y ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.UP: return port2.Up ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.DOWN: return port2.Down ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LEFT: return port2.Left ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RIGHT: return port2.Right ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.L: return port2.L.value > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.R: return port2.R.value > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LT: return port2.L.value; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RT: return port2.R.value; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LFULL: return port2.L.full ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RFULL: return port2.R.full ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_X: return port2.joystick.X; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_Y: return port2.joystick.Y; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_X: return port2.cStick.X; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_Y: return port2.cStick.Y; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_UP: return port2.joystick.Y > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_DOWN: return port2.joystick.Y < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_LEFT: return port2.joystick.X < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_RIGHT: return port2.joystick.X > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_UP: return port2.cStick.Y > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_DOWN: return port2.cStick.Y < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_LEFT: return port2.cStick.X < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_RIGHT: return port2.cStick.X > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_2_PREFIX + INPUT_NAMES.GCN_CONTROLLER.START: return port2.Start ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.A: return port3.A ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.B: return port3.B ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.X: return port3.X ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.Y: return port3.Y ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.UP: return port3.Up ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.DOWN: return port3.Down ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LEFT: return port3.Left ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RIGHT: return port3.Right ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.L: return port3.L.value > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.R: return port3.R.value > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LT: return port3.L.value; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RT: return port3.R.value; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LFULL: return port3.L.full ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RFULL: return port3.R.full ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_X: return port3.joystick.X; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_Y: return port3.joystick.Y; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_X: return port3.cStick.X; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_Y: return port3.cStick.Y; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_UP: return port3.joystick.Y > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_DOWN: return port3.joystick.Y < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_LEFT: return port3.joystick.X < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_RIGHT: return port3.joystick.X > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_UP: return port3.cStick.Y > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_DOWN: return port3.cStick.Y < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_LEFT: return port3.cStick.X < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_RIGHT: return port3.cStick.X > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_3_PREFIX + INPUT_NAMES.GCN_CONTROLLER.START: return port3.Start ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.A: return port4.A ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.B: return port4.B ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.X: return port4.X ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.Y: return port4.Y ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.UP: return port4.Up ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.DOWN: return port4.Down ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LEFT: return port4.Left ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RIGHT: return port4.Right ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.L: return port4.L.value > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.R: return port4.R.value > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LT: return port4.L.value; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RT: return port4.R.value; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.LFULL: return port4.L.full ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.RFULL: return port4.R.full ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_X: return port4.joystick.X; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_Y: return port4.joystick.Y; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_X: return port4.cStick.X; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_Y: return port4.cStick.Y; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_UP: return port4.joystick.Y > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_DOWN: return port4.joystick.Y < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_LEFT: return port4.joystick.X < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.JOY_RIGHT: return port4.joystick.X > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_UP: return port4.cStick.Y > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_DOWN: return port4.cStick.Y < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_LEFT: return port4.cStick.X < 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.C_RIGHT: return port4.cStick.X > 0 ? 1 : 0; case INPUT_NAMES.GCN_ADAPTER.PORT_4_PREFIX + INPUT_NAMES.GCN_CONTROLLER.START: return port4.Start ? 1 : 0; } return 0; } public void SetCalibration(Calibrations.CalibrationPreset preset) { switch (preset) { case Calibrations.CalibrationPreset.Default: port1.SetCalibration(Calibrations.Defaults.GameCubeControllerDefault); port2.SetCalibration(Calibrations.Defaults.GameCubeControllerDefault); port3.SetCalibration(Calibrations.Defaults.GameCubeControllerDefault); port4.SetCalibration(Calibrations.Defaults.GameCubeControllerDefault); break; case Calibrations.CalibrationPreset.Modest: port1.SetCalibration(Calibrations.Moderate.GameCubeControllerModest); port2.SetCalibration(Calibrations.Moderate.GameCubeControllerModest); port3.SetCalibration(Calibrations.Moderate.GameCubeControllerModest); port4.SetCalibration(Calibrations.Moderate.GameCubeControllerModest); break; case Calibrations.CalibrationPreset.Extra: port1.SetCalibration(Calibrations.Extras.GameCubeControllerExtra); port2.SetCalibration(Calibrations.Extras.GameCubeControllerExtra); port3.SetCalibration(Calibrations.Extras.GameCubeControllerExtra); port4.SetCalibration(Calibrations.Extras.GameCubeControllerExtra); break; case Calibrations.CalibrationPreset.Minimum: port1.SetCalibration(Calibrations.Minimum.GameCubeControllerMinimal); port2.SetCalibration(Calibrations.Minimum.GameCubeControllerMinimal); port3.SetCalibration(Calibrations.Minimum.GameCubeControllerMinimal); port4.SetCalibration(Calibrations.Minimum.GameCubeControllerMinimal); break; case Calibrations.CalibrationPreset.None: port1.SetCalibration(Calibrations.None.GameCubeControllerRaw); port2.SetCalibration(Calibrations.None.GameCubeControllerRaw); port3.SetCalibration(Calibrations.None.GameCubeControllerRaw); port4.SetCalibration(Calibrations.None.GameCubeControllerRaw); break; } } public void SetCalibration(INintrollerState from) { if (from.CalibrationEmpty) { // don't apply empty calibrations return; } if (from.GetType() == typeof(GameCubeAdapter)) { port1.SetCalibration(((GameCubeAdapter)from).port1); port2.SetCalibration(((GameCubeAdapter)from).port2); port3.SetCalibration(((GameCubeAdapter)from).port3); port4.SetCalibration(((GameCubeAdapter)from).port4); } } public string GetCalibrationString() { StringBuilder sb = new StringBuilder(); sb.Append("-gcn"); sb.Append("+"); sb.Append(port1.GetCalibrationString()); sb.Append("+"); sb.Append(port2.GetCalibrationString()); sb.Append("+"); sb.Append(port3.GetCalibrationString()); sb.Append("+"); sb.Append(port4.GetCalibrationString()); return sb.ToString(); } public void SetCalibration(string calibrationString) { if (calibrationString.Count(c => c == '0') > 5) { // don't set empty calibrations return; } // Index 0 should be "gcn" string[] ports = calibrationString.Split(new char[] { '+' }); if (ports.Length > 1) { port1.SetCalibration(ports[1]); } if (ports.Length > 2) { port2.SetCalibration(ports[2]); } if (ports.Length > 3) { port3.SetCalibration(ports[3]); } if (ports.Length > 4) { port4.SetCalibration(ports[4]); } } public IEnumerator<KeyValuePair<string, float>> GetEnumerator() { yield return new KeyValuePair<string, float>(INPUT_NAMES.GCN_ADAPTER.PORT_1_CONNECTED, port1Connected ? 1 : 0); yield return new KeyValuePair<string, float>(INPUT_NAMES.GCN_ADAPTER.PORT_2_CONNECTED, port2Connected ? 1 : 0); yield return new KeyValuePair<string, float>(INPUT_NAMES.GCN_ADAPTER.PORT_3_CONNECTED, port3Connected ? 1 : 0); yield return new KeyValuePair<string, float>(INPUT_NAMES.GCN_ADAPTER.PORT_4_CONNECTED, port4Connected ? 1 : 0); foreach (var p1 in port1) yield return p1; foreach (var p2 in port2) yield return p2; foreach (var p3 in port3) yield return p3; foreach (var p4 in port4) yield return p4; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public struct GameCubeController : IEnumerable<KeyValuePair<string, float>> { public Joystick joystick, cStick; public Trigger L, R; public bool A, B, X, Y; public bool Up, Down, Left, Right; public bool Z, Start; private string _prefix; public GameCubeController(string prefix) { this = new GameCubeController(); _prefix = prefix; } public bool CalibrationEmpty { get { if (joystick.maxX == 0 && joystick.maxY == 0 && cStick.maxX == 0 && cStick.maxY == 0) { return true; } else { return false; } } } public void Update(byte[] data) { // Buttons A = (data[1] & 0x01) != 0; B = (data[1] & 0x02) != 0; X = (data[1] & 0x04) != 0; Y = (data[1] & 0x08) != 0; Z = (data[2] & 0x02) != 0; Start = (data[2] & 0x01) != 0; // D-Pad Up = (data[1] & 0x80) != 0; Down = (data[1] & 0x40) != 0; Left = (data[1] & 0x10) != 0; Right = (data[1] & 0x20) != 0; // Joysticks joystick.rawX = data[3]; joystick.rawY = data[4]; cStick.rawX = data[5]; cStick.rawY = data[6]; // Triggers L.rawValue = data[7]; R.rawValue = data[8]; L.full = (data[2] & 0x08) != 0; R.full = (data[2] & 0x04) != 0; // Normalize joystick.Normalize(); cStick.Normalize(); L.Normalize(); R.Normalize(); } public void SetCalibration(GameCubeController from) { if (from.CalibrationEmpty) { // don't apply empty calibrations return; } joystick.Calibrate(from.joystick); cStick.Calibrate(from.cStick); L.Calibrate(from.L); R.Calibrate(from.R); } public void SetCalibration(string calibrationString) { if (calibrationString.Count(c => c == '0') > 5) { // don't set empty calibrations return; } string[] components = calibrationString.Split(new char[] { '-' }); foreach (string component in components) { if (component.StartsWith("joy")) { string[] joyLConfig = component.Split(new char[] { '|' }); for (int j = 1; j < joyLConfig.Length; j++) { int value = 0; if (int.TryParse(joyLConfig[j], out value)) { switch (j) { case 1: joystick.centerX = value; break; case 2: joystick.minX = value; break; case 3: joystick.maxX = value; break; case 4: joystick.deadX = value; break; case 5: joystick.centerY = value; break; case 6: joystick.minY = value; break; case 7: joystick.maxY = value; break; case 8: joystick.deadY = value; break; default: break; } } } } else if (component.StartsWith("cStk")) { string[] joyRConfig = component.Split(new char[] { '|' }); for (int c = 1; c < joyRConfig.Length; c++) { int value = 0; if (int.TryParse(joyRConfig[c], out value)) { switch (c) { case 1: cStick.centerX = value; break; case 2: cStick.minX = value; break; case 3: cStick.maxX = value; break; case 4: cStick.deadX = value; break; case 5: cStick.centerY = value; break; case 6: cStick.minY = value; break; case 7: cStick.maxY = value; break; case 8: cStick.deadY = value; break; default: break; } } } } else if (component.StartsWith("tl")) { string[] triggerLConfig = component.Split(new char[] { '|' }); for (int tl = 1; tl < triggerLConfig.Length; tl++) { int value = 0; if (int.TryParse(triggerLConfig[tl], out value)) { switch (tl) { case 1: L.min = value; break; case 2: L.max = value; break; default: break; } } } } else if (component.StartsWith("tr")) { string[] triggerRConfig = component.Split(new char[] { '|' }); for (int tr = 1; tr < triggerRConfig.Length; tr++) { int value = 0; if (int.TryParse(triggerRConfig[tr], out value)) { switch (tr) { case 1: R.min = value; break; case 2: R.max = value; break; default: break; } } } } } } public string GetCalibrationString() { StringBuilder sb = new StringBuilder(); sb.Append(":joy"); sb.Append("|"); sb.Append(joystick.centerX); sb.Append("|"); sb.Append(joystick.minX); sb.Append("|"); sb.Append(joystick.maxX); sb.Append("|"); sb.Append(joystick.deadX); sb.Append("|"); sb.Append(joystick.centerY); sb.Append("|"); sb.Append(joystick.minY); sb.Append("|"); sb.Append(joystick.maxY); sb.Append("|"); sb.Append(joystick.deadY); sb.Append(":cStk"); sb.Append("|"); sb.Append(cStick.centerX); sb.Append("|"); sb.Append(cStick.minX); sb.Append("|"); sb.Append(cStick.maxX); sb.Append("|"); sb.Append(cStick.deadX); sb.Append("|"); sb.Append(cStick.centerY); sb.Append("|"); sb.Append(cStick.minY); sb.Append("|"); sb.Append(cStick.maxY); sb.Append("|"); sb.Append(cStick.deadY); sb.Append(":tl"); sb.Append("|"); sb.Append(L.min); sb.Append("|"); sb.Append(L.max); sb.Append(":tr"); sb.Append("|"); sb.Append(R.min); sb.Append("|"); sb.Append(R.max); return sb.ToString(); } public IEnumerator<KeyValuePair<string, float>> GetEnumerator() { string prefix = string.IsNullOrEmpty(_prefix) ? "" : _prefix; yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.A, A ? 1 : 0); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.B, B ? 1 : 0); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.X, X ? 1 : 0); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.Y, Y ? 1 : 0); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.Z, Z ? 1 : 0); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.START, Start ? 1 : 0); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.UP, Up ? 1 : 0); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.DOWN, Down ? 1 : 0); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.LEFT, Left ? 1 : 0); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.RIGHT, Right ? 1 : 0); L.Normalize(); R.Normalize(); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.L, L.value > 0 ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.R, R.value > 0 ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.LFULL, L.full ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.RFULL, R.full ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.LT, L.value); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.RT, R.value); joystick.Normalize(); cStick.Normalize(); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.JOY_X, joystick.X); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.JOY_Y, joystick.Y); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.C_X, cStick.X); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.C_Y, cStick.Y); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.JOY_UP, joystick.Y > 0f ? joystick.Y : 0.0f); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.JOY_DOWN, joystick.Y > 0f ? 0.0f : -joystick.Y); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.JOY_LEFT, joystick.X > 0f ? 0.0f : -joystick.X); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.JOY_RIGHT, joystick.X > 0f ? joystick.X : 0.0f); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.C_UP, cStick.Y > 0f ? cStick.Y : 0.0f); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.C_DOWN, cStick.Y > 0f ? 0.0f : -cStick.Y); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.C_LEFT, cStick.X > 0f ? 0.0f : -cStick.X); yield return new KeyValuePair<string, float>(prefix + INPUT_NAMES.GCN_CONTROLLER.C_RIGHT, cStick.X > 0f ? cStick.X : 0.0f); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <|start_filename|>Scp/XInput_Scp/XInput_SCP.cpp<|end_filename|> #include "stdafx.h" static CSCPController* l_Pad[XUSER_MAX_COUNT]; static BOOL l_bPassThrough = false, l_bStarted = false, l_bUnloaded = false; static DWORD l_nPads = 0, l_nAttached = 0, l_nBtPads = 0; BOOL LoadApi(BOOL bEnable) { if (bEnable) l_nAttached++; else l_nAttached--; if (bEnable && !l_bStarted && !l_bUnloaded) { load_lib_usb(); WRAP_LoadXInput(true); // Load Bluetooth DS3s CBTConnection* BtPad = new CBTConnection(); if (BtPad->Open()) { l_nBtPads = BtPad->CollectionSize; for(DWORD Index = 0; Index < BtPad->CollectionSize; Index++) { l_Pad[l_nPads++] = BtPad; } } else delete BtPad; CSCPController* Pad; // Load DS3s if (l_nBtPads == 0) // Only if not using BTH Server { for (DWORD Index = 0; Index < XUSER_MAX_COUNT * CDS3Controller::CollectionSize && l_nPads < XUSER_MAX_COUNT; Index++) { Pad = new CDS3Controller(Index); if (Pad->Open()) l_Pad[l_nPads++] = Pad; else { delete Pad; break; } } } // Load SL3s for (DWORD Index = 0; Index < XUSER_MAX_COUNT * CSL3Controller::CollectionSize && l_nPads < XUSER_MAX_COUNT; Index++) { Pad = new CSL3Controller(Index); if (Pad->Open()) l_Pad[l_nPads++] = Pad; else { delete Pad; break; } } // Load DS2s for (DWORD Index = 0; Index < XUSER_MAX_COUNT * CDS2Controller::CollectionSize && l_nPads < XUSER_MAX_COUNT; Index++) { Pad = new CDS2Controller(Index); if (Pad->Open()) l_Pad[l_nPads++] = Pad; else delete Pad; } // Load X360s if (l_nBtPads == 0) // Only if not using BTH Server { for (DWORD Index = 0; Index < XUSER_MAX_COUNT * CX360Controller::CollectionSize && l_nPads < XUSER_MAX_COUNT; Index++) { Pad = new CX360Controller(Index); if (Pad->Open()) l_Pad[l_nPads++] = Pad; else delete Pad; } } l_bStarted = true; if (l_nPads == 0) { // No Devices found, PassThrough only l_bPassThrough = true; } } else if (!bEnable && l_bStarted && !l_bUnloaded && l_nAttached == 0) { l_bStarted = false; l_bUnloaded = true; if (l_nBtPads > 0) { l_Pad[0]->Close(); delete l_Pad[0]; } for (DWORD Index = l_nBtPads; Index < l_nPads; Index++) { l_Pad[Index]->Close(); delete l_Pad[Index]; } return WRAP_LoadXInput(bEnable); } return true; } DWORD WINAPI XInputGetState ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __out XINPUT_STATE* pState // Receives the current state ) { if (l_bUnloaded) return ERROR_DEVICE_NOT_CONNECTED; if (!l_bStarted) LoadApi(true); if (!l_bPassThrough) { if (dwUserIndex < l_nPads) { return l_Pad[dwUserIndex]->GetState(dwUserIndex, pState); } else { return ERROR_DEVICE_NOT_CONNECTED; } } return WRAP_XInputGetState(dwUserIndex, pState); } DWORD WINAPI XInputSetState ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __in XINPUT_VIBRATION* pVibration // The vibration information to send to the controller ) { if (l_bUnloaded) return ERROR_DEVICE_NOT_CONNECTED; if (!l_bStarted) LoadApi(true); if (!l_bPassThrough) { if (dwUserIndex < l_nPads) { return l_Pad[dwUserIndex]->SetState(dwUserIndex, pVibration); } else { return ERROR_DEVICE_NOT_CONNECTED; } } return WRAP_XInputSetState(dwUserIndex, pVibration); } DWORD WINAPI XInputGetCapabilities ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __in DWORD dwFlags, // Input flags that identify the device type __out XINPUT_CAPABILITIES* pCapabilities // Receives the capabilities ) { if (l_bUnloaded) return ERROR_DEVICE_NOT_CONNECTED; if (!l_bStarted) LoadApi(true); if (!l_bPassThrough) { if (dwUserIndex < l_nPads) { return l_Pad[dwUserIndex]->GetCapabilities(dwUserIndex, dwFlags, pCapabilities); } else { return ERROR_DEVICE_NOT_CONNECTED; } } return WRAP_XInputGetCapabilities(dwUserIndex, dwFlags, pCapabilities); } void WINAPI XInputEnable ( __in BOOL enable // [in] Indicates whether xinput is enabled or disabled. ) { if (l_bUnloaded) return; if (!l_bStarted) LoadApi(true); if (!enable) { XINPUT_VIBRATION Vibration = { 0, 0 }; for (DWORD nPad = 0; nPad < l_nPads; nPad++) { XInputSetState(nPad, &Vibration); } } WRAP_XInputEnable(enable); } DWORD WINAPI XInputGetDSoundAudioDeviceGuids ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __out GUID* pDSoundRenderGuid, // DSound device ID for render __out GUID* pDSoundCaptureGuid // DSound device ID for capture ) { if (l_bUnloaded) return ERROR_DEVICE_NOT_CONNECTED; if (!l_bStarted) LoadApi(true); if (!l_bPassThrough) { if (dwUserIndex < l_nPads) { return l_Pad[dwUserIndex]->GetDSoundAudioDeviceGuids(dwUserIndex, pDSoundRenderGuid, pDSoundCaptureGuid); } else { return ERROR_DEVICE_NOT_CONNECTED; } } return WRAP_XInputGetDSoundAudioDeviceGuids(dwUserIndex, pDSoundRenderGuid, pDSoundCaptureGuid); } DWORD WINAPI XInputGetBatteryInformation ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __in BYTE devType, // Which device on this user index __out XINPUT_BATTERY_INFORMATION* pBatteryInformation // Contains the level and types of batteries ) { if (l_bUnloaded) return ERROR_DEVICE_NOT_CONNECTED; if (!l_bStarted) LoadApi(true); if (!l_bPassThrough) { if (dwUserIndex < l_nPads) { return l_Pad[dwUserIndex]->GetBatteryInformation(dwUserIndex, devType, pBatteryInformation); } else { return ERROR_DEVICE_NOT_CONNECTED; } } return WRAP_XInputGetBatteryInformation(dwUserIndex, devType, pBatteryInformation); } DWORD WINAPI XInputGetKeystroke ( __in DWORD dwUserIndex, // Index of the gamer associated with the device __reserved DWORD dwReserved, // Reserved for future use __out PXINPUT_KEYSTROKE pKeystroke // Pointer to an XINPUT_KEYSTROKE structure that receives an input event. ) { if (l_bUnloaded) return ERROR_DEVICE_NOT_CONNECTED; if (!l_bStarted) LoadApi(true); if (!l_bPassThrough) { if (dwUserIndex < l_nPads) { return l_Pad[dwUserIndex]->GetKeystroke(dwUserIndex, dwReserved, pKeystroke); } else { return ERROR_DEVICE_NOT_CONNECTED; } } return WRAP_XInputGetKeystroke(dwUserIndex, dwReserved, pKeystroke); } DWORD WINAPI XInputGetExtended(DWORD dwUserIndex, SCP_EXTN* pPressure) { if (l_bUnloaded) return ERROR_DEVICE_NOT_CONNECTED; if (!l_bStarted) LoadApi(true); if (!l_bPassThrough) { if (dwUserIndex < l_nPads) { return l_Pad[dwUserIndex]->GetExtended(dwUserIndex, pPressure); } else { return ERROR_DEVICE_NOT_CONNECTED; } } return ERROR_NOT_SUPPORTED; } // UNDOCUMENTED DWORD WINAPI XInputGetStateEx(DWORD dwUserIndex, XINPUT_STATE* pState) { if (l_bUnloaded) return ERROR_DEVICE_NOT_CONNECTED; if (!l_bStarted) LoadApi(true); if (!l_bPassThrough) { if (dwUserIndex < l_nPads) { return l_Pad[dwUserIndex]->GetStateEx(dwUserIndex, pState); } else { return ERROR_DEVICE_NOT_CONNECTED; } } return WRAP_XInputGetStateEx(dwUserIndex, pState); } DWORD WINAPI XInputWaitForGuideButton(DWORD dwUserIndex, DWORD dwFlag, LPVOID pVoid) { if (l_bUnloaded) return ERROR_DEVICE_NOT_CONNECTED; if (!l_bStarted) LoadApi(true); if (!l_bPassThrough) { if (dwUserIndex < l_nPads) { return l_Pad[dwUserIndex]->WaitForGuideButton(dwUserIndex, dwFlag, pVoid); } else { return ERROR_DEVICE_NOT_CONNECTED; } } return WRAP_XInputWaitForGuideButton(dwUserIndex, dwFlag, pVoid); } DWORD WINAPI XInputCancelGuideButtonWait(DWORD dwUserIndex) { if (l_bUnloaded) return ERROR_DEVICE_NOT_CONNECTED; if (!l_bStarted) LoadApi(true); if (!l_bPassThrough) { if (dwUserIndex < l_nPads) { return l_Pad[dwUserIndex]->CancelGuideButtonWait(dwUserIndex); } else { return ERROR_DEVICE_NOT_CONNECTED; } } return WRAP_XInputCancelGuideButtonWait(dwUserIndex); } DWORD WINAPI XInputPowerOffController(DWORD dwUserIndex) { if (l_bUnloaded) return ERROR_DEVICE_NOT_CONNECTED; if (!l_bStarted) LoadApi(true); if (!l_bPassThrough) { if (dwUserIndex < l_nPads) { return l_Pad[dwUserIndex]->PowerOffController(dwUserIndex); } else { return ERROR_DEVICE_NOT_CONNECTED; } } return WRAP_XInputPowerOffController(dwUserIndex); } <|start_filename|>WiinUPro/Controls/NumPicker.xaml.cs<|end_filename|> using System; using System.Windows; using System.Windows.Controls; namespace WiinUPro { /// <summary> /// Interaction logic for NumPicker.xaml /// </summary> public partial class NumPicker : UserControl { /// <summary> /// Sets the selected value. /// Must be between the current minimum and maximum. /// </summary> public int Value { get { return _value; } set { if (value < _min) { _value = _min; } else if (value > _max) { _value = _max; } else { _value = value; } lblValue.Text = _value.ToString(); OnValueUpdate?.Invoke(_value); } } /// <summary> /// Sets the Minimum possible value. /// Must be less than the current maximum. /// </summary> public int Min { get { return _min; } set { if (_min <= _max) { _min = value; if (_value < value) { _value = value; lblValue.Text = _value.ToString(); } } } } /// <summary> /// Sets the Maximum possible value. /// Must be greater than the current minimum. /// </summary> public int Max { get { return _max; } set { if (_max >= _min) { _max = value; if (_value > value) { _value = value; lblValue.Text = _value.ToString(); } } } } public event Action<int> OnValueUpdate; private int _value = 0; private int _min = 0; private int _max = 100; public NumPicker() { InitializeComponent(); } public NumPicker(int startValue, int minimum, int maximum) : this() { _min = minimum; _max = maximum; _value = startValue; lblValue.Text = _value.ToString(); } private void btnDown_Click(object sender, RoutedEventArgs e) { Value -= 1; } private void btnUp_Click(object sender, RoutedEventArgs e) { Value += 1; } private void lblValue_TextChanged(object sender, TextChangedEventArgs e) { int output = 0; if (int.TryParse(lblValue.Text, out output)) { Value = output; } else { lblValue.Text = _value.ToString(); } } } } <|start_filename|>Scp/ScpControl/UsbDevice.Designer.cs<|end_filename|> namespace ScpControl { partial class UsbDevice { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.HID_Worker = new System.ComponentModel.BackgroundWorker(); this.tmUpdate = new ScpControl.ScpTimer(this.components); // // HID_Worker // this.HID_Worker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.HID_Worker_Thread); // // tmUpdate // this.tmUpdate.Enabled = false; this.tmUpdate.Interval = ((uint)(10u)); this.tmUpdate.Tag = null; this.tmUpdate.Tick += new System.EventHandler(this.On_Timer); } #endregion protected System.ComponentModel.BackgroundWorker HID_Worker; private ScpTimer tmUpdate; } } <|start_filename|>Scp/ScpBus/bus/buspdo.c<|end_filename|> #include "busenum.h" #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE, Bus_PDO_PnP) #pragma alloc_text(PAGE, Bus_PDO_QueryDeviceCaps) #pragma alloc_text(PAGE, Bus_PDO_QueryDeviceId) #pragma alloc_text(PAGE, Bus_PDO_QueryDeviceText) #pragma alloc_text(PAGE, Bus_PDO_QueryResources) #pragma alloc_text(PAGE, Bus_PDO_QueryResourceRequirements) #pragma alloc_text(PAGE, Bus_PDO_QueryDeviceRelations) #pragma alloc_text(PAGE, Bus_PDO_QueryBusInformation) #pragma alloc_text(PAGE, Bus_GetDeviceCapabilities) #pragma alloc_text(PAGE, Bus_PDO_QueryInterface) #endif NTSTATUS Bus_PDO_PnP(__in PDEVICE_OBJECT DeviceObject, __in PIRP Irp, __in PIO_STACK_LOCATION IrpStack, __in PPDO_DEVICE_DATA DeviceData) { NTSTATUS status; PAGED_CODE(); switch (IrpStack->MinorFunction) { case IRP_MN_START_DEVICE: DeviceData->DevicePowerState = PowerDeviceD0; SET_NEW_PNP_STATE(DeviceData, Started); status = IoRegisterDeviceInterface(DeviceObject, (LPGUID) &GUID_DEVINTERFACE_USB_DEVICE, NULL, &DeviceData->InterfaceName); if (NT_SUCCESS(status)) { IoSetDeviceInterfaceState(&DeviceData->InterfaceName, TRUE); } status = STATUS_SUCCESS; break; case IRP_MN_STOP_DEVICE: SET_NEW_PNP_STATE(DeviceData, Stopped); status = STATUS_SUCCESS; break; case IRP_MN_QUERY_STOP_DEVICE: SET_NEW_PNP_STATE(DeviceData, StopPending); status = STATUS_SUCCESS; break; case IRP_MN_CANCEL_STOP_DEVICE: if (DeviceData->DevicePnPState == StopPending) { RESTORE_PREVIOUS_PNP_STATE(DeviceData); } status = STATUS_SUCCESS; break; case IRP_MN_QUERY_REMOVE_DEVICE: SET_NEW_PNP_STATE(DeviceData, RemovePending); status = STATUS_SUCCESS; break; case IRP_MN_CANCEL_REMOVE_DEVICE: if (DeviceData->DevicePnPState == RemovePending) { RESTORE_PREVIOUS_PNP_STATE(DeviceData); } status = STATUS_SUCCESS; break; case IRP_MN_SURPRISE_REMOVAL: SET_NEW_PNP_STATE(DeviceData, SurpriseRemovePending); IoSetDeviceInterfaceState(&DeviceData->InterfaceName, FALSE); if (DeviceData->ReportedMissing) { PFDO_DEVICE_DATA fdoData; SET_NEW_PNP_STATE(DeviceData, Deleted); if (DeviceData->ParentFdo) { fdoData = FDO_FROM_PDO(DeviceData); ExAcquireFastMutex(&fdoData->Mutex); { RemoveEntryList(&DeviceData->Link); } ExReleaseFastMutex(&fdoData->Mutex); } status = Bus_DestroyPdo(DeviceObject, DeviceData); break; } status = STATUS_SUCCESS; break; case IRP_MN_REMOVE_DEVICE: IoSetDeviceInterfaceState(&DeviceData->InterfaceName, FALSE); if (DeviceData->ReportedMissing) { PFDO_DEVICE_DATA fdoData; SET_NEW_PNP_STATE(DeviceData, Deleted); if (DeviceData->ParentFdo) { fdoData = FDO_FROM_PDO(DeviceData); ExAcquireFastMutex(&fdoData->Mutex); { RemoveEntryList(&DeviceData->Link); } ExReleaseFastMutex(&fdoData->Mutex); } status = Bus_DestroyPdo(DeviceObject, DeviceData); break; } if (DeviceData->Present) { SET_NEW_PNP_STATE(DeviceData, NotStarted); status = STATUS_SUCCESS; } else { ASSERT(DeviceData->Present); status = STATUS_SUCCESS; } break; case IRP_MN_QUERY_CAPABILITIES: status = Bus_PDO_QueryDeviceCaps(DeviceData, Irp); break; case IRP_MN_QUERY_ID: Bus_KdPrint(("\tQueryId Type: %s\n", DbgDeviceIDString(IrpStack->Parameters.QueryId.IdType))); status = Bus_PDO_QueryDeviceId(DeviceData, Irp); break; case IRP_MN_QUERY_DEVICE_RELATIONS: Bus_KdPrint(("\tQueryDeviceRelation Type: %s\n", DbgDeviceRelationString(IrpStack->Parameters.QueryDeviceRelations.Type))); status = Bus_PDO_QueryDeviceRelations(DeviceData, Irp); break; case IRP_MN_QUERY_DEVICE_TEXT: status = Bus_PDO_QueryDeviceText(DeviceData, Irp); break; case IRP_MN_QUERY_RESOURCES: status = Bus_PDO_QueryResources(DeviceData, Irp); break; case IRP_MN_QUERY_RESOURCE_REQUIREMENTS: status = Bus_PDO_QueryResourceRequirements(DeviceData, Irp); break; case IRP_MN_QUERY_BUS_INFORMATION: status = Bus_PDO_QueryBusInformation(DeviceData, Irp); break; case IRP_MN_DEVICE_USAGE_NOTIFICATION: status = STATUS_UNSUCCESSFUL; break; case IRP_MN_EJECT: DeviceData->Present = FALSE; status = STATUS_SUCCESS; break; case IRP_MN_QUERY_INTERFACE: status = Bus_PDO_QueryInterface(DeviceData, Irp); break; case IRP_MN_FILTER_RESOURCE_REQUIREMENTS: default: status = Irp->IoStatus.Status; break; } Irp->IoStatus.Status = status; IoCompleteRequest (Irp, IO_NO_INCREMENT); return status; } NTSTATUS Bus_PDO_QueryDeviceCaps(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp) { PIO_STACK_LOCATION stack; PDEVICE_CAPABILITIES deviceCapabilities; DEVICE_CAPABILITIES parentCapabilities; NTSTATUS status; PAGED_CODE(); stack = IoGetCurrentIrpStackLocation(Irp); deviceCapabilities = stack->Parameters.DeviceCapabilities.Capabilities; if (deviceCapabilities->Version != 1 || deviceCapabilities->Size < sizeof(DEVICE_CAPABILITIES)) { return STATUS_UNSUCCESSFUL; } status = Bus_GetDeviceCapabilities(FDO_FROM_PDO(DeviceData)->NextLowerDriver, &parentCapabilities); if (!NT_SUCCESS(status)) { Bus_KdPrint(("\tQueryDeviceCaps failed\n")); return status; } RtlCopyMemory(deviceCapabilities->DeviceState, parentCapabilities.DeviceState, (PowerSystemShutdown + 1) * sizeof(DEVICE_POWER_STATE)); deviceCapabilities->DeviceState[PowerSystemWorking] = PowerDeviceD0; if (deviceCapabilities->DeviceState[PowerSystemSleeping1] != PowerDeviceD0) deviceCapabilities->DeviceState[PowerSystemSleeping1] = PowerDeviceD1; if (deviceCapabilities->DeviceState[PowerSystemSleeping2] != PowerDeviceD0) deviceCapabilities->DeviceState[PowerSystemSleeping2] = PowerDeviceD3; if (deviceCapabilities->DeviceState[PowerSystemSleeping3] != PowerDeviceD0) deviceCapabilities->DeviceState[PowerSystemSleeping3] = PowerDeviceD3; deviceCapabilities->DeviceWake = PowerDeviceD1; deviceCapabilities->DeviceD1 = TRUE; // Yes we can deviceCapabilities->DeviceD2 = FALSE; deviceCapabilities->WakeFromD0 = FALSE; deviceCapabilities->WakeFromD1 = TRUE; //Yes we can deviceCapabilities->WakeFromD2 = FALSE; deviceCapabilities->WakeFromD3 = FALSE; deviceCapabilities->D1Latency = 0; deviceCapabilities->D2Latency = 0; deviceCapabilities->D3Latency = 0; deviceCapabilities->EjectSupported = FALSE; deviceCapabilities->HardwareDisabled = FALSE; deviceCapabilities->Removable = TRUE; deviceCapabilities->SurpriseRemovalOK = TRUE; deviceCapabilities->UniqueID = TRUE; deviceCapabilities->SilentInstall = FALSE; deviceCapabilities->Address = DeviceData->SerialNo; return STATUS_SUCCESS; } NTSTATUS Bus_PDO_QueryDeviceId(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp) { PIO_STACK_LOCATION stack; PWCHAR buffer; ULONG length; NTSTATUS status = STATUS_SUCCESS; ULONG_PTR result; PAGED_CODE(); stack = IoGetCurrentIrpStackLocation(Irp); switch (stack->Parameters.QueryId.IdType) { case BusQueryDeviceID: buffer = ExAllocatePoolWithTag(PagedPool, DEVICE_HARDWARE_ID_LENGTH, BUSENUM_POOL_TAG); if (!buffer) { status = STATUS_INSUFFICIENT_RESOURCES; break; } RtlCopyMemory(buffer, DEVICE_HARDWARE_ID, DEVICE_HARDWARE_ID_LENGTH); Irp->IoStatus.Information = (ULONG_PTR) buffer; break; case BusQueryInstanceID: length = 11 * sizeof(WCHAR); buffer = ExAllocatePoolWithTag(PagedPool, length, BUSENUM_POOL_TAG); if (!buffer) { status = STATUS_INSUFFICIENT_RESOURCES; break; } RtlStringCchPrintfW(buffer, length / sizeof(WCHAR), L"%07d", DeviceData->SerialNo); Irp->IoStatus.Information = (ULONG_PTR) buffer; Bus_KdPrint(("\tInstanceID : %ws\n", buffer)); break; case BusQueryHardwareIDs: buffer = DeviceData->HardwareIDs; while (*(buffer++)) while (*(buffer++)); status = RtlULongPtrSub((ULONG_PTR) buffer, (ULONG_PTR) DeviceData->HardwareIDs, &result); if (!NT_SUCCESS(status)) { break; } length = (ULONG) result; buffer = ExAllocatePoolWithTag(PagedPool, length, BUSENUM_POOL_TAG); if (!buffer) { status = STATUS_INSUFFICIENT_RESOURCES; break; } RtlCopyMemory(buffer, DeviceData->HardwareIDs, length); Irp->IoStatus.Information = (ULONG_PTR) buffer; break; case BusQueryCompatibleIDs: length = BUSENUM_COMPATIBLE_IDS_LENGTH; buffer = ExAllocatePoolWithTag(PagedPool, length, BUSENUM_POOL_TAG); if (!buffer) { status = STATUS_INSUFFICIENT_RESOURCES; break; } RtlCopyMemory(buffer, BUSENUM_COMPATIBLE_IDS, length); Irp->IoStatus.Information = (ULONG_PTR) buffer; break; default: status = Irp->IoStatus.Status; break; } return status; } NTSTATUS Bus_PDO_QueryDeviceText(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp) { PWCHAR buffer; USHORT length; PIO_STACK_LOCATION stack; NTSTATUS status; PAGED_CODE(); stack = IoGetCurrentIrpStackLocation(Irp); switch (stack->Parameters.QueryDeviceText.DeviceTextType) { case DeviceTextDescription: if (!Irp->IoStatus.Information) { length = (USHORT)(wcslen(PRODUCT) + 1) * sizeof(WCHAR); buffer = ExAllocatePoolWithTag(PagedPool, length, BUSENUM_POOL_TAG); if (buffer == NULL ) { status = STATUS_INSUFFICIENT_RESOURCES; break; } RtlStringCchPrintfW(buffer, length / sizeof(WCHAR), L"%ws", PRODUCT); Bus_KdPrint(("\tDeviceTextDescription : %ws\n", buffer)); Irp->IoStatus.Information = (ULONG_PTR) buffer; } status = STATUS_SUCCESS; break; case DeviceTextLocationInformation: if (!Irp->IoStatus.Information) { length = (USHORT)(wcslen(VENDORNAME) + 1 + wcslen(MODEL) + 1 + 10) * sizeof(WCHAR); buffer = ExAllocatePoolWithTag(PagedPool, length, BUSENUM_POOL_TAG); if (buffer == NULL ) { status = STATUS_INSUFFICIENT_RESOURCES; break; } RtlStringCchPrintfW(buffer, length / sizeof(WCHAR), L"%ws%ws%02d", VENDORNAME, MODEL, DeviceData->SerialNo); Bus_KdPrint(("\tDeviceTextLocationInformation : %ws\n", buffer)); Irp->IoStatus.Information = (ULONG_PTR) buffer; } status = STATUS_SUCCESS; break; default: status = Irp->IoStatus.Status; break; } return status; } NTSTATUS Bus_PDO_QueryResources(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp) { UNREFERENCED_PARAMETER(DeviceData); PAGED_CODE(); return Irp->IoStatus.Status; } NTSTATUS Bus_PDO_QueryResourceRequirements(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp) { NTSTATUS status; UNREFERENCED_PARAMETER(DeviceData); UNREFERENCED_PARAMETER(Irp); PAGED_CODE(); status = STATUS_SUCCESS; return status; } NTSTATUS Bus_PDO_QueryDeviceRelations(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp) { PIO_STACK_LOCATION stack; PDEVICE_RELATIONS deviceRelations; NTSTATUS status; PAGED_CODE(); stack = IoGetCurrentIrpStackLocation(Irp); switch (stack->Parameters.QueryDeviceRelations.Type) { case TargetDeviceRelation: deviceRelations = (PDEVICE_RELATIONS) Irp->IoStatus.Information; if (deviceRelations) { ASSERTMSG("Someone above is handling TagerDeviceRelation", !deviceRelations); } deviceRelations = (PDEVICE_RELATIONS) ExAllocatePoolWithTag(PagedPool, sizeof(DEVICE_RELATIONS), BUSENUM_POOL_TAG); if (!deviceRelations) { status = STATUS_INSUFFICIENT_RESOURCES; break; } deviceRelations->Count = 1; deviceRelations->Objects[0] = DeviceData->Self; ObReferenceObject(DeviceData->Self); status = STATUS_SUCCESS; Irp->IoStatus.Information = (ULONG_PTR) deviceRelations; break; case BusRelations: // Not handled by PDO case EjectionRelations: // optional for PDO case RemovalRelations: // optional for PDO default: status = Irp->IoStatus.Status; break; } return status; } NTSTATUS Bus_PDO_QueryBusInformation(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp) { PPNP_BUS_INFORMATION busInfo; UNREFERENCED_PARAMETER(DeviceData); PAGED_CODE(); busInfo = ExAllocatePoolWithTag(PagedPool, sizeof(PNP_BUS_INFORMATION), BUSENUM_POOL_TAG); if (busInfo == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } busInfo->BusTypeGuid = GUID_BUS_TYPE_USB; busInfo->LegacyBusType = PNPBus; busInfo->BusNumber = 0; Irp->IoStatus.Information = (ULONG_PTR) busInfo; return STATUS_SUCCESS; } NTSTATUS Bus_GetDeviceCapabilities(__in PDEVICE_OBJECT DeviceObject, __out PDEVICE_CAPABILITIES DeviceCapabilities) { IO_STATUS_BLOCK ioStatus; KEVENT pnpEvent; NTSTATUS status; PDEVICE_OBJECT targetObject; PIO_STACK_LOCATION irpStack; PIRP pnpIrp; PAGED_CODE(); RtlZeroMemory(DeviceCapabilities, sizeof(DEVICE_CAPABILITIES)); DeviceCapabilities->Size = sizeof(DEVICE_CAPABILITIES); DeviceCapabilities->Version = 1; DeviceCapabilities->Address = ULONG_MAX; DeviceCapabilities->UINumber = ULONG_MAX; KeInitializeEvent(&pnpEvent, NotificationEvent, FALSE); targetObject = IoGetAttachedDeviceReference(DeviceObject); pnpIrp = IoBuildSynchronousFsdRequest(IRP_MJ_PNP, targetObject, NULL, 0, NULL, &pnpEvent, &ioStatus); if (pnpIrp == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; ObDereferenceObject(targetObject); return status; } pnpIrp->IoStatus.Status = STATUS_NOT_SUPPORTED; irpStack = IoGetNextIrpStackLocation(pnpIrp); RtlZeroMemory(irpStack, sizeof(IO_STACK_LOCATION)); irpStack->MajorFunction = IRP_MJ_PNP; irpStack->MinorFunction = IRP_MN_QUERY_CAPABILITIES; irpStack->Parameters.DeviceCapabilities.Capabilities = DeviceCapabilities; status = IoCallDriver(targetObject, pnpIrp); if (status == STATUS_PENDING) { KeWaitForSingleObject(&pnpEvent, Executive, KernelMode, FALSE, NULL); status = ioStatus.Status; } ObDereferenceObject(targetObject); return status; } VOID Bus_InterfaceReference(__in PVOID Context) { InterlockedIncrement((LONG *) &((PPDO_DEVICE_DATA) Context)->InterfaceRefCount); } VOID Bus_InterfaceDereference(__in PVOID Context) { InterlockedDecrement((LONG *) &((PPDO_DEVICE_DATA) Context)->InterfaceRefCount); } BOOLEAN USB_BUSIFFN Bus_IsDeviceHighSpeed(IN PVOID BusContext) { UNREFERENCED_PARAMETER(BusContext); Bus_KdPrint(("Bus_IsDeviceHighSpeed : TRUE\n")); return TRUE; } NTSTATUS USB_BUSIFFN Bus_QueryBusInformation(IN PVOID BusContext, IN ULONG Level, IN OUT PVOID BusInformationBuffer, IN OUT PULONG BusInformationBufferLength, OUT PULONG BusInformationActualLength) { UNREFERENCED_PARAMETER(BusContext); UNREFERENCED_PARAMETER(Level); UNREFERENCED_PARAMETER(BusInformationBuffer); UNREFERENCED_PARAMETER(BusInformationBufferLength); UNREFERENCED_PARAMETER(BusInformationActualLength); Bus_KdPrint(("Bus_QueryBusInformation : STATUS_UNSUCCESSFUL\n")); return STATUS_UNSUCCESSFUL; } NTSTATUS USB_BUSIFFN Bus_SubmitIsoOutUrb(IN PVOID BusContext, IN PURB Urb) { UNREFERENCED_PARAMETER(BusContext); UNREFERENCED_PARAMETER(Urb); Bus_KdPrint(("Bus_SubmitIsoOutUrb : STATUS_UNSUCCESSFUL\n")); return STATUS_UNSUCCESSFUL; } NTSTATUS USB_BUSIFFN Bus_QueryBusTime(IN PVOID BusContext, IN OUT PULONG CurrentUsbFrame) { UNREFERENCED_PARAMETER(BusContext); UNREFERENCED_PARAMETER(CurrentUsbFrame); Bus_KdPrint(("Bus_QueryBusTime : STATUS_UNSUCCESSFUL\n")); return STATUS_UNSUCCESSFUL; } VOID USB_BUSIFFN Bus_GetUSBDIVersion(IN PVOID BusContext, IN OUT PUSBD_VERSION_INFORMATION VersionInformation, IN OUT PULONG HcdCapabilities) { UNREFERENCED_PARAMETER(BusContext); Bus_KdPrint(("GetUSBDIVersion : 0x500, 0x200\n")); if (VersionInformation != NULL) { VersionInformation->USBDI_Version = 0x500; /* Usbport */ VersionInformation->Supported_USB_Version = 0x200; /* USB 2.0 */ } if (HcdCapabilities != NULL) { *HcdCapabilities = 0; } } NTSTATUS Bus_PDO_QueryInterface(__in PPDO_DEVICE_DATA DeviceData, __in PIRP Irp) { PIO_STACK_LOCATION irpStack; GUID * interfaceType; NTSTATUS status = STATUS_SUCCESS; PAGED_CODE(); irpStack = IoGetCurrentIrpStackLocation(Irp); interfaceType = (GUID *) irpStack->Parameters.QueryInterface.InterfaceType; if (IsEqualGUID(interfaceType, (PVOID) &USB_BUS_INTERFACE_USBDI_GUID)) { PUSB_BUS_INTERFACE_USBDI_V1 pInterface; Bus_KdPrint(("USB_BUS_INTERFACE_USBDI_GUID : Version %d Requested\n", (int) irpStack->Parameters.QueryInterface.Version)); if ((irpStack->Parameters.QueryInterface.Version != USB_BUSIF_USBDI_VERSION_0 && irpStack->Parameters.QueryInterface.Version != USB_BUSIF_USBDI_VERSION_1) || (irpStack->Parameters.QueryInterface.Version == USB_BUSIF_USBDI_VERSION_0 && irpStack->Parameters.QueryInterface.Size < sizeof(USB_BUS_INTERFACE_USBDI_V0)) || (irpStack->Parameters.QueryInterface.Version == USB_BUSIF_USBDI_VERSION_1 && irpStack->Parameters.QueryInterface.Size < sizeof(USB_BUS_INTERFACE_USBDI_V1))) { return STATUS_INVALID_PARAMETER; } pInterface = (PUSB_BUS_INTERFACE_USBDI_V1) irpStack->Parameters.QueryInterface.Interface; pInterface->BusContext = DeviceData; pInterface->InterfaceReference = (PINTERFACE_REFERENCE) Bus_InterfaceReference; pInterface->InterfaceDereference = (PINTERFACE_DEREFERENCE) Bus_InterfaceDereference; switch (irpStack->Parameters.QueryInterface.Version) { case USB_BUSIF_USBDI_VERSION_1: pInterface->IsDeviceHighSpeed = Bus_IsDeviceHighSpeed; case USB_BUSIF_USBDI_VERSION_0: pInterface->QueryBusInformation = Bus_QueryBusInformation; pInterface->SubmitIsoOutUrb = Bus_SubmitIsoOutUrb; pInterface->QueryBusTime = Bus_QueryBusTime; pInterface->GetUSBDIVersion = Bus_GetUSBDIVersion; break; } Bus_InterfaceReference(DeviceData); } else { Bus_KdPrint(("Query unknown interface GUID: %08X-%04X-%04X-%02X%02X%02X%02X%02X%02X%02X%02X - Version %d\n", (int) interfaceType->Data1, (int) interfaceType->Data2, (int) interfaceType->Data3, (int) interfaceType->Data4[0], (int) interfaceType->Data4[1], (int) interfaceType->Data4[2], (int) interfaceType->Data4[3], (int) interfaceType->Data4[4], (int) interfaceType->Data4[5], (int) interfaceType->Data4[6], (int) interfaceType->Data4[7], (int) irpStack->Parameters.QueryInterface.Version )); status = Irp->IoStatus.Status; } return status; } <|start_filename|>Scp/ScpControl/ScpDevice.cs<|end_filename|> using System; using System.ComponentModel; using System.Runtime.InteropServices; namespace ScpControl { public partial class ScpDevice : Component { public virtual Boolean IsActive { get { return m_IsActive; } } public virtual String Path { get { return m_Path; } } public ScpDevice() { InitializeComponent(); } public ScpDevice(IContainer container) { container.Add(this); InitializeComponent(); } public ScpDevice(String Class) { InitializeComponent(); this.m_Class = new Guid(Class); } public virtual Boolean Open(Int32 Instance = 0) { String DevicePath = String.Empty; if (Find(m_Class, ref DevicePath, Instance)) { Open(DevicePath); } return m_IsActive; } public virtual Boolean Open(String DevicePath) { m_Path = DevicePath.ToUpper(); if (GetDeviceHandle(m_Path)) { if (WinUsb_Initialize(m_FileHandle, ref m_WinUsbHandle)) { if (InitializeDevice()) { m_IsActive = true; } else { WinUsb_Free(m_WinUsbHandle); m_WinUsbHandle = (IntPtr) INVALID_HANDLE_VALUE; } } else { CloseHandle(m_FileHandle); } } return m_IsActive; } public virtual Boolean Start() { return m_IsActive; } public virtual Boolean Stop() { m_IsActive = false; if (!(m_WinUsbHandle == (IntPtr) INVALID_HANDLE_VALUE)) { WinUsb_AbortPipe(m_WinUsbHandle, m_IntIn); WinUsb_AbortPipe(m_WinUsbHandle, m_BulkIn); WinUsb_AbortPipe(m_WinUsbHandle, m_BulkOut); WinUsb_Free(m_WinUsbHandle); m_WinUsbHandle = (IntPtr) INVALID_HANDLE_VALUE; } if (m_FileHandle != IntPtr.Zero) { CloseHandle(m_FileHandle); m_FileHandle = IntPtr.Zero; } return true; } public virtual Boolean Close() { return Stop(); } public virtual Boolean ReadIntPipe (Byte[] Buffer, Int32 Length, ref Int32 Transfered) { if (!m_IsActive) return false; return WinUsb_ReadPipe(m_WinUsbHandle, m_IntIn, Buffer, Length, ref Transfered, IntPtr.Zero); } public virtual Boolean ReadBulkPipe (Byte[] Buffer, Int32 Length, ref Int32 Transfered) { if (!m_IsActive) return false; return WinUsb_ReadPipe(m_WinUsbHandle, m_BulkIn, Buffer, Length, ref Transfered, IntPtr.Zero); } public virtual Boolean WriteIntPipe (Byte[] Buffer, Int32 Length, ref Int32 Transfered) { if (!m_IsActive) return false; return WinUsb_WritePipe(m_WinUsbHandle, m_IntOut, Buffer, Length, ref Transfered, IntPtr.Zero); } public virtual Boolean WriteBulkPipe(Byte[] Buffer, Int32 Length, ref Int32 Transfered) { if (!m_IsActive) return false; return WinUsb_WritePipe(m_WinUsbHandle, m_BulkOut, Buffer, Length, ref Transfered, IntPtr.Zero); } public virtual Boolean SendTransfer(Byte RequestType, Byte Request, UInt16 Value, Byte[] Buffer, ref Int32 Transfered) { if (!m_IsActive) return false; WINUSB_SETUP_PACKET Setup = new WINUSB_SETUP_PACKET(); Setup.RequestType = RequestType; Setup.Request = Request; Setup.Value = Value; Setup.Index = 0; Setup.Length = (UInt16) Buffer.Length; return WinUsb_ControlTransfer(m_WinUsbHandle, Setup, Buffer, Buffer.Length, ref Transfered, IntPtr.Zero); } #region Constant and Structure Definitions public const Int32 SERVICE_CONTROL_STOP = 0x00000001; public const Int32 SERVICE_CONTROL_SHUTDOWN = 0x00000005; public const Int32 SERVICE_CONTROL_DEVICEEVENT = 0x0000000B; public const Int32 SERVICE_CONTROL_POWEREVENT = 0x0000000D; public const Int32 DBT_DEVICEARRIVAL = 0x8000; public const Int32 DBT_DEVICEQUERYREMOVE = 0x8001; public const Int32 DBT_DEVICEREMOVECOMPLETE = 0x8004; public const Int32 DBT_DEVTYP_DEVICEINTERFACE = 0x0005; public const Int32 DBT_DEVTYP_HANDLE = 0x0006; public const Int32 PBT_APMRESUMEAUTOMATIC = 0x0012; public const Int32 PBT_APMSUSPEND = 0x0004; public const Int32 DEVICE_NOTIFY_WINDOW_HANDLE = 0x0000; public const Int32 DEVICE_NOTIFY_SERVICE_HANDLE = 0x0001; public const Int32 DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 0x0004; public const Int32 WM_DEVICECHANGE = 0x0219; public const Int32 DIGCF_PRESENT = 0x0002; public const Int32 DIGCF_DEVICEINTERFACE = 0x0010; public delegate Int32 ServiceControlHandlerEx(Int32 Control, Int32 Type, IntPtr Data, IntPtr Context); [StructLayout(LayoutKind.Sequential)] public class DEV_BROADCAST_DEVICEINTERFACE { internal Int32 dbcc_size; internal Int32 dbcc_devicetype; internal Int32 dbcc_reserved; internal Guid dbcc_classguid; internal Int16 dbcc_name; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class DEV_BROADCAST_DEVICEINTERFACE_M { public Int32 dbcc_size; public Int32 dbcc_devicetype; public Int32 dbcc_reserved; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.U1, SizeConst = 16)] public Byte[] dbcc_classguid; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)] public Char[] dbcc_name; } [StructLayout(LayoutKind.Sequential)] public class DEV_BROADCAST_HDR { public Int32 dbch_size; public Int32 dbch_devicetype; public Int32 dbch_reserved; } [StructLayout(LayoutKind.Sequential)] protected struct SP_DEVICE_INTERFACE_DATA { internal Int32 cbSize; internal Guid InterfaceClassGuid; internal Int32 Flags; internal IntPtr Reserved; } protected const UInt32 FILE_ATTRIBUTE_NORMAL = 0x80; protected const UInt32 FILE_FLAG_OVERLAPPED = 0x40000000; protected const UInt32 FILE_SHARE_READ = 1; protected const UInt32 FILE_SHARE_WRITE = 2; protected const UInt32 GENERIC_READ = 0x80000000; protected const UInt32 GENERIC_WRITE = 0x40000000; protected const Int32 INVALID_HANDLE_VALUE = -1; protected const UInt32 OPEN_EXISTING = 3; protected const UInt32 DEVICE_SPEED = 1; protected const Byte USB_ENDPOINT_DIRECTION_MASK = 0x80; protected enum POLICY_TYPE { SHORT_PACKET_TERMINATE = 1, AUTO_CLEAR_STALL = 2, PIPE_TRANSFER_TIMEOUT = 3, IGNORE_SHORT_PACKETS = 4, ALLOW_PARTIAL_READS = 5, AUTO_FLUSH = 6, RAW_IO = 7, } protected enum USBD_PIPE_TYPE { UsbdPipeTypeControl = 0, UsbdPipeTypeIsochronous = 1, UsbdPipeTypeBulk = 2, UsbdPipeTypeInterrupt = 3, } protected enum USB_DEVICE_SPEED { UsbLowSpeed = 1, UsbFullSpeed = 2, UsbHighSpeed = 3, } [StructLayout(LayoutKind.Sequential)] protected struct USB_CONFIGURATION_DESCRIPTOR { internal Byte bLength; internal Byte bDescriptorType; internal UInt16 wTotalLength; internal Byte bNumInterfaces; internal Byte bConfigurationValue; internal Byte iConfiguration; internal Byte bmAttributes; internal Byte MaxPower; } [StructLayout(LayoutKind.Sequential)] protected struct USB_INTERFACE_DESCRIPTOR { internal Byte bLength; internal Byte bDescriptorType; internal Byte bInterfaceNumber; internal Byte bAlternateSetting; internal Byte bNumEndpoints; internal Byte bInterfaceClass; internal Byte bInterfaceSubClass; internal Byte bInterfaceProtocol; internal Byte iInterface; } [StructLayout(LayoutKind.Sequential)] protected struct WINUSB_PIPE_INFORMATION { internal USBD_PIPE_TYPE PipeType; internal Byte PipeId; internal UInt16 MaximumPacketSize; internal Byte Interval; } [StructLayout(LayoutKind.Sequential, Pack = 1)] protected struct WINUSB_SETUP_PACKET { internal Byte RequestType; internal Byte Request; internal UInt16 Value; internal UInt16 Index; internal UInt16 Length; } protected const Int32 DIF_PROPERTYCHANGE = 0x12; protected const Int32 DICS_ENABLE = 1; protected const Int32 DICS_DISABLE = 2; protected const Int32 DICS_PROPCHANGE = 3; protected const Int32 DICS_FLAG_GLOBAL = 1; [StructLayout(LayoutKind.Sequential)] protected struct SP_CLASSINSTALL_HEADER { internal Int32 cbSize; internal Int32 InstallFunction; } [StructLayout(LayoutKind.Sequential)] protected struct SP_PROPCHANGE_PARAMS { internal SP_CLASSINSTALL_HEADER ClassInstallHeader; internal Int32 StateChange; internal Int32 Scope; internal Int32 HwProfile; } #endregion #region Protected Data Members protected Guid m_Class = Guid.Empty; protected String m_Path = String.Empty; protected IntPtr m_FileHandle = IntPtr.Zero; private IntPtr m_WinUsbHandle = (IntPtr) INVALID_HANDLE_VALUE; protected Byte m_IntIn = 0xFF; protected Byte m_IntOut = 0xFF; protected Byte m_BulkIn = 0xFF; protected Byte m_BulkOut = 0xFF; protected Boolean m_IsActive = false; #endregion #region Static Helper Methods public enum Notified { Ignore = 0x0000, Arrival = 0x8000, QueryRemove = 0x8001, Removal = 0x8004 }; public static Boolean RegisterNotify(IntPtr Form, Guid Class, ref IntPtr Handle, Boolean Window = true) { IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; try { DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); Int32 Size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = Size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; devBroadcastDeviceInterface.dbcc_classguid = Class; devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(Size); Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); Handle = RegisterDeviceNotification(Form, devBroadcastDeviceInterfaceBuffer, Window ? DEVICE_NOTIFY_WINDOW_HANDLE : DEVICE_NOTIFY_SERVICE_HANDLE); Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); return Handle != IntPtr.Zero; } catch (Exception ex) { Console.WriteLine("{0} {1}", ex.HelpLink, ex.Message); throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } } public static Boolean UnregisterNotify(IntPtr Handle) { try { return UnregisterDeviceNotification(Handle); } catch (Exception ex) { Console.WriteLine("{0} {1}", ex.HelpLink, ex.Message); throw; } } #endregion #region Protected Methods protected virtual Boolean Find(Guid Target, ref String Path, Int32 Instance = 0) { IntPtr detailDataBuffer = IntPtr.Zero; IntPtr deviceInfoSet = IntPtr.Zero; try { SP_DEVICE_INTERFACE_DATA DeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA(), da = new SP_DEVICE_INTERFACE_DATA(); Int32 bufferSize = 0, memberIndex = 0; deviceInfoSet = SetupDiGetClassDevs(ref Target, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); DeviceInterfaceData.cbSize = da.cbSize = Marshal.SizeOf(DeviceInterfaceData); while (SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref Target, memberIndex, ref DeviceInterfaceData)) { SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref DeviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, ref da); { detailDataBuffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); if (SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref DeviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, ref da)) { IntPtr pDevicePathName = detailDataBuffer + 4; Path = Marshal.PtrToStringAuto(pDevicePathName).ToUpper(); Marshal.FreeHGlobal(detailDataBuffer); if (memberIndex == Instance) return true; } else Marshal.FreeHGlobal(detailDataBuffer); } memberIndex++; } } catch (Exception ex) { Console.WriteLine("{0} {1}", ex.HelpLink, ex.Message); throw; } finally { if (deviceInfoSet != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceInfoSet); } } return false; } protected virtual Boolean GetDeviceInstance(ref String Instance) { IntPtr detailDataBuffer = IntPtr.Zero; IntPtr deviceInfoSet = IntPtr.Zero; try { SP_DEVICE_INTERFACE_DATA DeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA(), da = new SP_DEVICE_INTERFACE_DATA(); Int32 bufferSize = 0, memberIndex = 0; deviceInfoSet = SetupDiGetClassDevs(ref m_Class, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); DeviceInterfaceData.cbSize = da.cbSize = Marshal.SizeOf(DeviceInterfaceData); while (SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref m_Class, memberIndex, ref DeviceInterfaceData)) { SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref DeviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, ref da); { detailDataBuffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); if (SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref DeviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, ref da)) { IntPtr pDevicePathName = detailDataBuffer + 4; String Current = Marshal.PtrToStringAuto(pDevicePathName).ToUpper(); Marshal.FreeHGlobal(detailDataBuffer); if (Current == Path) { Int32 nBytes = 256; IntPtr ptrInstanceBuf = Marshal.AllocHGlobal(nBytes); CM_Get_Device_ID(da.Flags, ptrInstanceBuf, nBytes, 0); Instance = Marshal.PtrToStringAuto(ptrInstanceBuf).ToUpper(); Marshal.FreeHGlobal(ptrInstanceBuf); return true; } } else Marshal.FreeHGlobal(detailDataBuffer); } memberIndex++; } } catch (Exception ex) { Console.WriteLine("{0} {1}", ex.HelpLink, ex.Message); throw; } finally { if (deviceInfoSet != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceInfoSet); } } return false; } protected virtual Boolean GetDeviceHandle(String Path) { Int32 LastError; m_FileHandle = CreateFile(Path, (GENERIC_WRITE | GENERIC_READ), FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0); if (m_FileHandle == IntPtr.Zero || m_FileHandle == (IntPtr) INVALID_HANDLE_VALUE) { m_FileHandle = IntPtr.Zero; LastError = GetLastError(); } return !(m_FileHandle == IntPtr.Zero); } protected virtual Boolean UsbEndpointDirectionIn(Int32 addr) { return (addr & 0x80) == 0x80; } protected virtual Boolean UsbEndpointDirectionOut(Int32 addr) { return (addr & 0x80) == 0x00; } protected virtual Boolean InitializeDevice() { try { USB_INTERFACE_DESCRIPTOR ifaceDescriptor = new USB_INTERFACE_DESCRIPTOR(); WINUSB_PIPE_INFORMATION pipeInfo = new WINUSB_PIPE_INFORMATION(); if (WinUsb_QueryInterfaceSettings(m_WinUsbHandle, 0, ref ifaceDescriptor)) { for (Int32 i = 0; i < ifaceDescriptor.bNumEndpoints; i++) { WinUsb_QueryPipe(m_WinUsbHandle, 0, System.Convert.ToByte(i), ref pipeInfo); if (((pipeInfo.PipeType == USBD_PIPE_TYPE.UsbdPipeTypeBulk) & UsbEndpointDirectionIn(pipeInfo.PipeId))) { m_BulkIn = pipeInfo.PipeId; WinUsb_FlushPipe(m_WinUsbHandle, m_BulkIn); } else if (((pipeInfo.PipeType == USBD_PIPE_TYPE.UsbdPipeTypeBulk) & UsbEndpointDirectionOut(pipeInfo.PipeId))) { m_BulkOut = pipeInfo.PipeId; WinUsb_FlushPipe(m_WinUsbHandle, m_BulkOut); } else if ((pipeInfo.PipeType == USBD_PIPE_TYPE.UsbdPipeTypeInterrupt) & UsbEndpointDirectionIn(pipeInfo.PipeId)) { m_IntIn = pipeInfo.PipeId; WinUsb_FlushPipe(m_WinUsbHandle, m_IntIn); } else if ((pipeInfo.PipeType == USBD_PIPE_TYPE.UsbdPipeTypeInterrupt) & UsbEndpointDirectionOut(pipeInfo.PipeId)) { m_IntOut = pipeInfo.PipeId; WinUsb_FlushPipe(m_WinUsbHandle, m_IntOut); } } return true; } return false; } catch (Exception ex) { Console.WriteLine("{0} {1}", ex.HelpLink, ex.Message); throw; } } protected virtual Boolean RestartDevice(String InstanceId) { IntPtr deviceInfoSet = IntPtr.Zero; try { SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA(); deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData); deviceInfoSet = SetupDiGetClassDevs(ref m_Class, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (SetupDiOpenDeviceInfo(deviceInfoSet, InstanceId, IntPtr.Zero, 0, ref deviceInterfaceData)) { SP_PROPCHANGE_PARAMS props = new SP_PROPCHANGE_PARAMS(); props.ClassInstallHeader = new SP_CLASSINSTALL_HEADER(); props.ClassInstallHeader.cbSize = Marshal.SizeOf(props.ClassInstallHeader); props.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE; props.Scope = DICS_FLAG_GLOBAL; props.StateChange = DICS_PROPCHANGE; props.HwProfile = 0x00; if (SetupDiSetClassInstallParams(deviceInfoSet, ref deviceInterfaceData, ref props, Marshal.SizeOf(props))) { return SetupDiChangeState(deviceInfoSet, ref deviceInterfaceData); } } } catch (Exception ex) { Console.WriteLine("{0} {1}", ex.HelpLink, ex.Message); throw; } finally { if (deviceInfoSet != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceInfoSet); } } return false; } #endregion #region Interop Definitions [DllImport("setupapi.dll", SetLastError = true)] protected static extern Int32 SetupDiCreateDeviceInfoList(ref System.Guid ClassGuid, Int32 hwndParent); [DllImport("setupapi.dll", SetLastError = true)] protected static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet); [DllImport("setupapi.dll", SetLastError = true)] protected static extern Boolean SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref System.Guid InterfaceClassGuid, Int32 MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern IntPtr SetupDiGetClassDevs(ref System.Guid ClassGuid, IntPtr Enumerator, IntPtr hwndParent, Int32 Flags); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, Int32 DeviceInterfaceDetailDataSize, ref Int32 RequiredSize, IntPtr DeviceInfoData); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, Int32 DeviceInterfaceDetailDataSize, ref Int32 RequiredSize, ref SP_DEVICE_INTERFACE_DATA DeviceInfoData); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] protected static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, Int32 Flags); [DllImport("user32.dll", SetLastError = true)] protected static extern Boolean UnregisterDeviceNotification(IntPtr Handle); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern IntPtr CreateFile(String lpFileName, UInt32 dwDesiredAccess, UInt32 dwShareMode, IntPtr lpSecurityAttributes, UInt32 dwCreationDisposition, UInt32 dwFlagsAndAttributes, UInt32 hTemplateFile); [DllImport("winusb.dll", SetLastError = true)] protected static extern Boolean WinUsb_Initialize(IntPtr DeviceHandle, ref IntPtr InterfaceHandle); [DllImport("winusb.dll", SetLastError = true)] protected static extern Boolean WinUsb_QueryInterfaceSettings(IntPtr InterfaceHandle, Byte AlternateInterfaceNumber, ref USB_INTERFACE_DESCRIPTOR UsbAltInterfaceDescriptor); [DllImport("winusb.dll", SetLastError = true)] protected static extern Boolean WinUsb_QueryPipe(IntPtr InterfaceHandle, Byte AlternateInterfaceNumber, Byte PipeIndex, ref WINUSB_PIPE_INFORMATION PipeInformation); [DllImport("winusb.dll", SetLastError = true)] protected static extern Boolean WinUsb_AbortPipe(IntPtr InterfaceHandle, Byte PipeID); [DllImport("winusb.dll", SetLastError = true)] protected static extern Boolean WinUsb_FlushPipe(IntPtr InterfaceHandle, Byte PipeID); [DllImport("winusb.dll", SetLastError = true)] protected static extern Boolean WinUsb_ControlTransfer(IntPtr InterfaceHandle, WINUSB_SETUP_PACKET SetupPacket, Byte[] Buffer, Int32 BufferLength, ref Int32 LengthTransferred, IntPtr Overlapped); [DllImport("winusb.dll", SetLastError = true)] protected static extern Boolean WinUsb_ReadPipe(IntPtr InterfaceHandle, Byte PipeID, Byte[] Buffer, Int32 BufferLength, ref Int32 LengthTransferred, IntPtr Overlapped); [DllImport("winusb.dll", SetLastError = true)] protected static extern Boolean WinUsb_WritePipe(IntPtr InterfaceHandle, Byte PipeID, Byte[] Buffer, Int32 BufferLength, ref Int32 LengthTransferred, IntPtr Overlapped); [DllImport("winusb.dll", SetLastError = true)] protected static extern Boolean WinUsb_Free(IntPtr InterfaceHandle); [DllImport("advapi32.dll", SetLastError = true)] public static extern IntPtr RegisterServiceCtrlHandlerEx(String ServiceName, ServiceControlHandlerEx Callback, IntPtr Context); [DllImport("kernel32.dll", SetLastError = true)] protected static extern Boolean DeviceIoControl(IntPtr DeviceHandle, Int32 IoControlCode, Byte[] InBuffer, Int32 InBufferSize, Byte[] OutBuffer, Int32 OutBufferSize, ref Int32 BytesReturned, IntPtr Overlapped); [DllImport("kernel32.dll", SetLastError = true)] protected static extern Boolean CloseHandle(IntPtr Handle); [DllImport("kernel32.dll")] protected static extern Int32 GetLastError(); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Int32 CM_Get_Device_ID(Int32 dnDevInst, IntPtr Buffer, Int32 BufferLen, Int32 ulFlags); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiOpenDeviceInfo(IntPtr DeviceInfoSet, String DeviceInstanceId, IntPtr hwndParent, Int32 Flags, ref SP_DEVICE_INTERFACE_DATA DeviceInfoData); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiChangeState(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] protected static extern Boolean SetupDiSetClassInstallParams(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, ref SP_PROPCHANGE_PARAMS ClassInstallParams, Int32 ClassInstallParamsSize); #endregion } } <|start_filename|>Scp/ScpMonitor/SettingsForm.Designer.cs<|end_filename|> namespace ScpMonitor { partial class SettingsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.gbFlip = new System.Windows.Forms.GroupBox(); this.cbRY = new System.Windows.Forms.CheckBox(); this.cbRX = new System.Windows.Forms.CheckBox(); this.cbLY = new System.Windows.Forms.CheckBox(); this.cbLX = new System.Windows.Forms.CheckBox(); this.tbIdle = new System.Windows.Forms.TrackBar(); this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.lblIdle = new System.Windows.Forms.Label(); this.cbLED = new System.Windows.Forms.CheckBox(); this.cbRumble = new System.Windows.Forms.CheckBox(); this.cbTriggers = new System.Windows.Forms.CheckBox(); this.tbLatency = new System.Windows.Forms.TrackBar(); this.lblLatency = new System.Windows.Forms.Label(); this.tbLeft = new System.Windows.Forms.TrackBar(); this.tbRight = new System.Windows.Forms.TrackBar(); this.gbThreshold = new System.Windows.Forms.GroupBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.cbNative = new System.Windows.Forms.CheckBox(); this.cbSSP = new System.Windows.Forms.CheckBox(); this.ttSSP = new System.Windows.Forms.ToolTip(this.components); this.cbForce = new System.Windows.Forms.CheckBox(); this.lblBrightness = new System.Windows.Forms.Label(); this.tbBrightness = new System.Windows.Forms.TrackBar(); this.gbFlip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.tbIdle)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tbLatency)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tbLeft)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tbRight)).BeginInit(); this.gbThreshold.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.tbBrightness)).BeginInit(); this.SuspendLayout(); // // gbFlip // this.gbFlip.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.gbFlip.Controls.Add(this.cbRY); this.gbFlip.Controls.Add(this.cbRX); this.gbFlip.Controls.Add(this.cbLY); this.gbFlip.Controls.Add(this.cbLX); this.gbFlip.Location = new System.Drawing.Point(12, 12); this.gbFlip.Name = "gbFlip"; this.gbFlip.Size = new System.Drawing.Size(270, 44); this.gbFlip.TabIndex = 0; this.gbFlip.TabStop = false; this.gbFlip.Text = " Flip Axis "; // // cbRY // this.cbRY.AutoSize = true; this.cbRY.Location = new System.Drawing.Point(201, 20); this.cbRY.Name = "cbRY"; this.cbRY.Size = new System.Drawing.Size(41, 17); this.cbRY.TabIndex = 3; this.cbRY.Text = "RY"; this.cbRY.UseVisualStyleBackColor = true; // // cbRX // this.cbRX.AutoSize = true; this.cbRX.Location = new System.Drawing.Point(141, 20); this.cbRX.Name = "cbRX"; this.cbRX.Size = new System.Drawing.Size(41, 17); this.cbRX.TabIndex = 2; this.cbRX.Text = "RX"; this.cbRX.UseVisualStyleBackColor = true; // // cbLY // this.cbLY.AutoSize = true; this.cbLY.Location = new System.Drawing.Point(81, 20); this.cbLY.Name = "cbLY"; this.cbLY.Size = new System.Drawing.Size(39, 17); this.cbLY.TabIndex = 1; this.cbLY.Text = "LY"; this.cbLY.UseVisualStyleBackColor = true; // // cbLX // this.cbLX.AutoSize = true; this.cbLX.Location = new System.Drawing.Point(21, 20); this.cbLX.Name = "cbLX"; this.cbLX.Size = new System.Drawing.Size(39, 17); this.cbLX.TabIndex = 0; this.cbLX.Text = "LX"; this.cbLX.UseVisualStyleBackColor = true; // // tbIdle // this.tbIdle.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbIdle.AutoSize = false; this.tbIdle.Location = new System.Drawing.Point(12, 169); this.tbIdle.Maximum = 30; this.tbIdle.Name = "tbIdle"; this.tbIdle.Size = new System.Drawing.Size(270, 34); this.tbIdle.TabIndex = 2; this.tbIdle.Value = 10; this.tbIdle.ValueChanged += new System.EventHandler(this.tbIdle_ValueChanged); // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOK.Location = new System.Drawing.Point(126, 447); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(75, 23); this.btnOK.TabIndex = 16; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(207, 447); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 17; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // lblIdle // this.lblIdle.AutoSize = true; this.lblIdle.Location = new System.Drawing.Point(12, 206); this.lblIdle.Name = "lblIdle"; this.lblIdle.Size = new System.Drawing.Size(125, 13); this.lblIdle.TabIndex = 3; this.lblIdle.Text = "Idle Timeout : 10 minutes"; // // cbLED // this.cbLED.AutoSize = true; this.cbLED.Location = new System.Drawing.Point(12, 373); this.cbLED.Name = "cbLED"; this.cbLED.Size = new System.Drawing.Size(85, 17); this.cbLED.TabIndex = 8; this.cbLED.Text = "Disable LED"; this.cbLED.UseVisualStyleBackColor = true; // // cbRumble // this.cbRumble.AutoSize = true; this.cbRumble.Location = new System.Drawing.Point(12, 396); this.cbRumble.Name = "cbRumble"; this.cbRumble.Size = new System.Drawing.Size(100, 17); this.cbRumble.TabIndex = 9; this.cbRumble.Text = "Disable Rumble"; this.cbRumble.UseVisualStyleBackColor = true; // // cbTriggers // this.cbTriggers.AutoSize = true; this.cbTriggers.Location = new System.Drawing.Point(153, 419); this.cbTriggers.Name = "cbTriggers"; this.cbTriggers.Size = new System.Drawing.Size(88, 17); this.cbTriggers.TabIndex = 10; this.cbTriggers.Text = "Map Triggers"; this.cbTriggers.UseVisualStyleBackColor = true; this.cbTriggers.Visible = false; // // tbLatency // this.tbLatency.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbLatency.AutoSize = false; this.tbLatency.LargeChange = 1; this.tbLatency.Location = new System.Drawing.Point(12, 231); this.tbLatency.Maximum = 16; this.tbLatency.Name = "tbLatency"; this.tbLatency.Size = new System.Drawing.Size(270, 34); this.tbLatency.TabIndex = 4; this.tbLatency.Value = 8; this.tbLatency.ValueChanged += new System.EventHandler(this.tbLatency_ValueChanged); // // lblLatency // this.lblLatency.AutoSize = true; this.lblLatency.Location = new System.Drawing.Point(12, 268); this.lblLatency.Name = "lblLatency"; this.lblLatency.Size = new System.Drawing.Size(151, 13); this.lblLatency.TabIndex = 5; this.lblLatency.Text = "DS3 Rumble Latency : 128 ms"; // // tbLeft // this.tbLeft.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbLeft.AutoSize = false; this.tbLeft.LargeChange = 8; this.tbLeft.Location = new System.Drawing.Point(78, 19); this.tbLeft.Maximum = 127; this.tbLeft.Name = "tbLeft"; this.tbLeft.Size = new System.Drawing.Size(186, 34); this.tbLeft.TabIndex = 1; this.tbLeft.TickFrequency = 8; // // tbRight // this.tbRight.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbRight.AutoSize = false; this.tbRight.LargeChange = 8; this.tbRight.Location = new System.Drawing.Point(78, 59); this.tbRight.Maximum = 127; this.tbRight.Name = "tbRight"; this.tbRight.Size = new System.Drawing.Size(186, 34); this.tbRight.TabIndex = 3; this.tbRight.TickFrequency = 8; // // gbThreshold // this.gbThreshold.Controls.Add(this.label2); this.gbThreshold.Controls.Add(this.label1); this.gbThreshold.Controls.Add(this.tbLeft); this.gbThreshold.Controls.Add(this.tbRight); this.gbThreshold.Location = new System.Drawing.Point(12, 62); this.gbThreshold.Name = "gbThreshold"; this.gbThreshold.Size = new System.Drawing.Size(270, 101); this.gbThreshold.TabIndex = 1; this.gbThreshold.TabStop = false; this.gbThreshold.Text = "Threshold"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(15, 63); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(59, 13); this.label2.TabIndex = 2; this.label2.Text = "Right Stick"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(15, 23); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(52, 13); this.label1.TabIndex = 0; this.label1.Text = "Left Stick"; // // cbNative // this.cbNative.AutoSize = true; this.cbNative.Location = new System.Drawing.Point(153, 373); this.cbNative.Name = "cbNative"; this.cbNative.Size = new System.Drawing.Size(122, 17); this.cbNative.TabIndex = 11; this.cbNative.Text = "Disable Native Feed"; this.cbNative.UseVisualStyleBackColor = true; // // cbSSP // this.cbSSP.AutoSize = true; this.cbSSP.Location = new System.Drawing.Point(153, 396); this.cbSSP.Name = "cbSSP"; this.cbSSP.Size = new System.Drawing.Size(85, 17); this.cbSSP.TabIndex = 12; this.cbSSP.Text = "Disable SSP"; this.cbSSP.UseVisualStyleBackColor = true; // // cbForce // this.cbForce.AutoSize = true; this.cbForce.Location = new System.Drawing.Point(12, 419); this.cbForce.Name = "cbForce"; this.cbForce.Size = new System.Drawing.Size(81, 17); this.cbForce.TabIndex = 18; this.cbForce.Text = "DS4 Repair"; this.ttSSP.SetToolTip(this.cbForce, "Force DS4 to Repair Bluetooth Link Key on USB Connection"); this.cbForce.UseVisualStyleBackColor = true; // // lblBrightness // this.lblBrightness.AutoSize = true; this.lblBrightness.Location = new System.Drawing.Point(12, 333); this.lblBrightness.Name = "lblBrightness"; this.lblBrightness.Size = new System.Drawing.Size(155, 13); this.lblBrightness.TabIndex = 7; this.lblBrightness.Text = "DS4 Light Bar Brightness : 128"; // // tbBrightness // this.tbBrightness.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbBrightness.AutoSize = false; this.tbBrightness.LargeChange = 16; this.tbBrightness.Location = new System.Drawing.Point(12, 296); this.tbBrightness.Maximum = 255; this.tbBrightness.Name = "tbBrightness"; this.tbBrightness.Size = new System.Drawing.Size(270, 34); this.tbBrightness.TabIndex = 6; this.tbBrightness.TickFrequency = 16; this.tbBrightness.Value = 128; this.tbBrightness.ValueChanged += new System.EventHandler(this.tbBrightness_ValueChanged); // // SettingsForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(294, 482); this.Controls.Add(this.cbForce); this.Controls.Add(this.lblBrightness); this.Controls.Add(this.tbBrightness); this.Controls.Add(this.cbSSP); this.Controls.Add(this.cbNative); this.Controls.Add(this.gbThreshold); this.Controls.Add(this.lblLatency); this.Controls.Add(this.tbLatency); this.Controls.Add(this.cbTriggers); this.Controls.Add(this.cbRumble); this.Controls.Add(this.cbLED); this.Controls.Add(this.lblIdle); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.tbIdle); this.Controls.Add(this.gbFlip); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SettingsForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Service Configuration"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form_Closing); this.Load += new System.EventHandler(this.Form_Load); this.gbFlip.ResumeLayout(false); this.gbFlip.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.tbIdle)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tbLatency)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tbLeft)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tbRight)).EndInit(); this.gbThreshold.ResumeLayout(false); this.gbThreshold.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.tbBrightness)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox gbFlip; private System.Windows.Forms.CheckBox cbRY; private System.Windows.Forms.CheckBox cbRX; private System.Windows.Forms.CheckBox cbLY; private System.Windows.Forms.CheckBox cbLX; private System.Windows.Forms.TrackBar tbIdle; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Label lblIdle; private System.Windows.Forms.CheckBox cbLED; private System.Windows.Forms.CheckBox cbRumble; private System.Windows.Forms.CheckBox cbTriggers; private System.Windows.Forms.TrackBar tbLatency; private System.Windows.Forms.Label lblLatency; private System.Windows.Forms.TrackBar tbLeft; private System.Windows.Forms.TrackBar tbRight; private System.Windows.Forms.GroupBox gbThreshold; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.CheckBox cbNative; private System.Windows.Forms.CheckBox cbSSP; private System.Windows.Forms.ToolTip ttSSP; private System.Windows.Forms.Label lblBrightness; private System.Windows.Forms.TrackBar tbBrightness; private System.Windows.Forms.CheckBox cbForce; } } <|start_filename|>Scp/XInput_Scp/DS3Controller.cpp<|end_filename|> #include "StdAfx.h" #define REPORT_SIZE 49 // Byte 3 Right Motor // Byte 5 Left Motor // Byte 10 LEDs - Bit Flags: 0x2 LED 1, 0x4 LED 2, 0x8 LED 3, 0x10 LED 4 static BYTE l_Report[REPORT_SIZE] = { 0x01, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static BYTE l_Flags[4] = { 0x02, 0x04, 0x08, 0x10 }; CDS3Controller::CDS3Controller(DWORD dwIndex) : CSCPController(dwIndex, REPORT_SIZE) { m_deviceId = _tcsdup(_T("vid_054c&pid_0268")); memcpy(m_Report, l_Report, m_dwReportSize); } void CDS3Controller::FormatReport(void) { m_Report[ 0] = (BYTE) m_lpHidDevice->OutputData[0].ReportID; m_Report[ 3] = (BYTE) (m_padVibration.wRightMotorSpeed > 0 ? 0x01 : 0); // Only has [ON|OFF] m_Report[ 5] = (BYTE) (m_padVibration.wLeftMotorSpeed >> 8); m_Report[10] = (BYTE) l_Flags[m_dwIndex]; } void CDS3Controller::XInputMapState(void) { m_padState.Gamepad.wButtons = 0; for (ULONG Index = 0, Axis = 0; Index < m_lpHidDevice->InputDataLength; Index++) { if (m_lpHidDevice->InputData[Index].IsButtonData) { for (ULONG j = 0; j < m_lpHidDevice->InputData[Index].ButtonData.MaxUsageLength; j++) { // Remap for Buttons switch(m_lpHidDevice->InputData[Index].ButtonData.Usages[j]) { case 1: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_BACK; break; case 2: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_LEFT_THUMB; break; case 3: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_RIGHT_THUMB; break; case 4: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_START; break; case 5: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_DPAD_UP; break; case 6: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_DPAD_RIGHT; break; case 7: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_DPAD_DOWN; break; case 8: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_DPAD_LEFT; break; case 11: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_LEFT_SHOULDER; break; case 12: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_RIGHT_SHOULDER; break; case 13: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_Y; break; case 14: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_B; break; case 15: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_A; break; case 16: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_X; break; case 17: m_padState.Gamepad.wButtons |= XINPUT_GAMEPAD_GUIDE; break; } } } else { // Remap for Axis switch(Axis++) { case 0: m_padState.Gamepad.sThumbRY = -Scale((SHORT) m_lpHidDevice->InputData[Index].ValueData.Value); break; case 1: m_padState.Gamepad.sThumbRX = Scale((SHORT) m_lpHidDevice->InputData[Index].ValueData.Value); break; case 2: m_padState.Gamepad.sThumbLY = -Scale((SHORT) m_lpHidDevice->InputData[Index].ValueData.Value); break; case 3: m_padState.Gamepad.sThumbLX = Scale((SHORT) m_lpHidDevice->InputData[Index].ValueData.Value); break; } } } // Remap for Triggers - Not Unpacked as Axis by UnpackReport m_padState.Gamepad.bLeftTrigger = m_lpHidDevice->InputReportBuffer[18]; m_padState.Gamepad.bRightTrigger = m_lpHidDevice->InputReportBuffer[19]; // Convert for Extension m_Extended.SCP_UP = ToPressure(m_lpHidDevice->InputReportBuffer[14]); m_Extended.SCP_RIGHT = ToPressure(m_lpHidDevice->InputReportBuffer[15]); m_Extended.SCP_DOWN = ToPressure(m_lpHidDevice->InputReportBuffer[16]); m_Extended.SCP_LEFT = ToPressure(m_lpHidDevice->InputReportBuffer[17]); m_Extended.SCP_LX = ToAxis(m_padState.Gamepad.sThumbLX); m_Extended.SCP_LY = ToAxis(m_padState.Gamepad.sThumbLY); m_Extended.SCP_L1 = ToPressure(m_lpHidDevice->InputReportBuffer[20]); m_Extended.SCP_L2 = ToPressure(m_lpHidDevice->InputReportBuffer[18]); m_Extended.SCP_L3 = m_padState.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_THUMB ? 1.0f : 0.0f; m_Extended.SCP_RX = ToAxis(m_padState.Gamepad.sThumbRX); m_Extended.SCP_RY = ToAxis(m_padState.Gamepad.sThumbRY); m_Extended.SCP_R1 = ToPressure(m_lpHidDevice->InputReportBuffer[21]); m_Extended.SCP_R2 = ToPressure(m_lpHidDevice->InputReportBuffer[19]); m_Extended.SCP_R3 = m_padState.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB ? 1.0f : 0.0f; m_Extended.SCP_T = ToPressure(m_lpHidDevice->InputReportBuffer[22]); m_Extended.SCP_C = ToPressure(m_lpHidDevice->InputReportBuffer[23]); m_Extended.SCP_X = ToPressure(m_lpHidDevice->InputReportBuffer[24]); m_Extended.SCP_S = ToPressure(m_lpHidDevice->InputReportBuffer[25]); m_Extended.SCP_SELECT = m_padState.Gamepad.wButtons & XINPUT_GAMEPAD_BACK ? 1.0f : 0.0f; m_Extended.SCP_START = m_padState.Gamepad.wButtons & XINPUT_GAMEPAD_START ? 1.0f : 0.0f; m_Extended.SCP_PS = m_padState.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE ? 1.0f : 0.0f; } <|start_filename|>Nintroller/ComponentStructs.cs<|end_filename|> using System; using System.Linq; namespace NintrollerLib { /// <summary> /// Standard buttons included on a Wii Remote /// </summary> public struct CoreButtons : INintrollerParsable { /// <summary></summary> public bool A, B; /// <summary></summary> public bool One, Two; /// <summary></summary> public bool Up, Down, Left, Right; /// <summary></summary> public bool Plus, Minus, Home; /// <summary> /// Start is the same as Plus /// </summary> public bool Start { get { return Plus; } set { Plus = value; } } /// <summary> /// Select is the same as Minus /// </summary> public bool Select { get { return Minus; } set { Minus = value; } } /// <summary> /// Parses core buttons based on 2 bytes from the input data. /// </summary> /// <param name="input">Byte array of controller data.</param> /// <param name="offset">Starting index of Core Button bytes.</param> public void Parse(byte[] input, int offset = 0) { InputReport type = (InputReport)input[0]; if (type != InputReport.ExtOnly) { A = (input[offset + 1] & 0x08) != 0; B = (input[offset + 1] & 0x04) != 0; One = (input[offset + 1] & 0x02) != 0; Two = (input[offset + 1] & 0x01) != 0; Home = (input[offset + 1] & 0x80) != 0; Minus = (input[offset + 1] & 0x10) != 0; Plus = (input[offset + 0] & 0x10) != 0; Up = (input[offset + 0] & 0x08) != 0; Down = (input[offset + 0] & 0x04) != 0; Right = (input[offset + 0] & 0x02) != 0; Left = (input[offset + 0] & 0x01) != 0; } } } /// <summary> /// Class to hold Accerlerometer data. /// </summary> public struct Accelerometer : INintrollerParsable, INintrollerNormalizable { /// <summary> /// Raw Value /// </summary> public int rawX, rawY, rawZ; /// <summary> /// Normalized Value /// </summary> public float X, Y, Z; // calibration values /// <summary>Middle / Neutral position.</summary> public int centerX, centerY, centerZ; /// <summary>Minimum position (registers as -1 when normalized)</summary> public int minX, minY, minZ; /// <summary>Maximum position (registers as +1 when normalized)</summary> public int maxX, maxY, maxZ; /// <summary>Magnitude where positions should be ignored when within.</summary> public int deadX, deadY, deadZ; /// <summary> /// Parses 3 byte accelerometer raw data. /// </summary> /// <param name="input"></param> /// <param name="offset"></param> public void Parse(byte[] input, int offset = 0) { rawX = input[offset + 0]; rawY = input[offset + 1]; rawZ = input[offset + 2]; } /// <summary> /// Copy calibration members from provided Accelerometer structure. /// </summary> /// <param name="calibration"></param> public void Calibrate(Accelerometer calibration) { centerX = calibration.centerX; centerY = calibration.centerY; centerZ = calibration.centerZ; minX = calibration.minX; minY = calibration.minY; minZ = calibration.minZ; maxX = calibration.maxX; maxY = calibration.maxY; maxZ = calibration.maxZ; deadX = calibration.deadX; deadY = calibration.deadY; deadZ = calibration.deadZ; } /// <summary> /// Calculates the normalized values. /// </summary> public void Normalize() { // Cubic deadzone if (Math.Abs(rawX) < deadX && Math.Abs(rawY) < deadY && Math.Abs(rawZ) < deadZ) { X = 0; Y = 0; Z = 0; return; } X = Nintroller.Normalize(rawX, minX, centerX, maxX, deadX); Y = Nintroller.Normalize(rawY, minY, centerY, maxY, deadY); Z = Nintroller.Normalize(rawZ, minZ, centerZ, maxZ, deadZ); } /// <summary> /// Converts normalized values to displayable string. /// </summary> /// <returns>String values of X, Y, Z</returns> public override string ToString() { return string.Format("X:{0} Y:{1} Z{2}", X, Y, Z); } } /// <summary> /// Class to hold Gyroscopic data. /// </summary> public struct Gyroscope : INintrollerParsable { public int rawX, rawY, rawZ; private Joystick joyConversion; public void Parse(byte[] input, int offset = 0) { InputReport type = (InputReport)input[0]; } } /// <summary> /// Individual IR sensor point. /// </summary> public struct IRPoint { /// <summary></summary> public int rawX, rawY, size; //public float x, y; /// <summary> /// If this point is visible or not /// </summary> public bool visible; } /// <summary> /// Collection of IR sensor data /// </summary> public struct IR : INintrollerParsable, INintrollerNormalizable { /// <summary> /// Individual IR Point /// </summary> public IRPoint point1, point2, point3, point4; /// <summary> /// Calculated rotation angle /// </summary> public float rotation; /// <summary> /// Distance between points 1 and 2 /// </summary> public float distance; /// <summary> /// Normalized pointer position /// </summary> public float X, Y; /// <summary> /// Area in which normalization returns 0 /// </summary> public INintrollerBounds boundingArea; /// <summary> /// Parse IR sensor data /// </summary> /// <param name="input"></param> /// <param name="offset"></param> public void Parse(byte[] input, int offset = 0) { point1.rawX = input[offset ] | ((input[offset + 2] >> 4) & 0x03) << 8; point1.rawY = input[offset + 1] | ((input[offset + 2] >> 6) & 0x03) << 8; if (input.Length - offset == 12) // InputReport.BtnsAccIR { // Extended Mode point2.rawX = input[offset + 3] | ((input[offset + 5] >> 4) & 0x03) << 8; point2.rawY = input[offset + 4] | ((input[offset + 5] >> 6) & 0x03) << 8; point3.rawX = input[offset + 6] | ((input[offset + 8] >> 4) & 0x03) << 8; point3.rawY = input[offset + 7] | ((input[offset + 8] >> 6) & 0x03) << 8; point4.rawX = input[offset + 9] | ((input[offset + 11] >> 4) & 0x03) << 8; point4.rawY = input[offset + 10] | ((input[offset + 11] >> 6) & 0x03) << 8; point1.size = input[offset + 2] & 0x0F; point2.size = input[offset + 5] & 0x0F; point3.size = input[offset + 8] & 0x0F; point4.size = input[offset + 11] & 0x0F; point1.visible = !(input[offset ] == 0xFF && input[offset + 1] == 0xFF && input[offset + 2] == 0xFF); point2.visible = !(input[offset + 3] == 0xFF && input[offset + 4] == 0xFF && input[offset + 5] == 0xFF); point3.visible = !(input[offset + 6] == 0xFF && input[offset + 7] == 0xFF && input[offset + 8] == 0xFF); point4.visible = !(input[offset + 9] == 0xFF && input[offset + 10] == 0xFF && input[offset + 11] == 0xFF); } else { // Basic Mode point2.rawX = input[offset + 3] | ((input[offset + 2] >> 0) & 0x03) << 8; point2.rawY = input[offset + 4] | ((input[offset + 2] >> 2) & 0x03) << 8; point3.rawX = input[offset + 5] | ((input[offset + 7] >> 4) & 0x03) << 8; point3.rawY = input[offset + 6] | ((input[offset + 7] >> 6) & 0x03) << 8; point4.rawX = input[offset + 8] | ((input[offset + 7] >> 0) & 0x03) << 8; point4.rawY = input[offset + 9] | ((input[offset + 7] >> 2) & 0x03) << 8; point1.size = 0x00; point2.size = 0x00; point3.size = 0x00; point4.size = 0x00; point1.visible = !(input[offset ] == 0xFF && input[offset + 1] == 0xFF); point2.visible = !(input[offset + 3] == 0xFF && input[offset + 4] == 0xFF); point3.visible = !(input[offset + 5] == 0xFF && input[offset + 6] == 0xFF); point4.visible = !(input[offset + 8] == 0xFF && input[offset + 9] == 0xFF); } } /// <summary> /// Calculates (X,Y) point, rotation, and distance /// </summary> public void Normalize() { if (!point1.visible && !point2.visible) { X = 0; Y = 0; rotation = 0; distance = 0; return; } IRPoint midPoint = new IRPoint(); if (point1.visible && point2.visible) { midPoint.rawX = point1.rawX + (point2.rawX - point1.rawX)/2; midPoint.rawY = point1.rawY + (point2.rawY - point1.rawY)/2; midPoint.visible = true; } else if (point1.visible) { midPoint = point1; } else if (point2.visible) { midPoint = point2; } if (midPoint.visible) { if (boundingArea == null) { boundingArea = new SquareBoundry() { center_x = 512, center_y = 512, width = 128, height = 128 }; } if (/*boundingArea != null && */boundingArea.InBounds(midPoint.rawX, midPoint.rawY)) { X = 0; Y = 0; } else { X = (midPoint.rawX - 512) / -256f; Y = (midPoint.rawY - 512) / -256f; } } else { X = 0; Y = 0; } } /// <summary> /// Creates a readable string of the IR normalized oint. /// </summary> /// <returns>String representing IR Point</returns> public override string ToString() { return string.Format("X:{0} Y:{1}", X, Y); } } /// <summary> /// Class to represent Trigger input /// </summary> public struct Trigger : INintrollerParsable, INintrollerNormalizable { /// <summary> /// Raw input value /// </summary> public short rawValue; /// <summary> /// Normalized input value /// </summary> public float value; /// <summary> /// Fully pressed /// </summary> public bool full; /// <summary> /// Calibration /// </summary> public int min, max; /// <summary> /// Parses trigger data /// </summary> /// <param name="input"></param> /// <param name="offset"></param> public void Parse(byte[] input, int offset = 0) { Parse(input, offset, false); } // TODO: Check if we shoud be using rawValue here, & set full public void Parse(byte[] input, int offset, bool isLeft) { if (isLeft) { value = (byte)(((input[offset] & 0x60) >> 2) | (input[offset + 1] >> 5)); } else { value = (byte)(input[offset] & 0x1F); } } /// <summary> /// Copy calibration members from another Trigger object /// </summary> /// <param name="calibration">Calibration data to copy</param> public void Calibrate(Trigger calibration) { min = calibration.min; max = calibration.max; } /// <summary> /// Normalize value /// </summary> public void Normalize() { if (rawValue < min) { value = 0f; } else { value = (float)(rawValue - min) / (float)(max == 0 ? 31 : max - min); } } } /// <summary> /// Class representing joystick data /// </summary> public struct Joystick : INintrollerNormalizable { /// <summary> /// Raw value /// </summary> public int rawX, rawY; /// <summary> /// Normalized value /// </summary> public float X, Y; // calibration values /// <summary>Middle / Neutral position.</summary> public int centerX, centerY; /// <summary>Minimum position (registers as -1 when normalized)</summary> public int minX, minY; /// <summary>Maximum position (registers as +1 when normalized)</summary> public int maxX, maxY; /// <summary>Magnitude where positions should be ignored when within.</summary> public int deadX, deadY; /// <summary>Asymetrical positions should be ignored when within.</summary> public int deadXp, deadXn, deadYp, deadYn; /// <summary>Minimum normalized output amount</summary> public float antiDeadzone; /// <summary> /// Copy calibration values from another Joystick object /// </summary> /// <param name="calibration">Joystick data to copy from</param> public void Calibrate(Joystick calibration) { centerX = calibration.centerX; centerY = calibration.centerY; minX = calibration.minX; minY = calibration.minY; maxX = calibration.maxX; maxY = calibration.maxY; if (calibration.deadXp == 0 && calibration.deadXn == 0) { deadX = calibration.deadX; deadXp = deadX; deadXn = -deadXp; } else { deadXp = calibration.deadXp; deadXn = calibration.deadXn; deadX = deadXp; } if (calibration.deadYp == 0 && calibration.deadYn == 0) { deadY = calibration.deadY; deadYp = deadY; deadYn = -deadY; } else { deadYp = calibration.deadYp; deadYn = calibration.deadYn; deadY = deadYp; } antiDeadzone = calibration.antiDeadzone; } /// <summary> /// Normalizes raw values to calculate X and Y /// </summary> public void Normalize() { // This is a square deadzone if ((rawX - centerX < deadXp && rawX - centerX > deadXn) && (rawY - centerY < deadYp && rawY - centerY > deadYn)) { X = 0; Y = 0; return; } X = Nintroller.Normalize(rawX, minX, centerX, maxX, deadXp, deadXn); Y = Nintroller.Normalize(rawY, minY, centerY, maxY, deadYp, deadYn); if (antiDeadzone != 0) { if (X != 0) X = X * (1f - antiDeadzone) + antiDeadzone * Math.Sign(X); if (Y != 0) Y = Y * (1f - antiDeadzone) + antiDeadzone * Math.Sign(Y); } } /// <summary> /// Creates a readable string value representing X and Y /// </summary> /// <returns>String of X and Y Axes</returns> public override string ToString() { return string.Format("X:{0} Y:{1}", X, Y); } } // Balance Board //if (offset == 0) // return; //raw.TopRight = (short)((short)r[offset ] << 8 | r[offset + 1]); //raw.BottomRight = (short)((short)r[offset + 2] << 8 | r[offset + 3]); //raw.TopLeft = (short)((short)r[offset + 4] << 8 | r[offset + 5]); //raw.BottomLeft = (short)((short)r[offset + 6] << 8 | r[offset + 7]); // Calculate other members (like weight distribution) /// <summary> /// Represents a circular boundry /// </summary> public struct CircularBoundry : INintrollerBounds { /// <summary>Center X of circle</summary> public int center_x; /// <summary>Center Y of circle</summary> public int center_y; /// <summary>Size of the circle</summary> public int radius; /// <summary> /// Creates a circular boundry with the given parameters. /// </summary> /// <param name="center_x">Center point X</param> /// <param name="center_y">Center point Y</param> /// <param name="radius">Size of the boundy</param> public CircularBoundry(int center_x, int center_y, int radius) { this.center_x = center_x; this.center_y = center_y; this.radius = radius; } /// <summary> /// Checks if point is within boundry. /// </summary> /// <param name="x">X point</param> /// <param name="y">Y point</param> /// <returns>True if within boundry</returns> public bool InBounds(float x, float y = 0) { var dist = Math.Sqrt(Math.Pow(center_x - x, 2) + Math.Pow(center_y - y, 2)); if (dist <= radius) return true; else return false; } } /// <summary> /// Represents a square/rectangular boundry /// </summary> public struct SquareBoundry : INintrollerBounds { /// <summary>Center X point of box</summary> public int center_x; /// <summary>Center Y point of box</summary> public int center_y; /// <summary>Width of box</summary> public int width; /// <summary>Height of box</summary> public int height; /// <summary> /// Creates a bounding area based on the given parameters. /// </summary> /// <param name="x">Center X</param> /// <param name="y">Center Y</param> /// <param name="w">Width</param> /// <param name="h">Height</param> public SquareBoundry(int x, int y, int w, int h) { center_x = x; center_y = y; width = w; height = h; } /// <summary> /// Checks if the given point is in the boundry /// </summary> /// <param name="x">X value</param> /// <param name="y">Y value</param> /// <returns>True if within the boundry</returns> public bool InBounds(float x, float y = 0) { if (x > (center_x - width/2) && x < (center_x + width/2)) { if (y > (center_y - height/2) && y < (center_y + height/2)) { return true; } } return false; } } } <|start_filename|>WiinUPro/Assignments/VJoyPOVAssignment.cs<|end_filename|> using System; namespace WiinUPro { public class VJoyPOVAssignment : IAssignment { public uint DeviceId { get; set; } public int POVNum { get; set; } public VJoyDirector.POVDirection Direction { get; set; } /// <summary> /// Set to use Turbo feature /// </summary> public bool TurboEnabled { get; set; } /// <summary> /// Turbo rate in milliseconds (0ms to 1000ms) /// </summary> public int TurboRate { get { return _turboRate; } set { _turboRate = Math.Min(Math.Max(0, value), 1000); } } /// <summary> /// What the applied value must be greater than to apply /// </summary> public float Threshold { get { return _threashold; } set { _threashold = value; } } private int _turboRate = 200; private float _threashold = 0.1f; private bool _lastState = false; private int _lastApplied = 0; public VJoyPOVAssignment() { } public VJoyPOVAssignment(VJoyDirector.POVDirection direction, uint device = 1, int povNum = -1) { Direction = direction; DeviceId = device; if (povNum == -1) { int.TryParse(direction.ToString().Substring(1, 1), out povNum); } POVNum = povNum; } public void Apply(float value) { bool isDown = value >= Threshold; if (TurboEnabled) { if (!isDown) { return; } int now = DateTime.Now.Millisecond; if (_lastApplied > now) { _lastApplied = _lastApplied + TurboRate - 1000; } VJoyDirector.Access.SetPOV(POVNum, Direction, now > _lastApplied + TurboRate, DeviceId); } else if (isDown != _lastState) { VJoyDirector.Access.SetPOV(POVNum, Direction, isDown, DeviceId); _lastState = isDown; } } public bool SameAs(IAssignment assignment) { var other = assignment as VJoyPOVAssignment; if (other == null) { return false; } bool result = true; result &= DeviceId == other.DeviceId; result &= POVNum == other.POVNum; result &= Direction == other.Direction; result &= Threshold == other.Threshold; result &= TurboEnabled == other.TurboEnabled; result &= TurboRate == other.TurboRate; return result; } public override bool Equals(object obj) { var other = obj as VJoyPOVAssignment; if (other == null) { return false; } else { return Direction == other.Direction && DeviceId == other.DeviceId; } } public override int GetHashCode() { int hash = (int)Direction + (int)DeviceId; return hash; } public override string ToString() { return Direction.ToString(); } public string GetDisplayName() { return $"Joy{ToString()}"; } } } <|start_filename|>WiinUPro/Assignments/KeyboardAssignment.cs<|end_filename|> using System; using InputManager; namespace WiinUPro { public class KeyboardAssignment : IAssignment { /// <summary> /// The Key to be simulated /// </summary> public VirtualKeyCode KeyCode { get; set; } /// <summary> /// Set to use Turbo feature /// </summary> public bool TurboEnabled { get; set; } /// <summary> /// Turbo rate in milliseconds (0ms to 1000ms) /// </summary> public int TurboRate { get { return _turboRate; } set { _turboRate = Math.Min(Math.Max(0, value), 1000); } } /// <summary> /// What the applied value must be greater than to apply /// </summary> public float Threshold { get { return _threashold; } set { _threashold = value; } } /// <summary> /// Set to apply key simulation when input is not being applied /// </summary> public bool InverseInput { get; set; } private int _turboRate = 200; private float _threashold = 0.1f; private bool _lastState = false; private int _lastApplied = 0; public KeyboardAssignment() { } public KeyboardAssignment(VirtualKeyCode key) { KeyCode = key; } public void Apply(float value) { bool isDown = value >= Threshold; if (InverseInput) { isDown = !isDown; } if (TurboEnabled) { if (!isDown) { return; } int now = DateTime.Now.Millisecond; if (_lastApplied > now) { _lastApplied = _lastApplied + TurboRate - 1000; } if (now > _lastApplied + TurboRate) { KeyboardDirector.Access.KeyPress(KeyCode); _lastApplied = now; } } else if (isDown != _lastState) { if (isDown) { KeyboardDirector.Access.KeyDown(KeyCode); } else { KeyboardDirector.Access.KeyUp(KeyCode); } _lastState = isDown; } } // Tests if the assignment is exactly the same public bool SameAs(IAssignment assignment) { var other = assignment as KeyboardAssignment; if (other == null) { return false; } bool result = true; result &= KeyCode == other.KeyCode; result &= InverseInput == other.InverseInput; result &= Threshold == other.Threshold; result &= TurboEnabled == other.TurboEnabled; result &= TurboRate == other.TurboRate; return result; } // Only compaires the Key being simulated public override bool Equals(object obj) { var other = obj as KeyboardAssignment; if (other == null) { return false; } else { return KeyCode == other.KeyCode; } } public override int GetHashCode() { int hash = (int)KeyCode + 1; return hash; } public override string ToString() { return KeyCode.ToString(); } public string GetDisplayName() { return ToString().Replace("VK_", "").Replace("K_", ""); } } } <|start_filename|>Scp/XInput_Scp/LibUsbApi.h<|end_filename|> #pragma once extern void load_lib_usb(); extern void init_lib_usb(); <|start_filename|>Scp/ScpPair/ScpForm.Designer.cs<|end_filename|> namespace ScpPair { partial class ScpForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.usbDevice = new ScpControl.UsbDs3(this.components); this.tmEnable = new System.Windows.Forms.Timer(this.components); this.tbMaster = new System.Windows.Forms.TextBox(); this.lblLocal = new System.Windows.Forms.Label(); this.lblRemote = new System.Windows.Forms.Label(); this.lblMac = new System.Windows.Forms.Label(); this.lblMaster = new System.Windows.Forms.Label(); this.btnSet = new System.Windows.Forms.Button(); this.SuspendLayout(); // // usbDevice // this.usbDevice.IsShutdown = false; this.usbDevice.PadId = ScpControl.DsPadId.One; // // tmEnable // this.tmEnable.Enabled = true; this.tmEnable.Tick += new System.EventHandler(this.tmEnable_Tick); // // tbMaster // this.tbMaster.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbMaster.Location = new System.Drawing.Point(12, 84); this.tbMaster.Name = "tbMaster"; this.tbMaster.Size = new System.Drawing.Size(194, 20); this.tbMaster.TabIndex = 0; // // lblLocal // this.lblLocal.AutoSize = true; this.lblLocal.Font = new System.Drawing.Font("Lucida Console", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblLocal.Location = new System.Drawing.Point(12, 9); this.lblLocal.Name = "lblLocal"; this.lblLocal.Size = new System.Drawing.Size(61, 12); this.lblLocal.TabIndex = 1; this.lblLocal.Text = "Local :"; // // lblRemote // this.lblRemote.AutoSize = true; this.lblRemote.Font = new System.Drawing.Font("Lucida Console", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblRemote.Location = new System.Drawing.Point(12, 38); this.lblRemote.Name = "lblRemote"; this.lblRemote.Size = new System.Drawing.Size(61, 12); this.lblRemote.TabIndex = 2; this.lblRemote.Text = "Remote :"; // // lblMac // this.lblMac.AutoSize = true; this.lblMac.Font = new System.Drawing.Font("Lucida Console", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblMac.Location = new System.Drawing.Point(79, 9); this.lblMac.Name = "lblMac"; this.lblMac.Size = new System.Drawing.Size(0, 12); this.lblMac.TabIndex = 3; // // lblMaster // this.lblMaster.AutoSize = true; this.lblMaster.Font = new System.Drawing.Font("Lucida Console", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblMaster.Location = new System.Drawing.Point(79, 38); this.lblMaster.Name = "lblMaster"; this.lblMaster.Size = new System.Drawing.Size(0, 12); this.lblMaster.TabIndex = 4; // // btnSet // this.btnSet.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnSet.Enabled = false; this.btnSet.Location = new System.Drawing.Point(131, 119); this.btnSet.Name = "btnSet"; this.btnSet.Size = new System.Drawing.Size(75, 23); this.btnSet.TabIndex = 5; this.btnSet.Text = "Set"; this.btnSet.UseVisualStyleBackColor = true; this.btnSet.Click += new System.EventHandler(this.btnSet_Click); this.btnSet.Enter += new System.EventHandler(this.Button_Enter); // // ScpForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(221, 154); this.Controls.Add(this.btnSet); this.Controls.Add(this.lblMaster); this.Controls.Add(this.lblMac); this.Controls.Add(this.lblRemote); this.Controls.Add(this.lblLocal); this.Controls.Add(this.tbMaster); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ScpForm"; this.Text = "SCP Pair Tool"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form_Close); this.Load += new System.EventHandler(this.Form_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private ScpControl.UsbDs3 usbDevice; private System.Windows.Forms.Timer tmEnable; private System.Windows.Forms.TextBox tbMaster; private System.Windows.Forms.Label lblLocal; private System.Windows.Forms.Label lblRemote; private System.Windows.Forms.Label lblMac; private System.Windows.Forms.Label lblMaster; private System.Windows.Forms.Button btnSet; } } <|start_filename|>Scp/ScpControl/BthDs3.cs<|end_filename|> using System; using System.ComponentModel; namespace ScpControl { public partial class BthDs3 : BthDevice { protected Byte[] m_Report = new Byte[] { 0x52, 0x01, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; protected Byte[][] m_InitReport = new Byte[][] { new Byte[] { 0x02, 0x00, 0x0F, 0x00, 0x08, 0x35, 0x03, 0x19, 0x12, 0x00, 0x00, 0x03, 0x00 }, new Byte[] { 0x04, 0x00, 0x10, 0x00, 0x0F, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x35, 0x06, 0x09, 0x02, 0x01, 0x09, 0x02, 0x02, 0x00 }, new Byte[] { 0x06, 0x00, 0x11, 0x00, 0x0D, 0x35, 0x03, 0x19, 0x11, 0x24, 0x01, 0x90, 0x35, 0x03, 0x09, 0x02, 0x06, 0x00 }, new Byte[] { 0x06, 0x00, 0x12, 0x00, 0x0F, 0x35, 0x03, 0x19, 0x11, 0x24, 0x01, 0x90, 0x35, 0x03, 0x09, 0x02, 0x06, 0x02, 0x00, 0x7F }, new Byte[] { 0x06, 0x00, 0x13, 0x00, 0x0F, 0x35, 0x03, 0x19, 0x11, 0x24, 0x01, 0x90, 0x35, 0x03, 0x09, 0x02, 0x06, 0x02, 0x00, 0x59 }, new Byte[] { 0x06, 0x00, 0x14, 0x00, 0x0F, 0x35, 0x03, 0x19, 0x11, 0x24, 0x01, 0x80, 0x35, 0x03, 0x09, 0x02, 0x06, 0x02, 0x00, 0x33 }, new Byte[] { 0x06, 0x00, 0x15, 0x00, 0x0F, 0x35, 0x03, 0x19, 0x11, 0x24, 0x01, 0x90, 0x35, 0x03, 0x09, 0x02, 0x06, 0x02, 0x00, 0x0D }, }; protected Byte[] m_Leds = { 0x02, 0x04, 0x08, 0x10, }; protected Byte[] m_Enable = { 0x53, 0xF4, 0x42, 0x03, 0x00, 0x00, }; public override DsPadId PadId { get { return (DsPadId) m_ControllerId; } set { m_ControllerId = (Byte) value; m_ReportArgs.Pad = PadId; m_Report[11] = m_Leds[m_ControllerId]; } } public BthDs3() { InitializeComponent(); } public BthDs3(IContainer container) { container.Add(this); InitializeComponent(); } public BthDs3(IBthDevice Device, Byte[] Master, Byte Lsb, Byte Msb) : base(Device, Master, Lsb, Msb) { } public override Boolean Start() { CanStartHid = false; m_State = DsState.Connected; if (Local.StartsWith("00:26:5C")) // Fix up for Fake DS3 { m_Enable[0] = 0xA3; m_Report[0] = 0xA2; m_Report[3] = 0x00; m_Report[5] = 0x00; } if (Remote_Name.EndsWith("-ghic")) // Fix up for Fake DS3 { m_Report[3] = 0x00; m_Report[5] = 0x00; } m_Queued = 1; m_Blocked = true; m_Last = DateTime.Now; m_Device.HID_Command(HCI_Handle.Bytes, Get_SCID(L2CAP.PSM.HID_Command), m_Enable); return base.Start(); } public override void Parse(Byte[] Report) { if (Report[10] == 0xFF) return; m_PlugStatus = Report[38]; m_BatteryStatus = Report[39]; m_CableStatus = Report[40]; if (m_Packet == 0) Rumble(0, 0); m_Packet++; m_ReportArgs.Report[2] = m_BatteryStatus; m_ReportArgs.Report[4] = (Byte)(m_Packet >> 0 & 0xFF); m_ReportArgs.Report[5] = (Byte)(m_Packet >> 8 & 0xFF); m_ReportArgs.Report[6] = (Byte)(m_Packet >> 16 & 0xFF); m_ReportArgs.Report[7] = (Byte)(m_Packet >> 24 & 0xFF); Ds3Button Buttons = (Ds3Button)((Report[11] << 0) | (Report[12] << 8) | (Report[13] << 16) | (Report[14] << 24)); Boolean Trigger = false, Active = false; // Quick Disconnect if ((Buttons & Ds3Button.L1) == Ds3Button.L1 && (Buttons & Ds3Button.R1) == Ds3Button.R1 && (Buttons & Ds3Button.PS) == Ds3Button.PS ) { Trigger = true; Report[13] ^= 0x1; } for (Int32 Index = 8; Index < 57; Index++) { m_ReportArgs.Report[Index] = Report[Index + 1]; } // Buttons for (Int32 Index = 11; Index < 15 && !Active; Index++) { if (Report[Index] != 0) Active = true; } // Axis for (Int32 Index = 15; Index < 19 && !Active; Index++) { if (Report[Index] < 117 || Report[Index] > 137) Active = true; } // Triggers & Pressure for (Int32 Index = 23; Index < 35 && !Active; Index++) { if (Report[Index] != 0) Active = true; } if (Active) { m_IsIdle = false; } else if (!m_IsIdle) { m_IsIdle = true; m_Idle = DateTime.Now; } if (Trigger && !m_IsDisconnect) { m_IsDisconnect = true; m_Disconnect = DateTime.Now; } else if (!Trigger && m_IsDisconnect) { m_IsDisconnect = false; } Publish(); } public override Boolean Rumble(Byte Large, Byte Small) { lock (this) { if (Global.DisableRumble) { m_Report[4] = 0; m_Report[6] = 0; } else { m_Report[4] = (Byte)(Small > 0 ? 0x01 : 0x00); m_Report[6] = Large; } if (!m_Blocked && Global.Latency == 0) { m_Last = DateTime.Now; m_Blocked = true; m_Device.HID_Command(HCI_Handle.Bytes, Get_SCID(L2CAP.PSM.HID_Command), m_Report); } else { m_Queued = 1; } } return true; } public override Boolean InitReport(Byte[] Report) { Boolean retVal = false; if (m_Init < m_InitReport.Length) { m_Device.HID_Command(HCI_Handle.Bytes, Get_SCID(L2CAP.PSM.HID_Service), m_InitReport[m_Init++]); } else if (m_Init == m_InitReport.Length) { m_Init++; retVal = true; } return retVal; } protected override void Process(DateTime Now) { lock (this) { if (m_State == DsState.Connected) { if ((Now - m_Tick).TotalMilliseconds >= 500 && m_Packet > 0) { m_Tick = Now; if (m_Queued == 0) m_Queued = 1; if (Battery < DsBattery.Medium) { m_Report[11] ^= m_Leds[m_ControllerId]; } else { m_Report[11] |= m_Leds[m_ControllerId]; } } if (Global.DisableLED) m_Report[11] = 0; if (!m_Blocked && m_Queued > 0) { if ((Now - m_Last).TotalMilliseconds >= Global.Latency) { m_Last = Now; m_Blocked = true; m_Queued--; m_Device.HID_Command(HCI_Handle.Bytes, Get_SCID(L2CAP.PSM.HID_Command), m_Report); } } } } } } } <|start_filename|>Scp/ScpUser/stdafx.h<|end_filename|> #pragma once #define STRICT #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <commdlg.h> #include <XInput.h> #include <tchar.h> #include <stdio.h> #include "Resource.h" #define XINPUT_GAMEPAD_GUIDE 0x400 <|start_filename|>Shared/Windows/DeviceListener.cs<|end_filename|> using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; namespace Shared.Windows { public class DeviceListener { #region Class Constants // https://msdn.microsoft.com/en-us/library/aa363480(v=vs.85).aspx private const int DbtDeviceArrival = 0x8000; // system detected a new device private const int DbtDeviceRemoveComplete = 0x8004; // device is gone private const int DbtDevNodesChanged = 0x0007; // A device has been added to or removed from the system. private const int DbtDevtypDeviceinterface = 5; private const int WmDevicechange = 0x0219; // device change event message // https://msdn.microsoft.com/en-us/library/aa363431(v=vs.85).aspx private const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 4; // https://msdn.microsoft.com/en-us/library/windows/hardware/ff553426(v=vs.85).aspx public static readonly Guid GuidInterfaceUSB = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED"); public static readonly Guid GuidInterfaceHID = new Guid("745A17A0-74D3-11D0-B6FE-00A0C90f57DA"); public static readonly Guid GuidInterfaceBT = new Guid("E0CBF06C-CD8B-4647-BB8A-263B43F0F974"); #endregion public static DeviceListener Instance { get; private set; } public event Action OnDevicesUpdated; private IntPtr notificationHandle; static DeviceListener() { Instance = new DeviceListener(); } private DeviceListener() { } public void RegisterDeviceNotification(Window window, Guid deviceClass, bool usbOnly = false) { var source = HwndSource.FromHwnd(new WindowInteropHelper(window).Handle); source.AddHook(HwndHandler); IntPtr windowHandle = source.Handle; var deviceInterface = new DevBroadcastDeviceInterface { DeviceType = DbtDevtypDeviceinterface, Reserved = 0, ClassGuid = deviceClass, Name = 0 }; deviceInterface.Size = Marshal.SizeOf(deviceInterface); IntPtr buffer = Marshal.AllocHGlobal(deviceInterface.Size); Marshal.StructureToPtr(deviceInterface, buffer, true); notificationHandle = RegisterDeviceNotification(windowHandle, buffer, usbOnly ? 0 : DEVICE_NOTIFY_ALL_INTERFACE_CLASSES); } public void UnregisterDeviceNotification() { UnregisterDeviceNotification(notificationHandle); } private IntPtr HwndHandler(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled) { // Only checking changed event since it gets called when devices are added and removed // while remove notifications don't always get called. if (msg == WmDevicechange && (int)wparam == DbtDevNodesChanged) { OnDevicesUpdated?.Invoke(); } handled = false; return IntPtr.Zero; } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr RegisterDeviceNotification(IntPtr recipient, IntPtr notificationFilter, int flags); [DllImport("user32.dll")] private static extern bool UnregisterDeviceNotification(IntPtr handle); [StructLayout(LayoutKind.Sequential)] private struct DevBroadcastDeviceInterface { internal int Size; internal int DeviceType; internal int Reserved; internal Guid ClassGuid; internal short Name; } } } <|start_filename|>Scp/XInput_Scp/BTConnection.h<|end_filename|> #pragma once class CBTConnection : public CSCPController { public: DWORD CollectionSize; CBTConnection(void); virtual BOOL Open(); virtual BOOL Close(); virtual DWORD GetState(DWORD dwUserIndex, XINPUT_STATE* pState); virtual DWORD SetState(DWORD dwUserIndex, XINPUT_VIBRATION* pVibration); virtual DWORD GetExtended(DWORD dwUserIndex, SCP_EXTN* pPressure); // UNDOCUMENTED virtual DWORD GetStateEx(DWORD dwUserIndex, XINPUT_STATE *pState); protected: static const unsigned short ControlPort = 26760; static const unsigned short ReportPort = 26761; XINPUT_STATE m_padState [4]; XINPUT_VIBRATION m_padVibration [4]; SCP_EXTN m_Extended [4]; volatile bool m_bInited, m_bConnected; SOCKET m_Control; SOCKET m_Report; virtual void Report(DWORD dwUserIndex); virtual void XInputMapState(DWORD dwUserIndex, UCHAR* Buffer, UCHAR Model); virtual BOOL Read(UCHAR* Buffer); static void ReadThread(void *lpController); }; <|start_filename|>Scp/ScpBus/bus/pnp.c<|end_filename|> #include "busenum.h" #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE, Bus_AddDevice) #pragma alloc_text(PAGE, Bus_PnP) #pragma alloc_text(PAGE, Bus_PlugInDevice) #pragma alloc_text(PAGE, Bus_InitializePdo) #pragma alloc_text(PAGE, Bus_UnPlugDevice) #pragma alloc_text(PAGE, Bus_DestroyPdo) #pragma alloc_text(PAGE, Bus_RemoveFdo) #pragma alloc_text(PAGE, Bus_FDO_PnP) #pragma alloc_text(PAGE, Bus_StartFdo) #pragma alloc_text(PAGE, Bus_SendIrpSynchronously) #pragma alloc_text(PAGE, Bus_EjectDevice) #endif NTSTATUS Bus_AddDevice(__in PDRIVER_OBJECT DriverObject, __in PDEVICE_OBJECT PhysicalDeviceObject) { NTSTATUS status; PDEVICE_OBJECT deviceObject = NULL; PFDO_DEVICE_DATA deviceData = NULL; PWCHAR deviceName = NULL; ULONG nameLength; UNREFERENCED_PARAMETER(nameLength); PAGED_CODE(); Bus_KdPrint(("Add Device: 0x%p\n", PhysicalDeviceObject)); status = IoCreateDevice(DriverObject, sizeof(FDO_DEVICE_DATA), NULL, FILE_DEVICE_BUS_EXTENDER, FILE_DEVICE_SECURE_OPEN, TRUE, &deviceObject); if (!NT_SUCCESS (status)) { goto End; } deviceData = (PFDO_DEVICE_DATA) deviceObject->DeviceExtension; RtlZeroMemory(deviceData, sizeof (FDO_DEVICE_DATA)); INITIALIZE_PNP_STATE(deviceData); deviceData->IsFDO = TRUE; deviceData->Self = deviceObject; ExInitializeFastMutex(&deviceData->Mutex); InitializeListHead(&deviceData->ListOfPDOs); deviceData->UnderlyingPDO = PhysicalDeviceObject; deviceData->DevicePowerState = PowerDeviceUnspecified; deviceData->SystemPowerState = PowerSystemWorking; deviceData->OutstandingIO = 1; KeInitializeEvent(&deviceData->RemoveEvent, SynchronizationEvent, FALSE); KeInitializeEvent(&deviceData->StopEvent, SynchronizationEvent, TRUE); deviceObject->Flags |= DO_POWER_PAGABLE; status = IoRegisterDeviceInterface(PhysicalDeviceObject, (LPGUID) &GUID_DEVINTERFACE_SCPVBUS, NULL, &deviceData->InterfaceName); if (!NT_SUCCESS(status)) { Bus_KdPrint(("AddDevice: IoRegisterDeviceInterface failed (%x)", status)); goto End; } deviceData->NextLowerDriver = IoAttachDeviceToDeviceStack(deviceObject, PhysicalDeviceObject); if (deviceData->NextLowerDriver == NULL) { status = STATUS_NO_SUCH_DEVICE; goto End; } deviceObject->Flags &= ~DO_DEVICE_INITIALIZING; End: if (deviceName) { ExFreePool(deviceName); } if (!NT_SUCCESS(status) && deviceObject) { if (deviceData && deviceData->NextLowerDriver) { IoDetachDevice(deviceData->NextLowerDriver); } IoDeleteDevice(deviceObject); } return status; } NTSTATUS Bus_PnP(PDEVICE_OBJECT DeviceObject, PIRP Irp) { PIO_STACK_LOCATION irpStack; NTSTATUS status; PCOMMON_DEVICE_DATA commonData; PAGED_CODE(); irpStack = IoGetCurrentIrpStackLocation(Irp); ASSERT(IRP_MJ_PNP == irpStack->MajorFunction); commonData = (PCOMMON_DEVICE_DATA) DeviceObject->DeviceExtension; if (commonData->DevicePnPState == Deleted) { Irp->IoStatus.Status = status = STATUS_NO_SUCH_DEVICE ; IoCompleteRequest(Irp, IO_NO_INCREMENT); return status; } if (commonData->IsFDO) { Bus_KdPrint(("FDO %s IRP:0x%p\n", PnPMinorFunctionString(irpStack->MinorFunction), Irp)); status = Bus_FDO_PnP(DeviceObject, Irp, irpStack, (PFDO_DEVICE_DATA) commonData); } else { Bus_KdPrint(("PDO %s IRP: 0x%p\n", PnPMinorFunctionString(irpStack->MinorFunction), Irp)); status = Bus_PDO_PnP(DeviceObject, Irp, irpStack, (PPDO_DEVICE_DATA) commonData); } return status; } NTSTATUS Bus_FDO_PnP(__in PDEVICE_OBJECT DeviceObject, __in PIRP Irp, __in PIO_STACK_LOCATION IrpStack, __in PFDO_DEVICE_DATA DeviceData) { NTSTATUS status; ULONG length, prevcount, numPdosPresent, numPdosMissing; PLIST_ENTRY entry, listHead, nextEntry; PPDO_DEVICE_DATA pdoData; PDEVICE_RELATIONS relations, oldRelations; PAGED_CODE(); Bus_IncIoCount(DeviceData); switch (IrpStack->MinorFunction) { case IRP_MN_START_DEVICE: status = Bus_SendIrpSynchronously(DeviceData->NextLowerDriver, Irp); if (NT_SUCCESS(status)) { status = Bus_StartFdo (DeviceData, Irp); } Irp->IoStatus.Status = status; IoCompleteRequest (Irp, IO_NO_INCREMENT); Bus_DecIoCount(DeviceData); return status; case IRP_MN_QUERY_STOP_DEVICE: SET_NEW_PNP_STATE(DeviceData, StopPending); Irp->IoStatus.Status = STATUS_SUCCESS; break; case IRP_MN_CANCEL_STOP_DEVICE: if (StopPending == DeviceData->DevicePnPState) { RESTORE_PREVIOUS_PNP_STATE(DeviceData); ASSERT(DeviceData->DevicePnPState == Started); } Irp->IoStatus.Status = STATUS_SUCCESS; break; case IRP_MN_STOP_DEVICE: Bus_DecIoCount(DeviceData); KeWaitForSingleObject(&DeviceData->StopEvent, Executive, KernelMode, FALSE, NULL); Bus_IncIoCount(DeviceData); SET_NEW_PNP_STATE(DeviceData, Stopped); Irp->IoStatus.Status = STATUS_SUCCESS; break; case IRP_MN_QUERY_REMOVE_DEVICE: SET_NEW_PNP_STATE(DeviceData, RemovePending); Irp->IoStatus.Status = STATUS_SUCCESS; break; case IRP_MN_CANCEL_REMOVE_DEVICE: if (DeviceData->DevicePnPState == RemovePending) { RESTORE_PREVIOUS_PNP_STATE(DeviceData); } Irp->IoStatus.Status = STATUS_SUCCESS; break; case IRP_MN_SURPRISE_REMOVAL: SET_NEW_PNP_STATE(DeviceData, SurpriseRemovePending); Bus_RemoveFdo(DeviceData); ExAcquireFastMutex(&DeviceData->Mutex); { listHead = &DeviceData->ListOfPDOs; for(entry = listHead->Flink,nextEntry = entry->Flink; entry != listHead; entry = nextEntry, nextEntry = entry->Flink) { pdoData = CONTAINING_RECORD(entry, PDO_DEVICE_DATA, Link); RemoveEntryList(&pdoData->Link); InitializeListHead(&pdoData->Link); pdoData->ParentFdo = NULL; pdoData->ReportedMissing = TRUE; } } ExReleaseFastMutex(&DeviceData->Mutex); Irp->IoStatus.Status = STATUS_SUCCESS; break; case IRP_MN_REMOVE_DEVICE: if (DeviceData->DevicePnPState != SurpriseRemovePending) { Bus_RemoveFdo(DeviceData); } SET_NEW_PNP_STATE(DeviceData, Deleted); Bus_DecIoCount(DeviceData); Bus_DecIoCount(DeviceData); KeWaitForSingleObject(&DeviceData->RemoveEvent, Executive, KernelMode, FALSE, NULL); ExAcquireFastMutex(&DeviceData->Mutex); { listHead = &DeviceData->ListOfPDOs; for(entry = listHead->Flink,nextEntry = entry->Flink; entry != listHead; entry = nextEntry, nextEntry = entry->Flink) { pdoData = CONTAINING_RECORD(entry, PDO_DEVICE_DATA, Link); RemoveEntryList(&pdoData->Link); if (pdoData->DevicePnPState == SurpriseRemovePending) { Bus_KdPrint(("\tFound a surprise removed device: 0x%p\n", pdoData->Self)); InitializeListHead(&pdoData->Link); pdoData->ParentFdo = NULL; pdoData->ReportedMissing = TRUE; continue; } Bus_DestroyPdo(pdoData->Self, pdoData); } } ExReleaseFastMutex(&DeviceData->Mutex); Irp->IoStatus.Status = STATUS_SUCCESS; IoSkipCurrentIrpStackLocation(Irp); status = IoCallDriver(DeviceData->NextLowerDriver, Irp); IoDetachDevice(DeviceData->NextLowerDriver); Bus_KdPrint(("\tDeleting FDO: 0x%p\n", DeviceObject)); IoDeleteDevice(DeviceObject); return status; case IRP_MN_QUERY_DEVICE_RELATIONS: Bus_KdPrint(("\tQueryDeviceRelation Type: %s\n", DbgDeviceRelationString(IrpStack->Parameters.QueryDeviceRelations.Type))); if (IrpStack->Parameters.QueryDeviceRelations.Type != BusRelations) { break; } ExAcquireFastMutex(&DeviceData->Mutex); oldRelations = (PDEVICE_RELATIONS) Irp->IoStatus.Information; if (oldRelations) { prevcount = oldRelations->Count; if (!DeviceData->NumPDOs) { ExReleaseFastMutex(&DeviceData->Mutex); break; } } else { prevcount = 0; } numPdosPresent = 0; numPdosMissing = 0; for (entry = DeviceData->ListOfPDOs.Flink; entry != &DeviceData->ListOfPDOs; entry = entry->Flink) { pdoData = CONTAINING_RECORD(entry, PDO_DEVICE_DATA, Link); if (pdoData->Present) numPdosPresent++; } length = sizeof(DEVICE_RELATIONS) + ((numPdosPresent + prevcount) * sizeof (PDEVICE_OBJECT)) - 1; relations = (PDEVICE_RELATIONS) ExAllocatePoolWithTag(PagedPool, length, BUSENUM_POOL_TAG); if (relations == NULL) { ExReleaseFastMutex(&DeviceData->Mutex); Irp->IoStatus.Status = status = STATUS_INSUFFICIENT_RESOURCES; IoCompleteRequest(Irp, IO_NO_INCREMENT); Bus_DecIoCount(DeviceData); return status; } if (prevcount) { RtlCopyMemory(relations->Objects, oldRelations->Objects, prevcount * sizeof (PDEVICE_OBJECT)); } relations->Count = prevcount + numPdosPresent; for (entry = DeviceData->ListOfPDOs.Flink; entry != &DeviceData->ListOfPDOs; entry = entry->Flink) { pdoData = CONTAINING_RECORD(entry, PDO_DEVICE_DATA, Link); if (pdoData->Present) { relations->Objects[prevcount] = pdoData->Self; ObReferenceObject(pdoData->Self); prevcount++; } else { pdoData->ReportedMissing = TRUE; numPdosMissing++; } } Bus_KdPrint(("#PDOS Present = %d, Reported = %d, Missing = %d, Listed = %d", numPdosPresent, relations->Count, numPdosMissing, DeviceData->NumPDOs)); if (oldRelations) { ExFreePool(oldRelations); } Irp->IoStatus.Information = (ULONG_PTR) relations; ExReleaseFastMutex(&DeviceData->Mutex); Irp->IoStatus.Status = STATUS_SUCCESS; break; default: break; } IoSkipCurrentIrpStackLocation(Irp); status = IoCallDriver(DeviceData->NextLowerDriver, Irp); Bus_DecIoCount(DeviceData); return status; } NTSTATUS Bus_StartFdo(__in PFDO_DEVICE_DATA FdoData, __in PIRP Irp) { NTSTATUS status; POWER_STATE powerState; UNREFERENCED_PARAMETER(Irp); PAGED_CODE(); status = IoSetDeviceInterfaceState(&FdoData->InterfaceName, TRUE); if (!NT_SUCCESS (status)) { Bus_KdPrint(("IoSetDeviceInterfaceState failed: 0x%x\n", status)); return status; } FdoData->DevicePowerState = PowerDeviceD0; powerState.DeviceState = PowerDeviceD0; PoSetPowerState(FdoData->Self, DevicePowerState, powerState); SET_NEW_PNP_STATE(FdoData, Started); return status; } VOID Bus_RemoveFdo(__in PFDO_DEVICE_DATA FdoData) { PAGED_CODE(); if (FdoData->InterfaceName.Buffer != NULL) { IoSetDeviceInterfaceState(&FdoData->InterfaceName, FALSE); ExFreePool(FdoData->InterfaceName.Buffer); RtlZeroMemory(&FdoData->InterfaceName, sizeof(UNICODE_STRING)); } } NTSTATUS Bus_SendIrpSynchronously(__in PDEVICE_OBJECT DeviceObject, __in PIRP Irp) { KEVENT event; NTSTATUS status; PAGED_CODE(); KeInitializeEvent(&event, NotificationEvent, FALSE); IoCopyCurrentIrpStackLocationToNext(Irp); IoSetCompletionRoutine(Irp, Bus_CompletionRoutine, &event, TRUE, TRUE, TRUE); status = IoCallDriver(DeviceObject, Irp); if (status == STATUS_PENDING) { KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL); status = Irp->IoStatus.Status; } return status; } NTSTATUS Bus_CompletionRoutine(PDEVICE_OBJECT DeviceObject, PIRP Irp, PVOID Context) { UNREFERENCED_PARAMETER(DeviceObject); if (Irp->PendingReturned == TRUE) { KeSetEvent((PKEVENT) Context, IO_NO_INCREMENT, FALSE); } return STATUS_MORE_PROCESSING_REQUIRED; } NTSTATUS Bus_DestroyPdo(PDEVICE_OBJECT Device, PPDO_DEVICE_DATA PdoData) { PFDO_DEVICE_DATA fdoData; PAGED_CODE(); fdoData = FDO_FROM_PDO(PdoData); fdoData->NumPDOs--; if (PdoData->InterfaceName.Buffer != NULL) { ExFreePool(PdoData->InterfaceName.Buffer); RtlZeroMemory(&PdoData->InterfaceName, sizeof(UNICODE_STRING)); } if (PdoData->HardwareIDs) { ExFreePool(PdoData->HardwareIDs); PdoData->HardwareIDs = NULL; } Bus_KdPrint(("\tDeleting PDO: 0x%p\n", Device)); IoDeleteDevice(Device); return STATUS_SUCCESS; } VOID Bus_InitializePdo(__drv_in(__drv_aliasesMem) PDEVICE_OBJECT Pdo, PFDO_DEVICE_DATA FdoData) { PPDO_DEVICE_DATA pdoData; PAGED_CODE(); pdoData = (PPDO_DEVICE_DATA) Pdo->DeviceExtension; Bus_KdPrint(("PDO 0x%p, Extension 0x%p\n", Pdo, pdoData)); pdoData->IsFDO = FALSE; pdoData->Self = Pdo; pdoData->ParentFdo = FdoData->Self; pdoData->Present = TRUE; pdoData->ReportedMissing = FALSE; INITIALIZE_PNP_STATE(pdoData); pdoData->DevicePowerState = PowerDeviceD3; pdoData->SystemPowerState = PowerSystemWorking; Pdo->Flags |= DO_POWER_PAGABLE; KeInitializeSpinLock(&pdoData->PendingQueueLock); InitializeListHead (&pdoData->PendingQueue); InitializeListHead (&pdoData->HoldingQueue); ExAcquireFastMutex(&FdoData->Mutex); { InsertTailList(&FdoData->ListOfPDOs, &pdoData->Link); FdoData->NumPDOs++; } ExReleaseFastMutex(&FdoData->Mutex); Pdo->Flags &= ~DO_DEVICE_INITIALIZING; } NTSTATUS Bus_PlugInDevice(PBUSENUM_PLUGIN_HARDWARE PlugIn, ULONG PlugInSize, PFDO_DEVICE_DATA FdoData) { PDEVICE_OBJECT pdo; PPDO_DEVICE_DATA pdoData; NTSTATUS status; ULONG length; BOOLEAN unique; PLIST_ENTRY entry; PAGED_CODE(); length = (PlugInSize - sizeof(BUSENUM_PLUGIN_HARDWARE)) / sizeof(WCHAR); Bus_KdPrint(("Exposing PDO\n" "====== Serial : %d\n" "====== Device : %ws\n" "====== Length : %d\n", PlugIn->SerialNo, BUS_HARDWARE_IDS, BUS_HARDWARE_IDS_LENGTH)); unique = TRUE; ExAcquireFastMutex(&FdoData->Mutex); { for (entry = FdoData->ListOfPDOs.Flink; entry != &FdoData->ListOfPDOs; entry = entry->Flink) { pdoData = CONTAINING_RECORD(entry, PDO_DEVICE_DATA, Link); if (PlugIn->SerialNo == pdoData->SerialNo && pdoData->DevicePnPState != SurpriseRemovePending) { unique = FALSE; break; } } } ExReleaseFastMutex(&FdoData->Mutex); if (!unique || PlugIn->SerialNo == 0) return STATUS_INVALID_PARAMETER; length *= sizeof(WCHAR); Bus_KdPrint(("FdoData->NextLowerDriver = 0x%p\n", FdoData->NextLowerDriver)); status = IoCreateDeviceSecure(FdoData->Self->DriverObject, sizeof(PDO_DEVICE_DATA), NULL, FILE_DEVICE_BUS_EXTENDER, FILE_AUTOGENERATED_DEVICE_NAME | FILE_DEVICE_SECURE_OPEN, FALSE, &SDDL_DEVOBJ_SYS_ALL_ADM_RWX_WORLD_RWX_RES_RWX, (LPCGUID) &GUID_DEVCLASS_X360WIRED, &pdo); if (!NT_SUCCESS(status)) { return status; } pdoData = (PPDO_DEVICE_DATA) pdo->DeviceExtension; pdoData->HardwareIDs = ExAllocatePoolWithTag(NonPagedPool, BUS_HARDWARE_IDS_LENGTH, BUSENUM_POOL_TAG); if (pdoData->HardwareIDs == NULL) { IoDeleteDevice(pdo); return STATUS_INSUFFICIENT_RESOURCES; } RtlCopyMemory(pdoData->HardwareIDs, BUS_HARDWARE_IDS, BUS_HARDWARE_IDS_LENGTH); pdoData->SerialNo = PlugIn->SerialNo; Bus_InitializePdo(pdo, FdoData); IoInvalidateDeviceRelations(FdoData->UnderlyingPDO, BusRelations); return status; } NTSTATUS Bus_UnPlugDevice(PBUSENUM_UNPLUG_HARDWARE UnPlug, PFDO_DEVICE_DATA FdoData) { PLIST_ENTRY entry; PPDO_DEVICE_DATA pdoData; BOOLEAN found = FALSE, plugOutAll; PAGED_CODE(); plugOutAll = (UnPlug->SerialNo == 0); ExAcquireFastMutex(&FdoData->Mutex); if (plugOutAll) { Bus_KdPrint(("Plugging out all the devices!\n")); } else { Bus_KdPrint(("Plugging out %d\n", UnPlug->SerialNo)); } if (FdoData->NumPDOs == 0) { ExReleaseFastMutex(&FdoData->Mutex); return STATUS_NO_SUCH_DEVICE; } for (entry = FdoData->ListOfPDOs.Flink; entry != &FdoData->ListOfPDOs; entry = entry->Flink) { pdoData = CONTAINING_RECORD(entry, PDO_DEVICE_DATA, Link); Bus_KdPrint(("Found device %d\n", pdoData->SerialNo)); if (plugOutAll || UnPlug->SerialNo == pdoData->SerialNo) { Bus_KdPrint(("Plugged out %d\n", pdoData->SerialNo)); pdoData->Present = FALSE; found = TRUE; if (!plugOutAll) break; } } ExReleaseFastMutex(&FdoData->Mutex); if (found) { IoInvalidateDeviceRelations(FdoData->UnderlyingPDO, BusRelations); return STATUS_SUCCESS; } Bus_KdPrint(("Device %d is not present\n", UnPlug->SerialNo)); return STATUS_INVALID_PARAMETER; } NTSTATUS Bus_EjectDevice(PBUSENUM_EJECT_HARDWARE Eject, PFDO_DEVICE_DATA FdoData) { PLIST_ENTRY entry; PPDO_DEVICE_DATA pdoData; BOOLEAN found = FALSE, ejectAll; PAGED_CODE(); ejectAll = (Eject->SerialNo == 0); ExAcquireFastMutex(&FdoData->Mutex); if (ejectAll) { Bus_KdPrint(("Ejecting all the pdos!\n")); } else { Bus_KdPrint(("Ejecting %d\n", Eject->SerialNo)); } if (FdoData->NumPDOs == 0) { Bus_KdPrint(("No devices to eject!\n")); ExReleaseFastMutex(&FdoData->Mutex); return STATUS_NO_SUCH_DEVICE; } for (entry = FdoData->ListOfPDOs.Flink; entry != &FdoData->ListOfPDOs; entry = entry->Flink) { pdoData = CONTAINING_RECORD(entry, PDO_DEVICE_DATA, Link); Bus_KdPrint(("Found device %d\n", pdoData->SerialNo)); if (ejectAll || Eject->SerialNo == pdoData->SerialNo) { Bus_KdPrint(("Ejected %d\n", pdoData->SerialNo)); found = TRUE; IoRequestDeviceEject(pdoData->Self); if (!ejectAll) break; } } ExReleaseFastMutex(&FdoData->Mutex); if (found) { return STATUS_SUCCESS; } Bus_KdPrint(("Device %d is not present\n", Eject->SerialNo)); return STATUS_INVALID_PARAMETER; } #if DBG PCHAR PnPMinorFunctionString(UCHAR MinorFunction) { switch (MinorFunction) { case IRP_MN_START_DEVICE: return "IRP_MN_START_DEVICE"; case IRP_MN_QUERY_REMOVE_DEVICE: return "IRP_MN_QUERY_REMOVE_DEVICE"; case IRP_MN_REMOVE_DEVICE: return "IRP_MN_REMOVE_DEVICE"; case IRP_MN_CANCEL_REMOVE_DEVICE: return "IRP_MN_CANCEL_REMOVE_DEVICE"; case IRP_MN_STOP_DEVICE: return "IRP_MN_STOP_DEVICE"; case IRP_MN_QUERY_STOP_DEVICE: return "IRP_MN_QUERY_STOP_DEVICE"; case IRP_MN_CANCEL_STOP_DEVICE: return "IRP_MN_CANCEL_STOP_DEVICE"; case IRP_MN_QUERY_DEVICE_RELATIONS: return "IRP_MN_QUERY_DEVICE_RELATIONS"; case IRP_MN_QUERY_INTERFACE: return "IRP_MN_QUERY_INTERFACE"; case IRP_MN_QUERY_CAPABILITIES: return "IRP_MN_QUERY_CAPABILITIES"; case IRP_MN_QUERY_RESOURCES: return "IRP_MN_QUERY_RESOURCES"; case IRP_MN_QUERY_RESOURCE_REQUIREMENTS: return "IRP_MN_QUERY_RESOURCE_REQUIREMENTS"; case IRP_MN_QUERY_DEVICE_TEXT: return "IRP_MN_QUERY_DEVICE_TEXT"; case IRP_MN_FILTER_RESOURCE_REQUIREMENTS: return "IRP_MN_FILTER_RESOURCE_REQUIREMENTS"; case IRP_MN_READ_CONFIG: return "IRP_MN_READ_CONFIG"; case IRP_MN_WRITE_CONFIG: return "IRP_MN_WRITE_CONFIG"; case IRP_MN_EJECT: return "IRP_MN_EJECT"; case IRP_MN_SET_LOCK: return "IRP_MN_SET_LOCK"; case IRP_MN_QUERY_ID: return "IRP_MN_QUERY_ID"; case IRP_MN_QUERY_PNP_DEVICE_STATE: return "IRP_MN_QUERY_PNP_DEVICE_STATE"; case IRP_MN_QUERY_BUS_INFORMATION: return "IRP_MN_QUERY_BUS_INFORMATION"; case IRP_MN_DEVICE_USAGE_NOTIFICATION: return "IRP_MN_DEVICE_USAGE_NOTIFICATION"; case IRP_MN_SURPRISE_REMOVAL: return "IRP_MN_SURPRISE_REMOVAL"; case IRP_MN_QUERY_LEGACY_BUS_INFORMATION: return "IRP_MN_QUERY_LEGACY_BUS_INFORMATION"; default: return "unknown_pnp_irp"; } } PCHAR DbgDeviceRelationString(__in DEVICE_RELATION_TYPE Type) { switch (Type) { case BusRelations: return "BusRelations"; case EjectionRelations: return "EjectionRelations"; case RemovalRelations: return "RemovalRelations"; case TargetDeviceRelation: return "TargetDeviceRelation"; default: return "UnKnown Relation"; } } PCHAR DbgDeviceIDString(BUS_QUERY_ID_TYPE Type) { switch (Type) { case BusQueryDeviceID: return "BusQueryDeviceID"; case BusQueryHardwareIDs: return "BusQueryHardwareIDs"; case BusQueryCompatibleIDs: return "BusQueryCompatibleIDs"; case BusQueryInstanceID: return "BusQueryInstanceID"; case BusQueryDeviceSerialNumber: return "BusQueryDeviceSerialNumber"; case BusQueryContainerID: return "BusQueryContainerID"; default: return "UnKnown ID"; } } #endif <|start_filename|>Nintroller/Controllers/Nunchuk.cs<|end_filename|> using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace NintrollerLib { public struct Nunchuk : INintrollerState, IWiimoteExtension { public Wiimote wiimote { get; set; } public Accelerometer accelerometer; public Joystick joystick; public bool C, Z; public Nunchuk(Wiimote wm) { this = new Nunchuk(); wiimote = wm; } public Nunchuk(byte[] rawData) { wiimote = new Wiimote(rawData); accelerometer = new Accelerometer(); joystick = new Joystick(); C = Z = false; Update(rawData); } public void Update(byte[] data) { int offset = Utils.GetExtensionOffset((InputReport)data[0]); if (offset > 0) { // Buttons C = (data[offset + 5] & 0x02) == 0; Z = (data[offset + 5] & 0x01) == 0; // Joystick joystick.rawX = data[offset]; joystick.rawY = data[offset + 1]; // Accelerometer accelerometer.Parse(data, offset + 2); // Normalize joystick.Normalize(); accelerometer.Normalize(); } wiimote = new Wiimote(data, wiimote); } public float GetValue(string input) { switch (input) { case INPUT_NAMES.NUNCHUK.C: return C ? 1 : 0; case INPUT_NAMES.NUNCHUK.Z: return Z ? 1 : 0; case INPUT_NAMES.NUNCHUK.JOY_X: return joystick.X; case INPUT_NAMES.NUNCHUK.JOY_Y: return joystick.Y; case INPUT_NAMES.NUNCHUK.ACC_X: return accelerometer.X; case INPUT_NAMES.NUNCHUK.ACC_Y: return accelerometer.Y; case INPUT_NAMES.NUNCHUK.ACC_Z: return accelerometer.Z; case INPUT_NAMES.NUNCHUK.UP: return joystick.Y > 0 ? 1 : 0; case INPUT_NAMES.NUNCHUK.DOWN: return joystick.Y < 0 ? 1 : 0; case INPUT_NAMES.NUNCHUK.RIGHT: return joystick.X > 0 ? 1 : 0; case INPUT_NAMES.NUNCHUK.LEFT: return joystick.X < 0 ? 1 : 0; case INPUT_NAMES.NUNCHUK.FACE_UP: return accelerometer.Z > 0 ? 1 : 0; case INPUT_NAMES.NUNCHUK.FACE_DOWN: return accelerometer.Z < 0 ? 1 : 0; case INPUT_NAMES.NUNCHUK.TILT_UP: return accelerometer.Y > 0 ? 1 : 0; case INPUT_NAMES.NUNCHUK.TILT_DOWN: return accelerometer.Y < 0 ? 1 : 0; case INPUT_NAMES.NUNCHUK.TILT_RIGHT: return accelerometer.X > 0 ? 1 : 0; case INPUT_NAMES.NUNCHUK.TILT_LEFT: return accelerometer.X < 0 ? 1 : 0; } return wiimote.GetValue(input); } public void SetCalibration(Calibrations.CalibrationPreset preset) { wiimote.SetCalibration(preset); switch (preset) { case Calibrations.CalibrationPreset.Default: SetCalibration(Calibrations.Defaults.NunchukDefault); break; case Calibrations.CalibrationPreset.Modest: SetCalibration(Calibrations.Moderate.NunchukModest); break; case Calibrations.CalibrationPreset.Extra: SetCalibration(Calibrations.Extras.NunchukExtra); break; case Calibrations.CalibrationPreset.Minimum: SetCalibration(Calibrations.Minimum.NunchukMinimal); break; case Calibrations.CalibrationPreset.None: SetCalibration(Calibrations.None.NunchukRaw); break; } } public void SetCalibration(INintrollerState from) { if (from.CalibrationEmpty) { // don't apply empty calibrations return; } if (from.GetType() == typeof(Nunchuk)) { accelerometer.Calibrate(((Nunchuk)from).accelerometer); joystick.Calibrate(((Nunchuk)from).joystick); wiimote.SetCalibration(((Nunchuk)from).wiimote); } else if (from.GetType() == typeof(Wiimote)) { wiimote.SetCalibration(from); } } public void SetCalibration(string calibrationString) { if (calibrationString.Count(c => c == '0') > 5) { // don't set empty calibrations return; } string[] components = calibrationString.Split(new char[] { ':' }); foreach (string component in components) { if (component.StartsWith("joy")) { string[] joyConfig = component.Split(new char[] { '|' }); for (int j = 1; j < joyConfig.Length; j++) { int value = 0; if (int.TryParse(joyConfig[j], out value)) { switch (j) { case 1: joystick.centerX = value; break; case 2: joystick.minX = value; break; case 3: joystick.maxX = value; break; case 4: joystick.deadX = value; break; case 5: joystick.centerY = value; break; case 6: joystick.minY = value; break; case 7: joystick.maxY = value; break; case 8: joystick.deadY = value; break; default: break; } } } } else if (component.StartsWith("acc")) { string[] accConfig = component.Split(new char[] { '|' }); for (int a = 1; a < accConfig.Length; a++) { int value = 0; if (int.TryParse(accConfig[a], out value)) { switch (a) { case 1: accelerometer.centerX = value; break; case 2: accelerometer.minX = value; break; case 3: accelerometer.maxX = value; break; case 4: accelerometer.deadX = value; break; case 5: accelerometer.centerY = value; break; case 6: accelerometer.minY = value; break; case 7: accelerometer.maxY = value; break; case 8: accelerometer.deadY = value; break; case 9: accelerometer.centerZ = value; break; case 10: accelerometer.minZ = value; break; case 11: accelerometer.maxZ = value; break; case 12: accelerometer.deadZ = value; break; default: break; } } } } } } public string GetCalibrationString() { StringBuilder sb = new StringBuilder(); sb.Append("-nun"); sb.Append(":joy"); sb.Append("|"); sb.Append(joystick.centerX); sb.Append("|"); sb.Append(joystick.minX); sb.Append("|"); sb.Append(joystick.maxX); sb.Append("|"); sb.Append(joystick.deadX); sb.Append("|"); sb.Append(joystick.centerY); sb.Append("|"); sb.Append(joystick.minY); sb.Append("|"); sb.Append(joystick.maxY); sb.Append("|"); sb.Append(joystick.deadY); // TODO: Right now only WiinUSoft uses the calibration string and this doesn't include deadXp/Xn ect. // Not an issue right now since WiinUSoft doesn't use asymetric dead zones, // but this will need to be updated if anything else uses it or find another solution. sb.Append(":acc"); sb.Append("|"); sb.Append(accelerometer.centerX); sb.Append("|"); sb.Append(accelerometer.minX); sb.Append("|"); sb.Append(accelerometer.maxX); sb.Append("|"); sb.Append(accelerometer.deadX); sb.Append("|"); sb.Append(accelerometer.centerY); sb.Append("|"); sb.Append(accelerometer.minY); sb.Append("|"); sb.Append(accelerometer.maxY); sb.Append("|"); sb.Append(accelerometer.deadY); sb.Append("|"); sb.Append(accelerometer.centerZ); sb.Append("|"); sb.Append(accelerometer.minZ); sb.Append("|"); sb.Append(accelerometer.maxZ); sb.Append("|"); sb.Append(accelerometer.deadZ); return sb.ToString(); } public bool CalibrationEmpty { get { if (accelerometer.maxX == 0 && accelerometer.maxY == 0 && accelerometer.maxZ == 0) { return true; } else if (joystick.maxX == 0 && joystick.maxY == 0) { return true; } else { return false; } } } public IEnumerator<KeyValuePair<string, float>> GetEnumerator() { // Wiimote foreach (var input in wiimote) { yield return input; } // Buttons yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.C, C ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.Z, Z ? 1.0f : 0.0f); // Joystick joystick.Normalize(); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.JOY_X, joystick.X); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.JOY_Y, joystick.Y); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.UP, joystick.Y > 0 ? joystick.Y : 0); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.DOWN, joystick.Y > 0 ? 0 : -joystick.Y); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.LEFT, joystick.X > 0 ? 0 : -joystick.X); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.RIGHT, joystick.X > 0 ? joystick.X : 0); // Accelerometer accelerometer.Normalize(); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.ACC_X, accelerometer.X); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.ACC_Y, accelerometer.Y); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.ACC_Z, accelerometer.Z); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.TILT_LEFT, accelerometer.X > 0 ? 0 : -accelerometer.X); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.TILT_RIGHT, accelerometer.X > 0 ? accelerometer.X : 0); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.TILT_UP, accelerometer.Y > 0 ? accelerometer.Y : 0); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.TILT_DOWN, accelerometer.Y > 0 ? 0 : -accelerometer.Y); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.FACE_UP, accelerometer.Z > 0 ? accelerometer.Z : 0); yield return new KeyValuePair<string, float>(INPUT_NAMES.NUNCHUK.FACE_DOWN, accelerometer.Z > 0 ? 0 : -accelerometer.Z); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <|start_filename|>Scp/ScpServer/ScpForm.Designer.cs<|end_filename|> namespace ScpServer { partial class ScpForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.lvDebug = new System.Windows.Forms.ListView(); this.chTime = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.chData = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.tmrUpdate = new System.Windows.Forms.Timer(this.components); this.pnlButton = new System.Windows.Forms.Panel(); this.btnClear = new System.Windows.Forms.Button(); this.btnBoth = new System.Windows.Forms.Button(); this.btnPair = new System.Windows.Forms.Button(); this.btnOff = new System.Windows.Forms.Button(); this.btnRight = new System.Windows.Forms.Button(); this.btnLeft = new System.Windows.Forms.Button(); this.btnStop = new System.Windows.Forms.Button(); this.btnStart = new System.Windows.Forms.Button(); this.lblHost = new System.Windows.Forms.Label(); this.pnlDebug = new System.Windows.Forms.Panel(); this.pnlStatus = new System.Windows.Forms.Panel(); this.gpPads = new System.Windows.Forms.GroupBox(); this.rbPad_4 = new System.Windows.Forms.RadioButton(); this.rbPad_3 = new System.Windows.Forms.RadioButton(); this.rbPad_2 = new System.Windows.Forms.RadioButton(); this.rbPad_1 = new System.Windows.Forms.RadioButton(); this.rootHub = new ScpControl.RootHub(this.components); this.pnlButton.SuspendLayout(); this.pnlDebug.SuspendLayout(); this.pnlStatus.SuspendLayout(); this.gpPads.SuspendLayout(); this.SuspendLayout(); // // lvDebug // this.lvDebug.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.chTime, this.chData}); this.lvDebug.Dock = System.Windows.Forms.DockStyle.Fill; this.lvDebug.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lvDebug.FullRowSelect = true; this.lvDebug.Location = new System.Drawing.Point(0, 0); this.lvDebug.Name = "lvDebug"; this.lvDebug.Size = new System.Drawing.Size(769, 370); this.lvDebug.TabIndex = 0; this.lvDebug.UseCompatibleStateImageBehavior = false; this.lvDebug.View = System.Windows.Forms.View.Details; this.lvDebug.Enter += new System.EventHandler(this.lvDebug_Enter); // // chTime // this.chTime.Text = "Time"; this.chTime.Width = 200; // // chData // this.chData.Text = "Data"; this.chData.Width = 525; // // tmrUpdate // this.tmrUpdate.Tick += new System.EventHandler(this.tmrUpdate_Tick); // // pnlButton // this.pnlButton.Controls.Add(this.btnClear); this.pnlButton.Controls.Add(this.btnBoth); this.pnlButton.Controls.Add(this.btnPair); this.pnlButton.Controls.Add(this.btnOff); this.pnlButton.Controls.Add(this.btnRight); this.pnlButton.Controls.Add(this.btnLeft); this.pnlButton.Controls.Add(this.btnStop); this.pnlButton.Controls.Add(this.btnStart); this.pnlButton.Dock = System.Windows.Forms.DockStyle.Bottom; this.pnlButton.Location = new System.Drawing.Point(0, 476); this.pnlButton.Name = "pnlButton"; this.pnlButton.Size = new System.Drawing.Size(769, 35); this.pnlButton.TabIndex = 10; // // btnClear // this.btnClear.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnClear.Enabled = false; this.btnClear.Location = new System.Drawing.Point(520, 6); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(75, 23); this.btnClear.TabIndex = 9; this.btnClear.Text = "Clear"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); this.btnClear.Enter += new System.EventHandler(this.Button_Enter); // // btnBoth // this.btnBoth.Enabled = false; this.btnBoth.Location = new System.Drawing.Point(12, 6); this.btnBoth.Name = "btnBoth"; this.btnBoth.Size = new System.Drawing.Size(75, 23); this.btnBoth.TabIndex = 3; this.btnBoth.Text = "Both"; this.btnBoth.UseVisualStyleBackColor = true; this.btnBoth.Click += new System.EventHandler(this.btnMotor_Click); this.btnBoth.Enter += new System.EventHandler(this.Button_Enter); // // btnPair // this.btnPair.Enabled = false; this.btnPair.Location = new System.Drawing.Point(336, 6); this.btnPair.Name = "btnPair"; this.btnPair.Size = new System.Drawing.Size(75, 23); this.btnPair.TabIndex = 7; this.btnPair.Text = "Pair"; this.btnPair.UseVisualStyleBackColor = true; this.btnPair.Click += new System.EventHandler(this.btnPair_Click); this.btnPair.Enter += new System.EventHandler(this.Button_Enter); // // btnOff // this.btnOff.Enabled = false; this.btnOff.Location = new System.Drawing.Point(255, 6); this.btnOff.Name = "btnOff"; this.btnOff.Size = new System.Drawing.Size(75, 23); this.btnOff.TabIndex = 6; this.btnOff.Text = "Off"; this.btnOff.UseVisualStyleBackColor = true; this.btnOff.Click += new System.EventHandler(this.btnMotor_Click); this.btnOff.Enter += new System.EventHandler(this.Button_Enter); // // btnRight // this.btnRight.Enabled = false; this.btnRight.Location = new System.Drawing.Point(174, 6); this.btnRight.Name = "btnRight"; this.btnRight.Size = new System.Drawing.Size(75, 23); this.btnRight.TabIndex = 5; this.btnRight.Text = "Right"; this.btnRight.UseVisualStyleBackColor = true; this.btnRight.Click += new System.EventHandler(this.btnMotor_Click); this.btnRight.Enter += new System.EventHandler(this.Button_Enter); // // btnLeft // this.btnLeft.Enabled = false; this.btnLeft.Location = new System.Drawing.Point(93, 6); this.btnLeft.Name = "btnLeft"; this.btnLeft.Size = new System.Drawing.Size(75, 23); this.btnLeft.TabIndex = 4; this.btnLeft.Text = "Left"; this.btnLeft.UseVisualStyleBackColor = true; this.btnLeft.Click += new System.EventHandler(this.btnMotor_Click); this.btnLeft.Enter += new System.EventHandler(this.Button_Enter); // // btnStop // this.btnStop.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnStop.Enabled = false; this.btnStop.Location = new System.Drawing.Point(682, 6); this.btnStop.Name = "btnStop"; this.btnStop.Size = new System.Drawing.Size(75, 23); this.btnStop.TabIndex = 2; this.btnStop.Text = "Stop"; this.btnStop.UseVisualStyleBackColor = true; this.btnStop.Click += new System.EventHandler(this.btnStop_Click); this.btnStop.Enter += new System.EventHandler(this.Button_Enter); // // btnStart // this.btnStart.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnStart.Location = new System.Drawing.Point(601, 6); this.btnStart.Name = "btnStart"; this.btnStart.Size = new System.Drawing.Size(75, 23); this.btnStart.TabIndex = 1; this.btnStart.Text = "Start"; this.btnStart.UseVisualStyleBackColor = true; this.btnStart.Click += new System.EventHandler(this.btnStart_Click); this.btnStart.Enter += new System.EventHandler(this.Button_Enter); // // lblHost // this.lblHost.AutoSize = true; this.lblHost.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblHost.Location = new System.Drawing.Point(12, 9); this.lblHost.Name = "lblHost"; this.lblHost.Size = new System.Drawing.Size(119, 13); this.lblHost.TabIndex = 0; this.lblHost.Text = "Host Address :"; // // pnlDebug // this.pnlDebug.Controls.Add(this.lvDebug); this.pnlDebug.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlDebug.Location = new System.Drawing.Point(0, 106); this.pnlDebug.Name = "pnlDebug"; this.pnlDebug.Size = new System.Drawing.Size(769, 370); this.pnlDebug.TabIndex = 11; // // pnlStatus // this.pnlStatus.Controls.Add(this.gpPads); this.pnlStatus.Controls.Add(this.lblHost); this.pnlStatus.Dock = System.Windows.Forms.DockStyle.Top; this.pnlStatus.Location = new System.Drawing.Point(0, 0); this.pnlStatus.Name = "pnlStatus"; this.pnlStatus.Size = new System.Drawing.Size(769, 106); this.pnlStatus.TabIndex = 9; // // gpPads // this.gpPads.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.gpPads.Controls.Add(this.rbPad_4); this.gpPads.Controls.Add(this.rbPad_3); this.gpPads.Controls.Add(this.rbPad_2); this.gpPads.Controls.Add(this.rbPad_1); this.gpPads.Location = new System.Drawing.Point(300, -4); this.gpPads.Name = "gpPads"; this.gpPads.Size = new System.Drawing.Size(465, 104); this.gpPads.TabIndex = 1; this.gpPads.TabStop = false; // // rbPad_4 // this.rbPad_4.AutoSize = true; this.rbPad_4.Enabled = false; this.rbPad_4.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rbPad_4.Location = new System.Drawing.Point(6, 79); this.rbPad_4.Name = "rbPad_4"; this.rbPad_4.Size = new System.Drawing.Size(185, 17); this.rbPad_4.TabIndex = 3; this.rbPad_4.TabStop = true; this.rbPad_4.Text = "Pad 4 : Disconnected"; this.rbPad_4.UseVisualStyleBackColor = true; // // rbPad_3 // this.rbPad_3.AutoSize = true; this.rbPad_3.Enabled = false; this.rbPad_3.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rbPad_3.Location = new System.Drawing.Point(6, 56); this.rbPad_3.Name = "rbPad_3"; this.rbPad_3.Size = new System.Drawing.Size(185, 17); this.rbPad_3.TabIndex = 2; this.rbPad_3.TabStop = true; this.rbPad_3.Text = "Pad 3 : Disconnected"; this.rbPad_3.UseVisualStyleBackColor = true; // // rbPad_2 // this.rbPad_2.AutoSize = true; this.rbPad_2.Enabled = false; this.rbPad_2.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rbPad_2.Location = new System.Drawing.Point(6, 33); this.rbPad_2.Name = "rbPad_2"; this.rbPad_2.Size = new System.Drawing.Size(185, 17); this.rbPad_2.TabIndex = 1; this.rbPad_2.TabStop = true; this.rbPad_2.Text = "Pad 2 : Disconnected"; this.rbPad_2.UseVisualStyleBackColor = true; // // rbPad_1 // this.rbPad_1.AutoSize = true; this.rbPad_1.Enabled = false; this.rbPad_1.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rbPad_1.Location = new System.Drawing.Point(6, 10); this.rbPad_1.Name = "rbPad_1"; this.rbPad_1.Size = new System.Drawing.Size(185, 17); this.rbPad_1.TabIndex = 0; this.rbPad_1.TabStop = true; this.rbPad_1.Text = "Pad 1 : Disconnected"; this.rbPad_1.UseVisualStyleBackColor = true; // // rootHub // this.rootHub.Debug += new System.EventHandler<ScpControl.DebugEventArgs>(this.On_Debug); // // ScpForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(769, 511); this.Controls.Add(this.pnlDebug); this.Controls.Add(this.pnlButton); this.Controls.Add(this.pnlStatus); this.MinimumSize = new System.Drawing.Size(785, 550); this.Name = "ScpForm"; this.Text = "SCP Server"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form_Close); this.Load += new System.EventHandler(this.Form_Load); this.pnlButton.ResumeLayout(false); this.pnlDebug.ResumeLayout(false); this.pnlStatus.ResumeLayout(false); this.pnlStatus.PerformLayout(); this.gpPads.ResumeLayout(false); this.gpPads.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ListView lvDebug; private System.Windows.Forms.ColumnHeader chTime; private System.Windows.Forms.ColumnHeader chData; private System.Windows.Forms.Timer tmrUpdate; private System.Windows.Forms.Panel pnlButton; private System.Windows.Forms.Button btnBoth; private System.Windows.Forms.Button btnPair; private System.Windows.Forms.Button btnOff; private System.Windows.Forms.Button btnRight; private System.Windows.Forms.Button btnLeft; private System.Windows.Forms.Button btnStop; private System.Windows.Forms.Button btnStart; private System.Windows.Forms.Label lblHost; private System.Windows.Forms.Panel pnlDebug; private System.Windows.Forms.Panel pnlStatus; private System.Windows.Forms.GroupBox gpPads; private System.Windows.Forms.RadioButton rbPad_4; private System.Windows.Forms.RadioButton rbPad_3; private System.Windows.Forms.RadioButton rbPad_2; private System.Windows.Forms.RadioButton rbPad_1; private System.Windows.Forms.Button btnClear; private ScpControl.RootHub rootHub; } } <|start_filename|>Scp/ScpPair/Properties/AssemblyInfo.cs<|end_filename|> using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ScpPair")] [assembly: AssemblyProduct("ScpPair")] [assembly: Guid("359e2b03-d7dd-48a2-893f-4ece5bd91258")] <|start_filename|>Nintroller/Controllers/Guitar.cs<|end_filename|> using System.Collections; using System.Collections.Generic; using System.Text; namespace NintrollerLib { public struct Guitar : INintrollerState, IWiimoteExtension { public Wiimote wiimote { get; set; } public bool Green, Red, Yellow, Blue, Orange; public bool StrumUp, StrumDown; public bool Minus, Plus; public Joystick joystick; public Trigger whammyBar; public byte touchBar; public bool T1, T2, T3, T4, T5; // Touch Frets public void Update(byte[] data) { // http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Guitar_Hero_(Wii)_Guitars // Byte 0: bits 0-5 = joy X // Byte 1: bits 0-5 = joy Y // Byte 2: bits 0-4 = touch // Byte 3: bits 0-4 = whammy // Byte 4: bit 2 = Plus, bit 4 = Minus, bit 6 = Strum Down // Byte 5: bit 0 = Strum Up, bit 3 = yellow // bit 4 = green, bit 5 = blue // bit 6 = red, bit 7 = orange int offset = Utils.GetExtensionOffset((InputReport)data[0]); if (offset > 0) { joystick.rawX = data[offset ] & 0x3F; joystick.rawY = data[offset + 1] & 0x3F; touchBar = (byte)(data[offset + 2] & 0x1F); whammyBar.rawValue = (byte)(data[offset + 3] & 0x1F); Plus = (data[offset + 4] & 0x04) == 0; Minus = (data[offset + 4] & 0x10) == 0; StrumDown = (data[offset + 4] & 0x40) == 0; StrumUp = (data[offset + 5] & 0x01) == 0; Yellow = (data[offset + 5] & 0x08) == 0; Green = (data[offset + 5] & 0x10) == 0; Blue = (data[offset + 5] & 0x20) == 0; Red = (data[offset + 5] & 0x40) == 0; Orange = (data[offset + 5] & 0x80) == 0; switch (touchBar) { default: case 0x0F: T1 = T2 = T3 = T4 = T5 = false; break; case 0x04: T1 = true; T2 = T3 = T4 = T5 = false; break; case 0x07: T1 = T2 = true; T3 = T4 = T5 = false; break; case 0x0A: T2 = true; T1 = T3 = T4 = T5 = false; break; case 0x0C: case 0x0D: T2 = T3 = true; T1 = T4 = T5 = false; break; case 0x12: case 0x13: T3 = true; T1 = T2 = T4 = T5 = false; break; case 0x14: case 0x15: T3 = T4 = true; T1 = T2 = T5 = false; break; case 0x17: case 0x18: T4 = true; T1 = T2 = T3 = T5 = false; break; case 0x1A: T4 = T5 = true; T1 = T2 = T3 = false; break; case 0x1F: T5 = true; T1 = T2 = T3 = T4 = false; break; } joystick.Normalize(); whammyBar.Normalize(); whammyBar.full = whammyBar.rawValue >= whammyBar.max; } wiimote = new Wiimote(data, wiimote); } public float GetValue(string input) { switch (input) { case INPUT_NAMES.GUITAR.GREEN: return Green ? 1 : 0; case INPUT_NAMES.GUITAR.RED: return Red ? 1 : 0; case INPUT_NAMES.GUITAR.YELLOW: return Yellow ? 1 : 0; case INPUT_NAMES.GUITAR.BLUE: return Blue ? 1 : 0; case INPUT_NAMES.GUITAR.ORANGE: return Orange ? 1 : 0; case INPUT_NAMES.GUITAR.MINUS: return Minus ? 1 : 0; case INPUT_NAMES.GUITAR.PLUS: return Plus ? 1 : 0; case INPUT_NAMES.GUITAR.TOUCH_1: return T1 ? 1 : 0; case INPUT_NAMES.GUITAR.TOUCH_2: return T2 ? 1 : 0; case INPUT_NAMES.GUITAR.TOUCH_3: return T3 ? 1 : 0; case INPUT_NAMES.GUITAR.TOUCH_4: return T4 ? 1 : 0; case INPUT_NAMES.GUITAR.TOUCH_5: return T5 ? 1 : 0; case INPUT_NAMES.GUITAR.STRUM_UP: return StrumUp ? 1 : 0; case INPUT_NAMES.GUITAR.STRUM_DOWN: return StrumDown ? 1 : 0; case INPUT_NAMES.GUITAR.JOY_X: return joystick.X; case INPUT_NAMES.GUITAR.JOY_Y: return joystick.Y; case INPUT_NAMES.GUITAR.UP: return joystick.Y > 0 ? 1 : 0; case INPUT_NAMES.GUITAR.DOWN: return joystick.Y < 0 ? 1 : 0; case INPUT_NAMES.GUITAR.LEFT: return joystick.X < 0 ? 1 : 0; case INPUT_NAMES.GUITAR.RIGHT: return joystick.X > 0 ? 1 : 0; case INPUT_NAMES.GUITAR.WHAMMY: return whammyBar.value > 0 ? 1 : 0; case INPUT_NAMES.GUITAR.WHAMMY_BAR: return whammyBar.value; case INPUT_NAMES.GUITAR.WHAMMY_FULL: return whammyBar.value >= whammyBar.max ? 1 : 0; } return wiimote.GetValue(input); } public void SetCalibration(Calibrations.CalibrationPreset preset) { wiimote.SetCalibration(preset); switch (preset) { case Calibrations.CalibrationPreset.Default: SetCalibration(Calibrations.Defaults.GuitarDefault); break; case Calibrations.CalibrationPreset.Minimum: SetCalibration(Calibrations.Minimum.GuitarMinimal); break; case Calibrations.CalibrationPreset.Modest: SetCalibration(Calibrations.Moderate.GuitarModest); break; case Calibrations.CalibrationPreset.Extra: SetCalibration(Calibrations.Extras.GuitarExtra); break; case Calibrations.CalibrationPreset.None: SetCalibration(Calibrations.None.GuitarRaw); break; } } public void SetCalibration(INintrollerState from) { if (from.CalibrationEmpty) { return; } if (from.GetType() == typeof(Guitar)) { joystick.Calibrate(((Guitar)from).joystick); whammyBar.Calibrate(((Guitar)from).whammyBar); wiimote.SetCalibration(((Guitar)from).wiimote); } else if (from.GetType() == typeof(Wiimote)) { wiimote.SetCalibration(from); } } public void SetCalibration(string calibrationString) { string[] components = calibrationString.Split(new char[] { ':' }); foreach (string component in components) { if (component.StartsWith("joy")) { string[] joyConfig = component.Split(new char[] { '|' }); for (int j = 1; j < joyConfig.Length; j++) { int value = 0; if (int.TryParse(joyConfig[j], out value)) { switch (j) { case 1: joystick.centerX = value; break; case 2: joystick.minX = value; break; case 3: joystick.maxX = value; break; case 4: joystick.deadX = value; break; case 5: joystick.centerY = value; break; case 6: joystick.minY = value; break; case 7: joystick.maxY = value; break; case 8: joystick.deadY = value; break; default: break; } } } } else if (component.StartsWith("t")) { string[] triggerConfig = component.Split(new char[] { '|' }); for (int t = 1; t < triggerConfig.Length; t++) { int value = 0; if (int.TryParse(triggerConfig[t], out value)) { switch (t) { case 1: whammyBar.min = value; break; case 2: whammyBar.max = value; break; } } } } } } public string GetCalibrationString() { StringBuilder sb = new StringBuilder(); sb.Append("-gut"); sb.Append(":joy"); sb.Append("|"); sb.Append(joystick.centerX); sb.Append("|"); sb.Append(joystick.minX); sb.Append("|"); sb.Append(joystick.maxX); sb.Append("|"); sb.Append(joystick.deadX); sb.Append("|"); sb.Append(joystick.centerY); sb.Append("|"); sb.Append(joystick.minY); sb.Append("|"); sb.Append(joystick.maxY); sb.Append("|"); sb.Append(joystick.deadY); sb.Append(":t"); sb.Append("|"); sb.Append(whammyBar.min); sb.Append("|"); sb.Append(whammyBar.max); return sb.ToString(); } public bool CalibrationEmpty { get { if (joystick.maxX == 0 && joystick.maxY == 0) { return true; } return false; } } public IEnumerator<KeyValuePair<string, float>> GetEnumerator() { foreach (var input in wiimote) { yield return input; } // Frets & Buttons yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.GREEN, Green ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.RED, Red ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.YELLOW, Yellow ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.BLUE, Blue ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.ORANGE, Orange ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.STRUM_UP, StrumUp ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.STRUM_DOWN, StrumDown ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.PLUS, Plus ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.MINUS, Minus ? 1.0f : 0.0f); // Joystick joystick.Normalize(); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.JOY_X, joystick.X); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.JOY_Y, joystick.Y); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.UP, joystick.Y > 0 ? joystick.Y : 0); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.DOWN, joystick.Y > 0 ? 0 : -joystick.Y); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.LEFT, joystick.X > 0 ? 0 : -joystick.X); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.RIGHT, joystick.X > 0 ? joystick.X : 0); // Whammy whammyBar.Normalize(); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.WHAMMY, whammyBar.value > 0 ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.WHAMMY_FULL, whammyBar.rawValue >= whammyBar.max ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.WHAMMY_BAR, whammyBar.value); // Touch Frets yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.TOUCH_1, T1 ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.TOUCH_2, T2 ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.TOUCH_3, T3 ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.TOUCH_4, T4 ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.GUITAR.TOUCH_5, T5 ? 1.0f : 0.0f); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <|start_filename|>Scp/ScpServer/Properties/AssemblyInfo.cs<|end_filename|> using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ScpServer")] [assembly: AssemblyProduct("ScpServer")] [assembly: Guid("a52b5b20-d9ee-4f32-8518-307fa14aa0c6")] <|start_filename|>WiinUPro/Windows/JoyCalibrationWindow.xaml.cs<|end_filename|> using Shared; using System; using System.Windows; using System.Windows.Controls; using NintrollerLib; namespace WiinUPro.Windows { /// <summary> /// Interaction logic for JoyCalibrationWindow.xaml /// </summary> public partial class JoyCalibrationWindow : Window { public bool Apply { get; protected set; } public Joystick Calibration { get { return _joystick; } } public string FileName { get; protected set; } protected int rawXCenter, rawYCenter; protected short rawXLimitMax, rawXLimitMin, rawYLimitMax, rawYLimitMin; protected short rawXDeadMax, rawXDeadMin, rawYDeadMax, rawYDeadMin; protected Joystick _joystick; protected Joystick _default; public string[] Assignments { get; protected set; } public JoyCalibrationWindow(Joystick noneCalibration, Joystick prevCalibration, string filename = "") { _default = noneCalibration; FileName = filename; InitializeComponent(); Set(prevCalibration); } private void Window_Loaded(object sender, RoutedEventArgs e) { Globalization.ApplyTranslations(this); } private void CenterXUpdated(int x) { rawXCenter = x; } private void CenterYUpdated(int y) { rawYCenter = y; } private void LimitsUpdated(int obj) { if (limitYPos == null || limitYNeg == null) return; if (limitXPos == null || limitXNeg == null) return; // Calculate Points var top = 500 - limitYPos.Value * 5; var left = 500 - limitXNeg.Value * 5; var bottom = 500 + limitYNeg.Value * 5; var right = 500 + limitXPos.Value * 5; // Adjust Points of the circle limitQ1Arc.Point = new Point(500, top); limitQ2Arc.Point = new Point(left, 500); limitQ3Arc.Point = new Point(500, bottom); limitQ4Arc.Point = new Point(right, 500); limitQ1Path.StartPoint = new Point(right, 500); // Adjust Radii limitQ1Arc.Size = new Size(right - 500, 500 - top); limitQ2Arc.Size = new Size(500 - left, 500 - top); limitQ3Arc.Size = new Size(500 - left, bottom - 500); limitQ4Arc.Size = new Size(right - 500, bottom - 500); } private void DeadzoneUpdated(int ignore) { if (deadYPos == null || deadYNeg == null) return; if (deadXPos == null || deadXNeg == null) return; // Calculate Points var top = 500 - Math.Max(deadYPos.Value, 1) * 5; var left = 500 - Math.Max(deadXNeg.Value, 1) * 5; var bottom = 500 + Math.Max(deadYNeg.Value, 1) * 5; var right = 500 + Math.Max(deadXPos.Value, 1) * 5; // Adjust Points of the circle deadQ1Arc.Point = new Point(500, top); deadQ2Arc.Point = new Point(left, 500); deadQ3Arc.Point = new Point(500, bottom); deadQ4Arc.Point = new Point(right, 500); deadQ1Path.StartPoint = new Point(right, 500); // Adjust Radii deadQ1Arc.Size = new Size(right - 500, 500 - top); deadQ2Arc.Size = new Size(500 - left, 500 - top); deadQ3Arc.Size = new Size(500 - left, bottom - 500); deadQ4Arc.Size = new Size(right - 500, bottom - 500); // Square rawDeadzoneSqr.Width = Math.Max((deadXPos.Value + deadXNeg.Value) * 5, 1); rawDeadzoneSqr.Height = Math.Max((deadYPos.Value + deadYNeg.Value) * 5, 1); rawDeadzoneSqr.Margin = new Thickness(600 - Math.Max(deadXNeg.Value * 5, 1), 600 - Math.Max(deadYPos.Value * 5, 1), 0, 0); } public void Update(Joystick joy) { // Display Raw Value (no deadzone & expected limits) Joystick rawDisplay = new Joystick(); rawDisplay.Calibrate(_default); rawDisplay.rawX = joy.rawX; rawDisplay.rawY = joy.rawY; rawDisplay.centerX = _default.centerX + rawXCenter; rawDisplay.centerY = _default.centerY + rawYCenter; rawDisplay.Normalize(); Canvas.SetLeft(raw, 500 * rawDisplay.X + 500 - raw.Width / 2); Canvas.SetTop(raw, -500 * rawDisplay.Y + 500 - raw.Height / 2); // Apply Center joy.centerX = _default.centerX + rawXCenter; joy.centerY = _default.centerY + rawYCenter; // Apply Limits joy.maxX = (int)Math.Round((_default.maxX - _default.centerX) * (limitXPos.Value / 100d)) + _default.centerX; joy.minX = _default.centerX - (int)Math.Round((_default.centerX - _default.minX) * (limitXNeg.Value / 100d)); joy.maxY = (int)Math.Round((_default.maxY - _default.centerY) * (limitYPos.Value / 100d)) + _default.centerX; joy.minY = _default.centerY - (int)Math.Round((_default.centerY - _default.minY) * (limitYNeg.Value / 100d)); // Apply Deadzone (not symetrical) joy.deadXp = (int)Math.Round((_default.maxX - _default.centerX) * (deadXPos.Value / 100d)); joy.deadXn = -(int)Math.Round((_default.maxX - _default.centerX) * (deadXNeg.Value / 100d)); joy.deadYp = (int)Math.Round((_default.maxY - _default.centerY) * (deadYPos.Value / 100d)); joy.deadYn = -(int)Math.Round((_default.maxY - _default.centerY) * (deadYNeg.Value / 100d)); joy.Normalize(); // Apply Anti Deadzone var anti = (float)antiDeadzoneSlider.Value / 100f; if (joy.X != 0) { var xRange = 1f - anti; joy.X = joy.X * xRange + anti * Math.Sign(joy.X); } if (joy.Y != 0) { var yRange = 1f - anti; joy.Y = joy.Y * yRange + anti * Math.Sign(joy.Y); } // Display Output Canvas.SetTop(@out, joy.Y * -500 + 500 - @out.Height / 2); Canvas.SetLeft(@out, joy.X * 500 + 500 - @out.Width / 2); xLabel.Content = string.Format("X: {0}%", Math.Round(joy.X * 100)); yLabel.Content = string.Format("Y: {0}%", Math.Round(joy.Y * 100)); } public void Set(Joystick prevCalibration) { centerX.Value = prevCalibration.centerX - _default.centerX; centerY.Value = prevCalibration.centerY - _default.centerY; limitXPos.Value = (int)Math.Round((prevCalibration.maxX - _default.centerX) / (double)(_default.maxX - _default.centerX) * 100d); limitXNeg.Value = (int)Math.Round((_default.centerX - prevCalibration.minX) / (double)(_default.centerX - _default.minX) * 100d); limitYPos.Value = (int)Math.Round((prevCalibration.maxY - _default.centerY) / (double)(_default.maxY - _default.centerY) * 100d); limitYNeg.Value = (int)Math.Round((_default.centerY - prevCalibration.minY) / (double)(_default.centerY - _default.minY) * 100d); deadXPos.Value = (int)Math.Round(prevCalibration.deadXp / (double)(_default.maxX - _default.centerX) * 100d); deadXNeg.Value = -(int)Math.Round(prevCalibration.deadXn / (double)(_default.centerX - _default.minX) * 100d); deadYPos.Value = (int)Math.Round(prevCalibration.deadYp / (double)(_default.maxY - _default.centerY) * 100d); deadYNeg.Value = -(int)Math.Round(prevCalibration.deadYn / (double)(_default.centerY - _default.minX) * 100d); antiDeadzoneSlider.Value = Math.Round(prevCalibration.antiDeadzone * 10); } protected void Convert() { _joystick = new Joystick(); _joystick.centerX = _default.centerX + rawXCenter; _joystick.centerY = _default.centerY + rawYCenter; _joystick.maxX = (int)Math.Round((_default.maxX - _default.centerX) * (limitXPos.Value / 100d) + _default.centerX); _joystick.minX = (int)Math.Round(_default.centerX - (_default.centerX - _default.minX) * (limitXNeg.Value / 100d)); _joystick.maxY = (int)Math.Round((_default.maxY - _default.centerY) * (limitYPos.Value / 100d) + _default.centerY); _joystick.minY = (int)Math.Round(_default.centerY - (_default.centerY - _default.minY) * (limitYNeg.Value / 100d)); _joystick.deadXp = (int)Math.Round((_default.maxX - _default.centerX) * (deadXPos.Value / 100d)); _joystick.deadXn = -(int)Math.Round((_default.maxX - _default.centerX) * (deadXNeg.Value / 100d)); _joystick.deadYp = (int)Math.Round((_default.maxY - _default.centerY) * (deadYPos.Value / 100d)); _joystick.deadYn = -(int)Math.Round((_default.maxY - _default.centerY) * (deadYNeg.Value / 100d)); _joystick.antiDeadzone = (float)antiDeadzoneSlider.Value / 10f; } private void antiDeadzoneSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { antiDeadzone.Height = antiDeadzone.Width = e.NewValue * 10; Canvas.SetTop(antiDeadzone, 500 - antiDeadzone.Height / 2); Canvas.SetLeft(antiDeadzone, 500 - antiDeadzone.Width / 2); antiDeadzoneLabel.Content = e.NewValue.ToString() + " %"; } private void acceptBtn_Click(object sender, RoutedEventArgs e) { Convert(); Apply = true; Close(); } private void cancelBtn_Click(object sender, RoutedEventArgs e) { Close(); } private void saveBtn_Click(object sender, RoutedEventArgs e) { Convert(); Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog(); dialog.FileName = string.IsNullOrEmpty(FileName) ? "joystick_calibration" : FileName; dialog.DefaultExt = ".joy"; dialog.Filter = App.JOY_CAL_FILTER; bool? doSave = dialog.ShowDialog(); if (doSave == true) { if (App.SaveToFile<Joystick>(dialog.FileName, _joystick)) { FileName = dialog.FileName; } } } private void loadBtn_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog(); dialog.FileName = string.IsNullOrEmpty(FileName) ? "joystick_calibration" : FileName; dialog.DefaultExt = ".joy"; dialog.Filter = App.JOY_CAL_FILTER; bool? doLoad = dialog.ShowDialog(); Joystick loadedConfig; if (doLoad == true && dialog.CheckFileExists) { if (App.LoadFromFile<Joystick>(dialog.FileName, out loadedConfig)) { FileName = dialog.FileName; Set(loadedConfig); } else { MessageBox.Show( Globalization.TranslateFormat("Calibration_Load_Error_Msg", dialog.FileName), Globalization.Translate("Calibration_Load_Error"), MessageBoxButton.OK, MessageBoxImage.Error); } } } } } <|start_filename|>Nintroller/Controllers/ClassicController.cs<|end_filename|> using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace NintrollerLib { public struct ClassicController : INintrollerState, IWiimoteExtension { public Wiimote wiimote { get; set; } public Joystick LJoy, RJoy; public Trigger L, R; public bool A, B, X, Y; public bool Up, Down, Left, Right; public bool ZL, ZR, LFull, RFull; public bool Plus, Minus, Home; public ClassicController(Wiimote wm) { this = new ClassicController(); wiimote = wm; } public bool Start { get { return Plus; } set { Plus = value; } } public bool Select { get { return Minus; } set { Minus = value; } } public void Update(byte[] data) { int offset = Utils.GetExtensionOffset((InputReport)data[0]); if (offset > 0) { // Buttons A = (data[offset + 5] & 0x10) == 0; B = (data[offset + 5] & 0x40) == 0; X = (data[offset + 5] & 0x08) == 0; Y = (data[offset + 5] & 0x20) == 0; LFull = (data[offset + 4] & 0x20) == 0; // Until the Click RFull = (data[offset + 4] & 0x02) == 0; // Until the Click ZL = (data[offset + 5] & 0x80) == 0; ZR = (data[offset + 5] & 0x04) == 0; Plus = (data[offset + 4] & 0x04) == 0; Minus = (data[offset + 4] & 0x10) == 0; Home = (data[offset + 4] & 0x08) == 0; // Dpad Up = (data[offset + 5] & 0x01) == 0; Down = (data[offset + 4] & 0x40) == 0; Left = (data[offset + 5] & 0x02) == 0; Right = (data[offset + 4] & 0x80) == 0; // Joysticks LJoy.rawX = (byte)(data[offset] & 0x3F); LJoy.rawY = (byte)(data[offset + 1] & 0x3F); RJoy.rawX = (byte)(data[offset + 2] >> 7 | (data[offset + 1] & 0xC0) >> 5 | (data[offset] & 0xC0) >> 3); RJoy.rawY = (byte)(data[offset + 2] & 0x1F); // Triggers L.rawValue = (byte)(((data[offset + 2] & 0x60) >> 2) | (data[offset + 3] >> 5)); R.rawValue = (byte)(data[offset + 3] & 0x1F); L.full = LFull; R.full = RFull; // Normalize LJoy.Normalize(); RJoy.Normalize(); L.Normalize(); R.Normalize(); } wiimote = new Wiimote(data, wiimote); } public float GetValue(string input) { switch (input) { case INPUT_NAMES.CLASSIC_CONTROLLER.A: return A ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.B: return B ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.X: return X ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.Y: return Y ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.UP: return Up ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.DOWN: return Down ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.LEFT: return Left ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.RIGHT: return Right ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.L: return L.value > 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.R: return R.value > 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.ZL: return ZL ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.ZR: return ZR ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.LX: return LJoy.X; case INPUT_NAMES.CLASSIC_CONTROLLER.LY: return LJoy.Y; case INPUT_NAMES.CLASSIC_CONTROLLER.RX: return RJoy.X; case INPUT_NAMES.CLASSIC_CONTROLLER.RY: return RJoy.Y; case INPUT_NAMES.CLASSIC_CONTROLLER.LUP: return LJoy.Y > 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.LDOWN: return LJoy.Y < 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.LLEFT: return LJoy.X < 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.LRIGHT: return LJoy.X > 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.RUP: return RJoy.Y > 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.RDOWN: return RJoy.Y < 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.RLEFT: return RJoy.X < 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.RRIGHT: return RJoy.X > 0 ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.LT: return L.value; case INPUT_NAMES.CLASSIC_CONTROLLER.RT: return R.value; case INPUT_NAMES.CLASSIC_CONTROLLER.LFULL: return L.full ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.RFULL: return R.full ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.SELECT: return Select ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.START: return Start ? 1 : 0; case INPUT_NAMES.CLASSIC_CONTROLLER.HOME: return Home ? 1 : 0; } return wiimote.GetValue(input); } public void SetCalibration(Calibrations.CalibrationPreset preset) { wiimote.SetCalibration(preset); switch (preset) { case Calibrations.CalibrationPreset.Default: //LJoy.Calibrate(Calibrations.Defaults.ClassicControllerDefault.LJoy); //RJoy.Calibrate(Calibrations.Defaults.ClassicControllerDefault.RJoy); //L.Calibrate(Calibrations.Defaults.ClassicControllerDefault.L); //R.Calibrate(Calibrations.Defaults.ClassicControllerDefault.R); SetCalibration(Calibrations.Defaults.ClassicControllerDefault); break; case Calibrations.CalibrationPreset.Modest: SetCalibration(Calibrations.Moderate.ClassicControllerModest); break; case Calibrations.CalibrationPreset.Extra: SetCalibration(Calibrations.Extras.ClassicControllerExtra); break; case Calibrations.CalibrationPreset.Minimum: SetCalibration(Calibrations.Minimum.ClassicControllerMinimal); break; case Calibrations.CalibrationPreset.None: SetCalibration(Calibrations.None.ClassicControllerRaw); break; } } public void SetCalibration(INintrollerState from) { if (from.CalibrationEmpty) { // don't apply empty calibrations return; } if (from.GetType() == typeof(ClassicController)) { LJoy.Calibrate(((ClassicController)from).LJoy); RJoy.Calibrate(((ClassicController)from).RJoy); L.Calibrate(((ClassicController)from).L); R.Calibrate(((ClassicController)from).R); } else if (from.GetType() == typeof(Wiimote)) { wiimote.SetCalibration(from); } } public void SetCalibration(string calibrationString) { if (calibrationString.Count(c => c == '0') > 5) { // don't set empty calibrations return; } string[] components = calibrationString.Split(new char[] { ':' }); foreach (string component in components) { if (component.StartsWith("joyL")) { string[] joyLConfig = component.Split(new char[] { '|' }); for (int jL = 1; jL < joyLConfig.Length; jL++) { int value = 0; if (int.TryParse(joyLConfig[jL], out value)) { switch (jL) { case 1: LJoy.centerX = value; break; case 2: LJoy.minX = value; break; case 3: LJoy.maxX = value; break; case 4: LJoy.deadX = value; break; case 5: LJoy.centerY = value; break; case 6: LJoy.minY = value; break; case 7: LJoy.maxY = value; break; case 8: LJoy.deadY = value; break; default: break; } } } } else if (component.StartsWith("joyR")) { string[] joyRConfig = component.Split(new char[] { '|' }); for (int jR = 1; jR < joyRConfig.Length; jR++) { int value = 0; if (int.TryParse(joyRConfig[jR], out value)) { switch (jR) { case 1: RJoy.centerX = value; break; case 2: RJoy.minX = value; break; case 3: RJoy.maxX = value; break; case 4: RJoy.deadX = value; break; case 5: RJoy.centerY = value; break; case 6: RJoy.minY = value; break; case 7: RJoy.maxY = value; break; case 8: RJoy.deadY = value; break; default: break; } } } } else if (component.StartsWith("tl")) { string[] triggerLConfig = component.Split(new char[] { '|' }); for (int tl = 1; tl < triggerLConfig.Length; tl++) { int value = 0; if (int.TryParse(triggerLConfig[tl], out value)) { switch (tl) { case 1: L.min = value; break; case 2: L.max = value; break; default: break; } } } } else if (component.StartsWith("tr")) { string[] triggerRConfig = component.Split(new char[] { '|' }); for (int tr = 1; tr < triggerRConfig.Length; tr++) { int value = 0; if (int.TryParse(triggerRConfig[tr], out value)) { switch (tr) { case 1: R.min = value; break; case 2: R.max = value; break; default: break; } } } } } } public string GetCalibrationString() { StringBuilder sb = new StringBuilder(); sb.Append("-cla"); sb.Append(":joyL"); sb.Append("|"); sb.Append(LJoy.centerX); sb.Append("|"); sb.Append(LJoy.minX); sb.Append("|"); sb.Append(LJoy.maxX); sb.Append("|"); sb.Append(LJoy.deadX); sb.Append("|"); sb.Append(LJoy.centerY); sb.Append("|"); sb.Append(LJoy.minY); sb.Append("|"); sb.Append(LJoy.maxY); sb.Append("|"); sb.Append(LJoy.deadY); sb.Append(":joyR"); sb.Append("|"); sb.Append(RJoy.centerX); sb.Append("|"); sb.Append(RJoy.minX); sb.Append("|"); sb.Append(RJoy.maxX); sb.Append("|"); sb.Append(RJoy.deadX); sb.Append("|"); sb.Append(RJoy.centerY); sb.Append("|"); sb.Append(RJoy.minY); sb.Append("|"); sb.Append(RJoy.maxY); sb.Append("|"); sb.Append(RJoy.deadY); sb.Append(":tl"); sb.Append("|"); sb.Append(L.min); sb.Append("|"); sb.Append(L.max); sb.Append(":tr"); sb.Append("|"); sb.Append(R.min); sb.Append("|"); sb.Append(R.max); return sb.ToString(); } public bool CalibrationEmpty { get { if (LJoy.maxX == 0 && LJoy.maxY == 0 && RJoy.maxX == 0 && RJoy.maxY == 0) { return true; } else { return false; } } } public IEnumerator<KeyValuePair<string, float>> GetEnumerator() { // Wiimote foreach (var input in wiimote) { yield return input; } yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.A, A ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.B, B ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.X, X ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.Y, Y ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.ZL, ZL ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.ZR, ZR ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.UP, Up ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.DOWN, Down ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.LEFT, Left ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.RIGHT, Right ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.START, Start ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.SELECT, Select ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.HOME, Home ? 1.0f : 0.0f); L.Normalize(); R.Normalize(); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.L, L.value > 0 ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.R, R.value > 0 ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.LFULL, L.full ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.RFULL, R.full ? 1.0f : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.LT, L.value); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.RT, R.value); LJoy.Normalize(); RJoy.Normalize(); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.LX, LJoy.X); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.LY, LJoy.Y); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.RX, RJoy.X); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.RY, RJoy.Y); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.LUP, LJoy.Y > 0f ? LJoy.Y : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.LDOWN, LJoy.Y > 0f ? 0.0f : -LJoy.Y); // These are inverted yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.LLEFT, LJoy.X > 0f ? 0.0f : -LJoy.X); // because they yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.LRIGHT, LJoy.X > 0f ? LJoy.X : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.RUP, RJoy.Y > 0f ? RJoy.Y : 0.0f); yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.RDOWN, RJoy.Y > 0f ? 0.0f : -RJoy.Y); // represents how far the yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.RLEFT, RJoy.X > 0f ? 0.0f : -RJoy.X); // input is left or down yield return new KeyValuePair<string, float>(INPUT_NAMES.CLASSIC_CONTROLLER.RRIGHT, RJoy.X > 0f ? RJoy.X : 0.0f); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <|start_filename|>Scp/Clean.cmd<|end_filename|> @echo OFF pushd "%~dp0.." rmdir /S /Q "Source\ScpControl\obj" rmdir /S /Q "Source\ScpInstaller\bin" rmdir /S /Q "Source\ScpInstaller\obj" rmdir /S /Q "Source\ScpMonitor\bin" rmdir /S /Q "Source\ScpMonitor\obj" rmdir /S /Q "Source\ScpPair\bin" rmdir /S /Q "Source\ScpPair\obj" rmdir /S /Q "Source\ScpServer\bin" rmdir /S /Q "Source\ScpServer\obj" rmdir /S /Q "Source\ScpService\bin" rmdir /S /Q "Source\ScpService\obj" rmdir /S /Q "Source\ScpUser\Build" rmdir /S /Q "Source\XInput_Scp\Build" rmdir /S /Q "Source\ipch" rmdir /S /Q "Sample\D3Mapper\bin" rmdir /S /Q "Sample\D3Mapper\obj" rmdir /S /Q "Sample\DskMapper\bin" rmdir /S /Q "Sample\DskMapper\obj" rmdir /S /Q "Sample\GtaMapper\bin" rmdir /S /Q "Sample\GtaMapper\obj" rmdir /S /Q "Source\ScpBus\bus\objchk_win7_amd64" rmdir /S /Q "Source\ScpBus\bus\objchk_win7_x86" rmdir /S /Q "Source\ScpBus\bus\objfre_win7_amd64" rmdir /S /Q "Source\ScpBus\bus\objfre_win7_x86" del /S /Q "*.sdf" del /S /Q "*.user" del /S /Q "*.log" del /S /Q "*.aps" del /S /Q /A:H "*.suo" del /S /Q "CommonInfo.cs" del /S /Q "Scp_All.ico" pushd bin del /S /Q "*.pdb" del /S /Q "*.lib" del /S /Q "*.exp" del /S /Q "*.exe.metagen" del /S /Q "*.vshost.exe" del /S /Q "*.vshost.exe.config" del /S /Q "*.vshost.exe.manifest" popd popd <|start_filename|>WiinUPro/Controls/JoyConLControl.xaml.cs<|end_filename|> using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using SharpDX.DirectInput; namespace WiinUPro { /// <summary> /// Interaction logic for JoyConLControl.xaml /// </summary> public partial class JoyConLControl : BaseControl, IJoyControl { public Guid AssociatedInstanceID { get; set; } public JoyConLControl() { InitializeComponent(); } public void UpdateVisual(JoystickUpdate[] updates) { foreach (var update in updates) { switch (update.Offset) { case JoystickOffset.Buttons0: leftBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons1: downBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons2: upBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons3: rightBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons4: slBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons5: srBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons8: minusBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons10: joyStickButton.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons13: shareBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons14: lBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.Buttons15: zlBtn.Opacity = update.Value > 0 ? 1 : 0; break; case JoystickOffset.PointOfViewControllers0: var margin = new Thickness(185, 599, 0, 0); if (update.Value == -1) { // nothing } else if (update.Value == 0) { margin.Left += 30; } else if (update.Value > 0 && update.Value < 9000) { margin.Left += 20; margin.Top += 20; } else if (update.Value == 9000) { margin.Top += 30; } else if (update.Value > 9000 && update.Value < 18000) { margin.Top += 20; margin.Left -= 20; } else if (update.Value == 18000) { margin.Left -= 30; } else if (update.Value > 18000 && update.Value < 27000) { margin.Left -= 20; margin.Top -= 20; } else if (update.Value == 27000) { margin.Top -= 30; } else if (update.Value > 27000) { margin.Top -= 20; margin.Left += 20; } joyStick.Margin = margin; joyStickButton.Margin = margin; break; } } } public void SetInputTooltip(string inputName, string tooltip) { if (Enum.TryParse(inputName, out JoystickOffset input)) { switch (input) { case JoystickOffset.Buttons0: leftBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons1: downBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons2: upBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons3: rightBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons4: slBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons5: srBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons8: minusBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons10: UpdateTooltipLine(joyStickButton, tooltip, 4); break; case JoystickOffset.Buttons13: shareBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons14: lBtn.ToolTip = tooltip; break; case JoystickOffset.Buttons15: zlBtn.ToolTip = tooltip; break; } } else { switch (inputName) { case "pov0N": UpdateTooltipLine(joyStickButton, tooltip, 2); break; case "pov0W": UpdateTooltipLine(joyStickButton, tooltip, 0); break; case "pov0E": UpdateTooltipLine(joyStickButton, tooltip, 3); break; case "pov0S": UpdateTooltipLine(joyStickButton, tooltip, 1); break; } } } public void ClearTooltips() { string unsetText = Shared.Globalization.Translate("Input_Unset"); leftBtn.ToolTip = unsetText; downBtn.ToolTip = unsetText; upBtn.ToolTip = unsetText; rightBtn.ToolTip = unsetText; slBtn.ToolTip = unsetText; srBtn.ToolTip = unsetText; minusBtn.ToolTip = unsetText; shareBtn.ToolTip = unsetText; UpdateTooltipLine(joyStickButton, unsetText, 0); UpdateTooltipLine(joyStickButton, unsetText, 1); UpdateTooltipLine(joyStickButton, unsetText, 2); UpdateTooltipLine(joyStickButton, unsetText, 3); UpdateTooltipLine(joyStickButton, unsetText, 4); } protected void SetupMenuForPad() { int i = 0; for (; i < 5; ++i) { (_analogMenu.Items[i] as Control).Visibility = Visibility.Visible; } for (; i < 13; ++i) { (_analogMenu.Items[i] as Control).Visibility = Visibility.Collapsed; } } protected virtual void OpenPadMenu(object sender, MouseButtonEventArgs e) { var item = sender as FrameworkElement; if (item != null) { _menuOwnerTag = item.Tag as string; SetupMenuForPad(); _analogMenuInput = _inputPrefix + (item.Tag as string); _analogMenu.IsOpen = true; } } protected override void OpenSelectedInput(object sender, RoutedEventArgs e) { string input = (sender as FrameworkElement)?.Tag?.ToString(); // Convert analog input names switch (input) { case "UP": input = "pov0W"; break; case "LEFT": input = "pov0S"; break; case "RIGHT": input = "pov0N"; break; case "DOWN": input = "pov0E"; break; case "S": input = "Buttons10"; break; } CallEvent_OnInputSelected(input); } protected override void CalibrateInput(string inputName) { // TODO } } } <|start_filename|>Scp/XInput_Scp/XInput_SCP.h<|end_filename|> #pragma once extern BOOL LoadApi(BOOL bEnable); typedef struct { float SCP_UP; float SCP_RIGHT; float SCP_DOWN; float SCP_LEFT; float SCP_LX; float SCP_LY; float SCP_L1; float SCP_L2; float SCP_L3; float SCP_RX; float SCP_RY; float SCP_R1; float SCP_R2; float SCP_R3; float SCP_T; float SCP_C; float SCP_X; float SCP_S; float SCP_SELECT; float SCP_START; float SCP_PS; } SCP_EXTN; DWORD WINAPI XInputGetExtended(DWORD dwUserIndex, SCP_EXTN* pPressure); <|start_filename|>Scp/ScpInstaller/Properties/AssemblyInfo.cs<|end_filename|> using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ScpDriver")] [assembly: AssemblyProduct("ScpDriver")] [assembly: Guid("57ba2291-9504-441d-a0fe-9ccdd326508c")] <|start_filename|>Scp/ScpControl/UsbDs3.cs<|end_filename|> using System; using System.ComponentModel; namespace ScpControl { public partial class UsbDs3 : UsbDevice { public static String USB_CLASS_GUID = "{E2824A09-DBAA-4407-85CA-C8E8FF5F6FFA}"; protected Byte[] m_Leds = { 0x02, 0x04, 0x08, 0x10 }; protected Byte[] m_Enable = { 0x42, 0x0C, 0x00, 0x00 }; protected Byte[] m_Report = { 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; public override DsPadId PadId { get { return (DsPadId) m_ControllerId; } set { m_ControllerId = (Byte) value; m_ReportArgs.Pad = PadId; m_Report[9] = m_Leds[m_ControllerId]; } } public UsbDs3() : base(USB_CLASS_GUID) { InitializeComponent(); } public UsbDs3(IContainer container) : base(USB_CLASS_GUID) { container.Add(this); InitializeComponent(); } public override Boolean Open(String DevicePath) { if (base.Open(DevicePath)) { m_State = DsState.Reserved; GetDeviceInstance(ref m_Instance); Int32 Transfered = 0; if (SendTransfer(0xA1, 0x01, 0x03F5, m_Buffer, ref Transfered)) { m_Master = new Byte[] { m_Buffer[2], m_Buffer[3], m_Buffer[4], m_Buffer[5], m_Buffer[6], m_Buffer[7] }; } if (SendTransfer(0xA1, 0x01, 0x03F2, m_Buffer, ref Transfered)) { m_Local = new Byte[] { m_Buffer[4], m_Buffer[5], m_Buffer[6], m_Buffer[7], m_Buffer[8], m_Buffer[9] }; } m_Mac = String.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}", m_Local[0], m_Local[1], m_Local[2], m_Local[3], m_Local[4], m_Local[5]); } return State == DsState.Reserved; } public override Boolean Start() { m_Model = (Byte) DsModel.DS3; if (IsActive) { Int32 Transfered = 0; if (SendTransfer(0x21, 0x09, 0x03F4, m_Enable, ref Transfered)) { base.Start(); } } return State == DsState.Connected; } public override Boolean Rumble(Byte Large, Byte Small) { lock (this) { Int32 Transfered = 0; if (Global.DisableRumble) { m_Report[2] = 0; m_Report[4] = 0; } else { m_Report[2] = (Byte)(Small > 0 ? 0x01 : 0x00); m_Report[4] = (Byte)(Large); } m_Report[9] = (Byte)(Global.DisableLED ? 0 : m_Leds[m_ControllerId]); return SendTransfer(0x21, 0x09, 0x0201, m_Report, ref Transfered); } } public override Boolean Pair(Byte[] Master) { Int32 Transfered = 0; Byte[] Buffer = { 0x00, 0x00, Master[0], Master[1], Master[2], Master[3], Master[4], Master[5] }; if (SendTransfer(0x21, 0x09, 0x03F5, Buffer, ref Transfered)) { for (Int32 Index = 0; Index < m_Master.Length; Index++) { m_Master[Index] = Master[Index]; } LogDebug(String.Format("++ Paired DS3 [{0}] To BTH Dongle [{1}]", Local, Remote)); return true; } LogDebug(String.Format("++ Pair Failed [{0}]", Local)); return false; } protected override void Parse(Byte[] Report) { if (Report[0] != 0x01) return; m_Packet++; m_ReportArgs.Report[2] = m_BatteryStatus = Report[30]; m_ReportArgs.Report[4] = (Byte)(m_Packet >> 0 & 0xFF); m_ReportArgs.Report[5] = (Byte)(m_Packet >> 8 & 0xFF); m_ReportArgs.Report[6] = (Byte)(m_Packet >> 16 & 0xFF); m_ReportArgs.Report[7] = (Byte)(m_Packet >> 24 & 0xFF); Ds3Button Buttons = (Ds3Button)((Report[2] << 0) | (Report[3] << 8) | (Report[4] << 16) | (Report[5] << 24)); Boolean Trigger = false; if ((Buttons & Ds3Button.L1) == Ds3Button.L1 && (Buttons & Ds3Button.R1) == Ds3Button.R1 && (Buttons & Ds3Button.PS) == Ds3Button.PS ) { Trigger = true; Report[4] ^= 0x1; } for (int Index = 8; Index < 57; Index++) { m_ReportArgs.Report[Index] = Report[Index - 8]; } if (Trigger && !m_IsDisconnect) { m_IsDisconnect = true; m_Disconnect = DateTime.Now; } else if (!Trigger && m_IsDisconnect) { m_IsDisconnect = false; } Publish(); } protected override void Process(DateTime Now) { lock (this) { if (m_IsDisconnect) { if ((Now - m_Disconnect).TotalMilliseconds >= 2000) { LogDebug("++ Quick Disconnect Triggered"); Shutdown(); return; } } if ((Now - m_Last).TotalMilliseconds >= 1500 && m_Packet > 0) { Int32 Transfered = 0; m_Last = Now; if (Battery == DsBattery.Charging) { m_Report[9] ^= m_Leds[m_ControllerId]; } else { m_Report[9] |= m_Leds[m_ControllerId]; } if (Global.DisableLED) m_Report[9] = 0; SendTransfer(0x21, 0x09, 0x0201, m_Report, ref Transfered); } } } } } <|start_filename|>Scp/Lilypad/Config.cpp<|end_filename|> #include "Global.h" #include "resource.h" #include "InputManager.h" #include "Config.h" #include "Diagnostics.h" #include "DeviceEnumerator.h" #include "KeyboardQueue.h" #include "WndProcEater.h" #include "DualShock3.h" // Needed to know if raw input is available. It requires XP or higher. #include "RawInput.h" GeneralConfig config; // 1 if running inside a PS2 emulator. Set to 1 on any // of the PS2-specific functions (PS2EgetLibVersion2, PS2EgetLibType). // Only affects if I allow read input in GS thread to be set. // Also disables usage of AutoAnalog mode if in PS2 mode. u8 ps2e = 0; HWND hWndProp = 0; int selected = 0; // Older versions of PCSX2 don't always create the ini dir on startup, so LilyPad does it // for it. But if PCSX2 sets the ini path with a call to setSettingsDir, then it means // we shouldn't make our own. bool createIniDir = true; HWND hWnds[2][4]; HWND hWndGeneral = 0; struct GeneralSettingsBool { wchar_t *name; unsigned int ControlId; u8 defaultValue; }; // Ties together config data structure, config files, and general config // dialog. const GeneralSettingsBool BoolOptionsInfo[] = { {L"Force Cursor Hide", IDC_FORCE_HIDE, 0}, {L"Mouse Unfocus", IDC_MOUSE_UNFOCUS, 1}, {L"Background", IDC_BACKGROUND, 1}, {L"Multiple Bindings", IDC_MULTIPLE_BINDING, 0}, {L"DirectInput Game Devices", IDC_G_DI, 1}, {L"XInput", IDC_G_XI, 1}, {L"DualShock 3", IDC_G_DS3, 0}, {L"Multitap 1", IDC_MULTITAP1, 0}, {L"Multitap 2", IDC_MULTITAP2, 0}, {L"Escape Fullscreen Hack", IDC_ESCAPE_FULLSCREEN_HACK, 1}, {L"Disable Screen Saver", IDC_DISABLE_SCREENSAVER, 1}, {L"Logging", IDC_DEBUG_FILE, 0}, {L"Save State in Title", IDC_SAVE_STATE_TITLE, 0}, //No longer required, PCSX2 now handles it - avih 2011-05-17 {L"GH2", IDC_GH2_HACK, 0}, {L"Turbo Key Hack", IDC_TURBO_KEY_HACK, 0}, {L"Vista Volume", IDC_VISTA_VOLUME, 1}, }; void Populate(int port, int slot); void SetupLogSlider(HWND hWndSlider) { SendMessage(hWndSlider, TBM_SETRANGEMIN, 0, 1); SendMessage(hWndSlider, TBM_SETPAGESIZE, 0, 1<<13); SendMessage(hWndSlider, TBM_SETRANGEMAX, 1, 1<<22); SendMessage(hWndSlider, TBM_SETTIC, 0, 1<<21); SendMessage(hWndSlider, TBM_SETTIC, 0, 1<<20); SendMessage(hWndSlider, TBM_SETTIC, 0, 3<<20); } int GetLogSliderVal(HWND hWnd, int id) { HWND hWndSlider = GetDlgItem(hWnd, id); int val = SendMessage(hWndSlider, TBM_GETPOS, 0, 0); if (val <= (1<<21)) { val = (val+16) >> 5; } else { double v = (val - (1<<21))/(double)((1<<22)- (1<<21)); double max = log((double)(1<<23)); double min = log((double)BASE_SENSITIVITY); v = v*(max-min)+min; // exp is not implemented in ntdll, so use pow instead. // More than accurate enough for my needs. // v = exp(v); v = pow(2.7182818284590451, v); if (v > (1<<23)) v = (1<<23); val = (int)floor(v+0.5); } if (!val) val = 1; if (IsDlgButtonChecked(hWnd, id+1) == BST_CHECKED) { val = -val; } return val; } void SetLogSliderVal(HWND hWnd, int id, HWND hWndText, int val) { HWND hWndSlider = GetDlgItem(hWnd, id); int sliderPos = 0; wchar_t temp[30]; EnableWindow(hWndSlider, val != 0); EnableWindow(hWndText, val != 0); EnableWindow(GetDlgItem(hWnd, id+1), val != 0); if (!val) val = BASE_SENSITIVITY; CheckDlgButton(hWnd, id+1, BST_CHECKED * (val<0)); if (val < 0) { val = -val; } if (val <= BASE_SENSITIVITY) { sliderPos = val<<5; } else { double max = log((double)(1<<23)); double min = log((double)BASE_SENSITIVITY); double v = log((double)(val)); v = (v-min)/(max-min); v = ((1<<22)- (1<<21)) *v + (1<<21); // _ftol sliderPos = (int)(floor(v+0.5)); } SendMessage(hWndSlider, TBM_SETPOS, 1, sliderPos); int val2 = (int)(1000*(__int64)val/BASE_SENSITIVITY); wsprintfW(temp, L"%i.%03i", val2/1000, val2%1000); SetWindowTextW(hWndText, temp); } void RefreshEnabledDevices(int updateDeviceList) { // Clears all device state. static int lastXInputState = -1; if (updateDeviceList || lastXInputState != config.gameApis.xInput) { EnumDevices(config.gameApis.xInput); lastXInputState = config.gameApis.xInput; } for (int i=0; i<dm->numDevices; i++) { Device *dev = dm->devices[i]; if (!dev->attached && dev->displayName[0] != '[') { wchar_t *newName = (wchar_t*) malloc(sizeof(wchar_t) * (wcslen(dev->displayName) + 12)); wsprintfW(newName, L"[Detached] %s", dev->displayName); free(dev->displayName); dev->displayName = newName; } if ((dev->type == KEYBOARD && dev->api == IGNORE_KEYBOARD) || (dev->type == KEYBOARD && dev->api == config.keyboardApi) || (dev->type == MOUSE && dev->api == config.mouseApi) || (dev->type == OTHER && ((dev->api == DI && config.gameApis.directInput) || (dev->api == DS3 && config.gameApis.dualShock3) || (dev->api == XINPUT && config.gameApis.xInput)))) { if (config.gameApis.dualShock3 && dev->api == DI && dev->displayName && !wcsicmp(dev->displayName, L"DX PLAYSTATION(R)3 Controller")) { dm->DisableDevice(i); } else { dm->EnableDevice(i); } } else { dm->DisableDevice(i); } } } // Disables/enables devices as necessary. Also updates diagnostic list // and pad1/pad2 bindings lists, depending on params. Also updates device // list, if indicated. // Must be called at some point when entering config mode, as I disable // (non-keyboard/mice) devices with no active bindings when the emulator's running. void RefreshEnabledDevicesAndDisplay(int updateDeviceList = 0, HWND hWnd = 0, int populate=0) { RefreshEnabledDevices(updateDeviceList); if (hWnd) { HWND hWndList = GetDlgItem(hWnd, IDC_LIST); ListView_SetExtendedListViewStyleEx(hWndList, LVS_EX_DOUBLEBUFFER, LVS_EX_DOUBLEBUFFER); int count = ListView_GetItemCount(hWndList); LVITEM item; item.iItem = 0; item.iSubItem = 0; item.mask = LVIF_TEXT | LVIF_PARAM; for (int j=0; j<dm->numDevices; j++) { if (dm->devices[j]->enabled && dm->devices[j]->api != IGNORE_KEYBOARD) { item.lParam = j; item.pszText = dm->devices[j]->displayName; if (count > 0) { ListView_SetItem(hWndList, &item); count --; } else { ListView_InsertItem(hWndList, &item); } item.iItem++; } } // This way, won't scroll list to start. while(count > 0) { ListView_DeleteItem(hWndList, item.iItem); count --; } } if (populate) { for (int i=0; i<8; i++) { Populate(i&1, i>>1); } } } wchar_t *GetCommandStringW(u8 command, int port, int slot) { static wchar_t temp[34]; if (command >= 0x20 && command <= 0x27) { if (config.padConfigs[port][slot].type == GuitarPad && (command == 0x20 || command == 0x22)) { HWND hWnd = GetDlgItem(hWnds[port][slot], 0x10F0+command); int res = GetWindowTextW(hWnd, temp, 20); if ((unsigned int)res-1 <= 18) return temp; } static wchar_t stick[2] = {'L', 'R'}; static wchar_t *dir[] = { L"Up", L"Right", L"Down", L"Left"}; wsprintfW(temp, L"%c-Stick %s", stick[(command-0x20)/4], dir[command & 3]); return temp; } /* Get text from the buttons. */ if (command >= 0x0C && command <=0x28) { HWND hWnd = GetDlgItem(hWnds[port][slot], 0x10F0+command); if (!hWnd) { wchar_t *strings[] = { L"Lock Buttons", L"Lock Input", L"Lock Direction", L"Mouse", L"Select", L"L3", L"R3", L"Start", L"Up", L"Right", L"Down", L"Left", L"L2", L"R2", L"L1", L"R1", L"Triangle", L"Circle", L"Square", L"Cross", L"L-Stick Up", L"L-Stick Right", L"L-Stick Down", L"L-Stick Left", L"R-Stick Up", L"R-Stick Right", L"R-Stick Down", L"R-Stick Left", L"Analog", }; return strings[command - 0xC]; } int res = GetWindowTextW(hWnd, temp, 20); if ((unsigned int)res-1 <= 18) return temp; } else if (command == 0x7F) { return L"Ignore Key"; } return L""; } static wchar_t iniFile[MAX_PATH*2] = L"inis/LilyPad.ini"; void CALLBACK PADsetSettingsDir( const char *dir ) { //swprintf_s( iniFile, L"%S", (dir==NULL) ? "inis" : dir ); //uint targlen = MultiByteToWideChar(CP_ACP, 0, dir, -1, NULL, 0); MultiByteToWideChar(CP_ACP, 0, dir, -1, iniFile, MAX_PATH*2); wcscat_s(iniFile, L"/LilyPad-SCP.ini"); createIniDir = false; } int GetBinding(int port, int slot, int index, Device *&dev, Binding *&b, ForceFeedbackBinding *&ffb); int BindCommand(Device *dev, unsigned int uid, unsigned int port, unsigned int slot, int command, int sensitivity, int turbo, int deadZone); int CreateEffectBinding(Device *dev, wchar_t *effectName, unsigned int port, unsigned int slot, unsigned int motor, ForceFeedbackBinding **binding); void SelChanged(int port, int slot) { HWND hWnd = hWnds[port][slot]; if (!hWnd) return; HWND hWndTemp, hWndList = GetDlgItem(hWnd, IDC_LIST); int j, i = ListView_GetSelectedCount(hWndList); wchar_t *devName = L"N/A"; wchar_t *key = L"N/A"; wchar_t *command = L"N/A"; // Second value is now turbo. int turbo = -1; int sensitivity = 0; int deadZone = 0; int nonButtons = 0; // Set if sensitivity != 0, but need to disable flip anyways. // Only used to relative axes. int disableFlip = 0; wchar_t temp[4][1000]; Device *dev; int bFound = 0; int ffbFound = 0; ForceFeedbackBinding *ffb = 0; Binding *b = 0; if (i >= 1) { int index = -1; int flipped = 0; while (1) { index = ListView_GetNextItem(hWndList, index, LVNI_SELECTED); if (index < 0) break; LVITEMW item; item.iItem = index; item.mask = LVIF_TEXT; item.pszText = temp[3]; for (j=0; j<3; j++) { item.iSubItem = j; item.cchTextMax = sizeof(temp[0])/sizeof(temp[3][0]); if (!ListView_GetItem(hWndList, &item)) break; if (!bFound && !ffbFound) wcscpy(temp[j], temp[3]); else if (wcsicmp(temp[j], temp[3])) { int q = 0; while (temp[j][q] == temp[3][q]) q++; if (q && temp[j][q-1] == ' ' && temp[j][q] && temp[j][q+1] == 0) q--; if (j == 1) { // Really ugly, but merges labels for multiple directions for same axis. if ((temp[j][q] == 0 || (temp[j][q] == ' ' && temp[j][q+2] == 0)) && (temp[3][q] == 0 || (temp[3][q] == ' ' && temp[3][q+2] == 0))) { temp[j][q] = 0; continue; } } // Merge different directions for same stick. else if (j == 2 && q > 4) { temp[j][q] = 0; continue; } wcscpy(temp[j], L"*"); } } if (j == 3) { devName = temp[0]; key = temp[1]; command = temp[2]; if (GetBinding(port, slot, index, dev, b, ffb)) { if (b) { bFound ++; VirtualControl *control = &dev->virtualControls[b->controlIndex]; // Ignore if (b->command != 0x7F) { // Only relative axes can't have negative sensitivity. if (((control->uid >> 16) & 0xFF) == RELAXIS) { disableFlip = 1; } turbo += b->turbo; if (b->sensitivity < 0) { flipped ++; sensitivity -= b->sensitivity; } else { sensitivity += b->sensitivity; } if (((control->uid >> 16)&0xFF) != PSHBTN && ((control->uid >> 16)&0xFF) != TGLBTN) { deadZone += b->deadZone; nonButtons++; } } else disableFlip = 1; } else ffbFound++; } } } if ((bFound && ffbFound) || ffbFound > 1) { ffb = 0; turbo = -1; deadZone = 0; sensitivity = 0; disableFlip = 1; bFound = ffbFound = 0; } else if (bFound) { turbo++; sensitivity /= bFound; if (nonButtons) { deadZone /= nonButtons; } if (bFound > 1) disableFlip = 1; else if (flipped) { sensitivity = -sensitivity; } } } for (i=IDC_SLIDER1; i<ID_DELETE; i++) { hWndTemp = GetDlgItem(hWnd, i); if (hWndTemp) ShowWindow(hWndTemp, ffb == 0); } for (i=0x1300; i<0x1400; i++) { hWndTemp = GetDlgItem(hWnd, i); if (hWndTemp) { int enable = ffb != 0; if (ffb && i >= IDC_FF_AXIS1_ENABLED) { int index = (i - IDC_FF_AXIS1_ENABLED) / 16; if (index >= dev->numFFAxes) { enable = 0; } else { int type = i - index*16; AxisEffectInfo *info = 0; if (dev->numFFAxes > index) { info = ffb->axes+index; } if (type == IDC_FF_AXIS1) { // takes care of IDC_FF_AXIS1_FLIP as well. SetupLogSlider(hWndTemp); int force = 0; if (info) { force = info->force; } SetLogSliderVal(hWnd, i, GetDlgItem(hWnd, i-IDC_FF_AXIS1+IDC_FF_AXIS1_SCALE), force); } else if (type == IDC_FF_AXIS1_ENABLED) { CheckDlgButton(hWnd, i, BST_CHECKED * (info->force!=0)); wsprintfW(temp[0], L"Axis %i", index+1); if (dev->ffAxes[index].displayName && wcslen(dev->ffAxes[index].displayName) < 50) { wchar_t *end = wcschr(temp[0], 0); wsprintfW(end, L": %s", dev->ffAxes[index].displayName); } SetWindowText(hWndTemp, temp[0]); } } } ShowWindow(hWndTemp, enable); } } if (!ffb) { SetLogSliderVal(hWnd, IDC_SLIDER1, GetDlgItem(hWnd, IDC_AXIS_SENSITIVITY1), sensitivity); SetLogSliderVal(hWnd, IDC_SLIDER_DEADZONE, GetDlgItem(hWnd, IDC_AXIS_DEADZONE), deadZone); if (disableFlip) EnableWindow(GetDlgItem(hWnd, IDC_FLIP1), 0); EnableWindow(GetDlgItem(hWnd, IDC_TURBO), turbo >= 0); if (turbo > 0 && turbo < bFound) { SendMessage(GetDlgItem(hWnd, IDC_TURBO), BM_SETSTYLE, BS_AUTO3STATE, 0); CheckDlgButton(hWnd, IDC_TURBO, BST_INDETERMINATE); } else { SendMessage(GetDlgItem(hWnd, IDC_TURBO), BM_SETSTYLE, BS_AUTOCHECKBOX, 0); CheckDlgButton(hWnd, IDC_TURBO, BST_CHECKED * (bFound && turbo == bFound)); } HWND hWndCombo = GetDlgItem(hWnd, IDC_AXIS_DIRECTION); int enableCombo = 0; SendMessage(hWndCombo, CB_RESETCONTENT, 0, 0); if (b && bFound == 1) { VirtualControl *control = &dev->virtualControls[b->controlIndex]; unsigned int uid = control->uid; if (((uid>>16) & 0xFF) == ABSAXIS) { enableCombo = 1; wchar_t *endings[3] = {L" -", L" +", L""}; wchar_t *string = temp[3]; wcscpy(string, key); wchar_t *end = wcschr(string, 0); int sel = 2; if (!(uid & UID_AXIS)) { end[-2] = 0; sel = (end[-1] == '+'); end -= 2; } for (int i=0; i<3; i++) { wcscpy(end, endings[i]); SendMessage(hWndCombo, CB_ADDSTRING, 0, (LPARAM) string); if (i == sel) SendMessage(hWndCombo, CB_SETCURSEL, i, 0); } } } EnableWindow(hWndCombo, enableCombo); if (!enableCombo) { SendMessage(hWndCombo, CB_ADDSTRING, 0, (LPARAM) key); SendMessage(hWndCombo, CB_SELECTSTRING, i, (LPARAM) key); } SetDlgItemText(hWnd, IDC_AXIS_DEVICE1, devName); SetDlgItemText(hWnd, IDC_AXIS_CONTROL1, command); } else { wchar_t temp2[2000]; wsprintfW(temp2, L"%s / %s", devName, command); SetDlgItemText(hWnd, ID_FF, temp2); hWndTemp = GetDlgItem(hWnd, IDC_FF_EFFECT); SendMessage(hWndTemp, CB_RESETCONTENT, 0, 0); for (i=0; i<dev->numFFEffectTypes; i++) { SendMessage(hWndTemp, CB_INSERTSTRING, i, (LPARAM)dev->ffEffectTypes[i].displayName); } SendMessage(hWndTemp, CB_SETCURSEL, ffb->effectIndex, 0); EnableWindow(hWndTemp, dev->numFFEffectTypes>1); } } void UnselectAll(HWND hWnd) { int i = ListView_GetSelectedCount(hWnd); while (i-- > 0) { int index = ListView_GetNextItem(hWnd, -1, LVNI_SELECTED); ListView_SetItemState(hWnd, index, 0, LVIS_SELECTED); } } int GetItemIndex(int port, int slot, Device *dev, ForceFeedbackBinding *binding) { int count = 0; for (int i = 0; i<dm->numDevices; i++) { Device *dev2 = dm->devices[i]; if (!dev2->enabled) continue; if (dev2 != dev) { count += dev2->pads[port][slot].numBindings + dev2->pads[port][slot].numFFBindings; continue; } return count += dev2->pads[port][slot].numBindings + (binding - dev2->pads[port][slot].ffBindings); } return -1; } int GetItemIndex(int port, int slot, Device *dev, Binding *binding) { int count = 0; for (int i = 0; i<dm->numDevices; i++) { Device *dev2 = dm->devices[i]; if (!dev2->enabled) continue; if (dev2 != dev) { count += dev2->pads[port][slot].numBindings + dev2->pads[port][slot].numFFBindings; continue; } return count += binding - dev->pads[port][slot].bindings; } return -1; } // Doesn't check if already displayed. int ListBoundCommand(int port, int slot, Device *dev, Binding *b) { if (!hWnds[port][slot]) return -1; HWND hWndList = GetDlgItem(hWnds[port][slot], IDC_LIST); int index = -1; if (hWndList) { index = GetItemIndex(port, slot, dev, b); if (index >= 0) { LVITEM item; item.mask = LVIF_TEXT; item.pszText = dev->displayName; item.iItem = index; item.iSubItem = 0; SendMessage(hWndList, LVM_INSERTITEM, 0, (LPARAM)&item); item.mask = LVIF_TEXT; item.iSubItem = 1; item.pszText = dev->GetVirtualControlName(&dev->virtualControls[b->controlIndex]); SendMessage(hWndList, LVM_SETITEM, 0, (LPARAM)&item); item.iSubItem = 2; item.pszText = GetCommandStringW(b->command, port, slot); SendMessage(hWndList, LVM_SETITEM, 0, (LPARAM)&item); } } return index; } int ListBoundEffect(int port, int slot, Device *dev, ForceFeedbackBinding *b) { if (!hWnds[port][slot]) return -1; HWND hWndList = GetDlgItem(hWnds[port][slot], IDC_LIST); int index = -1; if (hWndList) { index = GetItemIndex(port, slot, dev, b); if (index >= 0) { LVITEM item; item.mask = LVIF_TEXT; item.pszText = dev->displayName; item.iItem = index; item.iSubItem = 0; SendMessage(hWndList, LVM_INSERTITEM, 0, (LPARAM)&item); item.mask = LVIF_TEXT; item.iSubItem = 1; item.pszText = dev->ffEffectTypes[b->effectIndex].displayName; SendMessage(hWndList, LVM_SETITEM, 0, (LPARAM)&item); item.iSubItem = 2; wchar_t *ps2Motors[2] = {L"Big Motor", L"Small Motor"}; item.pszText = ps2Motors[b->motor]; SendMessage(hWndList, LVM_SETITEM, 0, (LPARAM)&item); } } return index; } // Only for use with control bindings. Affects all highlighted bindings. void ChangeValue(int port, int slot, int *newSensitivity, int *newTurbo, int *newDeadZone) { if (!hWnds[port][slot]) return; HWND hWndList = GetDlgItem(hWnds[port][slot], IDC_LIST); int count = ListView_GetSelectedCount(hWndList); if (count < 1) return; int index = -1; while (1) { index = ListView_GetNextItem(hWndList, index, LVNI_SELECTED); if (index < 0) break; Device *dev; Binding *b; ForceFeedbackBinding *ffb; if (!GetBinding(port, slot, index, dev, b, ffb) || ffb) return; if (newSensitivity) { // Don't change flip state when modifying multiple controls. if (count > 1 && b->sensitivity < 0) b->sensitivity = -*newSensitivity; else b->sensitivity = *newSensitivity; } if (newDeadZone) { if (b->deadZone) { b->deadZone = *newDeadZone; } } if (newTurbo) { b->turbo = *newTurbo; } } PropSheet_Changed(hWndProp, hWnds[port][slot]); SelChanged(port, slot); } // Only for use with effect bindings. void ChangeEffect(int port, int slot, int id, int *newForce, unsigned int *newEffectType) { if (!hWnds[port][slot]) return; HWND hWndList = GetDlgItem(hWnds[port][slot], IDC_LIST); int i = ListView_GetSelectedCount(hWndList); if (i != 1) return; int index = ListView_GetNextItem(hWndList, -1, LVNI_SELECTED); Device *dev; Binding *b; ForceFeedbackBinding *ffb; if (!GetBinding(port, slot, index, dev, b, ffb) || b) return; if (newForce) { unsigned int axisIndex = (id - IDC_FF_AXIS1_ENABLED)/16; if (axisIndex < (unsigned int)dev->numFFAxes) { ffb->axes[axisIndex].force = *newForce; } } if (newEffectType && *newEffectType < (unsigned int)dev->numFFEffectTypes) { ffb->effectIndex = *newEffectType; ListView_DeleteItem(hWndList, index); index = ListBoundEffect(port, slot, dev, ffb); ListView_SetItemState(hWndList, index, LVIS_SELECTED, LVIS_SELECTED); } PropSheet_Changed(hWndProp, hWnds[port][slot]); SelChanged(port, slot); } void Populate(int port, int slot) { if (!hWnds[port][slot]) return; HWND hWnd = GetDlgItem(hWnds[port][slot], IDC_LIST); ListView_DeleteAllItems(hWnd); int i, j; int multipleBinding = config.multipleBinding; config.multipleBinding = 1; for (j=0; j<dm->numDevices; j++) { Device *dev = dm->devices[j]; if (!dev->enabled) continue; for (i=0; i<dev->pads[port][slot].numBindings; i++) { ListBoundCommand(port, slot, dev, dev->pads[port][slot].bindings+i); } for (i=0; i<dev->pads[port][slot].numFFBindings; i++) { ListBoundEffect(port, slot, dev, dev->pads[port][slot].ffBindings+i); } } config.multipleBinding = multipleBinding; hWnd = GetDlgItem(hWnds[port][slot], IDC_FORCEFEEDBACK); SendMessage(hWnd, CB_RESETCONTENT, 0, 0); int added = 0; for (i=0; i<dm->numDevices; i++) { Device *dev = dm->devices[i]; if (dev->enabled && dev->numFFAxes && dev->numFFEffectTypes) { SendMessage(hWnd, CB_INSERTSTRING, added, (LPARAM)dev->displayName); SendMessage(hWnd, CB_SETITEMDATA, added, i); added++; } } SendMessage(hWnd, CB_SETCURSEL, 0, 0); EnableWindow(hWnd, added!=0); EnableWindow(GetDlgItem(hWnds[port][slot], ID_BIG_MOTOR), added!=0); EnableWindow(GetDlgItem(hWnds[port][slot], ID_SMALL_MOTOR), added!=0); SelChanged(port, slot); } int WritePrivateProfileInt(wchar_t *s1, wchar_t *s2, int v, wchar_t *ini) { wchar_t temp[100]; _itow(v, temp, 10); return WritePrivateProfileStringW(s1, s2, temp, ini); } void SetVolume(int volume) { if (volume > 100) volume = 100; if (volume < 0) volume = 0; config.volume = volume; unsigned int val = 0xFFFF * volume/100; val = val | (val<<16); for (int i=waveOutGetNumDevs()-1; i>=0; i--) { waveOutSetVolume((HWAVEOUT)i, val); } WritePrivateProfileInt(L"General Settings", L"Volume", config.volume, iniFile); } int SaveSettings(wchar_t *file=0) { // Need this either way for saving path. if (!file) { file = iniFile; } else { wchar_t *c = wcsrchr(file, '\\'); if (*c) { *c = 0; wcscpy(config.lastSaveConfigPath, file); wcscpy(config.lastSaveConfigFileName, c+1); *c = '\\'; } } DeleteFileW(file); WritePrivateProfileStringW(L"General Settings", L"Last Config Path", config.lastSaveConfigPath, iniFile); WritePrivateProfileStringW(L"General Settings", L"Last Config Name", config.lastSaveConfigFileName, iniFile); // Just check first, last, and all pad bindings. Should be more than enough. No real need to check // config path. int noError = 1; for (int i=0; i<sizeof(BoolOptionsInfo)/sizeof(BoolOptionsInfo[0]); i++) { noError &= WritePrivateProfileInt(L"General Settings", BoolOptionsInfo[i].name, config.bools[i], file); } WritePrivateProfileInt(L"General Settings", L"Close Hacks", config.closeHacks, file); WritePrivateProfileInt(L"General Settings", L"Keyboard Mode", config.keyboardApi, file); WritePrivateProfileInt(L"General Settings", L"Mouse Mode", config.mouseApi, file); WritePrivateProfileInt(L"General Settings", L"Volume", config.volume, file); for (int port=0; port<2; port++) { for (int slot=0; slot<4; slot++) { wchar_t temp[50]; wsprintf(temp, L"Pad %i %i", port, slot); WritePrivateProfileInt(temp, L"Mode", config.padConfigs[port][slot].type, file); noError &= WritePrivateProfileInt(temp, L"Auto Analog", config.padConfigs[port][slot].autoAnalog, file); } } for (int i=0; i<dm->numDevices; i++) { wchar_t id[50]; wchar_t temp[50], temp2[1000]; wsprintfW(id, L"Device %i", i); Device *dev = dm->devices[i]; wchar_t *name = dev->displayName; while (name[0] == '[') { wchar_t *name2 = wcschr(name, ']'); if (!name2) break; name = name2+1; while (iswspace(name[0])) name++; } WritePrivateProfileStringW(id, L"Display Name", name, file); WritePrivateProfileStringW(id, L"Instance ID", dev->instanceID, file); if (dev->productID) { WritePrivateProfileStringW(id, L"Product ID", dev->productID, file); } WritePrivateProfileInt(id, L"API", dev->api, file); WritePrivateProfileInt(id, L"Type", dev->type, file); int ffBindingCount = 0; int bindingCount = 0; for (int port=0; port<2; port++) { for (int slot=0; slot<4; slot++) { for (int j=0; j<dev->pads[port][slot].numBindings; j++) { Binding *b = dev->pads[port][slot].bindings+j; VirtualControl *c = &dev->virtualControls[b->controlIndex]; wsprintfW(temp, L"Binding %i", bindingCount++); wsprintfW(temp2, L"0x%08X, %i, %i, %i, %i, %i, %i", c->uid, port, b->command, b->sensitivity, b->turbo, slot, b->deadZone); noError &= WritePrivateProfileStringW(id, temp, temp2, file); } for (int j=0; j<dev->pads[port][slot].numFFBindings; j++) { ForceFeedbackBinding *b = dev->pads[port][slot].ffBindings+j; ForceFeedbackEffectType *eff = &dev->ffEffectTypes[b->effectIndex]; wsprintfW(temp, L"FF Binding %i", ffBindingCount++); wsprintfW(temp2, L"%s %i, %i, %i", eff->effectID, port, b->motor, slot); for (int k=0; k<dev->numFFAxes; k++) { ForceFeedbackAxis *axis = dev->ffAxes + k; AxisEffectInfo *info = b->axes + k; wsprintfW(wcschr(temp2,0), L", %i, %i", axis->id, info->force); } noError &= WritePrivateProfileStringW(id, temp, temp2, file); } } } } if (!noError) { MessageBoxA(hWndProp, "Unable to save settings. Make sure the disk is not full or write protected, the file isn't write protected, and that the app has permissions to write to the directory. On Vista, try running in administrator mode.", "Error Writing Configuration File", MB_OK | MB_ICONERROR); } return !noError; } u8 GetPrivateProfileBool(wchar_t *s1, wchar_t *s2, int def, wchar_t *ini) { return (0!=GetPrivateProfileIntW(s1, s2, def, ini)); } int LoadSettings(int force, wchar_t *file) { if (dm && !force) return 0; if( createIniDir ) { CreateDirectory(L"inis", 0); createIniDir = false; } // Could just do ClearDevices() instead, but if I ever add any extra stuff, // this will still work. UnloadConfigs(); dm = new InputDeviceManager(); if (!file) { file = iniFile; GetPrivateProfileStringW(L"General Settings", L"Last Config Path", L"inis", config.lastSaveConfigPath, sizeof(config.lastSaveConfigPath), file); GetPrivateProfileStringW(L"General Settings", L"Last Config Name", L"LilyPad.lily", config.lastSaveConfigFileName, sizeof(config.lastSaveConfigFileName), file); } else { wchar_t *c = wcsrchr(file, '\\'); if (c) { *c = 0; wcscpy(config.lastSaveConfigPath, file); wcscpy(config.lastSaveConfigFileName, c+1); *c = '\\'; WritePrivateProfileStringW(L"General Settings", L"Last Config Path", config.lastSaveConfigPath, iniFile); WritePrivateProfileStringW(L"General Settings", L"Last Config Name", config.lastSaveConfigFileName, iniFile); } } for (int i=0; i<sizeof(BoolOptionsInfo)/sizeof(BoolOptionsInfo[0]); i++) { config.bools[i] = GetPrivateProfileBool(L"General Settings", BoolOptionsInfo[i].name, BoolOptionsInfo[i].defaultValue, file); } config.closeHacks = (u8)GetPrivateProfileIntW(L"General Settings", L"Close Hacks", 0, file); if (config.closeHacks&1) config.closeHacks &= ~2; config.keyboardApi = (DeviceAPI)GetPrivateProfileIntW(L"General Settings", L"Keyboard Mode", WM, file); if (!config.keyboardApi) config.keyboardApi = WM; config.mouseApi = (DeviceAPI) GetPrivateProfileIntW(L"General Settings", L"Mouse Mode", 0, file); config.volume = GetPrivateProfileInt(L"General Settings", L"Volume", 100, file); OSVERSIONINFO os; os.dwOSVersionInfoSize = sizeof(os); config.osVersion = 0; if (GetVersionEx(&os)) { config.osVersion = os.dwMajorVersion; } if (config.osVersion < 6) config.vistaVolume = 0; if (!config.vistaVolume) config.volume = 100; if (config.vistaVolume) SetVolume(config.volume); if (!InitializeRawInput()) { if (config.keyboardApi == RAW) config.keyboardApi = WM; if (config.mouseApi == RAW) config.mouseApi = WM; } if (config.debug) { CreateDirectory(L"logs", 0); } for (int port=0; port<2; port++) { for (int slot=0; slot<4; slot++) { wchar_t temp[50]; wsprintf(temp, L"Pad %i %i", port, slot); config.padConfigs[port][slot].type = (PadType) GetPrivateProfileInt(temp, L"Mode", Dualshock2Pad, file); config.padConfigs[port][slot].autoAnalog = GetPrivateProfileBool(temp, L"Auto Analog", 0, file); } } int i=0; int multipleBinding = config.multipleBinding; // Disabling multiple binding only prevents new multiple bindings. config.multipleBinding = 1; while (1) { wchar_t id[50]; wchar_t temp[50], temp2[1000], temp3[1000], temp4[1000]; wsprintfW(id, L"Device %i", i++); if (!GetPrivateProfileStringW(id, L"Display Name", 0, temp2, 1000, file) || !temp2[0] || !GetPrivateProfileStringW(id, L"Instance ID", 0, temp3, 1000, file) || !temp3[0]) { if (i >= 100) break; continue; } wchar_t *id2 = 0; if (GetPrivateProfileStringW(id, L"Product ID", 0, temp4, 1000, file) && temp4[0]) id2 = temp4; int api = GetPrivateProfileIntW(id, L"API", 0, file); int type = GetPrivateProfileIntW(id, L"Type", 0, file); if (!api || !type) continue; Device *dev = new Device((DeviceAPI)api, (DeviceType)type, temp2, temp3, id2); dev->attached = 0; dm->AddDevice(dev); int j = 0; int last = 0; while (1) { wsprintfW(temp, L"Binding %i", j++); if (!GetPrivateProfileStringW(id, temp, 0, temp2, 1000, file)) { if (j >= 100) { if (!last) break; last = 0; } continue; } last = 1; unsigned int uid; int port, command, sensitivity, turbo, slot = 0, deadZone = 0; int w = 0; char string[1000]; while (temp2[w]) { string[w] = (char)temp2[w]; w++; } string[w] = 0; int len = sscanf(string, " %i , %i , %i , %i , %i , %i , %i", &uid, &port, &command, &sensitivity, &turbo, &slot, &deadZone); if (len >= 5 && type) { VirtualControl *c = dev->GetVirtualControl(uid); if (!c) c = dev->AddVirtualControl(uid, -1); if (c) { BindCommand(dev, uid, port, slot, command, sensitivity, turbo, deadZone); } } } j = 0; while (1) { wsprintfW(temp, L"FF Binding %i", j++); if (!GetPrivateProfileStringW(id, temp, 0, temp2, 1000, file)) { if (j >= 10) { if (!last) break; last = 0; } continue; } last = 1; int port, slot, motor; int w = 0; char string[1000]; char effect[1000]; while (temp2[w]) { string[w] = (char)temp2[w]; w++; } string[w] = 0; // wcstok not in ntdll. More effore than its worth to shave off // whitespace without it. if (sscanf(string, " %s %i , %i , %i", effect, &port, &motor, &slot) == 4) { char *s = strchr(strchr(strchr(string, ',')+1, ',')+1, ','); if (!s) continue; s++; w = 0; while (effect[w]) { temp2[w] = effect[w]; w++; } temp2[w] = 0; ForceFeedbackEffectType *eff = dev->GetForcefeedbackEffect(temp2); if (!eff) { // At the moment, don't record effect types. // Only used internally, anyways, so not an issue. dev->AddFFEffectType(temp2, temp2, EFFECT_CONSTANT); // eff = &dev->ffEffectTypes[dev->numFFEffectTypes-1]; } ForceFeedbackBinding *b; CreateEffectBinding(dev, temp2, port, slot, motor, &b); if (b) { while (1) { int axisID = atoi(s); if (!(s = strchr(s, ','))) break; s++; int force = atoi(s); int i; for (i=0; i<dev->numFFAxes; i++) { if (axisID == dev->ffAxes[i].id) break; } if (i == dev->numFFAxes) { dev->AddFFAxis(L"?", axisID); } b->axes[i].force = force; if (!(s = strchr(s, ','))) break; s++; } } } } } config.multipleBinding = multipleBinding; RefreshEnabledDevicesAndDisplay(1); return 0; } inline int GetPort(HWND hWnd, int *slot) { for (int i=0; i<sizeof(hWnds)/sizeof(hWnds[0][0]); i++) { if (hWnds[i&1][i>>1] == hWnd) { *slot = i>>1; return i&1; } } *slot = 0; return 0; } void Diagnostics(HWND hWnd) { HWND hWndList = GetDlgItem(hWnd, IDC_LIST); if (!hWndList) return; int index = ListView_GetNextItem(hWndList, -1, LVNI_SELECTED); if (index < 0) return; LVITEM item; memset(&item, 0, sizeof(item)); item.mask = LVIF_PARAM; item.iSubItem = 0; item.iItem = index; if (!ListView_GetItem(hWndList, &item)) return; Diagnose(item.lParam, hWnd); RefreshEnabledDevicesAndDisplay(0, hWnd, 1); } int GetBinding(int port, int slot, int index, Device *&dev, Binding *&b, ForceFeedbackBinding *&ffb) { ffb = 0; b = 0; for (int i = 0; i<dm->numDevices; i++) { dev = dm->devices[i]; if (!dev->enabled) continue; if (index < dev->pads[port][slot].numBindings) { b = dev->pads[port][slot].bindings + index; return 1; } index -= dev->pads[port][slot].numBindings; if (index < dev->pads[port][slot].numFFBindings) { ffb = dev->pads[port][slot].ffBindings + index; return 1; } index -= dev->pads[port][slot].numFFBindings; } return 0; } // Only used when deleting things from ListView. Will remove from listview if needed. void DeleteBinding(int port, int slot, Device *dev, Binding *b) { if (dev->enabled && hWnds[port][slot]) { int count = GetItemIndex(port, slot, dev, b); if (count >= 0) { HWND hWndList = GetDlgItem(hWnds[port][slot], IDC_LIST); if (hWndList) { ListView_DeleteItem(hWndList, count); } } } Binding *bindings = dev->pads[port][slot].bindings; int i = b - bindings; memmove(bindings+i, bindings+i+1, sizeof(Binding) * (dev->pads[port][slot].numBindings - i - 1)); dev->pads[port][slot].numBindings--; } void DeleteBinding(int port, int slot, Device *dev, ForceFeedbackBinding *b) { if (dev->enabled && hWnds[port][slot]) { int count = GetItemIndex(port, slot, dev, b); if (count >= 0) { HWND hWndList = GetDlgItem(hWnds[port][slot], IDC_LIST); if (hWndList) { ListView_DeleteItem(hWndList, count); } } } ForceFeedbackBinding *bindings = dev->pads[port][slot].ffBindings; int i = b - bindings; memmove(bindings+i, bindings+i+1, sizeof(Binding) * (dev->pads[port][slot].numFFBindings - i - 1)); dev->pads[port][slot].numFFBindings--; } int DeleteByIndex(int port, int slot, int index) { ForceFeedbackBinding *ffb; Binding *b; Device *dev; if (GetBinding(port, slot, index, dev, b, ffb)) { if (b) { DeleteBinding(port, slot, dev, b); } else { DeleteBinding(port, slot, dev, ffb); } return 1; } return 0; } int DeleteSelected(int port, int slot) { if (!hWnds[port][slot]) return 0; HWND hWnd = GetDlgItem(hWnds[port][slot], IDC_LIST); int changes = 0; while (1) { int index = ListView_GetNextItem(hWnd, -1, LVNI_SELECTED); if (index < 0) break; changes += DeleteByIndex(port, slot, index); } //ShowScrollBar(hWnd, SB_VERT, 1); return changes; } int CreateEffectBinding(Device *dev, wchar_t *effectID, unsigned int port, unsigned int slot, unsigned int motor, ForceFeedbackBinding **binding) { // Checks needed because I use this directly when loading bindings. // Note: dev->numFFAxes *can* be 0, for loading from file. *binding = 0; if (port > 1 || slot>3 || motor > 1 || !dev->numFFEffectTypes) { return -1; } ForceFeedbackEffectType *eff = 0; if (effectID) { eff = dev->GetForcefeedbackEffect(effectID); } if (!eff) { eff = dev->ffEffectTypes; } if (!eff) { return -1; } int effectIndex = eff - dev->ffEffectTypes; dev->pads[port][slot].ffBindings = (ForceFeedbackBinding*) realloc(dev->pads[port][slot].ffBindings, (dev->pads[port][slot].numFFBindings+1) * sizeof(ForceFeedbackBinding)); int newIndex = dev->pads[port][slot].numFFBindings; while (newIndex && dev->pads[port][slot].ffBindings[newIndex-1].motor >= motor) { dev->pads[port][slot].ffBindings[newIndex] = dev->pads[port][slot].ffBindings[newIndex-1]; newIndex--; } ForceFeedbackBinding *b = dev->pads[port][slot].ffBindings + newIndex; b->axes = (AxisEffectInfo*) calloc(dev->numFFAxes, sizeof(AxisEffectInfo)); b->motor = motor; b->effectIndex = effectIndex; dev->pads[port][slot].numFFBindings++; if (binding) *binding = b; return ListBoundEffect(port, slot, dev, b); } int BindCommand(Device *dev, unsigned int uid, unsigned int port, unsigned int slot, int command, int sensitivity, int turbo, int deadZone) { // Checks needed because I use this directly when loading bindings. if (port > 1 || slot>3) { return -1; } if (!sensitivity) sensitivity = BASE_SENSITIVITY; if ((uid>>16) & (PSHBTN|TGLBTN)) { deadZone = 0; } else if (!deadZone) { if ((uid>>16) & PRESSURE_BTN) { deadZone = 1; } else { deadZone = DEFAULT_DEADZONE; } } // Relative axes can have negative sensitivity. else if (((uid>>16) & 0xFF) == RELAXIS) { sensitivity = abs(sensitivity); } VirtualControl *c = dev->GetVirtualControl(uid); if (!c) return -1; // Add before deleting. Means I won't scroll up one line when scrolled down to bottom. int controlIndex = c - dev->virtualControls; int index = 0; PadBindings *p = dev->pads[port]+slot; p->bindings = (Binding*) realloc(p->bindings, (p->numBindings+1) * sizeof(Binding)); for (index = p->numBindings; index > 0; index--) { if (p->bindings[index-1].controlIndex < controlIndex) break; p->bindings[index] = p->bindings[index-1]; } Binding *b = p->bindings+index; p->numBindings++; b->command = command; b->controlIndex = controlIndex; b->turbo = turbo; b->sensitivity = sensitivity; b->deadZone = deadZone; // Where it appears in listview. int count = ListBoundCommand(port, slot, dev, b); int newBindingIndex = index; index = 0; while (index < p->numBindings) { if (index == newBindingIndex) { index ++; continue; } b = p->bindings + index; int nuke = 0; if (config.multipleBinding) { if (b->controlIndex == controlIndex && b->command == command) nuke = 1; } else { int uid2 = dev->virtualControls[b->controlIndex].uid; if (b->controlIndex == controlIndex || (!((uid2^uid) & 0xFFFFFF) && ((uid|uid2) & (UID_POV | UID_AXIS)))) nuke = 1; } if (!nuke) { index++; continue; } if (index < newBindingIndex) { newBindingIndex--; count --; } DeleteBinding(port, slot, dev, b); } if (!config.multipleBinding) { for (int port2=0; port2<2; port2++) { for (int slot2=0; slot2<4; slot2++) { if (port2==port && slot2 == slot) continue; PadBindings *p = dev->pads[port2]+slot2; for (int i=0; i < p->numBindings; i++) { Binding *b = p->bindings+i; int uid2 = dev->virtualControls[b->controlIndex].uid; if (b->controlIndex == controlIndex || (!((uid2^uid) & 0xFFFFFF) && ((uid|uid2) & (UID_POV | UID_AXIS)))) { DeleteBinding(port2, slot2, dev, b); i--; } } } } } return count; } // Does nothing, but makes sure I'm overriding the dialog's window proc, to block // default key handling. ExtraWndProcResult DoNothingWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *output) { return CONTINUE_BLISSFULLY; } void EndBinding(HWND hWnd) { if (selected) { KillTimer(hWnd, 1); int needRefreshDevices = 0; // If binding ignore keyboard, this will disable it and enable other devices. // 0xFF is used for testing force feedback. I disable all other devices first // just so I don't needlessly steal the mouse. if (selected == 0x7F || selected == 0xFF) { needRefreshDevices = 1; } selected = 0; dm->ReleaseInput(); ClearKeyQueue(); hWndButtonProc.Release(); // Safest to do this last. if (needRefreshDevices) { RefreshEnabledDevices(); } } } INT_PTR CALLBACK DialogProc(HWND hWnd, unsigned int msg, WPARAM wParam, LPARAM lParam) { int index = (hWnd == PropSheet_IndexToHwnd(hWndProp, 1)); int slot; int port = GetPort(hWnd, &slot); HWND hWndList = GetDlgItem(hWnd, IDC_LIST); switch (msg) { case WM_INITDIALOG: { ListView_SetExtendedListViewStyleEx(hWndList, LVS_EX_DOUBLEBUFFER, LVS_EX_DOUBLEBUFFER); LVCOLUMN c; c.mask = LVCF_TEXT | LVCF_WIDTH; c.cx = 101; c.pszText = L"Device"; ListView_InsertColumn(hWndList, 0, &c); c.cx = 70; c.pszText = L"PC Control"; ListView_InsertColumn(hWndList, 1, &c); c.cx = 84; c.pszText = L"PS2 Control"; ListView_InsertColumn(hWndList, 2, &c); selected = 0; port = (int)((PROPSHEETPAGE *)lParam)->lParam & 1; slot = (int)((PROPSHEETPAGE *)lParam)->lParam >> 1; hWnds[port][slot] = hWnd; SendMessage(hWndList, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT); SetupLogSlider(GetDlgItem(hWnd, IDC_SLIDER1)); SetupLogSlider(GetDlgItem(hWnd, IDC_SLIDER_DEADZONE)); if (port || slot) EnableWindow(GetDlgItem(hWnd, ID_IGNORE), 0); Populate(port, slot); } break; case WM_DEVICECHANGE: if (wParam == DBT_DEVNODES_CHANGED) { EndBinding(hWnd); RefreshEnabledDevicesAndDisplay(1, hWndGeneral, 1); } break; case WM_TIMER: // ignore generic timer callback and handle the hwnd-specific one which comes later if(hWnd == 0) return 0; if (!selected || selected == 0xFF) { // !selected is mostly for device added/removed when binding. selected = 0xFF; EndBinding(hWnd); } else { unsigned int uid; int value; // The old code re-bound our button hWndProcEater to GetDlgItem(hWnd, selected). But at best hWnd // was null (WM_TIMER is passed twice, once with a null parameter, and a second time that is hWnd // specific), and at worst 'selected' is a post-processed code "based" on cmd, so GetDlgItem // *always* returned NULL anyway. This resulted in hWndButton being null, which meant Device code // used hWnd instead. This may have caused odd behavior since the callbacks were still all eaten // by the initial GetDlgItem(hWnd, cmd) selection made when the timer was initialized. InitInfo info = {selected==0x7F, 1, hWndProp, &hWndButtonProc}; Device *dev = dm->GetActiveDevice(&info, &uid, &index, &value); if (dev) { int command = selected; // Good idea to do this first, as BindCommand modifies the ListView, which will // call it anyways, which is a bit funky. EndBinding(hWnd); UnselectAll(hWndList); int index = -1; if (command == 0x7F && dev->api == IGNORE_KEYBOARD) { index = BindCommand(dev, uid, 0, 0, command, BASE_SENSITIVITY, 0, 0); } else if (command < 0x30) { index = BindCommand(dev, uid, port, slot, command, BASE_SENSITIVITY, 0, 0); } if (index >= 0) { PropSheet_Changed(hWndProp, hWnds[port][slot]); ListView_SetItemState(hWndList, index, LVIS_SELECTED, LVIS_SELECTED); ListView_EnsureVisible(hWndList, index, 0); } } } break; case WM_SYSKEYDOWN: case WM_KEYDOWN: EndBinding(hWnd); break; case PSM_CANCELTOCLOSE: // Load(); break; case WM_ACTIVATE: EndBinding(hWnd); break; case WM_NOTIFY: { PSHNOTIFY* n = (PSHNOTIFY*) lParam; if (n->hdr.hwndFrom == hWndProp) { switch(n->hdr.code) { case PSN_QUERYCANCEL: case PSN_KILLACTIVE: EndBinding(hWnd); return 0; case PSN_SETACTIVE: return 0; case PSN_APPLY: SetWindowLong(hWnd, DWL_MSGRESULT, PSNRET_NOERROR); return 1; } break; } else if (n->hdr.idFrom == IDC_LIST) { static int NeedUpdate = 0; if (n->hdr.code == LVN_KEYDOWN) { NMLVKEYDOWN *key = (NMLVKEYDOWN *) n; if (key->wVKey == VK_DELETE || key->wVKey == VK_BACK) { if (DeleteSelected(port, slot)) PropSheet_Changed(hWndProp, hWnds[0]); } } // Update sensitivity and motor/binding display on redraw // rather than on itemchanged. This reduces blinking, as // I get 3 LVN_ITEMCHANGED messages, and first is sent before // the new item is set as being selected. else if (n->hdr.code == LVN_ITEMCHANGED) { NeedUpdate = 1; } else if (n->hdr.code == NM_CUSTOMDRAW && NeedUpdate) { NeedUpdate = 0; SelChanged(port, slot); } } } break; case WM_HSCROLL: { int id = GetDlgCtrlID((HWND)lParam); int val = GetLogSliderVal(hWnd, id); if (id == IDC_SLIDER1) { ChangeValue(port, slot, &val, 0, 0); } else if (id == IDC_SLIDER_DEADZONE) { ChangeValue(port, slot, 0, 0, &val); } else { ChangeEffect(port, slot, id, &val, 0); } } break; case WM_COMMAND: if (HIWORD(wParam)==CBN_SELCHANGE && LOWORD(wParam) == IDC_AXIS_DIRECTION) { int index = ListView_GetNextItem(hWndList, -1, LVNI_SELECTED); if (index >= 0) { int cbsel = SendMessage((HWND)lParam, CB_GETCURSEL, 0, 0); if (cbsel >= 0) { ForceFeedbackBinding *ffb; Binding *b; Device *dev; if (GetBinding(port, slot, index, dev, b, ffb)) { const static unsigned int axisUIDs[3] = {UID_AXIS_NEG, UID_AXIS_POS, UID_AXIS}; int uid = dev->virtualControls[b->controlIndex].uid; uid = (uid&0x00FFFFFF) | axisUIDs[cbsel]; Binding backup = *b; DeleteSelected(port, slot); int index = BindCommand(dev, uid, port, slot, backup.command, backup.sensitivity, backup.turbo, backup.deadZone); ListView_SetItemState(hWndList, index, LVIS_SELECTED, LVIS_SELECTED); PropSheet_Changed(hWndProp, hWnd); } } } } else if (HIWORD(wParam)==CBN_SELCHANGE && LOWORD(wParam) == IDC_FF_EFFECT) { int typeIndex = SendMessage((HWND)lParam, CB_GETCURSEL, 0, 0); if (typeIndex >= 0) ChangeEffect(port, slot, 0, 0, (unsigned int*)&typeIndex); } else if (HIWORD(wParam)==BN_CLICKED) { EndBinding(hWnd); int cmd = LOWORD(wParam); if (cmd == ID_DELETE) { if (DeleteSelected(port, slot)) PropSheet_Changed(hWndProp, hWnd); } else if (cmd == ID_CLEAR) { while (DeleteByIndex(port, slot, 0)) PropSheet_Changed(hWndProp, hWnd); } else if (cmd == ID_BIG_MOTOR || cmd == ID_SMALL_MOTOR) { int i = (int)SendMessage(GetDlgItem(hWnd, IDC_FORCEFEEDBACK), CB_GETCURSEL, 0, 0); if (i >= 0) { unsigned int index = (unsigned int)SendMessage(GetDlgItem(hWnd, IDC_FORCEFEEDBACK), CB_GETITEMDATA, i, 0); if (index < (unsigned int) dm->numDevices) { Device *dev = dm->devices[index]; ForceFeedbackBinding *b; wchar_t *effectID = 0; if (dev->api == DI) { // Constant effect. if (cmd == ID_BIG_MOTOR) effectID = L"13541C20-8E33-11D0-9AD0-00A0C9A06E35"; // Square. else effectID = L"13541C22-8E33-11D0-9AD0-00A0C9A06E35"; } int count = CreateEffectBinding(dev, effectID, port, slot, cmd-ID_BIG_MOTOR, &b); if (b) { int needSet = 1; if (dev->api == XINPUT && dev->numFFAxes == 2) { needSet = 0; if (cmd == ID_BIG_MOTOR) { b->axes[0].force = BASE_SENSITIVITY; } else { b->axes[1].force = BASE_SENSITIVITY; } } else if (dev->api == DS3 && dev->numFFAxes == 2) { needSet = 0; if (cmd == ID_BIG_MOTOR) { b->axes[0].force = BASE_SENSITIVITY; } else { b->axes[1].force = BASE_SENSITIVITY; } } else if (dev->api == DI) { int bigIndex=0, littleIndex=0; int j; for (j=0; j<dev->numFFAxes; j++) { // DI object instance. 0 is x-axis, 1 is y-axis. int instance = (dev->ffAxes[j].id>>8)&0xFFFF; if (instance == 0) { bigIndex = j; } else if (instance == 1) { littleIndex = j; } } needSet = 0; if (cmd == ID_BIG_MOTOR) { b->axes[bigIndex].force = BASE_SENSITIVITY; b->axes[littleIndex].force = 1; } else { b->axes[bigIndex].force = 1; b->axes[littleIndex].force = BASE_SENSITIVITY; } } if (needSet) { for (int j=0; j<2 && j <dev->numFFAxes; j++) { b->axes[j].force = BASE_SENSITIVITY; } } UnselectAll(hWndList); ListView_SetItemState(hWndList, count, LVIS_SELECTED, LVIS_SELECTED); ListView_EnsureVisible(hWndList, count, 0); } PropSheet_Changed(hWndProp, hWnd); } } } else if (cmd == ID_CONTROLS) { UnselectAll(hWndList); } else if (cmd == ID_TEST) { // Just in case... if (selected) break; Device *dev; Binding *b; ForceFeedbackBinding *ffb = 0; int selIndex = ListView_GetNextItem(hWndList, -1, LVNI_SELECTED); if (selIndex >= 0) { if (GetBinding(port, slot, selIndex, dev, b, ffb)) { selected = 0xFF; hWndButtonProc.SetWndHandle(GetDlgItem(hWnd, cmd)); InitInfo info = {0, 1, hWndProp, &hWndButtonProc}; for (int i=0; i<dm->numDevices; i++) { if (dm->devices[i] != dev) { dm->DisableDevice(i); } } dm->Update(&info); dm->PostRead(); dev->SetEffect(ffb, 255); Sleep(200); dm->Update(&info); SetTimer(hWnd, 1, 3000, 0); } } } else if ((cmd >= ID_LOCK_BUTTONS && cmd <= ID_ANALOG) || cmd == ID_IGNORE) {// || cmd == ID_FORCE_FEEDBACK) { // Messes up things, unfortunately. // End binding on a bunch of notification messages, and // this will send a bunch. // UnselectAll(hWndList); EndBinding(hWnd); if (cmd != ID_IGNORE) { selected = cmd-(ID_SELECT-0x10); } else { selected = 0x7F; for (int i=0; i<dm->numDevices; i++) { if (dm->devices[i]->api != IGNORE_KEYBOARD) { dm->DisableDevice(i); } else { dm->EnableDevice(i); } } } hWndButtonProc.SetWndHandle(GetDlgItem(hWnd, cmd)); hWndButtonProc.Eat(DoNothingWndProc, 0); InitInfo info = {selected==0x7F, 1, hWndProp, &hWndButtonProc}; int w = timeGetTime(); dm->Update(&info); dm->PostRead(); // Workaround for things that return 0 on first poll and something else ever after. Sleep(80); dm->Update(&info); dm->PostRead(); SetTimer(hWnd, 1, 30, 0); } if (cmd == IDC_TURBO) { // Don't allow setting it back to indeterminate. SendMessage(GetDlgItem(hWnd, IDC_TURBO), BM_SETSTYLE, BS_AUTOCHECKBOX, 0); int turbo = (IsDlgButtonChecked(hWnd, IDC_TURBO) == BST_CHECKED); ChangeValue(port, slot, 0, &turbo, 0); } else if (cmd == IDC_FLIP1) { int val = GetLogSliderVal(hWnd, IDC_SLIDER1); ChangeValue(port, slot, &val, 0, 0); } else if (cmd >= IDC_FF_AXIS1_ENABLED && cmd < IDC_FF_AXIS8_ENABLED + 16) { int index = (cmd - IDC_FF_AXIS1_ENABLED)/16; int val = GetLogSliderVal(hWnd, 16*index + IDC_FF_AXIS1); if (IsDlgButtonChecked(hWnd, 16*index + IDC_FF_AXIS1_ENABLED) != BST_CHECKED) { val = 0; } ChangeEffect(port, slot, cmd, &val, 0); } } break; default: break; } return 0; } // Returns 0 if pad doesn't exist due to mtap settings, as a convenience. int GetPadString(wchar_t *string, unsigned int port, unsigned int slot) { if (!slot && !config.multitap[port]) { wsprintfW(string, L"Pad %i", port+1); } else { wsprintfW(string, L"Pad %i%c", port+1, 'A'+slot); if (!config.multitap[port]) return 0; } return 1; } void UpdatePadPages() { HPROPSHEETPAGE pages[10]; int count = 0; memset(hWnds, 0, sizeof(hWnds)); int slot = 0; for (int port=0; port<2; port++) { for (int slot=0; slot<4; slot++) { if (config.padConfigs[port][slot].type == DisabledPad) continue; wchar_t title[20]; if (!GetPadString(title, port, slot)) continue; PROPSHEETPAGE psp; ZeroMemory(&psp, sizeof(psp)); psp.dwSize = sizeof(psp); psp.dwFlags = PSP_USETITLE | PSP_PREMATURE; psp.hInstance = hInst; psp.pfnDlgProc = DialogProc; psp.lParam = port | (slot<<1); psp.pszTitle = title; if (config.padConfigs[port][slot].type != GuitarPad) psp.pszTemplate = MAKEINTRESOURCE(IDD_CONFIG); else psp.pszTemplate = MAKEINTRESOURCE(IDD_CONFIG_GUITAR); pages[count] = CreatePropertySheetPage(&psp); if (pages[count]) count++; } } while (SendMessage(hWndProp, PSM_INDEXTOPAGE, 1, 0)) { PropSheet_RemovePage(hWndProp, 1, 0); } for (int i=0; i<count; i++) { PropSheet_AddPage(hWndProp, pages[i]); } } int ListIndexToPortAndSlot (int index, int *port, int *slot) { if (index < 0 || index >= 2 + 3*(config.multitap[0]+config.multitap[1])) { *port = 0; *slot = 0; return 0; } if (index < 1 + 3*config.multitap[0]) { *port = 0; *slot = index; } else { *port = 1; *slot = index-1-3*config.multitap[0]; } return 1; } void UpdatePadList(HWND hWnd) { static u8 recurse = 0; if (recurse) return; recurse = 1; HWND hWndList = GetDlgItem(hWnd, IDC_PAD_LIST); HWND hWndCombo = GetDlgItem(hWnd, IDC_PAD_TYPE); HWND hWndAnalog = GetDlgItem(hWnd, IDC_ANALOG_START1); int slot; int port; int index = 0; wchar_t *padTypes[] = {L"Unplugged", L"Dualshock 2", L"Guitar"}; for (port=0; port<2; port++) { for (slot = 0; slot<4; slot++) { wchar_t text[20]; if (!GetPadString(text, port, slot)) continue; LVITEM item; item.iItem = index; item.iSubItem = 0; item.mask = LVIF_TEXT; item.pszText = text; if (SendMessage(hWndList, LVM_GETITEMCOUNT, 0, 0) <= index) { ListView_InsertItem(hWndList, &item); } else { ListView_SetItem(hWndList, &item); } item.iSubItem = 1; if (2 < (unsigned int)config.padConfigs[port][slot].type) config.padConfigs[port][slot].type = Dualshock2Pad; item.pszText = padTypes[config.padConfigs[port][slot].type]; //if (!slot && !config.padConfigs[port][slot].type) // item.pszText = L"Unplugged (Kinda)"; ListView_SetItem(hWndList, &item); item.iSubItem = 2; int count = 0; for (int i = 0; i<dm->numDevices; i++) { Device *dev = dm->devices[i]; if (!dev->enabled) continue; count += dev->pads[port][slot].numBindings + dev->pads[port][slot].numFFBindings; } wsprintf(text, L"%i", count); item.pszText = text; ListView_SetItem(hWndList, &item); index++; } } while (ListView_DeleteItem(hWndList, index)); int sel = ListView_GetNextItem(hWndList, -1, LVNI_SELECTED); int enable; if (!ListIndexToPortAndSlot(sel, &port, &slot)) { enable = 0; SendMessage(hWndCombo, CB_SETCURSEL, -1, 0); CheckDlgButton(hWnd, IDC_ANALOG_START1, BST_UNCHECKED); } else { enable = 1; SendMessage(hWndCombo, CB_SETCURSEL, config.padConfigs[port][slot].type, 0); CheckDlgButton(hWnd, IDC_ANALOG_START1, BST_CHECKED*config.padConfigs[port][slot].autoAnalog); } EnableWindow(hWndCombo, enable); EnableWindow(hWndAnalog, enable && !ps2e); //ListView_SetExtendedListViewStyleEx(hWndList, LVS_EX_DOUBLEBUFFER|LVS_EX_ONECLICKACTIVATE, LVS_EX_DOUBLEBUFFER|LVS_EX_ONECLICKACTIVATE); recurse = 0; } INT_PTR CALLBACK GeneralDialogProc(HWND hWnd, unsigned int msg, WPARAM wParam, LPARAM lParam) { int i; HWND hWndList = GetDlgItem(hWnd, IDC_PAD_LIST); switch (msg) { case WM_INITDIALOG: { HWND hWndCombo = GetDlgItem(hWnd, IDC_PAD_TYPE); if (SendMessage(hWndCombo, CB_GETCOUNT, 0, 0) == 0) { LVCOLUMN c; c.mask = LVCF_TEXT | LVCF_WIDTH; c.cx = 50; c.pszText = L"Pad"; ListView_InsertColumn(hWndList, 0, &c); c.cx = 120; c.pszText = L"Type"; ListView_InsertColumn(hWndList, 1, &c); c.cx = 70; c.pszText = L"Bindings"; ListView_InsertColumn(hWndList, 2, &c); selected = 0; ListView_SetExtendedListViewStyleEx(hWndList, LVS_EX_FULLROWSELECT|LVS_EX_DOUBLEBUFFER, LVS_EX_FULLROWSELECT|LVS_EX_DOUBLEBUFFER); SendMessage(hWndList, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT); SendMessage(hWndCombo, CB_ADDSTRING, 0, (LPARAM) L"Unplugged"); SendMessage(hWndCombo, CB_ADDSTRING, 0, (LPARAM) L"Dualshock 2"); SendMessage(hWndCombo, CB_ADDSTRING, 0, (LPARAM) L"Guitar"); } } UpdatePadPages(); hWndGeneral = hWnd; RefreshEnabledDevicesAndDisplay(0, hWnd, 0); UpdatePadList(hWnd); if (!DualShock3Possible()) { config.gameApis.dualShock3 = 0; EnableWindow(GetDlgItem(hWnd, IDC_G_DS3), 0); } for (int j=0; j<sizeof(BoolOptionsInfo)/sizeof(BoolOptionsInfo[0]); j++) { CheckDlgButton(hWnd, BoolOptionsInfo[j].ControlId, BST_CHECKED * config.bools[j]); } CheckDlgButton(hWnd, IDC_CLOSE_HACK1, BST_CHECKED * (config.closeHacks&1)); CheckDlgButton(hWnd, IDC_CLOSE_HACK2, BST_CHECKED * ((config.closeHacks&2)>>1)); if (config.osVersion < 6) EnableWindow(GetDlgItem(hWnd, IDC_VISTA_VOLUME), 0); if (config.keyboardApi < 0 || config.keyboardApi > 3) config.keyboardApi = NO_API; CheckRadioButton(hWnd, IDC_KB_DISABLE, IDC_KB_RAW, IDC_KB_DISABLE + config.keyboardApi); if (config.mouseApi < 0 || config.mouseApi > 3) config.mouseApi = NO_API; CheckRadioButton(hWnd, IDC_M_DISABLE, IDC_M_RAW, IDC_M_DISABLE + config.mouseApi); if (!InitializeRawInput()) { EnableWindow(GetDlgItem(hWnd, IDC_KB_RAW), 0); EnableWindow(GetDlgItem(hWnd, IDC_M_RAW), 0); } break; case WM_DEVICECHANGE: if (wParam == DBT_DEVNODES_CHANGED) { RefreshEnabledDevicesAndDisplay(1, hWndGeneral, 1); UpdatePadList(hWnd); } break; case WM_COMMAND: if (LOWORD(wParam) == IDC_PAD_TYPE) { if (HIWORD(wParam) == CBN_SELCHANGE) { HWND hWndCombo = GetDlgItem(hWnd, IDC_PAD_TYPE); int index = ListView_GetNextItem(hWndList, -1, LVNI_SELECTED); int sel = SendMessage(hWndCombo, CB_GETCURSEL, 0, 0); int port, slot; if (sel < 0 || !ListIndexToPortAndSlot(index, &port, &slot)) break; if (sel != config.padConfigs[port][slot].type) { config.padConfigs[port][slot].type = (PadType)sel; UpdatePadList(hWnd); UpdatePadPages(); RefreshEnabledDevicesAndDisplay(0, hWnd, 1); PropSheet_Changed(hWndProp, hWnd); } } } else if (HIWORD(wParam)==BN_CLICKED && (LOWORD(wParam) == ID_LOAD || LOWORD(wParam) == ID_SAVE)) { OPENFILENAMEW ofn; memset (&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hWnd; ofn.lpstrFilter = L"LilyPad Config Files\0*.lily\0All Files\0*.*\0\0"; wchar_t file[MAX_PATH+1]; ofn.lpstrFile = file; ofn.nMaxFile = MAX_PATH; wcscpy(file, config.lastSaveConfigFileName); ofn.lpstrInitialDir = config.lastSaveConfigPath; ofn.Flags = OFN_DONTADDTORECENT | OFN_LONGNAMES | OFN_NOCHANGEDIR; if (LOWORD(wParam) == ID_LOAD) { ofn.lpstrTitle = L"Load LilyPad Configuration"; ofn.Flags |= OFN_FILEMUSTEXIST; if (GetOpenFileNameW(&ofn)) { LoadSettings(1, ofn.lpstrFile); GeneralDialogProc(hWnd, WM_INITDIALOG, 0, 0); PropSheet_Changed(hWndProp, hWnd); } } else { ofn.lpstrTitle = L"Save LilyPad Configuration"; ofn.Flags |= OFN_OVERWRITEPROMPT; if (GetSaveFileNameW(&ofn)) { if (SaveSettings(ofn.lpstrFile) == -1) { MessageBox(hWnd, L"Save fail", L"Couldn't save file.", MB_OK); } } } break; } else if (HIWORD(wParam)==BN_CLICKED && LOWORD(wParam) == ID_TEST) { Diagnostics(hWnd); RefreshEnabledDevices(); } else if (HIWORD(wParam)==BN_CLICKED && LOWORD(wParam) == ID_REFRESH) { RefreshEnabledDevicesAndDisplay(1, hWnd, 1); UpdatePadList(hWnd); } else if (HIWORD(wParam)==BN_CLICKED && LOWORD(wParam) == IDC_ANALOG_START1) { int index = ListView_GetNextItem(hWndList, -1, LVNI_SELECTED); int port, slot; if (!ListIndexToPortAndSlot(index, &port, &slot)) break; config.padConfigs[port][slot].autoAnalog = (IsDlgButtonChecked(hWnd, IDC_ANALOG_START1) == BST_CHECKED); PropSheet_Changed(hWndProp, hWnd); } else { int t = IDC_CLOSE_HACK1; int test = LOWORD(wParam); if (test == IDC_CLOSE_HACK1) { CheckDlgButton(hWnd, IDC_CLOSE_HACK2, BST_UNCHECKED); } else if (test == IDC_CLOSE_HACK2) { CheckDlgButton(hWnd, IDC_CLOSE_HACK1, BST_UNCHECKED); } int mtap = config.multitap[0] + 2*config.multitap[1]; int vistaVol = config.vistaVolume; for (int j=0; j<sizeof(BoolOptionsInfo)/sizeof(BoolOptionsInfo[0]); j++) { config.bools[j] = (IsDlgButtonChecked(hWnd, BoolOptionsInfo[j].ControlId) == BST_CHECKED); } config.closeHacks = (IsDlgButtonChecked(hWnd, IDC_CLOSE_HACK1) == BST_CHECKED) | ((IsDlgButtonChecked(hWnd, IDC_CLOSE_HACK2) == BST_CHECKED)<<1); if (!config.vistaVolume) { if (vistaVol) { // Restore volume if just disabled. Don't touch, otherwise, just in case // sound plugin plays with it. SetVolume(100); } config.vistaVolume = 100; } for (i=0; i<4; i++) { if (i && IsDlgButtonChecked(hWnd, IDC_KB_DISABLE+i) == BST_CHECKED) { config.keyboardApi = (DeviceAPI)i; } if (IsDlgButtonChecked(hWnd, IDC_M_DISABLE+i) == BST_CHECKED) { config.mouseApi = (DeviceAPI)i; } } if (mtap != config.multitap[0] + 2*config.multitap[1]) { UpdatePadPages(); } RefreshEnabledDevicesAndDisplay(0, hWnd, 1); UpdatePadList(hWnd); PropSheet_Changed(hWndProp, hWnd); } break; case WM_NOTIFY: { PSHNOTIFY* n = (PSHNOTIFY*) lParam; if (n->hdr.hwndFrom == hWndProp) { switch(n->hdr.code) { case PSN_QUERYCANCEL: case PSN_KILLACTIVE: EndBinding(hWnd); return 0; case PSN_SETACTIVE: //selected = 0; UpdatePadList(hWnd); return 0; case PSN_APPLY: selected = 0; if (SaveSettings()) { SetWindowLong(hWnd, DWL_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE); return 0; } SetWindowLong(hWnd, DWL_MSGRESULT, PSNRET_NOERROR); return 1; } } else if (n->hdr.idFrom == IDC_LIST && n->hdr.code == NM_DBLCLK) { Diagnostics(hWnd); } else if (n->hdr.idFrom == IDC_PAD_LIST) { if (n->hdr.code == LVN_ITEMCHANGED) { UpdatePadList(hWnd); } if (n->hdr.code == NM_RCLICK) { UpdatePadList(hWnd); int index = ListView_GetNextItem(hWndList, -1, LVNI_SELECTED); int port1, slot1, port2, slot2; if (!ListIndexToPortAndSlot(index, &port1, &slot1)) break; HMENU hMenu = CreatePopupMenu(); if (!hMenu) break; MENUITEMINFOW info; for (port2=1; port2>=0; port2--) { for (slot2 = 3; slot2>=0; slot2--) { wchar_t text[40]; wchar_t pad[20]; if (!GetPadString(pad, port2, slot2)) continue; info.cbSize = sizeof(info); info.fMask = MIIM_STRING | MIIM_ID; info.dwTypeData = text; if (port2 == port1 && slot2 == slot1) { int index = GetMenuItemCount(hMenu); wsprintfW(text, L"Clear %s Bindings", pad); info.wID = -1; InsertMenuItemW(hMenu, index, 1, &info); info.fMask = MIIM_TYPE; info.fType = MFT_SEPARATOR; InsertMenuItemW(hMenu, index, 1, &info); } else { info.wID = port2+2*slot2+1; wsprintfW(text, L"Swap with %s", pad); InsertMenuItemW(hMenu, 0, 1, &info); } } } POINT pos; GetCursorPos(&pos); short res = TrackPopupMenuEx(hMenu, TPM_NONOTIFY|TPM_RETURNCMD, pos.x, pos.y, hWndProp, 0); DestroyMenu(hMenu); if (!res) break; if (res > 0) { res--; slot2 = res / 2; port2 = res&1; PadConfig padCfgTemp = config.padConfigs[port1][slot1]; config.padConfigs[port1][slot1] = config.padConfigs[port2][slot2]; config.padConfigs[port2][slot2] = padCfgTemp; for (int i=0; i<dm->numDevices; i++) { if (dm->devices[i]->type == IGNORE) continue; PadBindings bindings = dm->devices[i]->pads[port1][slot1]; dm->devices[i]->pads[port1][slot1] = dm->devices[i]->pads[port2][slot2]; dm->devices[i]->pads[port2][slot2] = bindings; } } else { for (int i=0; i<dm->numDevices; i++) { if (dm->devices[i]->type == IGNORE) continue; free(dm->devices[i]->pads[port1][slot1].bindings); for (int j=0; j<dm->devices[i]->pads[port1][slot1].numFFBindings; j++) { free(dm->devices[i]->pads[port1][slot1].ffBindings[j].axes); } free(dm->devices[i]->pads[port1][slot1].ffBindings); memset(&dm->devices[i]->pads[port1][slot1], 0, sizeof(dm->devices[i]->pads[port1][slot1])); } } UpdatePadPages(); UpdatePadList(hWnd); PropSheet_Changed(hWndProp, hWnd); } } } break; default: break; } return 0; } int CALLBACK PropSheetProc(HWND hWnd, UINT msg, LPARAM lParam) { if (hWnd) hWndProp = hWnd; return 0; } void Configure() { // Can end up here without PADinit() being called first. LoadSettings(); // Can also end up here after running emulator a bit, and possibly // disabling some devices due to focus changes, or releasing mouse. RefreshEnabledDevices(0); memset(hWnds, 0, sizeof(hWnds)); PROPSHEETPAGE psp; ZeroMemory(&psp, sizeof(psp)); psp.dwSize = sizeof(psp); psp.dwFlags = PSP_USETITLE | PSP_PREMATURE; psp.hInstance = hInst; psp.pfnDlgProc = GeneralDialogProc; psp.pszTitle = L"General"; psp.pszTemplate = MAKEINTRESOURCE(IDD_GENERAL); HPROPSHEETPAGE page = CreatePropertySheetPage(&psp); if (!page) return; PROPSHEETHEADER psh; ZeroMemory(&psh, sizeof(psh)); psh.dwFlags = PSH_DEFAULT | PSH_USECALLBACK | PSH_NOCONTEXTHELP; psh.dwSize = sizeof(PROPSHEETHEADER); psh.pfnCallback = PropSheetProc; psh.hwndParent = GetActiveWindow(); psh.nPages = 1; psh.phpage = &page; wchar_t title[200]; GetNameAndVersionString(title); wcscat(title, L" Settings"); psh.pszCaption = title; PropertySheet(&psh); LoadSettings(1); memset(hWnds, 0, sizeof(hWnds)); } void UnloadConfigs() { if (dm) { delete dm; dm = 0; } } <|start_filename|>Scp/XInput_Scp/X360Controller.h<|end_filename|> #pragma once class CX360Controller : public CSCPController { public: static const DWORD CollectionSize = 1; protected: XINPUT_STATE m_State; public: CX360Controller(DWORD dwIndex); virtual BOOL Open(void); virtual BOOL Close(void); virtual DWORD GetState(DWORD dwUserIndex, XINPUT_STATE* pState); virtual DWORD SetState(DWORD dwUserIndex, XINPUT_VIBRATION* pVibration); virtual DWORD GetCapabilities(DWORD dwUserIndex, DWORD dwFlags, XINPUT_CAPABILITIES* pCapabilities); virtual DWORD GetDSoundAudioDeviceGuids(DWORD dwUserIndex, GUID* pDSoundRenderGuid, GUID* pDSoundCaptureGuid); virtual DWORD GetBatteryInformation(DWORD dwUserIndex, BYTE devType, XINPUT_BATTERY_INFORMATION* pBatteryInformation); virtual DWORD GetKeystroke(DWORD dwUserIndex, DWORD dwReserved, PXINPUT_KEYSTROKE pKeystroke); virtual DWORD GetExtended(DWORD dwUserIndex, SCP_EXTN *Pressure); // UNDOCUMENTED virtual DWORD GetStateEx(DWORD dwUserIndex, XINPUT_STATE *pState); virtual DWORD WaitForGuideButton(DWORD dwUserIndex, DWORD dwFlag, LPVOID pVoid); virtual DWORD CancelGuideButtonWait(DWORD dwUserIndex); virtual DWORD PowerOffController(DWORD dwUserIndex); }; <|start_filename|>Scp/ScpControl/Properties/AssemblyInfo.cs<|end_filename|> using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ScpControl")] [assembly: AssemblyProduct("ScpControl")] [assembly: Guid("8848658d-0ae2-43fe-9b7c-5ff3ad35c1a8")] <|start_filename|>Scp/ScpInstaller/ScpForm.Designer.cs<|end_filename|> namespace ScpDriver { partial class ScpForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnUninstall = new System.Windows.Forms.Button(); this.btnInstall = new System.Windows.Forms.Button(); this.InstallWorker = new System.ComponentModel.BackgroundWorker(); this.UninstallWorker = new System.ComponentModel.BackgroundWorker(); this.tbOutput = new System.Windows.Forms.TextBox(); this.pbRunning = new System.Windows.Forms.ProgressBar(); this.btnExit = new System.Windows.Forms.Button(); this.cbService = new System.Windows.Forms.CheckBox(); this.cbBluetooth = new System.Windows.Forms.CheckBox(); this.cbForce = new System.Windows.Forms.CheckBox(); this.cbDS3 = new System.Windows.Forms.CheckBox(); this.cbBus = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // btnUninstall // this.btnUninstall.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnUninstall.Location = new System.Drawing.Point(416, 377); this.btnUninstall.Name = "btnUninstall"; this.btnUninstall.Size = new System.Drawing.Size(75, 23); this.btnUninstall.TabIndex = 3; this.btnUninstall.Text = "&Uninstall"; this.btnUninstall.UseVisualStyleBackColor = true; this.btnUninstall.Click += new System.EventHandler(this.btnUninstall_Click); // // btnInstall // this.btnInstall.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnInstall.Location = new System.Drawing.Point(335, 377); this.btnInstall.Name = "btnInstall"; this.btnInstall.Size = new System.Drawing.Size(75, 23); this.btnInstall.TabIndex = 2; this.btnInstall.Text = "&Install"; this.btnInstall.UseVisualStyleBackColor = true; this.btnInstall.Click += new System.EventHandler(this.btnInstall_Click); // // InstallWorker // this.InstallWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.InstallWorker_DoWork); this.InstallWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.InstallWorker_RunWorkerCompleted); // // UninstallWorker // this.UninstallWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.UninstallWorker_DoWork); this.UninstallWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.UninstallWorker_RunWorkerCompleted); // // tbOutput // this.tbOutput.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbOutput.BackColor = System.Drawing.SystemColors.Window; this.tbOutput.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbOutput.Location = new System.Drawing.Point(13, 13); this.tbOutput.Multiline = true; this.tbOutput.Name = "tbOutput"; this.tbOutput.ReadOnly = true; this.tbOutput.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.tbOutput.Size = new System.Drawing.Size(559, 335); this.tbOutput.TabIndex = 4; this.tbOutput.TabStop = false; this.tbOutput.WordWrap = false; // // pbRunning // this.pbRunning.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pbRunning.Location = new System.Drawing.Point(13, 354); this.pbRunning.Name = "pbRunning"; this.pbRunning.Size = new System.Drawing.Size(559, 17); this.pbRunning.TabIndex = 5; // // btnExit // this.btnExit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnExit.Location = new System.Drawing.Point(497, 377); this.btnExit.Name = "btnExit"; this.btnExit.Size = new System.Drawing.Size(75, 23); this.btnExit.TabIndex = 0; this.btnExit.Text = "E&xit"; this.btnExit.UseVisualStyleBackColor = true; this.btnExit.Click += new System.EventHandler(this.btnExit_Click); // // cbService // this.cbService.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.cbService.AutoSize = true; this.cbService.Checked = true; this.cbService.CheckState = System.Windows.Forms.CheckState.Checked; this.cbService.Location = new System.Drawing.Point(102, 381); this.cbService.Name = "cbService"; this.cbService.Size = new System.Drawing.Size(110, 17); this.cbService.TabIndex = 6; this.cbService.Text = "Configure Service"; this.cbService.UseVisualStyleBackColor = true; // // cbBluetooth // this.cbBluetooth.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.cbBluetooth.AutoSize = true; this.cbBluetooth.Checked = true; this.cbBluetooth.CheckState = System.Windows.Forms.CheckState.Checked; this.cbBluetooth.Location = new System.Drawing.Point(218, 381); this.cbBluetooth.Name = "cbBluetooth"; this.cbBluetooth.Size = new System.Drawing.Size(102, 17); this.cbBluetooth.TabIndex = 7; this.cbBluetooth.Text = "Bluetooth Driver"; this.cbBluetooth.UseVisualStyleBackColor = true; // // cbForce // this.cbForce.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.cbForce.AutoSize = true; this.cbForce.Location = new System.Drawing.Point(13, 381); this.cbForce.Name = "cbForce"; this.cbForce.Size = new System.Drawing.Size(83, 17); this.cbForce.TabIndex = 8; this.cbForce.Text = "Force Install"; this.cbForce.UseVisualStyleBackColor = true; // // cbDS3 // this.cbDS3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.cbDS3.AutoSize = true; this.cbDS3.Checked = true; this.cbDS3.CheckState = System.Windows.Forms.CheckState.Checked; this.cbDS3.Location = new System.Drawing.Point(12, 450); this.cbDS3.Name = "cbDS3"; this.cbDS3.Size = new System.Drawing.Size(78, 17); this.cbDS3.TabIndex = 9; this.cbDS3.Text = "DS3 Driver"; this.cbDS3.UseVisualStyleBackColor = true; // // cbBus // this.cbBus.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.cbBus.AutoSize = true; this.cbBus.Checked = true; this.cbBus.CheckState = System.Windows.Forms.CheckState.Checked; this.cbBus.Location = new System.Drawing.Point(102, 450); this.cbBus.Name = "cbBus"; this.cbBus.Size = new System.Drawing.Size(75, 17); this.cbBus.TabIndex = 10; this.cbBus.Text = "Bus Driver"; this.cbBus.UseVisualStyleBackColor = true; // // ScpForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(584, 412); this.Controls.Add(this.cbBus); this.Controls.Add(this.cbDS3); this.Controls.Add(this.cbForce); this.Controls.Add(this.cbBluetooth); this.Controls.Add(this.cbService); this.Controls.Add(this.btnExit); this.Controls.Add(this.pbRunning); this.Controls.Add(this.tbOutput); this.Controls.Add(this.btnInstall); this.Controls.Add(this.btnUninstall); this.MinimumSize = new System.Drawing.Size(600, 450); this.Name = "ScpForm"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; this.Text = "SCP Driver Installer"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ScpForm_Close); this.Load += new System.EventHandler(this.ScpForm_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnUninstall; private System.Windows.Forms.Button btnInstall; private System.ComponentModel.BackgroundWorker InstallWorker; private System.ComponentModel.BackgroundWorker UninstallWorker; private System.Windows.Forms.TextBox tbOutput; private System.Windows.Forms.ProgressBar pbRunning; private System.Windows.Forms.Button btnExit; private System.Windows.Forms.CheckBox cbService; private System.Windows.Forms.CheckBox cbBluetooth; private System.Windows.Forms.CheckBox cbForce; private System.Windows.Forms.CheckBox cbDS3; private System.Windows.Forms.CheckBox cbBus; } }
raccoonwithspork/WiinUPro
<|start_filename|>src/CtaEventTracker.js<|end_filename|> import BaseElement from 'BaseElement'; import GTM from 'gtm'; export default class CtaEventTracker extends BaseElement { constructor(el) { super(el); this.trackCategory = null; this.trackLabel = null; this.elText = null; this.pageName = document.title; this.init(); } init() { this.el.addEventListener('click', this.onClick.bind(this)); } onDestroy() { this.el = null; } onClick() { this.elText = this.el.innerText || this.el.textContent; this.trackCategory = this.el.getAttribute('track-category') ? this.el.getAttribute('track-category') : this.pageName; this.trackLabel = this.el.getAttribute('track-label') ? this.el.getAttribute('track-label') : this.elText; GTM.push(this.trackCategory, 'click', this.trackLabel); } } <|start_filename|>src/gtm.js<|end_filename|> class GTM { push(category, action, label) { if (window.dataLayer) { window.dataLayer.push(Object.assign( { event: 'eventTrack' }, { eventCategory: category, eventAction: action, eventLabel: label } )); } } } export default new GTM(); <|start_filename|>src/BaseElement.js<|end_filename|> export default class BaseElement { constructor(el) { this.el = el; this.isInited = false; this.listenerList = []; } init() { throw new Error('init() method is not implemented'); } setVariables() { throw new Error('setVariables() is not implemented'); } addListeners() { throw new Error('addListeners() is not implemented'); } addListener(elem, eventName, eventCallback) { if (!elem || typeof elem.addEventListener !== 'function') return; elem.addEventListener(eventName, eventCallback); this.listenerList.push({ elem, eventName, eventCallback }); } removeListeners() { this.listenerList.forEach((listener) => { const { elem, eventName, eventCallback } = listener; elem.removeEventListener(eventName, eventCallback); }); this.listenerList = []; } onDestroy() { } destroy() { this.removeListeners(); this.onDestroy(); } }
kate-orlova/gtm-tracking
<|start_filename|>lib/vk.dart<|end_filename|> library virtual_keyboard; import 'dart:async'; import 'package:flutter/material.dart'; part 'src/key.action.dart'; part 'src/key.type.dart'; part './src/keys.dart'; part './src/keyboard.dart'; part 'src/keyboard.type.dart'; <|start_filename|>lib/src/keys.dart<|end_filename|> part of virtual_keyboard; /// US keyboard layout List<List<VirtualKeyboardKey>> usLayout = [ // Row 1 [ TextKey( "q", ), TextKey( "w", ), TextKey( "e", ), TextKey( "r", ), TextKey( "t", ), TextKey( "y", ), TextKey( "u", ), TextKey( "i", ), TextKey( "o", ), TextKey( "p", ), ], // Row 2 [ TextKey( "a", ), TextKey( "s", ), TextKey( "d", ), TextKey( "f", ), TextKey( "g", ), TextKey( "h", ), TextKey( "j", ), TextKey( "k", ), TextKey( "l", ), ], // Row 3 [ ActionKey(VirtualKeyboardKeyAction.Shift), TextKey( "z", ), TextKey( "x", ), TextKey( "c", ), TextKey( "v", ), TextKey( "b", ), TextKey( "n", ), TextKey( "m", ), ActionKey(VirtualKeyboardKeyAction.Backspace), ], // Row 4 [ ActionKey(VirtualKeyboardKeyAction.Symbols), TextKey(','), ActionKey(VirtualKeyboardKeyAction.Space), TextKey('.'), ActionKey(VirtualKeyboardKeyAction.Return), ] ]; /// Symbol layout List<List<VirtualKeyboardKey>> symbolLayout = [ // Row 1 [ TextKey( "1", ), TextKey( "2", ), TextKey( "3", ), TextKey( "4", ), TextKey( "5", ), TextKey( "6", ), TextKey( "7", ), TextKey( "8", ), TextKey( "9", ), TextKey( "0", ), ], // Row 2 [ TextKey('@'), TextKey('#'), TextKey('\$'), TextKey('_'), TextKey('-'), TextKey('+'), TextKey('('), TextKey(')'), TextKey('/'), ], // Row 3 [ TextKey('|'), TextKey('*'), TextKey('"'), TextKey('\''), TextKey(':'), TextKey(';'), TextKey('!'), TextKey('?'), ActionKey(VirtualKeyboardKeyAction.Backspace), ], // Row 5 [ ActionKey(VirtualKeyboardKeyAction.Alpha), TextKey(','), ActionKey(VirtualKeyboardKeyAction.Space), TextKey('.'), ActionKey(VirtualKeyboardKeyAction.Return), ] ]; /// numeric keyboard layout List<List<VirtualKeyboardKey>> numericLayout = [ // Row 1 [ TextKey('1'), TextKey('2'), TextKey('3'), ], // Row 1 [ TextKey('4'), TextKey('5'), TextKey('6'), ], // Row 1 [ TextKey('7'), TextKey('8'), TextKey('9'), ], // Row 1 [TextKey('.'), TextKey('0'), ActionKey(VirtualKeyboardKeyAction.Backspace)], ]; <|start_filename|>lib/src/keyboard.type.dart<|end_filename|> part of virtual_keyboard; /// Available Virtual Keyboard Types: /// `Numeric` - Numeric only. /// `Alphanumeric` - Alphanumeric: letters`[A-Z]` + numbers`[0-9]` + `@` + `.`. enum VirtualKeyboardType { Numeric, Alphanumeric, Symbolic } <|start_filename|>example/lib/main.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:vk/vk.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Virtual Keyboard Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Virtual Keyboard Example'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { // Holds the text that user typed. String text = ''; // True if shift enabled. bool shiftEnabled = false; // is true will show the numeric keyboard. bool isNumericMode = false; late TextEditingController _controllerText; @override void initState() { _controllerText = TextEditingController(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), child: TextField( controller: _controllerText, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Your text', ), )), SwitchListTile( title: Text( 'Keyboard Type = ' + (isNumericMode ? 'VirtualKeyboardType.Numeric' : 'VirtualKeyboardType.Alphanumeric'), ), value: isNumericMode, onChanged: (val) { setState(() { isNumericMode = val; }); }, ), Expanded( child: Container(), ), Container( color: Colors.grey.shade900, child: VirtualKeyboard( height: 400, type: isNumericMode ? VirtualKeyboardType.Numeric : VirtualKeyboardType.Alphanumeric, textController: _controllerText), ) ], ), ), ); } } <|start_filename|>lib/src/key.action.dart<|end_filename|> part of virtual_keyboard; /// Virtual keyboard actions. enum VirtualKeyboardKeyAction { Backspace, Return, Shift, Space, Symbols, Alpha } <|start_filename|>lib/src/keyboard.dart<|end_filename|> part of virtual_keyboard; /// The default keyboard height. Can we overriden by passing /// `height` argument to `VirtualKeyboard` widget. const double _virtualKeyboardDefaultHeight = 300; const int _virtualKeyboardBackspaceEventPerioud = 250; /// Virtual Keyboard widget. class VirtualKeyboard extends StatefulWidget { /// Keyboard Type: Should be inited in creation time. final VirtualKeyboardType type; /// The text controller final TextEditingController textController; /// Virtual keyboard height. Default is 300 final double height; /// Color for key texts and icons. final Color textColor; /// Font size for keyboard keys. final double fontSize; /// The builder function will be called for each Key object. final Widget Function(BuildContext context, VirtualKeyboardKey key)? builder; /// Set to true if you want only to show Caps letters. final bool alwaysCaps; VirtualKeyboard( {Key? key, required this.type, required this.textController, this.builder, this.height = _virtualKeyboardDefaultHeight, this.textColor = Colors.black, this.fontSize = 20, this.alwaysCaps = false}) : super(key: key); @override State<StatefulWidget> createState() { return _VirtualKeyboardState(); } } /// Holds the state for Virtual Keyboard class. class _VirtualKeyboardState extends State<VirtualKeyboard> { late double keyHeight; late double keySpacing; late double maxRowWidth; VirtualKeyboardType? type; // The builder function will be called for each Key object. Widget Function(BuildContext context, VirtualKeyboardKey key)? builder; late double height; late double width; TextSelection? cursorPosition; late TextEditingController textController; late Color textColor; late double fontSize; late bool alwaysCaps; // Text Style for keys. late TextStyle textStyle; // True if shift is enabled. bool isShiftEnabled = false; @override void didUpdateWidget(VirtualKeyboard oldWidget) { super.didUpdateWidget(oldWidget); setState(() { type = widget.type; height = widget.height; textColor = widget.textColor; fontSize = widget.fontSize; alwaysCaps = widget.alwaysCaps; // Init the Text Style for keys. textStyle = TextStyle( fontSize: fontSize, color: textColor, ); }); } void textControllerEvent() { if (textController.selection.toString() != "TextSelection.invalid") { cursorPosition = textController.selection; } else { if (cursorPosition == null) { cursorPosition = TextSelection(baseOffset: 0, extentOffset: 0); } else {} } } @override void initState() { super.initState(); textController = widget.textController; type = widget.type; height = widget.height; textColor = widget.textColor; fontSize = widget.fontSize; alwaysCaps = widget.alwaysCaps; textController.addListener(textControllerEvent); // Init the Text Style for keys. textStyle = TextStyle( fontWeight: FontWeight.w600, fontSize: fontSize, color: textColor, ); } @override Widget build(BuildContext context) { width = MediaQuery.of(context).size.width; switch (type) { case VirtualKeyboardType.Numeric: return _keyLayout(numericLayout); case VirtualKeyboardType.Alphanumeric: return _keyLayout(usLayout); case VirtualKeyboardType.Symbolic: return _keyLayout(symbolLayout); default: throw new Error(); } } Widget _keyLayout(List<List<VirtualKeyboardKey>> layout) { // arbritrary keySpacing = 8.0; double totalSpacing = keySpacing * (layout.length + 1); keyHeight = (height - totalSpacing) / layout.length; int maxLengthRow = 0; for (var layoutRow in layout) { if (layoutRow.length > maxLengthRow) { maxLengthRow = layoutRow.length; } } maxRowWidth = ((maxLengthRow - 1) * keySpacing) + (maxLengthRow * keyHeight); return Container( height: height, width: width, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: _rows(layout), ), ); } /// Returns the rows for keyboard. List<Widget> _rows(List<List<VirtualKeyboardKey>> layout) { // Generate keyboard row. List<Widget> rows = []; for (var rowEntry in layout.asMap().entries) { int rowNum = rowEntry.key; List<VirtualKeyboardKey> rowKeys = rowEntry.value; List<Widget> cols = []; for (var colEntry in rowKeys.asMap().entries) { int colNum = colEntry.key; VirtualKeyboardKey virtualKeyboardKey = colEntry.value; Widget keyWidget; if (builder == null) { // Check the key type. switch (virtualKeyboardKey.keyType) { case VirtualKeyboardKeyType.String: // Draw String key. keyWidget = _keyboardDefaultKey(virtualKeyboardKey); break; case VirtualKeyboardKeyType.Action: // Draw action key. keyWidget = _keyboardDefaultActionKey(virtualKeyboardKey); break; } } else { // Call the builder function, so the user can specify custom UI for keys. keyWidget = builder!(context, virtualKeyboardKey); throw 'builder function must return Widget'; } cols.add(keyWidget); // space between keys if (colNum != rowKeys.length - 1) { cols.add(SizedBox( width: keySpacing, )); } } rows.add(Material( color: Colors.transparent, child: ConstrainedBox( constraints: BoxConstraints(maxWidth: maxRowWidth), child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, // Generate keboard keys children: cols), ))); // space between rows if (rowNum != layout.length - 1) { rows.add(SizedBox( height: keySpacing, )); } } return rows; } // True if long press is enabled. late bool longPress; /// Creates default UI element for keyboard Key. Widget _keyboardDefaultKey(VirtualKeyboardKey key) { return Material( color: Colors.grey, borderRadius: BorderRadius.all(Radius.circular(10)), child: InkWell( highlightColor: Colors.blue, borderRadius: BorderRadius.all(Radius.circular(10)), onTap: () { _onKeyPress(key); }, child: Container( width: keyHeight, height: keyHeight, child: Center( child: Text( alwaysCaps ? key.capsText! : (isShiftEnabled ? key.capsText! : key.text!), style: textStyle, )), ), )); } void _onKeyPress(VirtualKeyboardKey key) { if (key.keyType == VirtualKeyboardKeyType.String) { String text = textController.text; if (cursorPosition == null) textControllerEvent(); textController.text = cursorPosition!.textBefore(text) + (isShiftEnabled ? key.capsText! : key.text!) + cursorPosition!.textAfter(text); cursorPosition = TextSelection( baseOffset: cursorPosition!.baseOffset + 1, extentOffset: cursorPosition!.extentOffset + 1); } else if (key.keyType == VirtualKeyboardKeyType.Action) { switch (key.action) { case VirtualKeyboardKeyAction.Backspace: if (textController.text.length == 0) return; if (cursorPosition!.start == 0) return; String text = textController.text; if (cursorPosition == null) textControllerEvent(); textController.text = cursorPosition!.start == text.length ? text.substring(0, text.length - 1) : text.substring(0, cursorPosition!.start - 1) + text.substring(cursorPosition!.start); cursorPosition = TextSelection( baseOffset: cursorPosition!.baseOffset - 1, extentOffset: cursorPosition!.extentOffset - 1); break; case VirtualKeyboardKeyAction.Return: textController.text += '\n'; break; case VirtualKeyboardKeyAction.Space: textController.text += key.text!; break; case VirtualKeyboardKeyAction.Shift: break; case VirtualKeyboardKeyAction.Alpha: setState(() { type = VirtualKeyboardType.Alphanumeric; }); break; case VirtualKeyboardKeyAction.Symbols: setState(() { type = VirtualKeyboardType.Symbolic; }); break; default: } } } /// Creates default UI element for keyboard Action Key. Widget _keyboardDefaultActionKey(VirtualKeyboardKey key) { // Holds the action key widget. Widget actionKey; // Switch the action type to build action Key widget. switch (key.action!) { case VirtualKeyboardKeyAction.Backspace: actionKey = GestureDetector( onLongPress: () { longPress = true; // Start sending backspace key events while longPress is true Timer.periodic( Duration(milliseconds: _virtualKeyboardBackspaceEventPerioud), (timer) { if (longPress) { _onKeyPress(key); } else { // Cancel timer. timer.cancel(); } }); }, onLongPressUp: () { // Cancel event loop longPress = false; }, child: Container( height: double.infinity, width: double.infinity, child: Icon( Icons.backspace, color: textColor, ), )); break; case VirtualKeyboardKeyAction.Shift: actionKey = Icon(Icons.arrow_upward, color: isShiftEnabled ? Colors.lime : textColor); break; case VirtualKeyboardKeyAction.Space: actionKey = Icon(Icons.space_bar, color: textColor); break; case VirtualKeyboardKeyAction.Return: actionKey = Icon( Icons.keyboard_return, color: textColor, ); break; case VirtualKeyboardKeyAction.Symbols: actionKey = Icon(Icons.emoji_symbols, color: textColor); break; case VirtualKeyboardKeyAction.Alpha: actionKey = Icon(Icons.sort_by_alpha, color: textColor); break; } var finalKey = Material( color: Colors.grey, borderRadius: BorderRadius.all(Radius.circular(10)), child: InkWell( borderRadius: BorderRadius.all(Radius.circular(10)), highlightColor: Colors.blue, onTap: () { if (key.action == VirtualKeyboardKeyAction.Shift) { if (!alwaysCaps) { setState(() { isShiftEnabled = !isShiftEnabled; }); } } _onKeyPress(key); }, child: Container( width: keyHeight, height: keyHeight, child: actionKey, ), ), ); if (key.willExpand) { return Expanded(child: finalKey); } else { return finalKey; } } } <|start_filename|>lib/src/key.type.dart<|end_filename|> part of virtual_keyboard; /// Type for virtual keyboard key. /// /// `Action` - Can be action key - Return, Backspace, etc. /// /// `String` - Keys that have text value - `Letters`, `Numbers`, `@` `.` enum VirtualKeyboardKeyType { Action, String } /// Virtual Keyboard key class VirtualKeyboardKey { /// Will the key expand in it's place bool willExpand = false; String? text; String? capsText; final VirtualKeyboardKeyType keyType; final VirtualKeyboardKeyAction? action; VirtualKeyboardKey( {this.text, this.capsText, required this.keyType, this.action}); } /// Shorthand for creating a simple text key class TextKey extends VirtualKeyboardKey { TextKey(String text, {String? capsText}) : super( text: text, capsText: capsText == null ? text.toUpperCase() : capsText, keyType: VirtualKeyboardKeyType.String); } /// Shorthand for creating action keys class ActionKey extends VirtualKeyboardKey { ActionKey(VirtualKeyboardKeyAction action) : super(keyType: VirtualKeyboardKeyType.Action, action: action) { switch (action) { case VirtualKeyboardKeyAction.Space: super.text = ' '; super.capsText = ' '; super.willExpand = true; break; case VirtualKeyboardKeyAction.Return: super.text = '\n'; super.capsText = '\n'; break; case VirtualKeyboardKeyAction.Backspace: super.willExpand = true; break; default: break; } } }
Taha-Firoz/virtual.keyboard.dart
<|start_filename|>js/pass-2.frag<|end_filename|> varying vec2 coord; uniform sampler2D tDiffuse; vec3 c0 = vec3(0.0, 0.0, 0.0); vec3 c1 = vec3(1.0, 1.0, 1.2); vec3 c2 = vec3(0.0, 0.0, 0.2); vec3 c3 = vec3(1.0, 0.5, 0.5); vec3 c4 = vec3(0.6, 0.0, 0.0); vec4 f(float lev, float x0, vec3 c0, float x1, vec3 c1) { lev = (lev - x0) / (x1 - x0); lev *= lev * lev * lev; return vec4(c1 * lev + c0 * (1.0 - lev), 1.0); } void main() { float lev = texture2D(tDiffuse, coord).x; /* XXX: should be configurable */ if (lev < 0.01) gl_FragColor = f(lev, 0.01, c0, 0.00, c0); else if (lev < 0.10) gl_FragColor = f(lev, 0.01, c0, 0.10, c1); else if (lev < 0.30) gl_FragColor = f(lev, 0.30, c2, 0.10, c1); else if (lev < 0.40) gl_FragColor = f(lev, 0.30, c2, 0.40, c3); else if (lev < 1.00) gl_FragColor = f(lev, 1.00, c4, 0.40, c3); else gl_FragColor = f(lev, 1.00, c4, 9.99, c4); return; if (lev < 0.1) discard; else if (lev < 0.4) { float v = 0.5 - lev; v = v * v * v * 20.0; gl_FragColor = vec4(vec3(v, v, v + 0.2), 1.0); } else { float v = 1.0 - lev; v = v * v * v * v * 2.0; gl_FragColor = vec4(vec3(v + 0.8, v + 0.2, v + 0.2), 1.0); } } <|start_filename|>js/navi.js<|end_filename|> /** * A navigation manager. * @constructor * @param {Number} x initial center point. * @param {Number} y initial center point. * @param {Number} scale initial scale. * @param {Number} dumping_factor dumping factor. */ Golgi.Navi = function(x, y, scale, dumping_factor) { var self = this; self.x = x || 0; self.y = y || 0; self.scale = scale || 40; var DUMPING_FACTOR = dumping_factor || 0.9; var drag_pos = { x: 0, y: 0 }; var prev_drag_pos = null; var move_velocity = { x: 0, y: 0 }; var pinch_dist = 0; var zoom_pos = { x: 0, y: 0 }; var scale_variation = 1.0; /* drag */ self.drag_start = function(pos) { drag_pos = prev_drag_pos = pos; }; self.drag_move = function(pos) { drag_pos = pos; }; self.drag_end = function() { prev_drag_pos = null; }; function do_drag() { if (prev_drag_pos) { move_velocity = { x: drag_pos.x - prev_drag_pos.x, y: drag_pos.y - prev_drag_pos.y }; prev_drag_pos = drag_pos; } self.x -= move_velocity.x; self.y -= move_velocity.y; drag_pos.x -= move_velocity.x; drag_pos.y -= move_velocity.y; zoom_pos.x -= move_velocity.x; zoom_pos.y -= move_velocity.y; move_velocity.x *= DUMPING_FACTOR; move_velocity.y *= DUMPING_FACTOR; } /* zoom (wheel / pinch) */ self.change_scale = function(pos, delta) { zoom_pos = pos; scale_variation *= Math.pow(delta, 1 - DUMPING_FACTOR); }; function hypot(pos1, pos2) { var x = pos2.x - pos1.x; var y = pos2.y - pos1.y; return Math.sqrt(x * x + y * y); } self.pinch_start = function(pos1, pos2) { pinch_dist = hypot(pos1, pos2); }; self.pinch_move = function(pos1, pos2) { var dist = hypot(pos1, pos2); var pos = { x: (pos1.x + pos2.x) / 2, y: (pos1.y + pos2.y) / 2 }; self.change_scale(pos, Math.pow(dist / pinch_dist, 2)); pinch_dist = dist; }; function do_zoom() { self.x = (self.x - zoom_pos.x) / scale_variation + zoom_pos.x; self.y = (self.y - zoom_pos.y) / scale_variation + zoom_pos.y; self.scale *= scale_variation; scale_variation = Math.pow(scale_variation, DUMPING_FACTOR); } self.update = function(step) { do_drag(); do_zoom(); }; self.set = function(x, y, scale) { move_velocity = { x: (self.x - x) * (1 - DUMPING_FACTOR), y: (self.y - y) * (1 - DUMPING_FACTOR) }; zoom_pos = { x: self.x, y: self.y }; scale_variation = Math.pow(scale / self.scale, 1 - DUMPING_FACTOR); }; }; <|start_filename|>js/pass-2.vert<|end_filename|> varying vec2 coord; void main() { coord = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } <|start_filename|>js/pass-1.frag<|end_filename|> varying float power; varying vec2 coord; void main() { vec2 xy = coord * 2.0 - 1.0; float v = 1.0 - sqrt(dot(xy, xy)); if (v < 0.0) v = 0.0; v *= v / 3.0 * power; gl_FragColor = vec4(vec3(v, v, v),1.0); } <|start_filename|>js/main.js<|end_filename|> var Golgi = {}; /** * main. */ window.onload = function() { new UI(new Golgi.State(), new Golgi.Navi()); }; <|start_filename|>js/state.js<|end_filename|> /** * A state manager. * @constructor */ Golgi.State = function() { var self = this; self.playing = false; self.speed = 1 / 16; self.tick = 0; self.univ = HashLife.EmptyUniverse; self.next_univ = self.univ; self.meta = {}; self.need_update = false; function pause() { self.playing = false; self.on_playing_changed(); } function load_univ(univ) { self.tick = self.speed; self.next_univ = univ; self.on_univ_loaded(); pause(); } function update_univ(univ) { self.tick = self.speed; self.next_univ = univ; self.need_update = true; self.on_univ_changed(); } function play() { self.playing = true; update_univ(self.univ.run(Math.ceil(self.speed))); self.on_playing_changed(); } self.write = function(pos) { self.meta = {}; var s = self.univ.get(pos.x, pos.y); load_univ(self.univ.set(pos.x, pos.y, !s)); }; self.load = function(rle) { var r = HashLife.load(rle); self.meta = r.meta; self.on_univ_loaded(); load_univ(r.univ); }; self.change_rule = function(rule) { var cells = {}, cell, univ, x, y; self.univ.each(function(x, y) { cells[x + ',' + y] = true; }); try { HashLife.change_rule(rule); univ = HashLife.EmptyUniverse; for (cell in cells) { cell = cell.split(','); univ = univ.set(Number(cell[0]), Number(cell[1]), true); } load_univ(univ); } catch (e) { alert('illegal rule denotation; it should be like \"B3/S23\".'); } }; self.reset = function() { pause(); update_univ(self.univ.run_back(self.univ.get_generation())); }; self.clear = function() { pause(); self.load('!'); }; self.change_speed = function(mult) { self.speed *= mult; self.on_speed_changed(); }; self.play = function() { self.playing ? pause() : play(); }; self.backward = function(step) { if (self.playing) { pause(); if (self.tick === 0) { update_univ(self.univ); } else { var univ = self.univ; self.tick = 1 - self.tick; self.univ = self.next_univ; update_univ(univ); } } else if (self.tick === 0) { var gen = self.univ.get_generation(); if (gen === 0) { alert('You can no longer go back!'); } else { if (gen < step) step = gen; update_univ(self.univ.run_back(step)); } } }; self.forward = function(step) { if (self.playing) { pause(); } else if (self.tick === 0) { update_univ(self.univ.run(step)); } }; self.update = function() { if (self.playing || self.tick) { self.tick += self.speed; if (self.tick >= 1) { self.tick = 0; self.univ = self.next_univ; if (self.playing) { update_univ(self.univ.run(Math.ceil(self.speed))); } else { self.need_update = true; self.on_univ_changed(); } } } }; }; <|start_filename|>js/pass-1.vert<|end_filename|> uniform float time, scale, size; uniform vec2 origin; attribute vec3 src, dst; varying float power; varying vec2 coord; void main() { float t = time; coord = uv; vec3 p = position; t = t * t * (3.0 - 2.0 * t); p *= size; p.xy -= origin; p.x += mix(src.x, dst.x, t); p.y += mix(src.y, dst.y, t); power = mix(src.z, dst.z, t); gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0 / scale); } <|start_filename|>js/cellview.js<|end_filename|> /** * A webgl-based cellular viewer * @constructor * @param {Node} dom A dom node of a wrapper div. * @param {Number} max_grid_num A maximun number of grid lines. */ Golgi.CellView = function(dom, max_grid_num) { var webgl_available = (function() { try { return window.WebGLRenderingContext && document.createElement('canvas').getContext('experimental-webgl'); } catch (e) { return false; } })(); if (!webgl_available) throw ('WebGL not avaiable'); var renderer, camera; var scene1, particles = null, uniforms, attributes; var scene2, texture, plane, grid, cross; function create_particles(count) { uniforms = { time: { type: 'f', value: 0.0 }, scale: { type: 'f', value: 1 }, size: { type: 'f', value: 1 }, origin: { type: 'v2', value: new THREE.Vector2(0, 0) } }; attributes = { src: { type: 'v3', value: [] }, dst: { type: 'v3', value: [] } }; var geom = new THREE.Geometry(); for (var j = 0; j < count; j++) { var uvs = []; for (var i = 0; i < 4; i++) { var x = Math.floor((i + 1) / 2) % 2, y = Math.floor(i / 2); geom.vertices.push(new THREE.Vector3(x - 0.5, y - 0.5, 0)); uvs.push(new THREE.Vector2(x, y)); attributes.src.value.push(new THREE.Vector3(0, 0, 0)); attributes.dst.value.push(new THREE.Vector3(0, 0, 0)); } geom.faces.push(new THREE.Face3(j * 4, j * 4 + 1, j * 4 + 2)); geom.faces.push(new THREE.Face3(j * 4, j * 4 + 2, j * 4 + 3)); geom.faceVertexUvs[0].push([uvs[0], uvs[1], uvs[2]]); geom.faceVertexUvs[0].push([uvs[0], uvs[2], uvs[3]]); } particles = new THREE.Mesh(geom, new THREE.ShaderMaterial({ blending: THREE.AdditiveBlending, depthWrite: false, transparent: true, uniforms: uniforms, attributes: attributes, vertexShader: Golgi.CellView.vert_pass_1, fragmentShader: Golgi.CellView.frag_pass_1 })); scene1.add(particles); } function delete_particles() { particles.geometry.dispose(); particles.material.dispose(); scene1.remove(particles); } function ensure_particles(count) { var c = particles ? particles.geometry.faces.length / 2 : 1; if (c >= count) { attributes.src.needsUpdate = attributes.dst.needsUpdate = true; return; } while (c < count) c *= 2; if (particles) delete_particles(); create_particles(c); } function make_particles(univ1, univ2, bbox, limit, blk) { univ1.query(bbox, limit, function(x, y, density) { if (limit > 1) return blk(x, y, 1, x, y, 1, density); var m = univ2.moore(x, y); for (var i in m) { var v = m[i], x2 = x + v.x, y2 = y + v.y; blk(x, y, 1 / m.length, x2, y2, 1 / univ1.moore(x2, y2).length, 1); } if (m.length === 0) blk(x, y, 1, x, y, 0, 1); }); if (limit === 1) univ2.query(bbox, limit, function(x, y, density) { if (univ1.moore(x, y).length === 0) blk(x, y, 0, x, y, 1, 1); }); } function set_particles(navi, state, sight) { var c = 0, i = 0, j; var limit = 1; while (limit * navi.scale < 2) limit *= 2; var nuniv = state.next_univ; make_particles(state.univ, nuniv, sight, limit, function() { c++; }); ensure_particles(c); uniforms.size.value = limit < 1 ? 3 : limit * 3; make_particles(state.univ, nuniv, sight, limit, function(sx, sy, sp, dx, dy, dp, p) { for (j = 0; j < 4; i++, j++) { attributes.src.value[i].set(sx, -sy, sp * p); attributes.dst.value[i].set(dx, -dy, dp * p); } }); for (; i < particles.geometry.faces.length * 2; i++) { attributes.src.value[i].set(0, 0, 0); attributes.dst.value[i].set(0, 0, 0); } } function setup_grid() { var i, geom; geom = new THREE.Geometry(); for (i = 1; i < max_grid_num; i++) { geom.vertices.push(new THREE.Vector3(0, i / max_grid_num, 1)); geom.vertices.push(new THREE.Vector3(1, i / max_grid_num, 1)); geom.vertices.push(new THREE.Vector3(i / max_grid_num, 0, 1)); geom.vertices.push(new THREE.Vector3(i / max_grid_num, 1, 1)); } grid = new THREE.Line(geom, new THREE.LineBasicMaterial({ blending: THREE.AdditiveBlending, color: 0x404040, opacity: 0.5, linewidth: 1 }), THREE.LinePieces); scene2.add(grid); geom = new THREE.Geometry(); geom.vertices.push(new THREE.Vector3(-1, 0, 2)); geom.vertices.push(new THREE.Vector3(1, 0, 2)); geom.vertices.push(new THREE.Vector3(0, -1, 2)); geom.vertices.push(new THREE.Vector3(0, 1, 2)); cross = new THREE.Line(geom, new THREE.LineBasicMaterial({ blending: THREE.AdditiveBlending, color: 0xffffff, opacity: 0.5, linewidth: 3 }), THREE.LinePieces); scene2.add(cross); } function set_grid(navi, grid_size) { var nx = navi.x, ny = navi.y; var nscale = navi.scale; var w = plane.scale.x / 2; var h = plane.scale.y / 2; var x = -nx * nscale; var y = -ny * nscale; if (x < -w - 5) x = -w - 5; if (x > w + 5) x = w + 5; if (y < -h - 5) y = -h - 5; if (y > h + 5) y = h + 5; cross.position.set(x, -y, 0); var s = grid_size * nscale * max_grid_num; grid.scale.set(s, s, 1); x = (Math.floor((nx - w / nscale) / grid_size) * grid_size - nx) * nscale; y = (Math.ceil((ny + h / nscale) / grid_size) * grid_size - ny) * nscale; grid.position.set(x, -y, 0); } function draw_all(navi, state) { uniforms.scale.value = navi.scale; uniforms.origin.value.set(navi.x, -navi.y); uniforms.time.value = state.tick; renderer.render(scene1, camera, texture, true); renderer.render(scene2, camera); } renderer = new THREE.WebGLRenderer(); renderer.setClearColor(0x000000, 1.0); camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 1, 4); camera.position.set(0, 0, 3); scene1 = new THREE.Scene(); ensure_particles(2); texture = new THREE.WebGLRenderTarget(1024, 1024); scene2 = new THREE.Scene(); plane = new THREE.PlaneGeometry(1, 1); plane = new THREE.Mesh(plane, new THREE.ShaderMaterial({ depthWrite: false, uniforms: { tDiffuse: { type: 't', value: texture } }, vertexShader: Golgi.CellView.vert_pass_2, fragmentShader: Golgi.CellView.frag_pass_2 })); scene2.add(plane); setup_grid(); this.init = function() { dom.appendChild(renderer.domElement); }; this.retire = function() { dom.removeChild(renderer.domElement); }; this.resize = function(width, height) { camera.left = -width / 2; camera.right = width / 2; camera.top = height / 2; camera.bottom = -height / 2; camera.updateProjectionMatrix(); cross.scale.set(width + 10, height + 10, 1); renderer.setSize(width, height); plane.scale.set(width, height, 1); }; this.draw = function(navi, state, sight, grid_size) { if (state.need_update) { state.need_update = false; set_particles(navi, state, sight); } if (grid_size) set_grid(navi, grid_size); cross.visible = grid.visible = !!grid_size; draw_all(navi, state); }; this.get_particle_count = function() { return particles.geometry.faces.length / 2; }; }; <|start_filename|>js/rectview.js<|end_filename|> /** * A canvas-based viewer * @constructor * @param {Node} dom A dom node of a wrapper div. * @param {Number} max_grid_num A maximun number of grid lines. */ Golgi.RectView = function(dom, max_grid_num) { var canvas = document.createElement('canvas'); dom.style.backgroundColor = '#000000'; var ctx = canvas.getContext('2d'); function draw_grid(l, r, t, b, nscale, grid_size) { /* grid */ ctx.beginPath(); ctx.lineWidth = 1.5 / nscale; ctx.strokeStyle = 'rgb(64,64,64)'; for (x = l; x <= r; x += grid_size) { ctx.moveTo(x, t); ctx.lineTo(x, b); } for (y = t; y <= b; y += grid_size) { ctx.moveTo(l, y); ctx.lineTo(r, y); } ctx.stroke(); /* x/y axises */ ctx.beginPath(); ctx.lineWidth = 3 / nscale; ctx.strokeStyle = 'rgb(255,255,255)'; ctx.moveTo(0, t); ctx.lineTo(0, b); ctx.moveTo(l, 0); ctx.lineTo(r, 0); ctx.stroke(); } var color; function draw_cells(nscale, state, sight) { var limit = 1; while (limit * nscale < 1) limit *= 2; ctx.transform(1, 0, 0, 1, -limit / 2, -limit / 2); var k = state.tick; state.next_univ.query(sight, limit, function(x, y, density) { ctx.fillStyle = color(density * k); ctx.fillRect(x, y, limit, limit); }); k = 1 - k; state.univ.query(sight, limit, function(x, y, density) { ctx.fillStyle = color(density * k); ctx.fillRect(x, y, limit, limit); }); } this.init = function() { dom.appendChild(canvas); }; this.retire = function() { dom.removeChild(canvas); }; this.resize = function(width, height) { canvas.width = width; canvas.height = height; }; this.draw = function(navi, state, sight, grid_size) { var nscale = navi.scale; var w = canvas.width / nscale; var h = canvas.height / nscale; ctx.setTransform(nscale, 0, 0, nscale, (w / 2 - navi.x) * nscale, (h / 2 - navi.y) * nscale); /* clear all */ ctx.clearRect(navi.x - w / 2, navi.y - h / 2, w, h); if (grid_size || true) { var x = (navi.x - w / 2) / grid_size; var y = (navi.y - h / 2) / grid_size; var l = Math.floor(x) * grid_size; var r = Math.ceil(x) * grid_size + w; var t = Math.floor(y) * grid_size; var b = Math.ceil(y) * grid_size + h; draw_grid(l, r, t, b, nscale, grid_size); } draw_cells(nscale, state, sight); }; this.set_color = function(s) { s = 'rgba(' + s + ','; color = function(a) { return s + a + ')'; }; }; this.get_particle_count = function() { return 'N/A'; }; }; <|start_filename|>js/hashlife.js<|end_filename|> /* A Javascript implementation of HashLife * Copyright (C) <NAME>, 2013 * * Hashlife[1] is a very fast algorithm for computing Conway's Game of Life. * * [1] Gosper, Bill (1984). "Exploiting Regularities in Large Cellular Spaces". * * Key points: * * - A universe is represented as a purely functional quadtree. * - The `run` function maps each 2^n-size node to any generation (less than * or equal to 2^(n-2)th) of 2^(n-1)-size node whose center is the same as * the original. * - The `run` function is memoized. * * Usage example: * * var univ = HashLife.EmptyUniverse; * univ = univ.load(rle); * univ = univ.run(count); * print(univ.dump()); */ HashLife = {}; new function() { /* An array representing the current birth rule */ var birth; /* a cell should live if birth[count] is true */ /* An array representing the current survival rule */ var survival; /* a cell should survive if survival[count] is true */ /* A bounding box for empty node/leaf */ var empty_box = { w: Infinity, e: -Infinity, n: Infinity, s: -Infinity }; /* Each node has the following properties/methods: * * - id: the node id * - size: the size of the node * - pop: the population (the number of living cells in the node) * - set: update function for a cell (purely functional) * - get: check function whether a cell is living or not * - dump: dumper (for debug) */ /* Two leaf nodes of quadtree: a dead cell and a live cell. */ var DeadCell = { id: 0, size: 1, pop: 0, set: function(x, y, cell) { return cell; }, get: function(x, y) { return false; }, dump: function() { return ['.']; }, each: function(off_x, off_y, query, minsize, blk) { }, bounding_box: function(x, y) { return empty_box; } }; var LiveCell = { id: 1, size: 1, pop: 1, set: function(x, y, cell) { return cell; }, get: function(x, y) { return true; }, dump: function() { return ['*']; }, each: function(off_x, off_y, query, minsize, blk) { blk(off_x, off_y, 1); }, bounding_box: function(x, y) { return { w: x, e: x, n: y, s: y }; } }; /* A internal node of quadtree */ var Node = function(nw, ne, sw, se) { this.id = _last_id++; this.pop = nw.pop + ne.pop + sw.pop + se.pop; this.size = nw.size * 2; /* four quadrants */ this.nw = nw; this.ne = ne; this.sw = sw; this.se = se; this.offset = this.size / 4; /* for garbage collection */ this.mark_id = -1; if (this.size > 4) this.memo = []; }; /* A cache of nodes */ var _cache = {}, _cache_size = 0; /* The sequence number for identifying node objects */ var _last_id = 2; /* A factory method for node */ function create_node(nw, ne, sw, se) { var key = nw.id + ',' + ne.id + ',' + sw.id + ',' + se.id; /* return a cached node if any */ if (_cache[key]) return _cache[key]; /* create a new node */ _cache_size++; return (_cache[key] = new Node(nw, ne, sw, se)); } /* A factory method for empty node of a given size */ /* size must be a power to 2 */ function create_empty_node(size) { var n = DeadCell; while (size > n.size) n = create_node(n, n, n, n); return n; } /* Updates a cell (in purely functional style) */ Node.prototype.set = function(x, y, cell) { var offset = this.offset; if (y < 0) { if (x < 0) return create_node( this.nw.set(x + offset, y + offset, cell), this.ne, this.sw, this.se); else return create_node( this.nw, this.ne.set(x - offset, y + offset, cell), this.sw, this.se); } else { if (x < 0) return create_node( this.nw, this.ne, this.sw.set(x + offset, y - offset, cell), this.se); else return create_node( this.nw, this.ne, this.sw, this.se.set(x - offset, y - offset, cell)); } }; /* Checks whether a cell is living or not */ Node.prototype.get = function(x, y) { var offset = this.offset; return y < 0 ? x < 0 ? this.nw.get(x + offset, y + offset) : this.ne.get(x - offset, y + offset) : x < 0 ? this.sw.get(x + offset, y - offset) : this.se.get(x - offset, y - offset); }; /* A dumper (for debug) */ Node.prototype.dump = function() { var nw = this.nw.dump(); var ne = this.ne.dump(); var sw = this.sw.dump(); var se = this.se.dump(); for (var i = 0; i < this.size / 2; i++) { nw[i] += ne[i]; sw[i] += se[i]; } return nw.concat(sw); }; /* Returns a new half-size node */ Node.prototype.sub_center = function() { return create_node(this.nw.se, this.ne.sw, this.sw.ne, this.se.nw); }; Node.prototype.sub_west = function() { return create_node(this.nw.sw, this.nw.se, this.sw.nw, this.sw.ne); }; Node.prototype.sub_east = function() { return create_node(this.ne.sw, this.ne.se, this.se.nw, this.se.ne); }; Node.prototype.sub_north = function() { return create_node(this.nw.ne, this.ne.nw, this.nw.se, this.ne.sw); }; Node.prototype.sub_south = function() { return create_node(this.sw.ne, this.se.nw, this.sw.se, this.se.sw); }; /* Runs the simulation (Case: size > 4) */ function run_step(self, step) { /* This function is the main trick of the algorithm. We write s(w, n, e, s) * for a (sub)node of this node where -1 <= w,n,e,s <= 1. The node itself * is written as s(-1, -1, 1, 1). * This function returns s(-1/2, -1/2, 1/2, 1/2) after a given step. */ /* let nXY be s((X-2)/2, (Y-2)/2, X/2, Y/2), i.e., each half-size subnode */ /* e.g., n00 is nw, i.e., s(-1, -1, 0, 0) */ var n00 = self.nw, n01 = self.sub_north(), n02 = self.ne; var n10 = self.sub_west(), n11 = self.sub_center(), n12 = self.sub_east(); var n20 = self.sw, n21 = self.sub_south(), n22 = self.se; var step1 = 0; if (self.offset / 2 < step) { step1 = self.offset / 2; step -= step1; } /* run each nXY in min(step, offset / 2) */ /* then, nXY is now s((X-3)/4, (Y-3)/4, (X-1)/4, (Y-1)/4) */ /* e.g., n00 is s(-3/4, -3/4, -1/4, -1/4) */ n00 = n00.run(step); n01 = n01.run(step); n02 = n02.run(step); n10 = n10.run(step); n11 = n11.run(step); n12 = n12.run(step); n20 = n20.run(step); n21 = n21.run(step); n22 = n22.run(step); /* merge each four nXYs and run each in the remaining steps */ /* e.g., merging n00, n01, n10, and n11 yields s(-3/4, -3/4, 1/4, 1/4), * and running it yields s(-1/2, -1/2, 0, 0). */ return create_node( create_node(n00, n01, n10, n11).run(step1), create_node(n01, n02, n11, n12).run(step1), create_node(n10, n11, n20, n21).run(step1), create_node(n11, n12, n21, n22).run(step1)); } /* Calculates the next state under the rule of Game of Life */ function apply_rule(bits) { var living = (bits >> 5) & 1; var count = 0; /* count the living cells in the Moore neighborhood */ bits &= 0x757; while (bits !== 0) { count += 1; bits &= bits - 1; } /* birth */ if (living) return survival[count] ? LiveCell : DeadCell; return birth[count] ? LiveCell : DeadCell; } var ccc = 0; /* Runs the simulation (Case: size == 4) */ function run_base(self) { var bits = 0; for (var y = -2; y < 2; y++) { for (var x = -2; x < 2; x++) { bits = (bits << 1) | (self.get(x, y) ? 1 : 0); } } return create_node( apply_rule(bits >> 5), apply_rule(bits >> 4), apply_rule(bits >> 1), apply_rule(bits)); } /* Runs the simulation in a given step (0 <= step <= 2^(size-2)) */ Node.prototype.run = function(step) { /* two trivial cases */ if (this.pop === 0) return this.nw; if (step === 0) return this.sub_center(); if (this.size === 4) { if (this.memo) return this.memo; this.memo = run_base(this); return this.memo; } var memo = this.memo[step]; if (memo) return memo; return (this.memo[step] = run_step(this, step)); }; /* Expands a node with empty sub node */ Node.prototype.expand = function(step) { if (this.size >= 8 && this.offset >= step && this.nw.pop === this.nw.se.se.pop && this.ne.pop === this.ne.sw.sw.pop && this.sw.pop === this.sw.ne.ne.pop && this.se.pop === this.se.nw.nw.pop) return this; var n = create_empty_node(this.size / 2); return create_node( create_node(n, n, n, this.nw), create_node(n, n, this.ne, n), create_node(n, this.sw, n, n), create_node(this.se, n, n, n)).expand(step); }; /* Shrink a node if three quadrants are empty */ Node.prototype.shrink = function(x, y) { if (this.size <= 8) return { off_x: x, off_y: y, node: this }; var pop = this.pop, offset = this.offset; if (pop === this.nw.pop) return this.nw.shrink(x - offset, y - offset); if (pop === this.ne.pop) return this.ne.shrink(x + offset, y - offset); if (pop === this.sw.pop) return this.sw.shrink(x - offset, y + offset); if (pop === this.se.pop) return this.se.shrink(x + offset, y + offset); var sub = this.sub_center(); if (pop === sub.pop) return sub.shrink(x, y); sub = this.sub_west(); if (pop === sub.pop) return sub.shrink(x - offset, y); sub = this.sub_east(); if (pop === sub.pop) return sub.shrink(x + offset, y); sub = this.sub_north(); if (pop === sub.pop) return sub.shrink(x, y - offset); sub = this.sub_south(); if (pop === sub.pop) return sub.shrink(x, y + offset); return { off_x: x, off_y: y, node: this }; }; /* Enumerates all living cells */ Node.prototype.each = function(off_x, off_y, query, minsize, blk) { if (this.pop === 0) return; var offset = this.offset; var size = this.size; if (size <= minsize) { blk(off_x, off_y, this.pop / (size * size)); } else { if (query.n < off_y) { if (query.w < off_x) this.nw.each(off_x - offset, off_y - offset, query, minsize, blk); if (off_x <= query.e) this.ne.each(off_x + offset, off_y - offset, query, minsize, blk); } if (off_y <= query.s) { if (query.w < off_x) this.sw.each(off_x - offset, off_y + offset, query, minsize, blk); if (off_x <= query.e) this.se.each(off_x + offset, off_y + offset, query, minsize, blk); } } }; /* Calculates the minimum bounding box for all living cells */ Node.prototype.bounding_box = function(x, y) { if (this.pop === 0) return empty_box; var offset = this.offset; var nw = this.nw, ne = this.ne, sw = this.sw, se = this.se; nw = nw.bounding_box(x - offset, y - offset); ne = ne.bounding_box(x + offset, y - offset); sw = sw.bounding_box(x - offset, y + offset); se = se.bounding_box(x + offset, y + offset); return { w: Math.min(nw.w, ne.w, sw.w, se.w), e: Math.max(nw.e, ne.e, sw.e, se.e), n: Math.min(nw.n, ne.n, sw.n, se.n), s: Math.max(nw.s, ne.s, sw.s, se.s) }; }; /* Each universe for cells has the following properties: * * - root: Node * - attr.off_x/off_y: the center point of root (from origin) * - attr.gen_count: the generation count * - attr.prev: the previous universe */ var Universe = function(root, attr) { this.root = root; this.attr = attr; }; /* Updates a cell (in purely functional style) */ Universe.prototype.set = function(x, y, alive) { x -= this.attr.off_x; y -= this.attr.off_y; var size = Math.max(Math.abs(x), Math.abs(y)); var root = this.root.expand(size).set(x, y, alive ? LiveCell : DeadCell); var attr = { off_x: this.attr.off_x, off_y: this.attr.off_y, gen_count: 0 }; return new Universe(root, attr); }; /* Checks whether a cell is living or not */ Universe.prototype.get = function(x, y) { var bound = this.root.offset * 2; x -= this.attr.off_x; y -= this.attr.off_y; if (x < -bound || bound <= x) return false; if (y < -bound || bound <= y) return false; return this.root.get(x, y); }; /* A dumper (for debug) */ Universe.prototype.dump = function() { return this.root.dump().join('\n'); }; var Window = 4; var Log2 = Math.log(2); function each_key_frame(n, blk) { var exp = Math.floor(Math.log((n + Window - 1) / Window) / Log2); var off = n + Window - 1 - Window * Math.pow(2, exp); var step = 1; for (; exp; exp--) { for (var i = Window - 1 + (off % 2); i; i--, n -= step) blk(n); off = Math.floor(off / 2); step *= 2; } for (off += 2; off; off--, n -= step) blk(n); } /* Runs the simulation in a given step */ Universe.prototype.run = function(step) { if (this.root.pop === 0) return this; var r = this.root.expand(step); r = r.run(step); r = r.shrink(this.attr.off_x, this.attr.off_y); var attr = { off_x: r.off_x, off_y: r.off_y, gen_count: this.attr.gen_count + step, prev: this }; r = new Universe(r.node, attr); if (attr.gen_count) { var n = r; each_key_frame(attr.gen_count, function(count) { if (count === 0) return; var prev = n.attr.prev; while (true) { if (!prev) break; if (!prev.attr.prev) break; if (prev.attr.prev.attr.gen_count < count) break; n.attr.prev = prev = prev.attr.prev; } if (prev && prev.attr.gen_count >= count) n = prev; }); } return r; }; /* Runs backward in a given step */ Universe.prototype.run_back = function(step) { var gen_count = this.attr.gen_count - step; var univ = this; if (gen_count < 0) throw 'cannot go back any more'; while (univ.attr.gen_count > gen_count) { univ = univ.attr.prev; } return univ.run(gen_count - univ.attr.gen_count); }; /* Returns the current generation */ Universe.prototype.get_generation = function() { return this.attr.gen_count; }; /* Returns the current population */ Universe.prototype.get_population = function() { return this.root.pop; }; /* Enumerates all living cells */ Universe.prototype.each = function(blk) { this.query({}, 0, blk); }; /* Enumerates all living cells in query region */ Universe.prototype.query = function(query, minsize, blk) { query = { w: query.w || -Infinity, e: query.e || Infinity, n: query.n || -Infinity, s: query.s || Infinity }; this.root.each(this.attr.off_x, this.attr.off_y, query, minsize, blk); }; /* Calculates the minimum bounding box for all living cells */ Universe.prototype.bounding_box = function() { var bbox = this.root.bounding_box(this.attr.off_x, this.attr.off_y); return { w: bbox.w - 0.5, e: bbox.e + 0.5, n: bbox.n - 0.5, s: bbox.s + 0.5 }; }; /* Returns all living moore neighbors (including the center cell) */ Universe.prototype.moore = function(x, y) { var i, j, a = []; for (j = -1; j <= 1; j++) { for (i = -1; i <= 1; i++) { if (this.get(x + i, y + j)) a.push({ x: i, y: j }); } } return a; }; /* Returns the current rule description */ HashLife.get_rule = function() { var i = 0, s = 'B'; for (i in birth) { if (birth[i]) s = s + i; } s = s + '/S'; for (i in survival) { if (survival[i]) s = s + i; } return s; }; /* Updates the rule */ HashLife.change_rule = function(rule) { var _re_rule = new RegExp( '^(?:B(\\d+)/S(\\d+)|S(\\d+)/B(\\d+)|(\\d+)/(\\d+))$', 'i'); var r; if ((r = _re_rule.exec(rule)) === null) throw ('unknown rule format: ' + rule); var _birth = r[1] || r[4] || r[6]; var _survival = r[2] || r[3] || r[5]; r = 'B' + _birth + '/S' + _survival; if (r == HashLife.get_rule()) return; function make_table(rule) { var i, table = []; for (i = 0; i < rule.length; i++) table[Number(rule[i])] = true; for (i = 0; i < table.length; i++) table[i] = table[i] || false; return table; } birth = make_table(_birth); survival = make_table(_survival); /* clear cache */ _last_id = 2; _cache = {}; _cache_size = 0; /* A universe that has no cell */ HashLife.EmptyUniverse = new Universe( create_empty_node(8), { off_x: 0, off_y: 0, gen_count: 0, prev: null }, null); }; /* Sets the default rule is B3/S23 */ HashLife.change_rule('B3/S23'); /* Regexps for parsing rle format */ var _re_rle = new RegExp( '\\s*(?:' + // skip spaces '#(.)\\s*(.*)|' + // comment line '(x.*)\\r?\\n|' + // header line '([\\d\\s]*)([bo\\$!])|' + // chunk '\\r|\\n' + // skip newline ')', 'g'); var _re_space = new RegExp('\\s', 'g'); var _re_header = new RegExp('rule=(.*)', 'i'); /* A parser for rle format */ HashLife.load = function(pattern) { var univ = null, r, x = 0, y = 0, stop = false; var last_index = 0; var name, author, comment = []; _re_rle.lastIndex = last_index; while (!stop && (r = _re_rle.exec(pattern)) !== null) { if (r.index !== last_index) break; last_index = _re_rle.lastIndex; if (r[1]) { switch (r[1]) { case 'N': name = r[2]; break; case 'O': author = r[2]; break; case 'C': comment.push(r[2]); break; } } else if (r[3]) { var attrs = r[3].replace(_re_space, '').split(','); for (var i in attrs) { var attr = attrs[i].split('='); if (attr[0] == 'rule') { HashLife.change_rule(attr[1]); univ = HashLife.EmptyUniverse; } } } else if (r[5]) { if (!univ) { HashLife.change_rule('B3/S23'); univ = HashLife.EmptyUniverse; } var len = Number(r[4].replace(_re_space, '')); if (!len) len = 1; switch (r[5]) { case 'b': case 'o': if (r[5] === 'o') { for (var i = 0; i < len; i++) univ = univ.set(x++, y, true); } else { x += len; } break; case '$': x = 0; y += len; break; case '!': stop = true; break; } } } if (!stop) throw ('unknown format: ' + pattern.substr(last_index, 10)); var r = univ.root.shrink(univ.attr.off_x, univ.attr.off_y); var attr = { off_x: r.off_x, off_y: r.off_y, gen_count: 0, prev: null }; var univ = new Universe(r.node, attr); var meta = { name: name, author: author, comment: comment }; return { univ: univ, meta: meta }; }; /* Marks a node (for a garbage collection) */ Node.prototype.mark = function(mark_id) { if (this.mark_id === mark_id) return; this.mark_id = mark_id; this.check = 0; if (this.offset >= 1) { this.nw.mark(mark_id); this.ne.mark(mark_id); this.sw.mark(mark_id); this.se.mark(mark_id); } if (this.size === 4) { if (this.memo) this.memo.mark(mark_id); } else { var memo = this.memo; for (var i in memo) memo[i].mark(mark_id); } }; /* Marks a universe */ Universe.prototype.mark = function(mark_id) { this.root.mark(mark_id); if (this.attr.prev) this.attr.prev.mark(mark_id); }; var _mark_id = 0; /* A garbage collection with mark and sweep */ HashLife.gc = function(universes) { _mark_id++; /* marking phase */ HashLife.EmptyUniverse.mark(_mark_id); for (var i in universes) universes[i].mark(_mark_id); /* sweeping phase */ for (var key in _cache) { if (_cache[key].mark_id !== _mark_id) { delete _cache[key]; _cache_size--; } } }; /* Returns the cache size */ HashLife.get_cache_size = function() { return _cache_size; }; } <|start_filename|>js/ui.js<|end_filename|> /** * A UI manager. * @constructor * @param {Golgi.State} state a state manager. * @param {Golgi.Navi} navi a navi manager. */ var UI = function(state, navi) { /* utilities */ function get(id) { return document.getElementById(id); } function on(obj, type, func) { if (typeof obj === 'string') obj = get(obj); if (obj.addEventListener) { obj.addEventListener(type, func, false); } else { obj.attachEvent(type, func); } } function show(id, html) { get(id).innerHTML = html; }; function cancel(e) { e.preventDefault(); e.stopPropagation(); } function error(msg) { alert('ERROR: ' + msg); } function auto_scale() { need_auto_scale = false; var bbox = state.univ.bounding_box(); if (!isFinite(bbox.w)) { bbox.w = bbox.n = -5; bbox.e = bbox.s = 5; } var bbox2 = state.next_univ.bounding_box(); if (!isFinite(bbox2.w)) { bbox2.w = bbox2.n = -5; bbox2.e = bbox2.s = 5; } if (bbox.w > bbox2.w) bbox.w = bbox2.w; if (bbox.e < bbox2.e) bbox.e = bbox2.e; if (bbox.n > bbox2.n) bbox.n = bbox2.n; if (bbox.s < bbox2.s) bbox.s = bbox2.s; var w = bbox.e - bbox.w; var h = bbox.s - bbox.n; var x = (bbox.w + bbox.e) / 2; var y = (bbox.n + bbox.s) / 2; var w = (bbox.e - bbox.w + 1) * 1.4; var h = (bbox.s - bbox.n + 1) * 1.4; var cw = canvas.clientWidth; var ch = canvas.clientHeight; var scale = Math.min(ch / h, cw / w); navi.set(x, y, scale); } function bbox_msg() { var bbox = state.univ.bounding_box(); var msg; if (isFinite(bbox.w)) { msg = 'W:' + bbox.w + ',E:' + bbox.e + ',N:' + bbox.n + ',S:' + bbox.s; } else { msg = 'N/A'; } return msg; } function load(id, text) { var select = get('examples'); if (text) { window.location.hash = ''; state.load(text); return; } if (id) { id = id.replace('#', '').replace(/_/g, ' '); if (Golgi.examples[id]) { window.location.hash = '#' + id.replace(/ /g, '_'); var i; for (i = 0; i < select.options.length; i++) { if (select.options[i].value == id) break; } select.selectedIndex = i; state.load(Golgi.examples[id]); return; } } var i = Math.floor(select.options.length * Math.random()); load(select.options[i].value); } /* properties */ var canvas = get('canvas'); var max_grid_num = 30; var current_view = null; var rectview = new Golgi.RectView(canvas, max_grid_num); var cellview = null; /* not initialized */ var need_auto_scale = false; /* commands */ function cmd_speed_up() { state.change_speed(2); } function cmd_speed_down() { state.change_speed(0.5); } function cmd_backward() { state.backward(Number(get('step').value)); } function cmd_forward() { state.forward(Number(get('step').value)); } function cmd_toggle_boards() { var display = get('check-hide-boards').checked ? 'none' : 'block'; get('board-status').style.display = display; get('board-meta').style.display = display; get('board-perf').style.display = display; get('board-config-hide').style.display = display; get('control').style.display = display; } function cmd_auto_scale() { if (get('check-auto-scale').checked) { need_auto_scale = true; state.on_univ_changed(); } } function cmd_change_view() { var cell = get('check-cell-view').checked; if (cell && !cellview) { /* try to initialize cellview */ try { cellview = new Golgi.CellView(canvas, max_grid_num); } catch (e) { error("Your graphics card and/or browser don't seem to support WebGL."); get('check-cell-view').checked = false; return; } } /* change the current view */ if (current_view) current_view.retire(); current_view = cell ? cellview : rectview; current_view.init(); /* inherit the current color to cell */ var rgb = document.defaultView.getComputedStyle(get('about-box')).color; rectview.set_color(rgb.slice(4, -1)); /* redraw */ current_view.resize(window.innerWidth, window.innerHeight); } /* mouse navigation */ new function() { function pos(e) { var scale = navi.scale; return { x: navi.x + (e.clientX - canvas.clientWidth / 2) / scale, y: navi.y + (e.clientY - canvas.clientHeight / 2) / scale }; } on('body', 'mousemove', function(e) { e.which === 1 ? navi.drag_move(pos(e)) : navi.drag_end(); }); on('body', 'mouseup', function(e) { cancel(e); navi.drag_end(); }); on('body', 'mousedown', function(e) { window.getSelection().collapse(document.body, 0); cancel(e); if (e.which === 1) { if (!get('check-edit-mode').checked) navi.drag_start(pos(e)); else state.write(pos(e)); } }); function mousewheel(e) { var delta = 0; if (e.wheelDelta) { // WebKit / Opera / Explorer 9 delta = e.wheelDelta / 40; } else if (e.detail) { // Firefox delta = -e.detail / 3; } if (delta) navi.change_scale(pos(e), Math.pow(2, 1 / delta)); } on('body', 'mousewheel', mousewheel); on('body', 'DOMMouseScroll', mousewheel); on('canvas', 'touchstart', function(e) { e.preventDefault(); if (!get('check-edit-mode').checked) { switch (e.touches.length) { case 1: navi.drag_start(pos(e.touches[0])); break; case 2: navi.pinch_start(pos(e.touches[0]), pos(e.touches[1])); break; } } else { state.write(pos(e.touches[0])); } }); on('canvas', 'touchend', function(e) { e.preventDefault(); navi.drag_end(); }); on('body', 'touchmove', function(e) { e.preventDefault(); switch (e.touches.length) { case 1: navi.drag_move(pos(e.touches[0])); break; case 2: navi.pinch_move(pos(e.touches[0]), pos(e.touches[1])); break; } }); }; /* file load */ new function() { function file_load(files) { if (files.length == 1) { var reader = new FileReader(); get('progress').style.display = 'table'; reader.onload = function(e) { try { load(null, e.target.result); } catch (e) { error('failed to load file: ' + e.toString()); } get('progress').style.display = 'none'; }; reader.readAsText(files[0]); } else if (files.length > 1) { error('cannot load multiple file!'); } } var fileapi_available = true; fileapi_available = fileapi_available && window.File; fileapi_available = fileapi_available && window.FileReader; fileapi_available = fileapi_available && window.FileList; fileapi_available = fileapi_available && window.Blob; if (fileapi_available) { on('canvas', 'drop', function(e) { cancel(e); file_load(e.dataTransfer.files); }); on('canvas', 'dragover', function(e) { cancel(e); e.dataTransfer.dropEffect = 'copy'; }); } on('file', 'change', function(e) { file_load(e.target.files); }); }; /* boards */ new function() { on('board-status', 'mousedown', cancel); on('board-meta', 'mousedown', function(e) { e.stopPropagation(); }); on('board-meta', 'mouseup', function(e) { e.stopPropagation(); }); on('board-perf', 'mousedown', cancel); on('board-config', 'mousedown', cancel); }; /* control */ new function() { on('control-body', 'mousedown', cancel); on('step', 'mousedown', function(e) { e.stopPropagation(); }); on('step', 'mouseup', function(e) { e.stopPropagation(); }); }; /* buttons */ new function() { on('button-play', 'click', state.play); on('button-fast', 'click', cmd_speed_up); on('button-slow', 'click', cmd_speed_down); on('button-backward', 'click', cmd_backward); on('button-forward', 'click', cmd_forward); on('button-load', 'click', function(e) { get('load').style.display = 'table'; }); on('button-reset', 'click', function() { state.reset(); }); on('button-clear', 'click', function() { state.clear(); }); on('button-about', 'click', function() { get('rule').value = HashLife.get_rule(); get('about').style.display = 'table'; }); }; /* load */ new function() { on('load', 'mousedown', function() { get('load').style.display = 'none'; }); on('load-box', 'mousedown', function(e) { e.stopPropagation(); }); on('load-box', 'mouseup', function(e) { e.stopPropagation(); }); on('button-file-load', 'click', function(e) { get('file').click(); get('load').style.display = 'none'; }); }; /* about */ new function() { var select = get('examples'); for (var i in Golgi.examples) { var option = document.createElement('option'); option.value = i; option.innerHTML = i; select.appendChild(option); } on('about', 'mousedown', function() { get('about').style.display = 'none'; }); on('about-box', 'mousedown', function(e) { e.stopPropagation(); }); on('about-box', 'mouseup', function(e) { e.stopPropagation(); }); on('examples', 'change', function(e) { var i = select.options[select.selectedIndex].value; load(i); get('about').style.display = 'none'; }); on('button-set-rule', 'click', function(e) { state.change_rule(get('rule').value); get('about').style.display = 'none'; }); on('css-list', 'change', function(e) { var s = get('css-list'); var css = s.options[s.selectedIndex].value; get('body').className = css; cmd_change_view(); }); }; /* config */ new function() { on('check-hide-boards', 'change', cmd_toggle_boards); on('check-auto-scale', 'change', cmd_auto_scale); on('check-cell-view', 'change', cmd_change_view); }; /* perf */ var update_fps = null; new function() { var perf_graph = get('perf-graph'); while (perf_graph.children.length < 100) { var bar = document.createElement('span'); bar.className = 'perf-graph-bar'; perf_graph.appendChild(bar); } var prev_time = Date.now(); var frames = 0; update_fps = function() { var time = Date.now(); frames++; if (time > prev_time + 1000) { fps = Math.round(frames * 1000 / (time - prev_time)); show('show-fps', fps); var child = perf_graph.appendChild(perf_graph.firstChild); child.style.height = Math.min(30, 30 - (fps / 100) * 30) + 'px'; frames = 0; prev_time = time; } }; }; /* window */ new function() { /* resize */ on(window, 'resize', function() { current_view.resize(window.innerWidth, window.innerHeight); }, false); /* key */ on(window, 'keydown', function(e) { if (e.ctrlKey || e.altKey || e.shiftKey) return; switch (e.keyCode) { case 13: // return state.play(); break; case 32: // space case 39: // right cmd_forward(); break; case 37: // left cmd_backward(); break; case 38: // up cmd_speed_up(); break; case 40: // down cmd_speed_down(); break; case 65: // a get('check-auto-scale').click(); break; case 67: // c state.clear(); break; case 69: // e get('check-edit-mode').click(); break; case 71: // g get('check-show-grid').click(); break; case 79: // o get('file').click(); break; case 82: // r state.reset(); break; case 86: // v get('check-cell-view').click(); break; //default: // console.log(e.keyCode); } }); function sight_box() { var cw = canvas.clientWidth; var ch = canvas.clientHeight; var scale = navi.scale; var nw = { x: navi.x - cw / scale, y: navi.y - ch / scale }; var se = { x: navi.x + cw / scale, y: navi.y + ch / scale }; // must also calculate based on target return { w: nw.x, e: se.x, n: nw.y, s: se.y }; } function get_grid_size() { if (!get('check-show-grid').checked) return 0; var max_coord = Math.max(canvas.clientWidth, canvas.clientHeight); var grid_th = max_coord / navi.scale / max_grid_num; var grid_size = 1; while (grid_size <= grid_th && (grid_size *= 5) <= grid_th) grid_size *= 2; show('show-grid-size', grid_size); return grid_size; } function tick() { document.body.scrollTop = document.body.scrollLeft = 0; navi.update(); state.update(); current_view.draw(navi, state, sight_box(), get_grid_size()); update_fps(); requestAnimationFrame(tick); } requestAnimationFrame(tick); }; /* state change events */ new function() { state.on_speed_changed = function() { var v = state.speed; if (v < 1) v = '1/' + (1 / v); show('show-speed', v); }; state.on_playing_changed = function() { var msg = state.playing ? 'playing' : 'pausing'; get('button-play').className = msg; }; state.on_univ_loaded = function() { var meta = state.meta; show('show-name', meta && meta.name || 'N/A'); show('show-author', meta && meta.author || 'N/A'); var comment = meta && meta.comment ? meta.comment.join('<br />') : 'N/A'; show('show-comment', comment); show('show-rule', HashLife.get_rule()); need_auto_scale = true; }; state.on_univ_changed = function() { show('show-generation', state.univ.get_generation()); show('show-population', state.univ.get_population()); show('show-cache-size', HashLife.get_cache_size()); show('show-bound', bbox_msg()); show('show-particle-count', current_view.get_particle_count()); if (need_auto_scale || state.playing && get('check-auto-scale').checked) auto_scale(); }; }; /* init */ new function() { cmd_change_view(); state.change_speed(1); load(window.location.hash); }; };
mame/gol
<|start_filename|>honeycombio/resource_query.go<|end_filename|> package honeycombio import ( "context" "encoding/json" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/kvrhdn/go-honeycombio" ) func newQuery() *schema.Resource { return &schema.Resource{ CreateContext: resourceQueryCreate, ReadContext: resourceQueryRead, UpdateContext: nil, DeleteContext: schema.NoopContext, Importer: nil, Schema: map[string]*schema.Schema{ "query_json": { Type: schema.TypeString, Required: true, ForceNew: true, ValidateDiagFunc: validateQueryJSON(), }, "dataset": { Type: schema.TypeString, Required: true, ForceNew: true, }, }, } } func resourceQueryCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*honeycombio.Client) dataset := d.Get("dataset").(string) var querySpec honeycombio.QuerySpec err := json.Unmarshal([]byte(d.Get("query_json").(string)), &querySpec) if err != nil { return diag.FromErr(err) } query, err := client.Queries.Create(ctx, dataset, &querySpec) if err != nil { return diag.FromErr(err) } d.SetId(*query.ID) return resourceQueryRead(ctx, d, meta) } func resourceQueryRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*honeycombio.Client) dataset := d.Get("dataset").(string) query, err := client.Queries.Get(ctx, dataset, d.Id()) if err != nil { if err == honeycombio.ErrNotFound { d.SetId("") return nil } return diag.FromErr(err) } d.SetId(*query.ID) // Normalize the query before converting it to JSON to avoid unwanted diffs query.ID = nil if query.FilterCombination == "" { query.FilterCombination = honeycombio.FilterCombinationAnd } queryJSON, err := encodeQuery(query) if err != nil { return diag.FromErr(err) } d.Set("query_json", queryJSON) return nil }
olegy2008/terraform-provider-honeycombio
<|start_filename|>build-scripts/build-win.cmd<|end_filename|> set CSC_LINK=%cd%\build-assets\win-cert.pfx set CSC_KEY_PASSWORD=password call yarn package <|start_filename|>rn-cli.config.js<|end_filename|> const blacklist = require('metro').createBlacklist; module.exports = { getTransformModulePath() { return require.resolve("react-native-typescript-transformer"); }, getSourceExts() { return ["ts", "tsx"]; }, getBlacklistRE: function() { return blacklist([/dist\/mac\/.*/, "dist/mac/*"]); } }; <|start_filename|>public/electron.js<|end_filename|> const { app, BrowserWindow, protocol } = require("electron"); const isDev = require("electron-is-dev"); const url = require('url'); const path = require("path"); require('electron-debug')(); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow; function createWindow() { // Create the browser window. mainWindow = new BrowserWindow({ width: 800, height: 600, center: true, icon: path.join(__dirname, "../public/icons/png/64x64.png"), webPreferences: { webSecurity: true }, }); let urlPath = url.format({ pathname: path.join(__dirname, '../build', 'index.html'), protocol: 'file:', slashes: true }); mainWindow.loadURL((isDev) ? 'http://localhost:3000' : urlPath); if (isDev) { mainWindow.webContents.openDevTools(); } mainWindow.once("ready-to-show", () => { mainWindow.show(); }); // Prompt users before window close mainWindow.on("close", e => { // e.preventDefault(); }); // Emitted when the window is closed. mainWindow.on("closed", () => { mainWindow = null; }); } app.on("ready", () => { protocol.interceptFileProtocol('file', (request, callback) => { const url = request.url.substr(7) callback({ path: path.normalize(`${url}`) }) }, (err) => { if (err) console.log('Failed to register protocol'); }); createWindow(); }); app.on('window-all-closed', () => { // Respect the OSX convention of having the application in memory even // after all windows have been closed if (process.platform !== 'darwin') { app.quit(); } }) app.on("activate", () => { if (mainWindow === null) { createWindow(); } }); <|start_filename|>index.js<|end_filename|> /** * Application entry point */ import App from "./src"; export default App;
codi45/app
<|start_filename|>lib/pangu.coffee<|end_filename|> {CompositeDisposable} = require 'atom' pangu = require 'pangu' RangeFinder = require './range-finder' module.exports = config: autoPanguEnabled: title: 'Auto spacing on save' type: 'boolean' default: false ignoredFilenames: title: 'Auto spacing ignored filenames' type: 'array' default: [] items: type: 'string' skipNoCJKLine: title: 'Skip on lines without Chinese, Japanese and Korean' type: 'boolean' default: false ignoredPattern: title: 'Ignoring text with the matched pattern, e.g. \\*\\*[^\\*\\*]+\\*\\*, <pre>(.*?)</pre>' type: 'string' default: '' subscriptions: null activate: -> @subscriptions = new CompositeDisposable @subscriptions.add atom.commands.add 'atom-text-editor', 'pangu:spacing': => @spacing() @subscriptions.add atom.workspace.observeTextEditors (editor) => @subscriptions.add editor.onDidSave => autoPanguEnabled = atom.config.get('pangu.autoPanguEnabled') # return immediately if automatic spacing is disabled return unless autoPanguEnabled editor = atom.workspace.getActiveTextEditor() currentFilePath = editor.getPath() minimatch = require('minimatch') ignoredFilenames = atom.config.get('pangu.ignoredFilenames') ? [] ignoredFilenames = [ignoredFilenames] if typeof ignoredFilenames is 'string' isIgnored = false for ignoreFilename in ignoredFilenames when ignoreFilename try isIgnored = true if minimatch(currentFilePath, ignoreFilename, matchBase: true, dot: true) catch error atom.notifications.addWarning("Error parsing ignore pattern (#{ignoreFilename})", detail: error.message) @spacing() if not isIgnored deactivate: -> @subscriptions.dispose() spacingText: (text) -> skipNoCJKLine = atom.config.get('pangu.skipNoCJKLine') if skipNoCJKLine and not /[\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/.test text return text else return pangu.spacing(text) mergeTwoArrays: (firstTexts, secondTexts) -> mergedArray = [] for text, index in firstTexts mergedArray.push(text) mergedArray.push(secondTexts[index]) mergedArray spacing: -> console.log 'Pangu: spacing' editor = atom.workspace.getActiveTextEditor() # return immediately if file is empty return unless editor.getText() sortableRanges = RangeFinder.rangesFor(editor) ignoredPattern = atom.config.get('pangu.ignoredPattern') for range in sortableRanges textLines = editor.getTextInBufferRange(range).split('\n') insertedTextLines = [] for textLine in textLines if ignoredPattern re = new RegExp(ignoredPattern, 'g') ignoredTexts = textLine.match(re) if ignoredTexts notIgnoredTexts = textLine.split(re) newArray = [] for text in notIgnoredTexts text = @spacingText(textLine) newArray.push(text) newArray = @mergeTwoArrays(newArray, ignoredTexts) textLine = newArray.join('') else textLine = @spacingText(textLine) else textLine = @spacingText(textLine) insertedTextLines.push(textLine) editor.setTextInBufferRange(range, insertedTextLines.join('\n')) if insertedTextLines != textLines <|start_filename|>package.json<|end_filename|> { "name": "pangu", "main": "./lib/pangu", "version": "0.5.0", "description": "Adding space between Chinese/Japanese/Korean and English characters to file in Atom.io editor.", "keywords": [ "chinese", "japanese", "korean", "english", "pangu", "spacing" ], "activationCommands": { "atom-text-editor": [ "core:save", "pangu:spacing" ] }, "repository": "https://github.com/7kfpun/atom-pangu", "license": "MIT", "engines": { "atom": ">=0.174.0 <2.0.0" }, "dependencies": { "minimatch": "^3.0.2", "pangu": "git+https://github.com/vinta/pangu.js.git" } } <|start_filename|>menus/pangu.cson<|end_filename|> 'menu': [ { 'label': 'Packages' 'submenu': [ 'label': 'Pangu' 'submenu': [ { 'label': 'Pangu spacing' 'command': 'pangu:spacing' } ] ] } ]
7kfpun/atom-pangu
<|start_filename|>test/index.js<|end_filename|> const babel = require("@babel/core"); const { expect } = require("chai"); const path = require("path"); const fs = require("fs"); const transformer = require("../lib"); function removeSpaces(str) { return str.replace(/\s/gm, ""); } const fixturesDir = path.join(__dirname, "fixtures"); describe("transform redom jsx", () => { for (const caseName of fs.readdirSync(fixturesDir)) { it(`supports ${caseName.split("-").join(" ")}`, () => { const fixtureDir = path.join(fixturesDir, caseName); const actual = babel.transformFileSync( path.join(fixtureDir, "actual.js"), { plugins: [transformer] } ); const expected = fs.readFileSync(path.join(fixtureDir, "expected.js"), 'utf8'); expect(removeSpaces(actual.code)).to.equal(removeSpaces(expected)); }); }; }); <|start_filename|>package.json<|end_filename|> { "name": "babel-plugin-transform-redom-jsx", "version": "3.0.3", "description": "Babel plugin for RE:DOM jsx", "main": "lib/index.js", "scripts": { "test": "mocha ./test/index.js" }, "repository": "https://github.com/tomerigal/babel-plugin-transform-redom-jsx", "keywords": [ "babel", "redom", "jsx" ], "author": "<NAME>", "license": "MIT", "dependencies": { "@babel/plugin-syntax-jsx": "^7.16.0" }, "devDependencies": { "@babel/core": "^7.16.0", "chai": "^4.3.4", "mocha": "^9.1.3" }, "files": [ "lib" ] } <|start_filename|>test/fixtures/this-on-children/actual.js<|end_filename|> function Test() { <MyComp this="a" prop="a"> <div this="b"></div> {<div this="c"></div>} <div this={'a' + 'b'}></div> </MyComp> } <|start_filename|>lib/index.js<|end_filename|> module.exports = function(babel) { var t = babel.types; return { inherits: require("@babel/plugin-syntax-jsx").default, name: "transform-redom-jsx", visitor: { JSXElement(path, file) { const thisAttr = []; const restAttr = []; const isComponent = path.node.openingElement.name.name.match(/^[A-Z]/); let node = path.node; for (const attr of path.node.openingElement.attributes) { if (t.isJSXSpreadAttribute(attr)) { restAttr.push(attr); } else if (attr.name.name === "this") { thisAttr.push(attr); } else { restAttr.push(attr); } } if (isComponent) { var attribObj = restAttr.length ? buildOpeningElementAttributes(restAttr, file) : t.objectExpression([]); var children = t.react.buildChildren(path.node).map(node => { if (t.isLiteral(node)) { return t.callExpression(t.identifier("text"), [node]); } return node; }); node = t.newExpression( t.identifier(path.node.openingElement.name.name), [attribObj].concat(children) ); } if (thisAttr.length) { const attr = thisAttr[thisAttr.length - 1]; const thisMember = t.isJSXExpressionContainer(attr.value) ? attr.value.expression : attr.value; const assignToThis = t.assignmentExpression( "=", t.memberExpression(t.thisExpression(), thisMember, true), node ); path.node.openingElement.attributes = restAttr; node = t.isJSXElement(path.parent) ? t.jSXExpressionContainer(assignToThis) : assignToThis; } if (node !== path.node) { path.replaceWith(node); } } } }; function convertAttributeValue(node) { if (t.isJSXExpressionContainer(node)) { return node.expression; } else { return node; } } function convertAttribute(node) { let value = convertAttributeValue(node.value || t.booleanLiteral(true)); if (t.isStringLiteral(value) && !t.isJSXExpressionContainer(node.value)) { value.value = value.value.replace(/\n\s+/g, " "); } if (t.isValidIdentifier(node.name.name)) { node.name.type = "Identifier"; } else { node.name = t.stringLiteral(node.name.name); } return t.inherits(t.objectProperty(node.name, value), node); } function buildOpeningElementAttributes(attribs, file) { let _props = []; let objs = []; let useBuiltIns = file.opts.useBuiltIns || false; if (typeof useBuiltIns !== "boolean") { throw new Error( "transform-react-jsx currently only accepts a boolean option for useBuiltIns (defaults to false)" ); } function pushProps() { if (!_props.length) return; objs.push(t.objectExpression(_props)); _props = []; } while (attribs.length) { let prop = attribs.shift(); if (t.isJSXSpreadAttribute(prop)) { pushProps(); objs.push(prop.argument); } else { _props.push(convertAttribute(prop)); } } pushProps(); if (objs.length === 1) { // only one object attribs = objs[0]; } else { // looks like we have multiple objects if (!t.isObjectExpression(objs[0])) { objs.unshift(t.objectExpression([])); } const helper = useBuiltIns ? t.memberExpression(t.identifier("Object"), t.identifier("assign")) : file.addHelper("extends"); // spread it attribs = t.callExpression(helper, objs); } return attribs; } }; <|start_filename|>test/fixtures/this-attr/expected.js<|end_filename|> function Test() { this["a"] = <div> {this["b"] = <div></div>} {this["c"] = <div></div>} {this['a' + 'b'] = <div></div>} </div>; }
tomerigal/babel-plugin-transform-redom-jsx